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 // Other ideas/concepts are from:
38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
41 // Vectorizing Compilers.
43 //===----------------------------------------------------------------------===//
45 #include "llvm/Transforms/Vectorize.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/EquivalenceClasses.h"
48 #include "llvm/ADT/Hashing.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/ADT/StringExtras.h"
56 #include "llvm/Analysis/AliasAnalysis.h"
57 #include "llvm/Analysis/AliasSetTracker.h"
58 #include "llvm/Analysis/BlockFrequencyInfo.h"
59 #include "llvm/Analysis/LoopInfo.h"
60 #include "llvm/Analysis/LoopIterator.h"
61 #include "llvm/Analysis/LoopPass.h"
62 #include "llvm/Analysis/ScalarEvolution.h"
63 #include "llvm/Analysis/ScalarEvolutionExpander.h"
64 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
65 #include "llvm/Analysis/TargetTransformInfo.h"
66 #include "llvm/Analysis/ValueTracking.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugInfo.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/DiagnosticInfo.h"
72 #include "llvm/IR/Dominators.h"
73 #include "llvm/IR/Function.h"
74 #include "llvm/IR/IRBuilder.h"
75 #include "llvm/IR/Instructions.h"
76 #include "llvm/IR/IntrinsicInst.h"
77 #include "llvm/IR/LLVMContext.h"
78 #include "llvm/IR/Module.h"
79 #include "llvm/IR/PatternMatch.h"
80 #include "llvm/IR/Type.h"
81 #include "llvm/IR/Value.h"
82 #include "llvm/IR/ValueHandle.h"
83 #include "llvm/IR/Verifier.h"
84 #include "llvm/Pass.h"
85 #include "llvm/Support/BranchProbability.h"
86 #include "llvm/Support/CommandLine.h"
87 #include "llvm/Support/Debug.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Scalar.h"
90 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
91 #include "llvm/Transforms/Utils/Local.h"
92 #include "llvm/Transforms/Utils/VectorUtils.h"
98 using namespace llvm::PatternMatch;
100 #define LV_NAME "loop-vectorize"
101 #define DEBUG_TYPE LV_NAME
103 STATISTIC(LoopsVectorized, "Number of loops vectorized");
104 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
106 static cl::opt<unsigned>
107 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
108 cl::desc("Sets the SIMD width. Zero is autoselect."));
110 static cl::opt<unsigned>
111 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
112 cl::desc("Sets the vectorization unroll count. "
113 "Zero is autoselect."));
116 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
117 cl::desc("Enable if-conversion during vectorization."));
119 /// We don't vectorize loops with a known constant trip count below this number.
120 static cl::opt<unsigned>
121 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
123 cl::desc("Don't vectorize loops with a constant "
124 "trip count that is smaller than this "
127 /// This enables versioning on the strides of symbolically striding memory
128 /// accesses in code like the following.
129 /// for (i = 0; i < N; ++i)
130 /// A[i * Stride1] += B[i * Stride2] ...
132 /// Will be roughly translated to
133 /// if (Stride1 == 1 && Stride2 == 1) {
134 /// for (i = 0; i < N; i+=4)
138 static cl::opt<bool> EnableMemAccessVersioning(
139 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
140 cl::desc("Enable symblic stride memory access versioning"));
142 /// We don't unroll loops with a known constant trip count below this number.
143 static const unsigned TinyTripCountUnrollThreshold = 128;
145 /// When performing memory disambiguation checks at runtime do not make more
146 /// than this number of comparisons.
147 static const unsigned RuntimeMemoryCheckThreshold = 8;
149 /// Maximum simd width.
150 static const unsigned MaxVectorWidth = 64;
152 static cl::opt<unsigned> ForceTargetNumScalarRegs(
153 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
154 cl::desc("A flag that overrides the target's number of scalar registers."));
156 static cl::opt<unsigned> ForceTargetNumVectorRegs(
157 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
158 cl::desc("A flag that overrides the target's number of vector registers."));
160 /// Maximum vectorization unroll count.
161 static const unsigned MaxUnrollFactor = 16;
163 static cl::opt<unsigned> ForceTargetMaxScalarUnrollFactor(
164 "force-target-max-scalar-unroll", cl::init(0), cl::Hidden,
165 cl::desc("A flag that overrides the target's max unroll factor for scalar "
168 static cl::opt<unsigned> ForceTargetMaxVectorUnrollFactor(
169 "force-target-max-vector-unroll", cl::init(0), cl::Hidden,
170 cl::desc("A flag that overrides the target's max unroll factor for "
171 "vectorized loops."));
173 static cl::opt<unsigned> ForceTargetInstructionCost(
174 "force-target-instruction-cost", cl::init(0), cl::Hidden,
175 cl::desc("A flag that overrides the target's expected cost for "
176 "an instruction to a single constant value. Mostly "
177 "useful for getting consistent testing."));
179 static cl::opt<unsigned> SmallLoopCost(
180 "small-loop-cost", cl::init(20), cl::Hidden,
181 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
183 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
184 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
185 cl::desc("Enable the use of the block frequency analysis to access PGO "
186 "heuristics minimizing code growth in cold regions and being more "
187 "aggressive in hot regions."));
189 // Runtime unroll loops for load/store throughput.
190 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
191 "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
192 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
194 /// The number of stores in a loop that are allowed to need predication.
195 static cl::opt<unsigned> NumberOfStoresToPredicate(
196 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
197 cl::desc("Max number of stores to be predicated behind an if."));
199 static cl::opt<bool> EnableIndVarRegisterHeur(
200 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
201 cl::desc("Count the induction variable only once when unrolling"));
203 static cl::opt<bool> EnableCondStoresVectorization(
204 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
205 cl::desc("Enable if predication of stores during vectorization."));
209 // Forward declarations.
210 class LoopVectorizationLegality;
211 class LoopVectorizationCostModel;
212 class LoopVectorizeHints;
214 /// Optimization analysis message produced during vectorization. Messages inform
215 /// the user why vectorization did not occur.
218 raw_string_ostream Out;
222 Report(Instruction *I = nullptr) : Out(Message), Instr(I) {
223 Out << "loop not vectorized: ";
226 template <typename A> Report &operator<<(const A &Value) {
231 Instruction *getInstr() { return Instr; }
233 std::string &str() { return Out.str(); }
234 operator Twine() { return Out.str(); }
237 /// InnerLoopVectorizer vectorizes loops which contain only one basic
238 /// block to a specified vectorization factor (VF).
239 /// This class performs the widening of scalars into vectors, or multiple
240 /// scalars. This class also implements the following features:
241 /// * It inserts an epilogue loop for handling loops that don't have iteration
242 /// counts that are known to be a multiple of the vectorization factor.
243 /// * It handles the code generation for reduction variables.
244 /// * Scalarization (implementation using scalars) of un-vectorizable
246 /// InnerLoopVectorizer does not perform any vectorization-legality
247 /// checks, and relies on the caller to check for the different legality
248 /// aspects. The InnerLoopVectorizer relies on the
249 /// LoopVectorizationLegality class to provide information about the induction
250 /// and reduction variables that were found to a given vectorization factor.
251 class InnerLoopVectorizer {
253 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
254 DominatorTree *DT, const DataLayout *DL,
255 const TargetLibraryInfo *TLI, unsigned VecWidth,
256 unsigned UnrollFactor)
257 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
258 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
259 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
262 // Perform the actual loop widening (vectorization).
263 void vectorize(LoopVectorizationLegality *L) {
265 // Create a new empty loop. Unlink the old loop and connect the new one.
267 // Widen each instruction in the old loop to a new one in the new loop.
268 // Use the Legality module to find the induction and reduction variables.
270 // Register the new loop and update the analysis passes.
274 virtual ~InnerLoopVectorizer() {}
277 /// A small list of PHINodes.
278 typedef SmallVector<PHINode*, 4> PhiVector;
279 /// When we unroll loops we have multiple vector values for each scalar.
280 /// This data structure holds the unrolled and vectorized values that
281 /// originated from one scalar instruction.
282 typedef SmallVector<Value*, 2> VectorParts;
284 // When we if-convert we need create edge masks. We have to cache values so
285 // that we don't end up with exponential recursion/IR.
286 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
287 VectorParts> EdgeMaskCache;
289 /// \brief Add code that checks at runtime if the accessed arrays overlap.
291 /// Returns a pair of instructions where the first element is the first
292 /// instruction generated in possibly a sequence of instructions and the
293 /// second value is the final comparator value or NULL if no check is needed.
294 std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
296 /// \brief Add checks for strides that where assumed to be 1.
298 /// Returns the last check instruction and the first check instruction in the
299 /// pair as (first, last).
300 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
302 /// Create an empty loop, based on the loop ranges of the old loop.
303 void createEmptyLoop();
304 /// Copy and widen the instructions from the old loop.
305 virtual void vectorizeLoop();
307 /// \brief The Loop exit block may have single value PHI nodes where the
308 /// incoming value is 'Undef'. While vectorizing we only handled real values
309 /// that were defined inside the loop. Here we fix the 'undef case'.
313 /// A helper function that computes the predicate of the block BB, assuming
314 /// that the header block of the loop is set to True. It returns the *entry*
315 /// mask for the block BB.
316 VectorParts createBlockInMask(BasicBlock *BB);
317 /// A helper function that computes the predicate of the edge between SRC
319 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
321 /// A helper function to vectorize a single BB within the innermost loop.
322 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
324 /// Vectorize a single PHINode in a block. This method handles the induction
325 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
326 /// arbitrary length vectors.
327 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
328 unsigned UF, unsigned VF, PhiVector *PV);
330 /// Insert the new loop to the loop hierarchy and pass manager
331 /// and update the analysis passes.
332 void updateAnalysis();
334 /// This instruction is un-vectorizable. Implement it as a sequence
335 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
336 /// scalarized instruction behind an if block predicated on the control
337 /// dependence of the instruction.
338 virtual void scalarizeInstruction(Instruction *Instr,
339 bool IfPredicateStore=false);
341 /// Vectorize Load and Store instructions,
342 virtual void vectorizeMemoryInstruction(Instruction *Instr);
344 /// Create a broadcast instruction. This method generates a broadcast
345 /// instruction (shuffle) for loop invariant values and for the induction
346 /// value. If this is the induction variable then we extend it to N, N+1, ...
347 /// this is needed because each iteration in the loop corresponds to a SIMD
349 virtual Value *getBroadcastInstrs(Value *V);
351 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
352 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
353 /// The sequence starts at StartIndex.
354 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
356 /// When we go over instructions in the basic block we rely on previous
357 /// values within the current basic block or on loop invariant values.
358 /// When we widen (vectorize) values we place them in the map. If the values
359 /// are not within the map, they have to be loop invariant, so we simply
360 /// broadcast them into a vector.
361 VectorParts &getVectorValue(Value *V);
363 /// Generate a shuffle sequence that will reverse the vector Vec.
364 virtual Value *reverseVector(Value *Vec);
366 /// This is a helper class that holds the vectorizer state. It maps scalar
367 /// instructions to vector instructions. When the code is 'unrolled' then
368 /// then a single scalar value is mapped to multiple vector parts. The parts
369 /// are stored in the VectorPart type.
371 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
373 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
375 /// \return True if 'Key' is saved in the Value Map.
376 bool has(Value *Key) const { return MapStorage.count(Key); }
378 /// Initializes a new entry in the map. Sets all of the vector parts to the
379 /// save value in 'Val'.
380 /// \return A reference to a vector with splat values.
381 VectorParts &splat(Value *Key, Value *Val) {
382 VectorParts &Entry = MapStorage[Key];
383 Entry.assign(UF, Val);
387 ///\return A reference to the value that is stored at 'Key'.
388 VectorParts &get(Value *Key) {
389 VectorParts &Entry = MapStorage[Key];
392 assert(Entry.size() == UF);
397 /// The unroll factor. Each entry in the map stores this number of vector
401 /// Map storage. We use std::map and not DenseMap because insertions to a
402 /// dense map invalidates its iterators.
403 std::map<Value *, VectorParts> MapStorage;
406 /// The original loop.
408 /// Scev analysis to use.
417 const DataLayout *DL;
418 /// Target Library Info.
419 const TargetLibraryInfo *TLI;
421 /// The vectorization SIMD factor to use. Each vector will have this many
426 /// The vectorization unroll factor to use. Each scalar is vectorized to this
427 /// many different vector instructions.
430 /// The builder that we use
433 // --- Vectorization state ---
435 /// The vector-loop preheader.
436 BasicBlock *LoopVectorPreHeader;
437 /// The scalar-loop preheader.
438 BasicBlock *LoopScalarPreHeader;
439 /// Middle Block between the vector and the scalar.
440 BasicBlock *LoopMiddleBlock;
441 ///The ExitBlock of the scalar loop.
442 BasicBlock *LoopExitBlock;
443 ///The vector loop body.
444 SmallVector<BasicBlock *, 4> LoopVectorBody;
445 ///The scalar loop body.
446 BasicBlock *LoopScalarBody;
447 /// A list of all bypass blocks. The first block is the entry of the loop.
448 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
450 /// The new Induction variable which was added to the new block.
452 /// The induction variable of the old basic block.
453 PHINode *OldInduction;
454 /// Holds the extended (to the widest induction type) start index.
456 /// Maps scalars to widened vectors.
458 EdgeMaskCache MaskCache;
460 LoopVectorizationLegality *Legal;
463 class InnerLoopUnroller : public InnerLoopVectorizer {
465 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
466 DominatorTree *DT, const DataLayout *DL,
467 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
468 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
471 void scalarizeInstruction(Instruction *Instr,
472 bool IfPredicateStore = false) override;
473 void vectorizeMemoryInstruction(Instruction *Instr) override;
474 Value *getBroadcastInstrs(Value *V) override;
475 Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate) override;
476 Value *reverseVector(Value *Vec) override;
479 /// \brief Look for a meaningful debug location on the instruction or it's
481 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
486 if (I->getDebugLoc() != Empty)
489 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
490 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
491 if (OpInst->getDebugLoc() != Empty)
498 /// \brief Set the debug location in the builder using the debug location in the
500 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
501 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
502 B.SetCurrentDebugLocation(Inst->getDebugLoc());
504 B.SetCurrentDebugLocation(DebugLoc());
508 /// \return string containing a file name and a line # for the given loop.
509 static std::string getDebugLocString(const Loop *L) {
512 raw_string_ostream OS(Result);
513 const DebugLoc LoopDbgLoc = L->getStartLoc();
514 if (!LoopDbgLoc.isUnknown())
515 LoopDbgLoc.print(L->getHeader()->getContext(), OS);
517 // Just print the module name.
518 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
525 /// \brief Propagate known metadata from one instruction to another.
526 static void propagateMetadata(Instruction *To, const Instruction *From) {
527 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
528 From->getAllMetadataOtherThanDebugLoc(Metadata);
530 for (auto M : Metadata) {
531 unsigned Kind = M.first;
533 // These are safe to transfer (this is safe for TBAA, even when we
534 // if-convert, because should that metadata have had a control dependency
535 // on the condition, and thus actually aliased with some other
536 // non-speculated memory access when the condition was false, this would be
537 // caught by the runtime overlap checks).
538 if (Kind != LLVMContext::MD_tbaa &&
539 Kind != LLVMContext::MD_alias_scope &&
540 Kind != LLVMContext::MD_noalias &&
541 Kind != LLVMContext::MD_fpmath)
544 To->setMetadata(Kind, M.second);
548 /// \brief Propagate known metadata from one instruction to a vector of others.
549 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
551 if (Instruction *I = dyn_cast<Instruction>(V))
552 propagateMetadata(I, From);
555 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
556 /// to what vectorization factor.
557 /// This class does not look at the profitability of vectorization, only the
558 /// legality. This class has two main kinds of checks:
559 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
560 /// will change the order of memory accesses in a way that will change the
561 /// correctness of the program.
562 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
563 /// checks for a number of different conditions, such as the availability of a
564 /// single induction variable, that all types are supported and vectorize-able,
565 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
566 /// This class is also used by InnerLoopVectorizer for identifying
567 /// induction variable and the different reduction variables.
568 class LoopVectorizationLegality {
572 unsigned NumPredStores;
574 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
575 DominatorTree *DT, TargetLibraryInfo *TLI,
576 AliasAnalysis *AA, Function *F)
577 : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
578 DT(DT), TLI(TLI), AA(AA), TheFunction(F), Induction(nullptr),
579 WidestIndTy(nullptr), HasFunNoNaNAttr(false), MaxSafeDepDistBytes(-1U) {
582 /// This enum represents the kinds of reductions that we support.
584 RK_NoReduction, ///< Not a reduction.
585 RK_IntegerAdd, ///< Sum of integers.
586 RK_IntegerMult, ///< Product of integers.
587 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
588 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
589 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
590 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
591 RK_FloatAdd, ///< Sum of floats.
592 RK_FloatMult, ///< Product of floats.
593 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
596 /// This enum represents the kinds of inductions that we support.
598 IK_NoInduction, ///< Not an induction variable.
599 IK_IntInduction, ///< Integer induction variable. Step = 1.
600 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
601 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
602 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
605 // This enum represents the kind of minmax reduction.
606 enum MinMaxReductionKind {
616 /// This struct holds information about reduction variables.
617 struct ReductionDescriptor {
618 ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
619 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
621 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
622 MinMaxReductionKind MK)
623 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
625 // The starting value of the reduction.
626 // It does not have to be zero!
627 TrackingVH<Value> StartValue;
628 // The instruction who's value is used outside the loop.
629 Instruction *LoopExitInstr;
630 // The kind of the reduction.
632 // If this a min/max reduction the kind of reduction.
633 MinMaxReductionKind MinMaxKind;
636 /// This POD struct holds information about a potential reduction operation.
637 struct ReductionInstDesc {
638 ReductionInstDesc(bool IsRedux, Instruction *I) :
639 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
641 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
642 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
644 // Is this instruction a reduction candidate.
646 // The last instruction in a min/max pattern (select of the select(icmp())
647 // pattern), or the current reduction instruction otherwise.
648 Instruction *PatternLastInst;
649 // If this is a min/max pattern the comparison predicate.
650 MinMaxReductionKind MinMaxKind;
653 /// This struct holds information about the memory runtime legality
654 /// check that a group of pointers do not overlap.
655 struct RuntimePointerCheck {
656 RuntimePointerCheck() : Need(false) {}
658 /// Reset the state of the pointer runtime information.
665 DependencySetId.clear();
669 /// Insert a pointer and calculate the start and end SCEVs.
670 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
671 unsigned DepSetId, unsigned ASId, ValueToValueMap &Strides);
673 /// This flag indicates if we need to add the runtime check.
675 /// Holds the pointers that we need to check.
676 SmallVector<TrackingVH<Value>, 2> Pointers;
677 /// Holds the pointer value at the beginning of the loop.
678 SmallVector<const SCEV*, 2> Starts;
679 /// Holds the pointer value at the end of the loop.
680 SmallVector<const SCEV*, 2> Ends;
681 /// Holds the information if this pointer is used for writing to memory.
682 SmallVector<bool, 2> IsWritePtr;
683 /// Holds the id of the set of pointers that could be dependent because of a
684 /// shared underlying object.
685 SmallVector<unsigned, 2> DependencySetId;
686 /// Holds the id of the disjoint alias set to which this pointer belongs.
687 SmallVector<unsigned, 2> AliasSetId;
690 /// A struct for saving information about induction variables.
691 struct InductionInfo {
692 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
693 InductionInfo() : StartValue(nullptr), IK(IK_NoInduction) {}
695 TrackingVH<Value> StartValue;
700 /// ReductionList contains the reduction descriptors for all
701 /// of the reductions that were found in the loop.
702 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
704 /// InductionList saves induction variables and maps them to the
705 /// induction descriptor.
706 typedef MapVector<PHINode*, InductionInfo> InductionList;
708 /// Returns true if it is legal to vectorize this loop.
709 /// This does not mean that it is profitable to vectorize this
710 /// loop, only that it is legal to do so.
713 /// Returns the Induction variable.
714 PHINode *getInduction() { return Induction; }
716 /// Returns the reduction variables found in the loop.
717 ReductionList *getReductionVars() { return &Reductions; }
719 /// Returns the induction variables found in the loop.
720 InductionList *getInductionVars() { return &Inductions; }
722 /// Returns the widest induction type.
723 Type *getWidestInductionType() { return WidestIndTy; }
725 /// Returns True if V is an induction variable in this loop.
726 bool isInductionVariable(const Value *V);
728 /// Return true if the block BB needs to be predicated in order for the loop
729 /// to be vectorized.
730 bool blockNeedsPredication(BasicBlock *BB);
732 /// Check if this pointer is consecutive when vectorizing. This happens
733 /// when the last index of the GEP is the induction variable, or that the
734 /// pointer itself is an induction variable.
735 /// This check allows us to vectorize A[idx] into a wide load/store.
737 /// 0 - Stride is unknown or non-consecutive.
738 /// 1 - Address is consecutive.
739 /// -1 - Address is consecutive, and decreasing.
740 int isConsecutivePtr(Value *Ptr);
742 /// Returns true if the value V is uniform within the loop.
743 bool isUniform(Value *V);
745 /// Returns true if this instruction will remain scalar after vectorization.
746 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
748 /// Returns the information that we collected about runtime memory check.
749 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
751 /// This function returns the identity element (or neutral element) for
753 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
755 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
757 bool hasStride(Value *V) { return StrideSet.count(V); }
758 bool mustCheckStrides() { return !StrideSet.empty(); }
759 SmallPtrSet<Value *, 8>::iterator strides_begin() {
760 return StrideSet.begin();
762 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
765 /// Check if a single basic block loop is vectorizable.
766 /// At this point we know that this is a loop with a constant trip count
767 /// and we only need to check individual instructions.
768 bool canVectorizeInstrs();
770 /// When we vectorize loops we may change the order in which
771 /// we read and write from memory. This method checks if it is
772 /// legal to vectorize the code, considering only memory constrains.
773 /// Returns true if the loop is vectorizable
774 bool canVectorizeMemory();
776 /// Return true if we can vectorize this loop using the IF-conversion
778 bool canVectorizeWithIfConvert();
780 /// Collect the variables that need to stay uniform after vectorization.
781 void collectLoopUniforms();
783 /// Return true if all of the instructions in the block can be speculatively
784 /// executed. \p SafePtrs is a list of addresses that are known to be legal
785 /// and we know that we can read from them without segfault.
786 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
788 /// Returns True, if 'Phi' is the kind of reduction variable for type
789 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
790 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
791 /// Returns a struct describing if the instruction 'I' can be a reduction
792 /// variable of type 'Kind'. If the reduction is a min/max pattern of
793 /// select(icmp()) this function advances the instruction pointer 'I' from the
794 /// compare instruction to the select instruction and stores this pointer in
795 /// 'PatternLastInst' member of the returned struct.
796 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
797 ReductionInstDesc &Desc);
798 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
799 /// pattern corresponding to a min(X, Y) or max(X, Y).
800 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
801 ReductionInstDesc &Prev);
802 /// Returns the induction kind of Phi. This function may return NoInduction
803 /// if the PHI is not an induction variable.
804 InductionKind isInductionVariable(PHINode *Phi);
806 /// \brief Collect memory access with loop invariant strides.
808 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
810 void collectStridedAcccess(Value *LoadOrStoreInst);
812 /// Report an analysis message to assist the user in diagnosing loops that are
814 void emitAnalysis(Report &Message) {
815 DebugLoc DL = TheLoop->getStartLoc();
816 if (Instruction *I = Message.getInstr())
817 DL = I->getDebugLoc();
818 emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
819 *TheFunction, DL, Message.str());
822 /// The loop that we evaluate.
826 /// DataLayout analysis.
827 const DataLayout *DL;
830 /// Target Library Info.
831 TargetLibraryInfo *TLI;
835 Function *TheFunction;
837 // --- vectorization state --- //
839 /// Holds the integer induction variable. This is the counter of the
842 /// Holds the reduction variables.
843 ReductionList Reductions;
844 /// Holds all of the induction variables that we found in the loop.
845 /// Notice that inductions don't need to start at zero and that induction
846 /// variables can be pointers.
847 InductionList Inductions;
848 /// Holds the widest induction type encountered.
851 /// Allowed outside users. This holds the reduction
852 /// vars which can be accessed from outside the loop.
853 SmallPtrSet<Value*, 4> AllowedExit;
854 /// This set holds the variables which are known to be uniform after
856 SmallPtrSet<Instruction*, 4> Uniforms;
857 /// We need to check that all of the pointers in this list are disjoint
859 RuntimePointerCheck PtrRtCheck;
860 /// Can we assume the absence of NaNs.
861 bool HasFunNoNaNAttr;
863 unsigned MaxSafeDepDistBytes;
865 ValueToValueMap Strides;
866 SmallPtrSet<Value *, 8> StrideSet;
869 /// LoopVectorizationCostModel - estimates the expected speedups due to
871 /// In many cases vectorization is not profitable. This can happen because of
872 /// a number of reasons. In this class we mainly attempt to predict the
873 /// expected speedup/slowdowns due to the supported instruction set. We use the
874 /// TargetTransformInfo to query the different backends for the cost of
875 /// different operations.
876 class LoopVectorizationCostModel {
878 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
879 LoopVectorizationLegality *Legal,
880 const TargetTransformInfo &TTI,
881 const DataLayout *DL, const TargetLibraryInfo *TLI,
882 const Function *F, const LoopVectorizeHints *Hints)
883 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI), TheFunction(F), Hints(Hints) {}
885 /// Information about vectorization costs
886 struct VectorizationFactor {
887 unsigned Width; // Vector width with best cost
888 unsigned Cost; // Cost of the loop with that width
890 /// \return The most profitable vectorization factor and the cost of that VF.
891 /// This method checks every power of two up to VF. If UserVF is not ZERO
892 /// then this vectorization factor will be selected if vectorization is
894 VectorizationFactor selectVectorizationFactor(bool OptForSize);
896 /// \return The size (in bits) of the widest type in the code that
897 /// needs to be vectorized. We ignore values that remain scalar such as
898 /// 64 bit loop indices.
899 unsigned getWidestType();
901 /// \return The most profitable unroll factor.
902 /// If UserUF is non-zero then this method finds the best unroll-factor
903 /// based on register pressure and other parameters.
904 /// VF and LoopCost are the selected vectorization factor and the cost of the
906 unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost);
908 /// \brief A struct that represents some properties of the register usage
910 struct RegisterUsage {
911 /// Holds the number of loop invariant values that are used in the loop.
912 unsigned LoopInvariantRegs;
913 /// Holds the maximum number of concurrent live intervals in the loop.
914 unsigned MaxLocalUsers;
915 /// Holds the number of instructions in the loop.
916 unsigned NumInstructions;
919 /// \return information about the register usage of the loop.
920 RegisterUsage calculateRegisterUsage();
923 /// Returns the expected execution cost. The unit of the cost does
924 /// not matter because we use the 'cost' units to compare different
925 /// vector widths. The cost that is returned is *not* normalized by
926 /// the factor width.
927 unsigned expectedCost(unsigned VF);
929 /// Returns the execution time cost of an instruction for a given vector
930 /// width. Vector width of one means scalar.
931 unsigned getInstructionCost(Instruction *I, unsigned VF);
933 /// A helper function for converting Scalar types to vector types.
934 /// If the incoming type is void, we return void. If the VF is 1, we return
936 static Type* ToVectorTy(Type *Scalar, unsigned VF);
938 /// Returns whether the instruction is a load or store and will be a emitted
939 /// as a vector operation.
940 bool isConsecutiveLoadOrStore(Instruction *I);
942 /// Report an analysis message to assist the user in diagnosing loops that are
944 void emitAnalysis(Report &Message) {
945 DebugLoc DL = TheLoop->getStartLoc();
946 if (Instruction *I = Message.getInstr())
947 DL = I->getDebugLoc();
948 emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
949 *TheFunction, DL, Message.str());
952 /// The loop that we evaluate.
956 /// Loop Info analysis.
958 /// Vectorization legality.
959 LoopVectorizationLegality *Legal;
960 /// Vector target information.
961 const TargetTransformInfo &TTI;
962 /// Target data layout information.
963 const DataLayout *DL;
964 /// Target Library Info.
965 const TargetLibraryInfo *TLI;
966 const Function *TheFunction;
967 // Loop Vectorize Hint.
968 const LoopVectorizeHints *Hints;
971 /// Utility class for getting and setting loop vectorizer hints in the form
972 /// of loop metadata.
973 class LoopVectorizeHints {
976 FK_Undefined = -1, ///< Not selected.
977 FK_Disabled = 0, ///< Forcing disabled.
978 FK_Enabled = 1, ///< Forcing enabled.
981 LoopVectorizeHints(const Loop *L, bool DisableUnrolling)
982 : Width(VectorizationFactor),
983 Unroll(DisableUnrolling),
985 LoopID(L->getLoopID()) {
987 // force-vector-unroll overrides DisableUnrolling.
988 if (VectorizationUnroll.getNumOccurrences() > 0)
989 Unroll = VectorizationUnroll;
991 DEBUG(if (DisableUnrolling && Unroll == 1) dbgs()
992 << "LV: Unrolling disabled by the pass manager\n");
995 /// Return the loop metadata prefix.
996 static StringRef Prefix() { return "llvm.loop."; }
998 MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) const {
999 SmallVector<Value*, 2> Vals;
1000 Vals.push_back(MDString::get(Context, Name));
1001 Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
1002 return MDNode::get(Context, Vals);
1005 /// Mark the loop L as already vectorized by setting the width to 1.
1006 void setAlreadyVectorized(Loop *L) {
1007 LLVMContext &Context = L->getHeader()->getContext();
1011 // Create a new loop id with one more operand for the already_vectorized
1012 // hint. If the loop already has a loop id then copy the existing operands.
1013 SmallVector<Value*, 4> Vals(1);
1015 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
1016 Vals.push_back(LoopID->getOperand(i));
1019 createHint(Context, Twine(Prefix(), "vectorize.width").str(), Width));
1021 createHint(Context, Twine(Prefix(), "interleave.count").str(), 1));
1023 MDNode *NewLoopID = MDNode::get(Context, Vals);
1024 // Set operand 0 to refer to the loop id itself.
1025 NewLoopID->replaceOperandWith(0, NewLoopID);
1027 L->setLoopID(NewLoopID);
1029 LoopID->replaceAllUsesWith(NewLoopID);
1034 std::string emitRemark() const {
1036 if (Force == LoopVectorizeHints::FK_Disabled)
1037 R << "vectorization is explicitly disabled";
1039 R << "use -Rpass-analysis=loop-vectorize for more info";
1040 if (Force == LoopVectorizeHints::FK_Enabled) {
1041 R << " (Force=true";
1043 R << ", Vector Width=" << Width;
1045 R << ", Interleave Count=" << Unroll;
1053 unsigned getWidth() const { return Width; }
1054 unsigned getUnroll() const { return Unroll; }
1055 enum ForceKind getForce() const { return Force; }
1056 MDNode *getLoopID() const { return LoopID; }
1059 /// Find hints specified in the loop metadata.
1060 void getHints(const Loop *L) {
1064 // First operand should refer to the loop id itself.
1065 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1066 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1068 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1069 const MDString *S = nullptr;
1070 SmallVector<Value*, 4> Args;
1072 // The expected hint is either a MDString or a MDNode with the first
1073 // operand a MDString.
1074 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1075 if (!MD || MD->getNumOperands() == 0)
1077 S = dyn_cast<MDString>(MD->getOperand(0));
1078 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1079 Args.push_back(MD->getOperand(i));
1081 S = dyn_cast<MDString>(LoopID->getOperand(i));
1082 assert(Args.size() == 0 && "too many arguments for MDString");
1088 // Check if the hint starts with the loop metadata prefix.
1089 StringRef Hint = S->getString();
1090 if (!Hint.startswith(Prefix()))
1092 // Remove the prefix.
1093 Hint = Hint.substr(Prefix().size(), StringRef::npos);
1095 if (Args.size() == 1)
1096 getHint(Hint, Args[0]);
1100 // Check string hint with one operand.
1101 void getHint(StringRef Hint, Value *Arg) {
1102 const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
1104 unsigned Val = C->getZExtValue();
1106 if (Hint == "vectorize.width") {
1107 if (isPowerOf2_32(Val) && Val <= MaxVectorWidth)
1110 DEBUG(dbgs() << "LV: ignoring invalid width hint metadata\n");
1111 } else if (Hint == "vectorize.enable") {
1112 if (C->getBitWidth() == 1)
1113 Force = Val == 1 ? LoopVectorizeHints::FK_Enabled
1114 : LoopVectorizeHints::FK_Disabled;
1116 DEBUG(dbgs() << "LV: ignoring invalid enable hint metadata\n");
1117 } else if (Hint == "interleave.count") {
1118 if (isPowerOf2_32(Val) && Val <= MaxUnrollFactor)
1121 DEBUG(dbgs() << "LV: ignoring invalid unroll hint metadata\n");
1123 DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint << '\n');
1127 /// Vectorization width.
1129 /// Vectorization unroll factor.
1131 /// Vectorization forced
1132 enum ForceKind Force;
1137 static void emitMissedWarning(Function *F, Loop *L,
1138 const LoopVectorizeHints &LH) {
1139 emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1140 L->getStartLoc(), LH.emitRemark());
1142 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1143 if (LH.getWidth() != 1)
1144 emitLoopVectorizeWarning(
1145 F->getContext(), *F, L->getStartLoc(),
1146 "failed explicitly specified loop vectorization");
1147 else if (LH.getUnroll() != 1)
1148 emitLoopInterleaveWarning(
1149 F->getContext(), *F, L->getStartLoc(),
1150 "failed explicitly specified loop interleaving");
1154 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1156 return V.push_back(&L);
1158 for (Loop *InnerL : L)
1159 addInnerLoop(*InnerL, V);
1162 /// The LoopVectorize Pass.
1163 struct LoopVectorize : public FunctionPass {
1164 /// Pass identification, replacement for typeid
1167 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1169 DisableUnrolling(NoUnrolling),
1170 AlwaysVectorize(AlwaysVectorize) {
1171 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1174 ScalarEvolution *SE;
1175 const DataLayout *DL;
1177 TargetTransformInfo *TTI;
1179 BlockFrequencyInfo *BFI;
1180 TargetLibraryInfo *TLI;
1182 bool DisableUnrolling;
1183 bool AlwaysVectorize;
1185 BlockFrequency ColdEntryFreq;
1187 bool runOnFunction(Function &F) override {
1188 SE = &getAnalysis<ScalarEvolution>();
1189 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1190 DL = DLP ? &DLP->getDataLayout() : nullptr;
1191 LI = &getAnalysis<LoopInfo>();
1192 TTI = &getAnalysis<TargetTransformInfo>();
1193 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1194 BFI = &getAnalysis<BlockFrequencyInfo>();
1195 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1196 AA = &getAnalysis<AliasAnalysis>();
1198 // Compute some weights outside of the loop over the loops. Compute this
1199 // using a BranchProbability to re-use its scaling math.
1200 const BranchProbability ColdProb(1, 5); // 20%
1201 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1203 // If the target claims to have no vector registers don't attempt
1205 if (!TTI->getNumberOfRegisters(true))
1209 DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1210 << ": Missing data layout\n");
1214 // Build up a worklist of inner-loops to vectorize. This is necessary as
1215 // the act of vectorizing or partially unrolling a loop creates new loops
1216 // and can invalidate iterators across the loops.
1217 SmallVector<Loop *, 8> Worklist;
1220 addInnerLoop(*L, Worklist);
1222 LoopsAnalyzed += Worklist.size();
1224 // Now walk the identified inner loops.
1225 bool Changed = false;
1226 while (!Worklist.empty())
1227 Changed |= processLoop(Worklist.pop_back_val());
1229 // Process each loop nest in the function.
1233 bool processLoop(Loop *L) {
1234 assert(L->empty() && "Only process inner loops.");
1237 const std::string DebugLocStr = getDebugLocString(L);
1240 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1241 << L->getHeader()->getParent()->getName() << "\" from "
1242 << DebugLocStr << "\n");
1244 LoopVectorizeHints Hints(L, DisableUnrolling);
1246 DEBUG(dbgs() << "LV: Loop hints:"
1248 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1250 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1252 : "?")) << " width=" << Hints.getWidth()
1253 << " unroll=" << Hints.getUnroll() << "\n");
1255 // Function containing loop
1256 Function *F = L->getHeader()->getParent();
1258 // Looking at the diagnostic output is the only way to determine if a loop
1259 // was vectorized (other than looking at the IR or machine code), so it
1260 // is important to generate an optimization remark for each loop. Most of
1261 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1262 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1263 // less verbose reporting vectorized loops and unvectorized loops that may
1264 // benefit from vectorization, respectively.
1266 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1267 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1268 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1269 L->getStartLoc(), Hints.emitRemark());
1273 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1274 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1275 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1276 L->getStartLoc(), Hints.emitRemark());
1280 if (Hints.getWidth() == 1 && Hints.getUnroll() == 1) {
1281 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1282 emitOptimizationRemarkAnalysis(
1283 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1284 "loop not vectorized: vector width and interleave count are "
1285 "explicitly set to 1");
1289 // Check the loop for a trip count threshold:
1290 // do not vectorize loops with a tiny trip count.
1291 BasicBlock *Latch = L->getLoopLatch();
1292 const unsigned TC = SE->getSmallConstantTripCount(L, Latch);
1293 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1294 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1295 << "This loop is not worth vectorizing.");
1296 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1297 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1299 DEBUG(dbgs() << "\n");
1300 emitOptimizationRemarkAnalysis(
1301 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1302 "vectorization is not beneficial and is not explicitly forced");
1307 // Check if it is legal to vectorize the loop.
1308 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI, AA, F);
1309 if (!LVL.canVectorize()) {
1310 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1311 emitMissedWarning(F, L, Hints);
1315 // Use the cost model.
1316 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI, F, &Hints);
1318 // Check the function attributes to find out if this function should be
1319 // optimized for size.
1320 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1321 F->hasFnAttribute(Attribute::OptimizeForSize);
1323 // Compute the weighted frequency of this loop being executed and see if it
1324 // is less than 20% of the function entry baseline frequency. Note that we
1325 // always have a canonical loop here because we think we *can* vectoriez.
1326 // FIXME: This is hidden behind a flag due to pervasive problems with
1327 // exactly what block frequency models.
1328 if (LoopVectorizeWithBlockFrequency) {
1329 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1330 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1331 LoopEntryFreq < ColdEntryFreq)
1335 // Check the function attributes to see if implicit floats are allowed.a
1336 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1337 // an integer loop and the vector instructions selected are purely integer
1338 // vector instructions?
1339 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1340 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1341 "attribute is used.\n");
1342 emitOptimizationRemarkAnalysis(
1343 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1344 "loop not vectorized due to NoImplicitFloat attribute");
1345 emitMissedWarning(F, L, Hints);
1349 // Select the optimal vectorization factor.
1350 const LoopVectorizationCostModel::VectorizationFactor VF =
1351 CM.selectVectorizationFactor(OptForSize);
1353 // Select the unroll factor.
1355 CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
1357 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1358 << DebugLocStr << '\n');
1359 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1361 if (VF.Width == 1) {
1362 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
1365 emitOptimizationRemarkAnalysis(
1366 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1367 "not beneficial to vectorize and user disabled interleaving");
1370 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1372 // Report the unrolling decision.
1373 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1374 Twine("unrolled with interleaving factor " +
1376 " (vectorization not beneficial)"));
1378 // We decided not to vectorize, but we may want to unroll.
1380 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1381 Unroller.vectorize(&LVL);
1383 // If we decided that it is *legal* to vectorize the loop then do it.
1384 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1388 // Report the vectorization decision.
1389 emitOptimizationRemark(
1390 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1391 Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1392 ", unrolling interleave factor: " + Twine(UF) + ")");
1395 // Mark the loop as already vectorized to avoid vectorizing again.
1396 Hints.setAlreadyVectorized(L);
1398 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1402 void getAnalysisUsage(AnalysisUsage &AU) const override {
1403 AU.addRequiredID(LoopSimplifyID);
1404 AU.addRequiredID(LCSSAID);
1405 AU.addRequired<BlockFrequencyInfo>();
1406 AU.addRequired<DominatorTreeWrapperPass>();
1407 AU.addRequired<LoopInfo>();
1408 AU.addRequired<ScalarEvolution>();
1409 AU.addRequired<TargetTransformInfo>();
1410 AU.addRequired<AliasAnalysis>();
1411 AU.addPreserved<LoopInfo>();
1412 AU.addPreserved<DominatorTreeWrapperPass>();
1413 AU.addPreserved<AliasAnalysis>();
1418 } // end anonymous namespace
1420 //===----------------------------------------------------------------------===//
1421 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1422 // LoopVectorizationCostModel.
1423 //===----------------------------------------------------------------------===//
1425 static Value *stripIntegerCast(Value *V) {
1426 if (CastInst *CI = dyn_cast<CastInst>(V))
1427 if (CI->getOperand(0)->getType()->isIntegerTy())
1428 return CI->getOperand(0);
1432 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1434 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1436 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1437 ValueToValueMap &PtrToStride,
1438 Value *Ptr, Value *OrigPtr = nullptr) {
1440 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1442 // If there is an entry in the map return the SCEV of the pointer with the
1443 // symbolic stride replaced by one.
1444 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1445 if (SI != PtrToStride.end()) {
1446 Value *StrideVal = SI->second;
1449 StrideVal = stripIntegerCast(StrideVal);
1451 // Replace symbolic stride by one.
1452 Value *One = ConstantInt::get(StrideVal->getType(), 1);
1453 ValueToValueMap RewriteMap;
1454 RewriteMap[StrideVal] = One;
1457 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1458 DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1463 // Otherwise, just return the SCEV of the original pointer.
1464 return SE->getSCEV(Ptr);
1467 void LoopVectorizationLegality::RuntimePointerCheck::insert(
1468 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
1469 unsigned ASId, ValueToValueMap &Strides) {
1470 // Get the stride replaced scev.
1471 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1472 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1473 assert(AR && "Invalid addrec expression");
1474 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1475 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1476 Pointers.push_back(Ptr);
1477 Starts.push_back(AR->getStart());
1478 Ends.push_back(ScEnd);
1479 IsWritePtr.push_back(WritePtr);
1480 DependencySetId.push_back(DepSetId);
1481 AliasSetId.push_back(ASId);
1484 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1485 // We need to place the broadcast of invariant variables outside the loop.
1486 Instruction *Instr = dyn_cast<Instruction>(V);
1488 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1489 Instr->getParent()) != LoopVectorBody.end());
1490 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1492 // Place the code for broadcasting invariant variables in the new preheader.
1493 IRBuilder<>::InsertPointGuard Guard(Builder);
1495 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1497 // Broadcast the scalar into all locations in the vector.
1498 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1503 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1505 assert(Val->getType()->isVectorTy() && "Must be a vector");
1506 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1507 "Elem must be an integer");
1508 // Create the types.
1509 Type *ITy = Val->getType()->getScalarType();
1510 VectorType *Ty = cast<VectorType>(Val->getType());
1511 int VLen = Ty->getNumElements();
1512 SmallVector<Constant*, 8> Indices;
1514 // Create a vector of consecutive numbers from zero to VF.
1515 for (int i = 0; i < VLen; ++i) {
1516 int64_t Idx = Negate ? (-i) : i;
1517 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1520 // Add the consecutive indices to the vector value.
1521 Constant *Cv = ConstantVector::get(Indices);
1522 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1523 return Builder.CreateAdd(Val, Cv, "induction");
1526 /// \brief Find the operand of the GEP that should be checked for consecutive
1527 /// stores. This ignores trailing indices that have no effect on the final
1529 static unsigned getGEPInductionOperand(const DataLayout *DL,
1530 const GetElementPtrInst *Gep) {
1531 unsigned LastOperand = Gep->getNumOperands() - 1;
1532 unsigned GEPAllocSize = DL->getTypeAllocSize(
1533 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1535 // Walk backwards and try to peel off zeros.
1536 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1537 // Find the type we're currently indexing into.
1538 gep_type_iterator GEPTI = gep_type_begin(Gep);
1539 std::advance(GEPTI, LastOperand - 1);
1541 // If it's a type with the same allocation size as the result of the GEP we
1542 // can peel off the zero index.
1543 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1551 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1552 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1553 // Make sure that the pointer does not point to structs.
1554 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1557 // If this value is a pointer induction variable we know it is consecutive.
1558 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1559 if (Phi && Inductions.count(Phi)) {
1560 InductionInfo II = Inductions[Phi];
1561 if (IK_PtrInduction == II.IK)
1563 else if (IK_ReversePtrInduction == II.IK)
1567 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1571 unsigned NumOperands = Gep->getNumOperands();
1572 Value *GpPtr = Gep->getPointerOperand();
1573 // If this GEP value is a consecutive pointer induction variable and all of
1574 // the indices are constant then we know it is consecutive. We can
1575 Phi = dyn_cast<PHINode>(GpPtr);
1576 if (Phi && Inductions.count(Phi)) {
1578 // Make sure that the pointer does not point to structs.
1579 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1580 if (GepPtrType->getElementType()->isAggregateType())
1583 // Make sure that all of the index operands are loop invariant.
1584 for (unsigned i = 1; i < NumOperands; ++i)
1585 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1588 InductionInfo II = Inductions[Phi];
1589 if (IK_PtrInduction == II.IK)
1591 else if (IK_ReversePtrInduction == II.IK)
1595 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1597 // Check that all of the gep indices are uniform except for our induction
1599 for (unsigned i = 0; i != NumOperands; ++i)
1600 if (i != InductionOperand &&
1601 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1604 // We can emit wide load/stores only if the last non-zero index is the
1605 // induction variable.
1606 const SCEV *Last = nullptr;
1607 if (!Strides.count(Gep))
1608 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1610 // Because of the multiplication by a stride we can have a s/zext cast.
1611 // We are going to replace this stride by 1 so the cast is safe to ignore.
1613 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1614 // %0 = trunc i64 %indvars.iv to i32
1615 // %mul = mul i32 %0, %Stride1
1616 // %idxprom = zext i32 %mul to i64 << Safe cast.
1617 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1619 Last = replaceSymbolicStrideSCEV(SE, Strides,
1620 Gep->getOperand(InductionOperand), Gep);
1621 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1623 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1627 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1628 const SCEV *Step = AR->getStepRecurrence(*SE);
1630 // The memory is consecutive because the last index is consecutive
1631 // and all other indices are loop invariant.
1634 if (Step->isAllOnesValue())
1641 bool LoopVectorizationLegality::isUniform(Value *V) {
1642 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1645 InnerLoopVectorizer::VectorParts&
1646 InnerLoopVectorizer::getVectorValue(Value *V) {
1647 assert(V != Induction && "The new induction variable should not be used.");
1648 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1650 // If we have a stride that is replaced by one, do it here.
1651 if (Legal->hasStride(V))
1652 V = ConstantInt::get(V->getType(), 1);
1654 // If we have this scalar in the map, return it.
1655 if (WidenMap.has(V))
1656 return WidenMap.get(V);
1658 // If this scalar is unknown, assume that it is a constant or that it is
1659 // loop invariant. Broadcast V and save the value for future uses.
1660 Value *B = getBroadcastInstrs(V);
1661 return WidenMap.splat(V, B);
1664 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1665 assert(Vec->getType()->isVectorTy() && "Invalid type");
1666 SmallVector<Constant*, 8> ShuffleMask;
1667 for (unsigned i = 0; i < VF; ++i)
1668 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1670 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1671 ConstantVector::get(ShuffleMask),
1675 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1676 // Attempt to issue a wide load.
1677 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1678 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1680 assert((LI || SI) && "Invalid Load/Store instruction");
1682 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1683 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1684 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1685 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1686 // An alignment of 0 means target abi alignment. We need to use the scalar's
1687 // target abi alignment in such a case.
1689 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1690 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1691 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1692 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1694 if (SI && Legal->blockNeedsPredication(SI->getParent()))
1695 return scalarizeInstruction(Instr, true);
1697 if (ScalarAllocatedSize != VectorElementSize)
1698 return scalarizeInstruction(Instr);
1700 // If the pointer is loop invariant or if it is non-consecutive,
1701 // scalarize the load.
1702 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1703 bool Reverse = ConsecutiveStride < 0;
1704 bool UniformLoad = LI && Legal->isUniform(Ptr);
1705 if (!ConsecutiveStride || UniformLoad)
1706 return scalarizeInstruction(Instr);
1708 Constant *Zero = Builder.getInt32(0);
1709 VectorParts &Entry = WidenMap.get(Instr);
1711 // Handle consecutive loads/stores.
1712 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1713 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1714 setDebugLocFromInst(Builder, Gep);
1715 Value *PtrOperand = Gep->getPointerOperand();
1716 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1717 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1719 // Create the new GEP with the new induction variable.
1720 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1721 Gep2->setOperand(0, FirstBasePtr);
1722 Gep2->setName("gep.indvar.base");
1723 Ptr = Builder.Insert(Gep2);
1725 setDebugLocFromInst(Builder, Gep);
1726 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1727 OrigLoop) && "Base ptr must be invariant");
1729 // The last index does not have to be the induction. It can be
1730 // consecutive and be a function of the index. For example A[I+1];
1731 unsigned NumOperands = Gep->getNumOperands();
1732 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1733 // Create the new GEP with the new induction variable.
1734 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1736 for (unsigned i = 0; i < NumOperands; ++i) {
1737 Value *GepOperand = Gep->getOperand(i);
1738 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1740 // Update last index or loop invariant instruction anchored in loop.
1741 if (i == InductionOperand ||
1742 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1743 assert((i == InductionOperand ||
1744 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1745 "Must be last index or loop invariant");
1747 VectorParts &GEPParts = getVectorValue(GepOperand);
1748 Value *Index = GEPParts[0];
1749 Index = Builder.CreateExtractElement(Index, Zero);
1750 Gep2->setOperand(i, Index);
1751 Gep2->setName("gep.indvar.idx");
1754 Ptr = Builder.Insert(Gep2);
1756 // Use the induction element ptr.
1757 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1758 setDebugLocFromInst(Builder, Ptr);
1759 VectorParts &PtrVal = getVectorValue(Ptr);
1760 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1765 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1766 "We do not allow storing to uniform addresses");
1767 setDebugLocFromInst(Builder, SI);
1768 // We don't want to update the value in the map as it might be used in
1769 // another expression. So don't use a reference type for "StoredVal".
1770 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1772 for (unsigned Part = 0; Part < UF; ++Part) {
1773 // Calculate the pointer for the specific unroll-part.
1774 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1777 // If we store to reverse consecutive memory locations then we need
1778 // to reverse the order of elements in the stored value.
1779 StoredVal[Part] = reverseVector(StoredVal[Part]);
1780 // If the address is consecutive but reversed, then the
1781 // wide store needs to start at the last vector element.
1782 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1783 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1786 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1787 DataTy->getPointerTo(AddressSpace));
1789 Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
1790 propagateMetadata(NewSI, SI);
1796 assert(LI && "Must have a load instruction");
1797 setDebugLocFromInst(Builder, LI);
1798 for (unsigned Part = 0; Part < UF; ++Part) {
1799 // Calculate the pointer for the specific unroll-part.
1800 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1803 // If the address is consecutive but reversed, then the
1804 // wide store needs to start at the last vector element.
1805 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1806 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1809 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1810 DataTy->getPointerTo(AddressSpace));
1811 LoadInst *NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
1812 propagateMetadata(NewLI, LI);
1813 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
1817 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1818 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1819 // Holds vector parameters or scalars, in case of uniform vals.
1820 SmallVector<VectorParts, 4> Params;
1822 setDebugLocFromInst(Builder, Instr);
1824 // Find all of the vectorized parameters.
1825 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1826 Value *SrcOp = Instr->getOperand(op);
1828 // If we are accessing the old induction variable, use the new one.
1829 if (SrcOp == OldInduction) {
1830 Params.push_back(getVectorValue(SrcOp));
1834 // Try using previously calculated values.
1835 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1837 // If the src is an instruction that appeared earlier in the basic block
1838 // then it should already be vectorized.
1839 if (SrcInst && OrigLoop->contains(SrcInst)) {
1840 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1841 // The parameter is a vector value from earlier.
1842 Params.push_back(WidenMap.get(SrcInst));
1844 // The parameter is a scalar from outside the loop. Maybe even a constant.
1845 VectorParts Scalars;
1846 Scalars.append(UF, SrcOp);
1847 Params.push_back(Scalars);
1851 assert(Params.size() == Instr->getNumOperands() &&
1852 "Invalid number of operands");
1854 // Does this instruction return a value ?
1855 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1857 Value *UndefVec = IsVoidRetTy ? nullptr :
1858 UndefValue::get(VectorType::get(Instr->getType(), VF));
1859 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1860 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1862 Instruction *InsertPt = Builder.GetInsertPoint();
1863 BasicBlock *IfBlock = Builder.GetInsertBlock();
1864 BasicBlock *CondBlock = nullptr;
1867 Loop *VectorLp = nullptr;
1868 if (IfPredicateStore) {
1869 assert(Instr->getParent()->getSinglePredecessor() &&
1870 "Only support single predecessor blocks");
1871 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1872 Instr->getParent());
1873 VectorLp = LI->getLoopFor(IfBlock);
1874 assert(VectorLp && "Must have a loop for this block");
1877 // For each vector unroll 'part':
1878 for (unsigned Part = 0; Part < UF; ++Part) {
1879 // For each scalar that we create:
1880 for (unsigned Width = 0; Width < VF; ++Width) {
1883 Value *Cmp = nullptr;
1884 if (IfPredicateStore) {
1885 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1886 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1887 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1888 LoopVectorBody.push_back(CondBlock);
1889 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
1890 // Update Builder with newly created basic block.
1891 Builder.SetInsertPoint(InsertPt);
1894 Instruction *Cloned = Instr->clone();
1896 Cloned->setName(Instr->getName() + ".cloned");
1897 // Replace the operands of the cloned instructions with extracted scalars.
1898 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1899 Value *Op = Params[op][Part];
1900 // Param is a vector. Need to extract the right lane.
1901 if (Op->getType()->isVectorTy())
1902 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1903 Cloned->setOperand(op, Op);
1906 // Place the cloned scalar in the new loop.
1907 Builder.Insert(Cloned);
1909 // If the original scalar returns a value we need to place it in a vector
1910 // so that future users will be able to use it.
1912 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1913 Builder.getInt32(Width));
1915 if (IfPredicateStore) {
1916 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1917 LoopVectorBody.push_back(NewIfBlock);
1918 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
1919 Builder.SetInsertPoint(InsertPt);
1920 Instruction *OldBr = IfBlock->getTerminator();
1921 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1922 OldBr->eraseFromParent();
1923 IfBlock = NewIfBlock;
1929 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1933 if (Instruction *I = dyn_cast<Instruction>(V))
1934 return I->getParent() == Loc->getParent() ? I : nullptr;
1938 std::pair<Instruction *, Instruction *>
1939 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1940 Instruction *tnullptr = nullptr;
1941 if (!Legal->mustCheckStrides())
1942 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1944 IRBuilder<> ChkBuilder(Loc);
1947 Value *Check = nullptr;
1948 Instruction *FirstInst = nullptr;
1949 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1950 SE = Legal->strides_end();
1952 Value *Ptr = stripIntegerCast(*SI);
1953 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1955 // Store the first instruction we create.
1956 FirstInst = getFirstInst(FirstInst, C, Loc);
1958 Check = ChkBuilder.CreateOr(Check, C);
1963 // We have to do this trickery because the IRBuilder might fold the check to a
1964 // constant expression in which case there is no Instruction anchored in a
1966 LLVMContext &Ctx = Loc->getContext();
1967 Instruction *TheCheck =
1968 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
1969 ChkBuilder.Insert(TheCheck, "stride.not.one");
1970 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
1972 return std::make_pair(FirstInst, TheCheck);
1975 std::pair<Instruction *, Instruction *>
1976 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
1977 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1978 Legal->getRuntimePointerCheck();
1980 Instruction *tnullptr = nullptr;
1981 if (!PtrRtCheck->Need)
1982 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1984 unsigned NumPointers = PtrRtCheck->Pointers.size();
1985 SmallVector<TrackingVH<Value> , 2> Starts;
1986 SmallVector<TrackingVH<Value> , 2> Ends;
1988 LLVMContext &Ctx = Loc->getContext();
1989 SCEVExpander Exp(*SE, "induction");
1990 Instruction *FirstInst = nullptr;
1992 for (unsigned i = 0; i < NumPointers; ++i) {
1993 Value *Ptr = PtrRtCheck->Pointers[i];
1994 const SCEV *Sc = SE->getSCEV(Ptr);
1996 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1997 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1999 Starts.push_back(Ptr);
2000 Ends.push_back(Ptr);
2002 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
2003 unsigned AS = Ptr->getType()->getPointerAddressSpace();
2005 // Use this type for pointer arithmetic.
2006 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
2008 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
2009 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
2010 Starts.push_back(Start);
2011 Ends.push_back(End);
2015 IRBuilder<> ChkBuilder(Loc);
2016 // Our instructions might fold to a constant.
2017 Value *MemoryRuntimeCheck = nullptr;
2018 for (unsigned i = 0; i < NumPointers; ++i) {
2019 for (unsigned j = i+1; j < NumPointers; ++j) {
2020 // No need to check if two readonly pointers intersect.
2021 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
2024 // Only need to check pointers between two different dependency sets.
2025 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
2027 // Only need to check pointers in the same alias set.
2028 if (PtrRtCheck->AliasSetId[i] != PtrRtCheck->AliasSetId[j])
2031 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
2032 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
2034 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
2035 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
2036 "Trying to bounds check pointers with different address spaces");
2038 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
2039 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
2041 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
2042 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
2043 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
2044 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
2046 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
2047 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
2048 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
2049 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
2050 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
2051 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2052 if (MemoryRuntimeCheck) {
2053 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
2055 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2057 MemoryRuntimeCheck = IsConflict;
2061 // We have to do this trickery because the IRBuilder might fold the check to a
2062 // constant expression in which case there is no Instruction anchored in a
2064 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
2065 ConstantInt::getTrue(Ctx));
2066 ChkBuilder.Insert(Check, "memcheck.conflict");
2067 FirstInst = getFirstInst(FirstInst, Check, Loc);
2068 return std::make_pair(FirstInst, Check);
2071 void InnerLoopVectorizer::createEmptyLoop() {
2073 In this function we generate a new loop. The new loop will contain
2074 the vectorized instructions while the old loop will continue to run the
2077 [ ] <-- Back-edge taken count overflow check.
2080 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2083 || [ ] <-- vector pre header.
2087 || [ ]_| <-- vector loop.
2090 | >[ ] <--- middle-block.
2093 -|- >[ ] <--- new preheader.
2097 | [ ]_| <-- old scalar loop to handle remainder.
2100 >[ ] <-- exit block.
2104 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2105 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
2106 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2107 assert(BypassBlock && "Invalid loop structure");
2108 assert(ExitBlock && "Must have an exit block");
2110 // Some loops have a single integer induction variable, while other loops
2111 // don't. One example is c++ iterators that often have multiple pointer
2112 // induction variables. In the code below we also support a case where we
2113 // don't have a single induction variable.
2114 OldInduction = Legal->getInduction();
2115 Type *IdxTy = Legal->getWidestInductionType();
2117 // Find the loop boundaries.
2118 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2119 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2121 // The exit count might have the type of i64 while the phi is i32. This can
2122 // happen if we have an induction variable that is sign extended before the
2123 // compare. The only way that we get a backedge taken count is that the
2124 // induction variable was signed and as such will not overflow. In such a case
2125 // truncation is legal.
2126 if (ExitCount->getType()->getPrimitiveSizeInBits() >
2127 IdxTy->getPrimitiveSizeInBits())
2128 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2130 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2131 // Get the total trip count from the count by adding 1.
2132 ExitCount = SE->getAddExpr(BackedgeTakeCount,
2133 SE->getConstant(BackedgeTakeCount->getType(), 1));
2135 // Expand the trip count and place the new instructions in the preheader.
2136 // Notice that the pre-header does not change, only the loop body.
2137 SCEVExpander Exp(*SE, "induction");
2139 // We need to test whether the backedge-taken count is uint##_max. Adding one
2140 // to it will cause overflow and an incorrect loop trip count in the vector
2141 // body. In case of overflow we want to directly jump to the scalar remainder
2143 Value *BackedgeCount =
2144 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2145 BypassBlock->getTerminator());
2146 if (BackedgeCount->getType()->isPointerTy())
2147 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2148 "backedge.ptrcnt.to.int",
2149 BypassBlock->getTerminator());
2150 Instruction *CheckBCOverflow =
2151 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2152 Constant::getAllOnesValue(BackedgeCount->getType()),
2153 "backedge.overflow", BypassBlock->getTerminator());
2155 // The loop index does not have to start at Zero. Find the original start
2156 // value from the induction PHI node. If we don't have an induction variable
2157 // then we know that it starts at zero.
2158 Builder.SetInsertPoint(BypassBlock->getTerminator());
2159 Value *StartIdx = ExtendedIdx = OldInduction ?
2160 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2162 ConstantInt::get(IdxTy, 0);
2164 // We need an instruction to anchor the overflow check on. StartIdx needs to
2165 // be defined before the overflow check branch. Because the scalar preheader
2166 // is going to merge the start index and so the overflow branch block needs to
2167 // contain a definition of the start index.
2168 Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
2169 StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
2170 BypassBlock->getTerminator());
2172 // Count holds the overall loop count (N).
2173 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2174 BypassBlock->getTerminator());
2176 LoopBypassBlocks.push_back(BypassBlock);
2178 // Split the single block loop into the two loop structure described above.
2179 BasicBlock *VectorPH =
2180 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2181 BasicBlock *VecBody =
2182 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2183 BasicBlock *MiddleBlock =
2184 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2185 BasicBlock *ScalarPH =
2186 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2188 // Create and register the new vector loop.
2189 Loop* Lp = new Loop();
2190 Loop *ParentLoop = OrigLoop->getParentLoop();
2192 // Insert the new loop into the loop nest and register the new basic blocks
2193 // before calling any utilities such as SCEV that require valid LoopInfo.
2195 ParentLoop->addChildLoop(Lp);
2196 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
2197 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
2198 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
2200 LI->addTopLevelLoop(Lp);
2202 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
2204 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2206 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2208 // Generate the induction variable.
2209 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2210 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2211 // The loop step is equal to the vectorization factor (num of SIMD elements)
2212 // times the unroll factor (num of SIMD instructions).
2213 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2215 // This is the IR builder that we use to add all of the logic for bypassing
2216 // the new vector loop.
2217 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2218 setDebugLocFromInst(BypassBuilder,
2219 getDebugLocFromInstOrOperands(OldInduction));
2221 // We may need to extend the index in case there is a type mismatch.
2222 // We know that the count starts at zero and does not overflow.
2223 if (Count->getType() != IdxTy) {
2224 // The exit count can be of pointer type. Convert it to the correct
2226 if (ExitCount->getType()->isPointerTy())
2227 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2229 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2232 // Add the start index to the loop count to get the new end index.
2233 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2235 // Now we need to generate the expression for N - (N % VF), which is
2236 // the part that the vectorized body will execute.
2237 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2238 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2239 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2240 "end.idx.rnd.down");
2242 // Now, compare the new count to zero. If it is zero skip the vector loop and
2243 // jump to the scalar loop.
2245 BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2247 BasicBlock *LastBypassBlock = BypassBlock;
2249 // Generate code to check that the loops trip count that we computed by adding
2250 // one to the backedge-taken count will not overflow.
2252 auto PastOverflowCheck =
2253 std::next(BasicBlock::iterator(OverflowCheckAnchor));
2254 BasicBlock *CheckBlock =
2255 LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2257 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2258 LoopBypassBlocks.push_back(CheckBlock);
2259 Instruction *OldTerm = LastBypassBlock->getTerminator();
2260 BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2261 OldTerm->eraseFromParent();
2262 LastBypassBlock = CheckBlock;
2265 // Generate the code to check that the strides we assumed to be one are really
2266 // one. We want the new basic block to start at the first instruction in a
2267 // sequence of instructions that form a check.
2268 Instruction *StrideCheck;
2269 Instruction *FirstCheckInst;
2270 std::tie(FirstCheckInst, StrideCheck) =
2271 addStrideCheck(LastBypassBlock->getTerminator());
2273 // Create a new block containing the stride check.
2274 BasicBlock *CheckBlock =
2275 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2277 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2278 LoopBypassBlocks.push_back(CheckBlock);
2280 // Replace the branch into the memory check block with a conditional branch
2281 // for the "few elements case".
2282 Instruction *OldTerm = LastBypassBlock->getTerminator();
2283 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2284 OldTerm->eraseFromParent();
2287 LastBypassBlock = CheckBlock;
2290 // Generate the code that checks in runtime if arrays overlap. We put the
2291 // checks into a separate block to make the more common case of few elements
2293 Instruction *MemRuntimeCheck;
2294 std::tie(FirstCheckInst, MemRuntimeCheck) =
2295 addRuntimeCheck(LastBypassBlock->getTerminator());
2296 if (MemRuntimeCheck) {
2297 // Create a new block containing the memory check.
2298 BasicBlock *CheckBlock =
2299 LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
2301 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2302 LoopBypassBlocks.push_back(CheckBlock);
2304 // Replace the branch into the memory check block with a conditional branch
2305 // for the "few elements case".
2306 Instruction *OldTerm = LastBypassBlock->getTerminator();
2307 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2308 OldTerm->eraseFromParent();
2310 Cmp = MemRuntimeCheck;
2311 LastBypassBlock = CheckBlock;
2314 LastBypassBlock->getTerminator()->eraseFromParent();
2315 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2318 // We are going to resume the execution of the scalar loop.
2319 // Go over all of the induction variables that we found and fix the
2320 // PHIs that are left in the scalar version of the loop.
2321 // The starting values of PHI nodes depend on the counter of the last
2322 // iteration in the vectorized loop.
2323 // If we come from a bypass edge then we need to start from the original
2326 // This variable saves the new starting index for the scalar loop.
2327 PHINode *ResumeIndex = nullptr;
2328 LoopVectorizationLegality::InductionList::iterator I, E;
2329 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2330 // Set builder to point to last bypass block.
2331 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2332 for (I = List->begin(), E = List->end(); I != E; ++I) {
2333 PHINode *OrigPhi = I->first;
2334 LoopVectorizationLegality::InductionInfo II = I->second;
2336 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2337 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2338 MiddleBlock->getTerminator());
2339 // We might have extended the type of the induction variable but we need a
2340 // truncated version for the scalar loop.
2341 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2342 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2343 MiddleBlock->getTerminator()) : nullptr;
2345 // Create phi nodes to merge from the backedge-taken check block.
2346 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2347 ScalarPH->getTerminator());
2348 BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2350 PHINode *BCTruncResumeVal = nullptr;
2351 if (OrigPhi == OldInduction) {
2353 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2354 ScalarPH->getTerminator());
2355 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2358 Value *EndValue = nullptr;
2360 case LoopVectorizationLegality::IK_NoInduction:
2361 llvm_unreachable("Unknown induction");
2362 case LoopVectorizationLegality::IK_IntInduction: {
2363 // Handle the integer induction counter.
2364 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2366 // We have the canonical induction variable.
2367 if (OrigPhi == OldInduction) {
2368 // Create a truncated version of the resume value for the scalar loop,
2369 // we might have promoted the type to a larger width.
2371 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2372 // The new PHI merges the original incoming value, in case of a bypass,
2373 // or the value at the end of the vectorized loop.
2374 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2375 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2376 TruncResumeVal->addIncoming(EndValue, VecBody);
2378 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2380 // We know what the end value is.
2381 EndValue = IdxEndRoundDown;
2382 // We also know which PHI node holds it.
2383 ResumeIndex = ResumeVal;
2387 // Not the canonical induction variable - add the vector loop count to the
2389 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2390 II.StartValue->getType(),
2392 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
2395 case LoopVectorizationLegality::IK_ReverseIntInduction: {
2396 // Convert the CountRoundDown variable to the PHI size.
2397 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2398 II.StartValue->getType(),
2400 // Handle reverse integer induction counter.
2401 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
2404 case LoopVectorizationLegality::IK_PtrInduction: {
2405 // For pointer induction variables, calculate the offset using
2407 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2411 case LoopVectorizationLegality::IK_ReversePtrInduction: {
2412 // The value at the end of the loop for the reverse pointer is calculated
2413 // by creating a GEP with a negative index starting from the start value.
2414 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2415 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2417 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2423 // The new PHI merges the original incoming value, in case of a bypass,
2424 // or the value at the end of the vectorized loop.
2425 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2426 if (OrigPhi == OldInduction)
2427 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2429 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2431 ResumeVal->addIncoming(EndValue, VecBody);
2433 // Fix the scalar body counter (PHI node).
2434 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2436 // The old induction's phi node in the scalar body needs the truncated
2438 if (OrigPhi == OldInduction) {
2439 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2440 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2442 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2443 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2447 // If we are generating a new induction variable then we also need to
2448 // generate the code that calculates the exit value. This value is not
2449 // simply the end of the counter because we may skip the vectorized body
2450 // in case of a runtime check.
2452 assert(!ResumeIndex && "Unexpected resume value found");
2453 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2454 MiddleBlock->getTerminator());
2455 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2456 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2457 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2460 // Make sure that we found the index where scalar loop needs to continue.
2461 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2462 "Invalid resume Index");
2464 // Add a check in the middle block to see if we have completed
2465 // all of the iterations in the first vector loop.
2466 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2467 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2468 ResumeIndex, "cmp.n",
2469 MiddleBlock->getTerminator());
2471 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2472 // Remove the old terminator.
2473 MiddleBlock->getTerminator()->eraseFromParent();
2475 // Create i+1 and fill the PHINode.
2476 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2477 Induction->addIncoming(StartIdx, VectorPH);
2478 Induction->addIncoming(NextIdx, VecBody);
2479 // Create the compare.
2480 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2481 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2483 // Now we have two terminators. Remove the old one from the block.
2484 VecBody->getTerminator()->eraseFromParent();
2486 // Get ready to start creating new instructions into the vectorized body.
2487 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2490 LoopVectorPreHeader = VectorPH;
2491 LoopScalarPreHeader = ScalarPH;
2492 LoopMiddleBlock = MiddleBlock;
2493 LoopExitBlock = ExitBlock;
2494 LoopVectorBody.push_back(VecBody);
2495 LoopScalarBody = OldBasicBlock;
2497 LoopVectorizeHints Hints(Lp, true);
2498 Hints.setAlreadyVectorized(Lp);
2501 /// This function returns the identity element (or neutral element) for
2502 /// the operation K.
2504 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2509 // Adding, Xoring, Oring zero to a number does not change it.
2510 return ConstantInt::get(Tp, 0);
2511 case RK_IntegerMult:
2512 // Multiplying a number by 1 does not change it.
2513 return ConstantInt::get(Tp, 1);
2515 // AND-ing a number with an all-1 value does not change it.
2516 return ConstantInt::get(Tp, -1, true);
2518 // Multiplying a number by 1 does not change it.
2519 return ConstantFP::get(Tp, 1.0L);
2521 // Adding zero to a number does not change it.
2522 return ConstantFP::get(Tp, 0.0L);
2524 llvm_unreachable("Unknown reduction kind");
2528 /// This function translates the reduction kind to an LLVM binary operator.
2530 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2532 case LoopVectorizationLegality::RK_IntegerAdd:
2533 return Instruction::Add;
2534 case LoopVectorizationLegality::RK_IntegerMult:
2535 return Instruction::Mul;
2536 case LoopVectorizationLegality::RK_IntegerOr:
2537 return Instruction::Or;
2538 case LoopVectorizationLegality::RK_IntegerAnd:
2539 return Instruction::And;
2540 case LoopVectorizationLegality::RK_IntegerXor:
2541 return Instruction::Xor;
2542 case LoopVectorizationLegality::RK_FloatMult:
2543 return Instruction::FMul;
2544 case LoopVectorizationLegality::RK_FloatAdd:
2545 return Instruction::FAdd;
2546 case LoopVectorizationLegality::RK_IntegerMinMax:
2547 return Instruction::ICmp;
2548 case LoopVectorizationLegality::RK_FloatMinMax:
2549 return Instruction::FCmp;
2551 llvm_unreachable("Unknown reduction operation");
2555 Value *createMinMaxOp(IRBuilder<> &Builder,
2556 LoopVectorizationLegality::MinMaxReductionKind RK,
2559 CmpInst::Predicate P = CmpInst::ICMP_NE;
2562 llvm_unreachable("Unknown min/max reduction kind");
2563 case LoopVectorizationLegality::MRK_UIntMin:
2564 P = CmpInst::ICMP_ULT;
2566 case LoopVectorizationLegality::MRK_UIntMax:
2567 P = CmpInst::ICMP_UGT;
2569 case LoopVectorizationLegality::MRK_SIntMin:
2570 P = CmpInst::ICMP_SLT;
2572 case LoopVectorizationLegality::MRK_SIntMax:
2573 P = CmpInst::ICMP_SGT;
2575 case LoopVectorizationLegality::MRK_FloatMin:
2576 P = CmpInst::FCMP_OLT;
2578 case LoopVectorizationLegality::MRK_FloatMax:
2579 P = CmpInst::FCMP_OGT;
2584 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2585 RK == LoopVectorizationLegality::MRK_FloatMax)
2586 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2588 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2590 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2595 struct CSEDenseMapInfo {
2596 static bool canHandle(Instruction *I) {
2597 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2598 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2600 static inline Instruction *getEmptyKey() {
2601 return DenseMapInfo<Instruction *>::getEmptyKey();
2603 static inline Instruction *getTombstoneKey() {
2604 return DenseMapInfo<Instruction *>::getTombstoneKey();
2606 static unsigned getHashValue(Instruction *I) {
2607 assert(canHandle(I) && "Unknown instruction!");
2608 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2609 I->value_op_end()));
2611 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2612 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2613 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2615 return LHS->isIdenticalTo(RHS);
2620 /// \brief Check whether this block is a predicated block.
2621 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2622 /// = ...; " blocks. We start with one vectorized basic block. For every
2623 /// conditional block we split this vectorized block. Therefore, every second
2624 /// block will be a predicated one.
2625 static bool isPredicatedBlock(unsigned BlockNum) {
2626 return BlockNum % 2;
2629 ///\brief Perform cse of induction variable instructions.
2630 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2631 // Perform simple cse.
2632 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2633 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2634 BasicBlock *BB = BBs[i];
2635 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2636 Instruction *In = I++;
2638 if (!CSEDenseMapInfo::canHandle(In))
2641 // Check if we can replace this instruction with any of the
2642 // visited instructions.
2643 if (Instruction *V = CSEMap.lookup(In)) {
2644 In->replaceAllUsesWith(V);
2645 In->eraseFromParent();
2648 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2649 // ...;" blocks for predicated stores. Every second block is a predicated
2651 if (isPredicatedBlock(i))
2659 /// \brief Adds a 'fast' flag to floating point operations.
2660 static Value *addFastMathFlag(Value *V) {
2661 if (isa<FPMathOperator>(V)){
2662 FastMathFlags Flags;
2663 Flags.setUnsafeAlgebra();
2664 cast<Instruction>(V)->setFastMathFlags(Flags);
2669 void InnerLoopVectorizer::vectorizeLoop() {
2670 //===------------------------------------------------===//
2672 // Notice: any optimization or new instruction that go
2673 // into the code below should be also be implemented in
2676 //===------------------------------------------------===//
2677 Constant *Zero = Builder.getInt32(0);
2679 // In order to support reduction variables we need to be able to vectorize
2680 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2681 // stages. First, we create a new vector PHI node with no incoming edges.
2682 // We use this value when we vectorize all of the instructions that use the
2683 // PHI. Next, after all of the instructions in the block are complete we
2684 // add the new incoming edges to the PHI. At this point all of the
2685 // instructions in the basic block are vectorized, so we can use them to
2686 // construct the PHI.
2687 PhiVector RdxPHIsToFix;
2689 // Scan the loop in a topological order to ensure that defs are vectorized
2691 LoopBlocksDFS DFS(OrigLoop);
2694 // Vectorize all of the blocks in the original loop.
2695 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2696 be = DFS.endRPO(); bb != be; ++bb)
2697 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2699 // At this point every instruction in the original loop is widened to
2700 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2701 // that we vectorized. The PHI nodes are currently empty because we did
2702 // not want to introduce cycles. Notice that the remaining PHI nodes
2703 // that we need to fix are reduction variables.
2705 // Create the 'reduced' values for each of the induction vars.
2706 // The reduced values are the vector values that we scalarize and combine
2707 // after the loop is finished.
2708 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2710 PHINode *RdxPhi = *it;
2711 assert(RdxPhi && "Unable to recover vectorized PHI");
2713 // Find the reduction variable descriptor.
2714 assert(Legal->getReductionVars()->count(RdxPhi) &&
2715 "Unable to find the reduction variable");
2716 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2717 (*Legal->getReductionVars())[RdxPhi];
2719 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2721 // We need to generate a reduction vector from the incoming scalar.
2722 // To do so, we need to generate the 'identity' vector and override
2723 // one of the elements with the incoming scalar reduction. We need
2724 // to do it in the vector-loop preheader.
2725 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2727 // This is the vector-clone of the value that leaves the loop.
2728 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2729 Type *VecTy = VectorExit[0]->getType();
2731 // Find the reduction identity variable. Zero for addition, or, xor,
2732 // one for multiplication, -1 for And.
2735 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2736 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2737 // MinMax reduction have the start value as their identify.
2739 VectorStart = Identity = RdxDesc.StartValue;
2741 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2746 // Handle other reduction kinds:
2748 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2749 VecTy->getScalarType());
2752 // This vector is the Identity vector where the first element is the
2753 // incoming scalar reduction.
2754 VectorStart = RdxDesc.StartValue;
2756 Identity = ConstantVector::getSplat(VF, Iden);
2758 // This vector is the Identity vector where the first element is the
2759 // incoming scalar reduction.
2760 VectorStart = Builder.CreateInsertElement(Identity,
2761 RdxDesc.StartValue, Zero);
2765 // Fix the vector-loop phi.
2766 // We created the induction variable so we know that the
2767 // preheader is the first entry.
2768 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2770 // Reductions do not have to start at zero. They can start with
2771 // any loop invariant values.
2772 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2773 BasicBlock *Latch = OrigLoop->getLoopLatch();
2774 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2775 VectorParts &Val = getVectorValue(LoopVal);
2776 for (unsigned part = 0; part < UF; ++part) {
2777 // Make sure to add the reduction stat value only to the
2778 // first unroll part.
2779 Value *StartVal = (part == 0) ? VectorStart : Identity;
2780 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2781 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2782 LoopVectorBody.back());
2785 // Before each round, move the insertion point right between
2786 // the PHIs and the values we are going to write.
2787 // This allows us to write both PHINodes and the extractelement
2789 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2791 VectorParts RdxParts;
2792 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2793 for (unsigned part = 0; part < UF; ++part) {
2794 // This PHINode contains the vectorized reduction variable, or
2795 // the initial value vector, if we bypass the vector loop.
2796 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2797 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2798 Value *StartVal = (part == 0) ? VectorStart : Identity;
2799 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2800 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2801 NewPhi->addIncoming(RdxExitVal[part],
2802 LoopVectorBody.back());
2803 RdxParts.push_back(NewPhi);
2806 // Reduce all of the unrolled parts into a single vector.
2807 Value *ReducedPartRdx = RdxParts[0];
2808 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2809 setDebugLocFromInst(Builder, ReducedPartRdx);
2810 for (unsigned part = 1; part < UF; ++part) {
2811 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2812 // Floating point operations had to be 'fast' to enable the reduction.
2813 ReducedPartRdx = addFastMathFlag(
2814 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2815 ReducedPartRdx, "bin.rdx"));
2817 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2818 ReducedPartRdx, RdxParts[part]);
2822 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2823 // and vector ops, reducing the set of values being computed by half each
2825 assert(isPowerOf2_32(VF) &&
2826 "Reduction emission only supported for pow2 vectors!");
2827 Value *TmpVec = ReducedPartRdx;
2828 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2829 for (unsigned i = VF; i != 1; i >>= 1) {
2830 // Move the upper half of the vector to the lower half.
2831 for (unsigned j = 0; j != i/2; ++j)
2832 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2834 // Fill the rest of the mask with undef.
2835 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2836 UndefValue::get(Builder.getInt32Ty()));
2839 Builder.CreateShuffleVector(TmpVec,
2840 UndefValue::get(TmpVec->getType()),
2841 ConstantVector::get(ShuffleMask),
2844 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2845 // Floating point operations had to be 'fast' to enable the reduction.
2846 TmpVec = addFastMathFlag(Builder.CreateBinOp(
2847 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2849 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2852 // The result is in the first element of the vector.
2853 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2854 Builder.getInt32(0));
2857 // Create a phi node that merges control-flow from the backedge-taken check
2858 // block and the middle block.
2859 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2860 LoopScalarPreHeader->getTerminator());
2861 BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
2862 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2864 // Now, we need to fix the users of the reduction variable
2865 // inside and outside of the scalar remainder loop.
2866 // We know that the loop is in LCSSA form. We need to update the
2867 // PHI nodes in the exit blocks.
2868 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2869 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2870 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2871 if (!LCSSAPhi) break;
2873 // All PHINodes need to have a single entry edge, or two if
2874 // we already fixed them.
2875 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2877 // We found our reduction value exit-PHI. Update it with the
2878 // incoming bypass edge.
2879 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2880 // Add an edge coming from the bypass.
2881 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2884 }// end of the LCSSA phi scan.
2886 // Fix the scalar loop reduction variable with the incoming reduction sum
2887 // from the vector body and from the backedge value.
2888 int IncomingEdgeBlockIdx =
2889 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2890 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2891 // Pick the other block.
2892 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2893 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
2894 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2895 }// end of for each redux variable.
2899 // Remove redundant induction instructions.
2900 cse(LoopVectorBody);
2903 void InnerLoopVectorizer::fixLCSSAPHIs() {
2904 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2905 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2906 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2907 if (!LCSSAPhi) break;
2908 if (LCSSAPhi->getNumIncomingValues() == 1)
2909 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2914 InnerLoopVectorizer::VectorParts
2915 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2916 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2919 // Look for cached value.
2920 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2921 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2922 if (ECEntryIt != MaskCache.end())
2923 return ECEntryIt->second;
2925 VectorParts SrcMask = createBlockInMask(Src);
2927 // The terminator has to be a branch inst!
2928 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2929 assert(BI && "Unexpected terminator found");
2931 if (BI->isConditional()) {
2932 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2934 if (BI->getSuccessor(0) != Dst)
2935 for (unsigned part = 0; part < UF; ++part)
2936 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2938 for (unsigned part = 0; part < UF; ++part)
2939 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2941 MaskCache[Edge] = EdgeMask;
2945 MaskCache[Edge] = SrcMask;
2949 InnerLoopVectorizer::VectorParts
2950 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2951 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2953 // Loop incoming mask is all-one.
2954 if (OrigLoop->getHeader() == BB) {
2955 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2956 return getVectorValue(C);
2959 // This is the block mask. We OR all incoming edges, and with zero.
2960 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2961 VectorParts BlockMask = getVectorValue(Zero);
2964 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2965 VectorParts EM = createEdgeMask(*it, BB);
2966 for (unsigned part = 0; part < UF; ++part)
2967 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2973 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2974 InnerLoopVectorizer::VectorParts &Entry,
2975 unsigned UF, unsigned VF, PhiVector *PV) {
2976 PHINode* P = cast<PHINode>(PN);
2977 // Handle reduction variables:
2978 if (Legal->getReductionVars()->count(P)) {
2979 for (unsigned part = 0; part < UF; ++part) {
2980 // This is phase one of vectorizing PHIs.
2981 Type *VecTy = (VF == 1) ? PN->getType() :
2982 VectorType::get(PN->getType(), VF);
2983 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2984 LoopVectorBody.back()-> getFirstInsertionPt());
2990 setDebugLocFromInst(Builder, P);
2991 // Check for PHI nodes that are lowered to vector selects.
2992 if (P->getParent() != OrigLoop->getHeader()) {
2993 // We know that all PHIs in non-header blocks are converted into
2994 // selects, so we don't have to worry about the insertion order and we
2995 // can just use the builder.
2996 // At this point we generate the predication tree. There may be
2997 // duplications since this is a simple recursive scan, but future
2998 // optimizations will clean it up.
3000 unsigned NumIncoming = P->getNumIncomingValues();
3002 // Generate a sequence of selects of the form:
3003 // SELECT(Mask3, In3,
3004 // SELECT(Mask2, In2,
3006 for (unsigned In = 0; In < NumIncoming; In++) {
3007 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3009 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3011 for (unsigned part = 0; part < UF; ++part) {
3012 // We might have single edge PHIs (blocks) - use an identity
3013 // 'select' for the first PHI operand.
3015 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3018 // Select between the current value and the previous incoming edge
3019 // based on the incoming mask.
3020 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3021 Entry[part], "predphi");
3027 // This PHINode must be an induction variable.
3028 // Make sure that we know about it.
3029 assert(Legal->getInductionVars()->count(P) &&
3030 "Not an induction variable");
3032 LoopVectorizationLegality::InductionInfo II =
3033 Legal->getInductionVars()->lookup(P);
3036 case LoopVectorizationLegality::IK_NoInduction:
3037 llvm_unreachable("Unknown induction");
3038 case LoopVectorizationLegality::IK_IntInduction: {
3039 assert(P->getType() == II.StartValue->getType() && "Types must match");
3040 Type *PhiTy = P->getType();
3042 if (P == OldInduction) {
3043 // Handle the canonical induction variable. We might have had to
3045 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
3047 // Handle other induction variables that are now based on the
3049 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
3051 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
3052 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
3055 Broadcasted = getBroadcastInstrs(Broadcasted);
3056 // After broadcasting the induction variable we need to make the vector
3057 // consecutive by adding 0, 1, 2, etc.
3058 for (unsigned part = 0; part < UF; ++part)
3059 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
3062 case LoopVectorizationLegality::IK_ReverseIntInduction:
3063 case LoopVectorizationLegality::IK_PtrInduction:
3064 case LoopVectorizationLegality::IK_ReversePtrInduction:
3065 // Handle reverse integer and pointer inductions.
3066 Value *StartIdx = ExtendedIdx;
3067 // This is the normalized GEP that starts counting at zero.
3068 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
3071 // Handle the reverse integer induction variable case.
3072 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
3073 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
3074 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
3076 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
3079 // This is a new value so do not hoist it out.
3080 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
3081 // After broadcasting the induction variable we need to make the
3082 // vector consecutive by adding ... -3, -2, -1, 0.
3083 for (unsigned part = 0; part < UF; ++part)
3084 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
3089 // Handle the pointer induction variable case.
3090 assert(P->getType()->isPointerTy() && "Unexpected type.");
3092 // Is this a reverse induction ptr or a consecutive induction ptr.
3093 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
3096 // This is the vector of results. Notice that we don't generate
3097 // vector geps because scalar geps result in better code.
3098 for (unsigned part = 0; part < UF; ++part) {
3100 int EltIndex = (part) * (Reverse ? -1 : 1);
3101 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3104 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
3106 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
3108 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
3110 Entry[part] = SclrGep;
3114 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3115 for (unsigned int i = 0; i < VF; ++i) {
3116 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
3117 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3120 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
3122 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
3124 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
3126 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3127 Builder.getInt32(i),
3130 Entry[part] = VecVal;
3136 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3137 // For each instruction in the old loop.
3138 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3139 VectorParts &Entry = WidenMap.get(it);
3140 switch (it->getOpcode()) {
3141 case Instruction::Br:
3142 // Nothing to do for PHIs and BR, since we already took care of the
3143 // loop control flow instructions.
3145 case Instruction::PHI:{
3146 // Vectorize PHINodes.
3147 widenPHIInstruction(it, Entry, UF, VF, PV);
3151 case Instruction::Add:
3152 case Instruction::FAdd:
3153 case Instruction::Sub:
3154 case Instruction::FSub:
3155 case Instruction::Mul:
3156 case Instruction::FMul:
3157 case Instruction::UDiv:
3158 case Instruction::SDiv:
3159 case Instruction::FDiv:
3160 case Instruction::URem:
3161 case Instruction::SRem:
3162 case Instruction::FRem:
3163 case Instruction::Shl:
3164 case Instruction::LShr:
3165 case Instruction::AShr:
3166 case Instruction::And:
3167 case Instruction::Or:
3168 case Instruction::Xor: {
3169 // Just widen binops.
3170 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3171 setDebugLocFromInst(Builder, BinOp);
3172 VectorParts &A = getVectorValue(it->getOperand(0));
3173 VectorParts &B = getVectorValue(it->getOperand(1));
3175 // Use this vector value for all users of the original instruction.
3176 for (unsigned Part = 0; Part < UF; ++Part) {
3177 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3179 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
3180 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
3181 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
3182 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
3183 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
3185 if (VecOp && isa<PossiblyExactOperator>(VecOp))
3186 VecOp->setIsExact(BinOp->isExact());
3188 // Copy the fast-math flags.
3189 if (VecOp && isa<FPMathOperator>(V))
3190 VecOp->setFastMathFlags(it->getFastMathFlags());
3195 propagateMetadata(Entry, it);
3198 case Instruction::Select: {
3200 // If the selector is loop invariant we can create a select
3201 // instruction with a scalar condition. Otherwise, use vector-select.
3202 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3204 setDebugLocFromInst(Builder, it);
3206 // The condition can be loop invariant but still defined inside the
3207 // loop. This means that we can't just use the original 'cond' value.
3208 // We have to take the 'vectorized' value and pick the first lane.
3209 // Instcombine will make this a no-op.
3210 VectorParts &Cond = getVectorValue(it->getOperand(0));
3211 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3212 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3214 Value *ScalarCond = (VF == 1) ? Cond[0] :
3215 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3217 for (unsigned Part = 0; Part < UF; ++Part) {
3218 Entry[Part] = Builder.CreateSelect(
3219 InvariantCond ? ScalarCond : Cond[Part],
3224 propagateMetadata(Entry, it);
3228 case Instruction::ICmp:
3229 case Instruction::FCmp: {
3230 // Widen compares. Generate vector compares.
3231 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3232 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3233 setDebugLocFromInst(Builder, it);
3234 VectorParts &A = getVectorValue(it->getOperand(0));
3235 VectorParts &B = getVectorValue(it->getOperand(1));
3236 for (unsigned Part = 0; Part < UF; ++Part) {
3239 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3241 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3245 propagateMetadata(Entry, it);
3249 case Instruction::Store:
3250 case Instruction::Load:
3251 vectorizeMemoryInstruction(it);
3253 case Instruction::ZExt:
3254 case Instruction::SExt:
3255 case Instruction::FPToUI:
3256 case Instruction::FPToSI:
3257 case Instruction::FPExt:
3258 case Instruction::PtrToInt:
3259 case Instruction::IntToPtr:
3260 case Instruction::SIToFP:
3261 case Instruction::UIToFP:
3262 case Instruction::Trunc:
3263 case Instruction::FPTrunc:
3264 case Instruction::BitCast: {
3265 CastInst *CI = dyn_cast<CastInst>(it);
3266 setDebugLocFromInst(Builder, it);
3267 /// Optimize the special case where the source is the induction
3268 /// variable. Notice that we can only optimize the 'trunc' case
3269 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3270 /// c. other casts depend on pointer size.
3271 if (CI->getOperand(0) == OldInduction &&
3272 it->getOpcode() == Instruction::Trunc) {
3273 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3275 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3276 for (unsigned Part = 0; Part < UF; ++Part)
3277 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
3278 propagateMetadata(Entry, it);
3281 /// Vectorize casts.
3282 Type *DestTy = (VF == 1) ? CI->getType() :
3283 VectorType::get(CI->getType(), VF);
3285 VectorParts &A = getVectorValue(it->getOperand(0));
3286 for (unsigned Part = 0; Part < UF; ++Part)
3287 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3288 propagateMetadata(Entry, it);
3292 case Instruction::Call: {
3293 // Ignore dbg intrinsics.
3294 if (isa<DbgInfoIntrinsic>(it))
3296 setDebugLocFromInst(Builder, it);
3298 Module *M = BB->getParent()->getParent();
3299 CallInst *CI = cast<CallInst>(it);
3300 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3301 assert(ID && "Not an intrinsic call!");
3303 case Intrinsic::lifetime_end:
3304 case Intrinsic::lifetime_start:
3305 scalarizeInstruction(it);
3308 bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
3309 for (unsigned Part = 0; Part < UF; ++Part) {
3310 SmallVector<Value *, 4> Args;
3311 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3312 if (HasScalarOpd && i == 1) {
3313 Args.push_back(CI->getArgOperand(i));
3316 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3317 Args.push_back(Arg[Part]);
3319 Type *Tys[] = {CI->getType()};
3321 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3323 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3324 Entry[Part] = Builder.CreateCall(F, Args);
3327 propagateMetadata(Entry, it);
3334 // All other instructions are unsupported. Scalarize them.
3335 scalarizeInstruction(it);
3338 }// end of for_each instr.
3341 void InnerLoopVectorizer::updateAnalysis() {
3342 // Forget the original basic block.
3343 SE->forgetLoop(OrigLoop);
3345 // Update the dominator tree information.
3346 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3347 "Entry does not dominate exit.");
3349 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3350 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3351 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3353 // Due to if predication of stores we might create a sequence of "if(pred)
3354 // a[i] = ...; " blocks.
3355 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3357 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3358 else if (isPredicatedBlock(i)) {
3359 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3361 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3365 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3366 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3367 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3368 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3370 DEBUG(DT->verifyDomTree());
3373 /// \brief Check whether it is safe to if-convert this phi node.
3375 /// Phi nodes with constant expressions that can trap are not safe to if
3377 static bool canIfConvertPHINodes(BasicBlock *BB) {
3378 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3379 PHINode *Phi = dyn_cast<PHINode>(I);
3382 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3383 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3390 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3391 if (!EnableIfConversion) {
3392 emitAnalysis(Report() << "if-conversion is disabled");
3396 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3398 // A list of pointers that we can safely read and write to.
3399 SmallPtrSet<Value *, 8> SafePointes;
3401 // Collect safe addresses.
3402 for (Loop::block_iterator BI = TheLoop->block_begin(),
3403 BE = TheLoop->block_end(); BI != BE; ++BI) {
3404 BasicBlock *BB = *BI;
3406 if (blockNeedsPredication(BB))
3409 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3410 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3411 SafePointes.insert(LI->getPointerOperand());
3412 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3413 SafePointes.insert(SI->getPointerOperand());
3417 // Collect the blocks that need predication.
3418 BasicBlock *Header = TheLoop->getHeader();
3419 for (Loop::block_iterator BI = TheLoop->block_begin(),
3420 BE = TheLoop->block_end(); BI != BE; ++BI) {
3421 BasicBlock *BB = *BI;
3423 // We don't support switch statements inside loops.
3424 if (!isa<BranchInst>(BB->getTerminator())) {
3425 emitAnalysis(Report(BB->getTerminator())
3426 << "loop contains a switch statement");
3430 // We must be able to predicate all blocks that need to be predicated.
3431 if (blockNeedsPredication(BB)) {
3432 if (!blockCanBePredicated(BB, SafePointes)) {
3433 emitAnalysis(Report(BB->getTerminator())
3434 << "control flow cannot be substituted for a select");
3437 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3438 emitAnalysis(Report(BB->getTerminator())
3439 << "control flow cannot be substituted for a select");
3444 // We can if-convert this loop.
3448 bool LoopVectorizationLegality::canVectorize() {
3449 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3450 // be canonicalized.
3451 if (!TheLoop->getLoopPreheader()) {
3453 Report() << "loop control flow is not understood by vectorizer");
3457 // We can only vectorize innermost loops.
3458 if (TheLoop->getSubLoopsVector().size()) {
3459 emitAnalysis(Report() << "loop is not the innermost loop");
3463 // We must have a single backedge.
3464 if (TheLoop->getNumBackEdges() != 1) {
3466 Report() << "loop control flow is not understood by vectorizer");
3470 // We must have a single exiting block.
3471 if (!TheLoop->getExitingBlock()) {
3473 Report() << "loop control flow is not understood by vectorizer");
3477 // We need to have a loop header.
3478 DEBUG(dbgs() << "LV: Found a loop: " <<
3479 TheLoop->getHeader()->getName() << '\n');
3481 // Check if we can if-convert non-single-bb loops.
3482 unsigned NumBlocks = TheLoop->getNumBlocks();
3483 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3484 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3488 // ScalarEvolution needs to be able to find the exit count.
3489 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3490 if (ExitCount == SE->getCouldNotCompute()) {
3491 emitAnalysis(Report() << "could not determine number of loop iterations");
3492 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3496 // Check if we can vectorize the instructions and CFG in this loop.
3497 if (!canVectorizeInstrs()) {
3498 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3502 // Go over each instruction and look at memory deps.
3503 if (!canVectorizeMemory()) {
3504 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3508 // Collect all of the variables that remain uniform after vectorization.
3509 collectLoopUniforms();
3511 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3512 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3515 // Okay! We can vectorize. At this point we don't have any other mem analysis
3516 // which may limit our maximum vectorization factor, so just return true with
3521 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3522 if (Ty->isPointerTy())
3523 return DL.getIntPtrType(Ty);
3525 // It is possible that char's or short's overflow when we ask for the loop's
3526 // trip count, work around this by changing the type size.
3527 if (Ty->getScalarSizeInBits() < 32)
3528 return Type::getInt32Ty(Ty->getContext());
3533 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3534 Ty0 = convertPointerToIntegerType(DL, Ty0);
3535 Ty1 = convertPointerToIntegerType(DL, Ty1);
3536 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3541 /// \brief Check that the instruction has outside loop users and is not an
3542 /// identified reduction variable.
3543 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3544 SmallPtrSet<Value *, 4> &Reductions) {
3545 // Reduction instructions are allowed to have exit users. All other
3546 // instructions must not have external users.
3547 if (!Reductions.count(Inst))
3548 //Check that all of the users of the loop are inside the BB.
3549 for (User *U : Inst->users()) {
3550 Instruction *UI = cast<Instruction>(U);
3551 // This user may be a reduction exit value.
3552 if (!TheLoop->contains(UI)) {
3553 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3560 bool LoopVectorizationLegality::canVectorizeInstrs() {
3561 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3562 BasicBlock *Header = TheLoop->getHeader();
3564 // Look for the attribute signaling the absence of NaNs.
3565 Function &F = *Header->getParent();
3566 if (F.hasFnAttribute("no-nans-fp-math"))
3567 HasFunNoNaNAttr = F.getAttributes().getAttribute(
3568 AttributeSet::FunctionIndex,
3569 "no-nans-fp-math").getValueAsString() == "true";
3571 // For each block in the loop.
3572 for (Loop::block_iterator bb = TheLoop->block_begin(),
3573 be = TheLoop->block_end(); bb != be; ++bb) {
3575 // Scan the instructions in the block and look for hazards.
3576 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3579 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3580 Type *PhiTy = Phi->getType();
3581 // Check that this PHI type is allowed.
3582 if (!PhiTy->isIntegerTy() &&
3583 !PhiTy->isFloatingPointTy() &&
3584 !PhiTy->isPointerTy()) {
3585 emitAnalysis(Report(it)
3586 << "loop control flow is not understood by vectorizer");
3587 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3591 // If this PHINode is not in the header block, then we know that we
3592 // can convert it to select during if-conversion. No need to check if
3593 // the PHIs in this block are induction or reduction variables.
3594 if (*bb != Header) {
3595 // Check that this instruction has no outside users or is an
3596 // identified reduction value with an outside user.
3597 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3599 emitAnalysis(Report(it) << "value could not be identified as "
3600 "an induction or reduction variable");
3604 // We only allow if-converted PHIs with more than two incoming values.
3605 if (Phi->getNumIncomingValues() != 2) {
3606 emitAnalysis(Report(it)
3607 << "control flow not understood by vectorizer");
3608 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3612 // This is the value coming from the preheader.
3613 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3614 // Check if this is an induction variable.
3615 InductionKind IK = isInductionVariable(Phi);
3617 if (IK_NoInduction != IK) {
3618 // Get the widest type.
3620 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3622 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3624 // Int inductions are special because we only allow one IV.
3625 if (IK == IK_IntInduction) {
3626 // Use the phi node with the widest type as induction. Use the last
3627 // one if there are multiple (no good reason for doing this other
3628 // than it is expedient).
3629 if (!Induction || PhiTy == WidestIndTy)
3633 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3634 Inductions[Phi] = InductionInfo(StartValue, IK);
3636 // Until we explicitly handle the case of an induction variable with
3637 // an outside loop user we have to give up vectorizing this loop.
3638 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3639 emitAnalysis(Report(it) << "use of induction value outside of the "
3640 "loop is not handled by vectorizer");
3647 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3648 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3651 if (AddReductionVar(Phi, RK_IntegerMult)) {
3652 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3655 if (AddReductionVar(Phi, RK_IntegerOr)) {
3656 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3659 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3660 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3663 if (AddReductionVar(Phi, RK_IntegerXor)) {
3664 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3667 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3668 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3671 if (AddReductionVar(Phi, RK_FloatMult)) {
3672 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3675 if (AddReductionVar(Phi, RK_FloatAdd)) {
3676 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3679 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3680 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3685 emitAnalysis(Report(it) << "value that could not be identified as "
3686 "reduction is used outside the loop");
3687 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3689 }// end of PHI handling
3691 // We still don't handle functions. However, we can ignore dbg intrinsic
3692 // calls and we do handle certain intrinsic and libm functions.
3693 CallInst *CI = dyn_cast<CallInst>(it);
3694 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3695 emitAnalysis(Report(it) << "call instruction cannot be vectorized");
3696 DEBUG(dbgs() << "LV: Found a call site.\n");
3700 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
3701 // second argument is the same (i.e. loop invariant)
3703 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
3704 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
3705 emitAnalysis(Report(it)
3706 << "intrinsic instruction cannot be vectorized");
3707 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
3712 // Check that the instruction return type is vectorizable.
3713 // Also, we can't vectorize extractelement instructions.
3714 if ((!VectorType::isValidElementType(it->getType()) &&
3715 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3716 emitAnalysis(Report(it)
3717 << "instruction return type cannot be vectorized");
3718 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3722 // Check that the stored type is vectorizable.
3723 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3724 Type *T = ST->getValueOperand()->getType();
3725 if (!VectorType::isValidElementType(T)) {
3726 emitAnalysis(Report(ST) << "store instruction cannot be vectorized");
3729 if (EnableMemAccessVersioning)
3730 collectStridedAcccess(ST);
3733 if (EnableMemAccessVersioning)
3734 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3735 collectStridedAcccess(LI);
3737 // Reduction instructions are allowed to have exit users.
3738 // All other instructions must not have external users.
3739 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3740 emitAnalysis(Report(it) << "value cannot be used outside the loop");
3749 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3750 if (Inductions.empty()) {
3751 emitAnalysis(Report()
3752 << "loop induction variable could not be identified");
3760 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3761 /// return the induction operand of the gep pointer.
3762 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3763 const DataLayout *DL, Loop *Lp) {
3764 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3768 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3770 // Check that all of the gep indices are uniform except for our induction
3772 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3773 if (i != InductionOperand &&
3774 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3776 return GEP->getOperand(InductionOperand);
3779 ///\brief Look for a cast use of the passed value.
3780 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3781 Value *UniqueCast = nullptr;
3782 for (User *U : Ptr->users()) {
3783 CastInst *CI = dyn_cast<CastInst>(U);
3784 if (CI && CI->getType() == Ty) {
3794 ///\brief Get the stride of a pointer access in a loop.
3795 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3796 /// pointer to the Value, or null otherwise.
3797 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3798 const DataLayout *DL, Loop *Lp) {
3799 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3800 if (!PtrTy || PtrTy->isAggregateType())
3803 // Try to remove a gep instruction to make the pointer (actually index at this
3804 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3805 // pointer, otherwise, we are analyzing the index.
3806 Value *OrigPtr = Ptr;
3808 // The size of the pointer access.
3809 int64_t PtrAccessSize = 1;
3811 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3812 const SCEV *V = SE->getSCEV(Ptr);
3816 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3817 V = C->getOperand();
3819 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3823 V = S->getStepRecurrence(*SE);
3827 // Strip off the size of access multiplication if we are still analyzing the
3829 if (OrigPtr == Ptr) {
3830 DL->getTypeAllocSize(PtrTy->getElementType());
3831 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3832 if (M->getOperand(0)->getSCEVType() != scConstant)
3835 const APInt &APStepVal =
3836 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3838 // Huge step value - give up.
3839 if (APStepVal.getBitWidth() > 64)
3842 int64_t StepVal = APStepVal.getSExtValue();
3843 if (PtrAccessSize != StepVal)
3845 V = M->getOperand(1);
3850 Type *StripedOffRecurrenceCast = nullptr;
3851 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3852 StripedOffRecurrenceCast = C->getType();
3853 V = C->getOperand();
3856 // Look for the loop invariant symbolic value.
3857 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3861 Value *Stride = U->getValue();
3862 if (!Lp->isLoopInvariant(Stride))
3865 // If we have stripped off the recurrence cast we have to make sure that we
3866 // return the value that is used in this loop so that we can replace it later.
3867 if (StripedOffRecurrenceCast)
3868 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3873 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
3874 Value *Ptr = nullptr;
3875 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3876 Ptr = LI->getPointerOperand();
3877 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3878 Ptr = SI->getPointerOperand();
3882 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3886 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3887 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3888 Strides[Ptr] = Stride;
3889 StrideSet.insert(Stride);
3892 void LoopVectorizationLegality::collectLoopUniforms() {
3893 // We now know that the loop is vectorizable!
3894 // Collect variables that will remain uniform after vectorization.
3895 std::vector<Value*> Worklist;
3896 BasicBlock *Latch = TheLoop->getLoopLatch();
3898 // Start with the conditional branch and walk up the block.
3899 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3901 // Also add all consecutive pointer values; these values will be uniform
3902 // after vectorization (and subsequent cleanup) and, until revectorization is
3903 // supported, all dependencies must also be uniform.
3904 for (Loop::block_iterator B = TheLoop->block_begin(),
3905 BE = TheLoop->block_end(); B != BE; ++B)
3906 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3908 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3909 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3911 while (Worklist.size()) {
3912 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3913 Worklist.pop_back();
3915 // Look at instructions inside this loop.
3916 // Stop when reaching PHI nodes.
3917 // TODO: we need to follow values all over the loop, not only in this block.
3918 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3921 // This is a known uniform.
3924 // Insert all operands.
3925 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3930 /// \brief Analyses memory accesses in a loop.
3932 /// Checks whether run time pointer checks are needed and builds sets for data
3933 /// dependence checking.
3934 class AccessAnalysis {
3936 /// \brief Read or write access location.
3937 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3938 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3940 /// \brief Set of potential dependent memory accesses.
3941 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
3943 AccessAnalysis(const DataLayout *Dl, AliasAnalysis *AA, DepCandidates &DA) :
3944 DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
3946 /// \brief Register a load and whether it is only read from.
3947 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
3948 Value *Ptr = const_cast<Value*>(Loc.Ptr);
3949 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
3950 Accesses.insert(MemAccessInfo(Ptr, false));
3952 ReadOnlyPtr.insert(Ptr);
3955 /// \brief Register a store.
3956 void addStore(AliasAnalysis::Location &Loc) {
3957 Value *Ptr = const_cast<Value*>(Loc.Ptr);
3958 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
3959 Accesses.insert(MemAccessInfo(Ptr, true));
3962 /// \brief Check whether we can check the pointers at runtime for
3963 /// non-intersection.
3964 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3965 unsigned &NumComparisons, ScalarEvolution *SE,
3966 Loop *TheLoop, ValueToValueMap &Strides,
3967 bool ShouldCheckStride = false);
3969 /// \brief Goes over all memory accesses, checks whether a RT check is needed
3970 /// and builds sets of dependent accesses.
3971 void buildDependenceSets() {
3972 processMemAccesses();
3975 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
3977 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
3978 void resetDepChecks() { CheckDeps.clear(); }
3980 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
3983 typedef SetVector<MemAccessInfo> PtrAccessSet;
3985 /// \brief Go over all memory access and check whether runtime pointer checks
3986 /// are needed /// and build sets of dependency check candidates.
3987 void processMemAccesses();
3989 /// Set of all accesses.
3990 PtrAccessSet Accesses;
3992 /// Set of accesses that need a further dependence check.
3993 MemAccessInfoSet CheckDeps;
3995 /// Set of pointers that are read only.
3996 SmallPtrSet<Value*, 16> ReadOnlyPtr;
3998 const DataLayout *DL;
4000 /// An alias set tracker to partition the access set by underlying object and
4001 //intrinsic property (such as TBAA metadata).
4002 AliasSetTracker AST;
4004 /// Sets of potentially dependent accesses - members of one set share an
4005 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
4006 /// dependence check.
4007 DepCandidates &DepCands;
4009 bool IsRTCheckNeeded;
4012 } // end anonymous namespace
4014 /// \brief Check whether a pointer can participate in a runtime bounds check.
4015 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
4017 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
4018 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4022 return AR->isAffine();
4025 /// \brief Check the stride of the pointer and ensure that it does not wrap in
4026 /// the address space.
4027 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
4028 const Loop *Lp, ValueToValueMap &StridesMap);
4030 bool AccessAnalysis::canCheckPtrAtRT(
4031 LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
4032 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
4033 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
4034 // Find pointers with computable bounds. We are going to use this information
4035 // to place a runtime bound check.
4036 bool CanDoRT = true;
4038 bool IsDepCheckNeeded = isDependencyCheckNeeded();
4041 // We assign a consecutive id to access from different alias sets.
4042 // Accesses between different groups doesn't need to be checked.
4044 for (auto &AS : AST) {
4045 unsigned NumReadPtrChecks = 0;
4046 unsigned NumWritePtrChecks = 0;
4048 // We assign consecutive id to access from different dependence sets.
4049 // Accesses within the same set don't need a runtime check.
4050 unsigned RunningDepId = 1;
4051 DenseMap<Value *, unsigned> DepSetId;
4054 Value *Ptr = A.getValue();
4055 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
4056 MemAccessInfo Access(Ptr, IsWrite);
4059 ++NumWritePtrChecks;
4063 if (hasComputableBounds(SE, StridesMap, Ptr) &&
4064 // When we run after a failing dependency check we have to make sure we
4065 // don't have wrapping pointers.
4066 (!ShouldCheckStride ||
4067 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
4068 // The id of the dependence set.
4071 if (IsDepCheckNeeded) {
4072 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
4073 unsigned &LeaderId = DepSetId[Leader];
4075 LeaderId = RunningDepId++;
4078 // Each access has its own dependence set.
4079 DepId = RunningDepId++;
4081 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
4083 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
4089 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
4090 NumComparisons += 0; // Only one dependence set.
4092 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
4093 NumWritePtrChecks - 1));
4099 // If the pointers that we would use for the bounds comparison have different
4100 // address spaces, assume the values aren't directly comparable, so we can't
4101 // use them for the runtime check. We also have to assume they could
4102 // overlap. In the future there should be metadata for whether address spaces
4104 unsigned NumPointers = RtCheck.Pointers.size();
4105 for (unsigned i = 0; i < NumPointers; ++i) {
4106 for (unsigned j = i + 1; j < NumPointers; ++j) {
4107 // Only need to check pointers between two different dependency sets.
4108 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
4110 // Only need to check pointers in the same alias set.
4111 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
4114 Value *PtrI = RtCheck.Pointers[i];
4115 Value *PtrJ = RtCheck.Pointers[j];
4117 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
4118 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
4120 DEBUG(dbgs() << "LV: Runtime check would require comparison between"
4121 " different address spaces\n");
4130 void AccessAnalysis::processMemAccesses() {
4131 // We process the set twice: first we process read-write pointers, last we
4132 // process read-only pointers. This allows us to skip dependence tests for
4133 // read-only pointers.
4135 DEBUG(dbgs() << "LV: Processing memory accesses...\n");
4136 DEBUG(dbgs() << " AST: "; AST.dump());
4137 DEBUG(dbgs() << "LV: Accesses:\n");
4139 for (auto A : Accesses)
4140 dbgs() << "\t" << *A.getPointer() << " (" <<
4141 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
4142 "read-only" : "read")) << ")\n";
4145 // The AliasSetTracker has nicely partitioned our pointers by metadata
4146 // compatibility and potential for underlying-object overlap. As a result, we
4147 // only need to check for potential pointer dependencies within each alias
4149 for (auto &AS : AST) {
4150 // Note that both the alias-set tracker and the alias sets themselves used
4151 // linked lists internally and so the iteration order here is deterministic
4152 // (matching the original instruction order within each set).
4154 bool SetHasWrite = false;
4156 // Map of pointers to last access encountered.
4157 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
4158 UnderlyingObjToAccessMap ObjToLastAccess;
4160 // Set of access to check after all writes have been processed.
4161 PtrAccessSet DeferredAccesses;
4163 // Iterate over each alias set twice, once to process read/write pointers,
4164 // and then to process read-only pointers.
4165 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
4166 bool UseDeferred = SetIteration > 0;
4167 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
4170 Value *Ptr = A.getValue();
4171 bool IsWrite = S.count(MemAccessInfo(Ptr, true));
4173 // If we're using the deferred access set, then it contains only reads.
4174 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
4175 if (UseDeferred && !IsReadOnlyPtr)
4177 // Otherwise, the pointer must be in the PtrAccessSet, either as a read
4179 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
4180 S.count(MemAccessInfo(Ptr, false))) &&
4181 "Alias-set pointer not in the access set?");
4183 MemAccessInfo Access(Ptr, IsWrite);
4184 DepCands.insert(Access);
4186 // Memorize read-only pointers for later processing and skip them in the
4187 // first round (they need to be checked after we have seen all write
4188 // pointers). Note: we also mark pointer that are not consecutive as
4189 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need
4190 // the second check for "!IsWrite".
4191 if (!UseDeferred && IsReadOnlyPtr) {
4192 DeferredAccesses.insert(Access);
4196 // If this is a write - check other reads and writes for conflicts. If
4197 // this is a read only check other writes for conflicts (but only if
4198 // there is no other write to the ptr - this is an optimization to
4199 // catch "a[i] = a[i] + " without having to do a dependence check).
4200 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
4201 CheckDeps.insert(Access);
4202 IsRTCheckNeeded = true;
4208 // Create sets of pointers connected by a shared alias set and
4209 // underlying object.
4210 typedef SmallVector<Value*, 16> ValueVector;
4211 ValueVector TempObjects;
4212 GetUnderlyingObjects(Ptr, TempObjects, DL);
4213 for (Value *UnderlyingObj : TempObjects) {
4214 UnderlyingObjToAccessMap::iterator Prev =
4215 ObjToLastAccess.find(UnderlyingObj);
4216 if (Prev != ObjToLastAccess.end())
4217 DepCands.unionSets(Access, Prev->second);
4219 ObjToLastAccess[UnderlyingObj] = Access;
4227 /// \brief Checks memory dependences among accesses to the same underlying
4228 /// object to determine whether there vectorization is legal or not (and at
4229 /// which vectorization factor).
4231 /// This class works under the assumption that we already checked that memory
4232 /// locations with different underlying pointers are "must-not alias".
4233 /// We use the ScalarEvolution framework to symbolically evalutate access
4234 /// functions pairs. Since we currently don't restructure the loop we can rely
4235 /// on the program order of memory accesses to determine their safety.
4236 /// At the moment we will only deem accesses as safe for:
4237 /// * A negative constant distance assuming program order.
4239 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
4240 /// a[i] = tmp; y = a[i];
4242 /// The latter case is safe because later checks guarantuee that there can't
4243 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
4244 /// the same variable: a header phi can only be an induction or a reduction, a
4245 /// reduction can't have a memory sink, an induction can't have a memory
4246 /// source). This is important and must not be violated (or we have to
4247 /// resort to checking for cycles through memory).
4249 /// * A positive constant distance assuming program order that is bigger
4250 /// than the biggest memory access.
4252 /// tmp = a[i] OR b[i] = x
4253 /// a[i+2] = tmp y = b[i+2];
4255 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
4257 /// * Zero distances and all accesses have the same size.
4259 class MemoryDepChecker {
4261 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
4262 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
4264 MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
4265 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
4266 ShouldRetryWithRuntimeCheck(false) {}
4268 /// \brief Register the location (instructions are given increasing numbers)
4269 /// of a write access.
4270 void addAccess(StoreInst *SI) {
4271 Value *Ptr = SI->getPointerOperand();
4272 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
4273 InstMap.push_back(SI);
4277 /// \brief Register the location (instructions are given increasing numbers)
4278 /// of a write access.
4279 void addAccess(LoadInst *LI) {
4280 Value *Ptr = LI->getPointerOperand();
4281 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
4282 InstMap.push_back(LI);
4286 /// \brief Check whether the dependencies between the accesses are safe.
4288 /// Only checks sets with elements in \p CheckDeps.
4289 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4290 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
4292 /// \brief The maximum number of bytes of a vector register we can vectorize
4293 /// the accesses safely with.
4294 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
4296 /// \brief In same cases when the dependency check fails we can still
4297 /// vectorize the loop with a dynamic array access check.
4298 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
4301 ScalarEvolution *SE;
4302 const DataLayout *DL;
4303 const Loop *InnermostLoop;
4305 /// \brief Maps access locations (ptr, read/write) to program order.
4306 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
4308 /// \brief Memory access instructions in program order.
4309 SmallVector<Instruction *, 16> InstMap;
4311 /// \brief The program order index to be used for the next instruction.
4314 // We can access this many bytes in parallel safely.
4315 unsigned MaxSafeDepDistBytes;
4317 /// \brief If we see a non-constant dependence distance we can still try to
4318 /// vectorize this loop with runtime checks.
4319 bool ShouldRetryWithRuntimeCheck;
4321 /// \brief Check whether there is a plausible dependence between the two
4324 /// Access \p A must happen before \p B in program order. The two indices
4325 /// identify the index into the program order map.
4327 /// This function checks whether there is a plausible dependence (or the
4328 /// absence of such can't be proved) between the two accesses. If there is a
4329 /// plausible dependence but the dependence distance is bigger than one
4330 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
4331 /// distance is smaller than any other distance encountered so far).
4332 /// Otherwise, this function returns true signaling a possible dependence.
4333 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
4334 const MemAccessInfo &B, unsigned BIdx,
4335 ValueToValueMap &Strides);
4337 /// \brief Check whether the data dependence could prevent store-load
4339 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
4342 } // end anonymous namespace
4344 static bool isInBoundsGep(Value *Ptr) {
4345 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
4346 return GEP->isInBounds();
4350 /// \brief Check whether the access through \p Ptr has a constant stride.
4351 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
4352 const Loop *Lp, ValueToValueMap &StridesMap) {
4353 const Type *Ty = Ptr->getType();
4354 assert(Ty->isPointerTy() && "Unexpected non-ptr");
4356 // Make sure that the pointer does not point to aggregate types.
4357 const PointerType *PtrTy = cast<PointerType>(Ty);
4358 if (PtrTy->getElementType()->isAggregateType()) {
4359 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
4364 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
4366 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4368 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
4369 << *Ptr << " SCEV: " << *PtrScev << "\n");
4373 // The accesss function must stride over the innermost loop.
4374 if (Lp != AR->getLoop()) {
4375 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
4376 *Ptr << " SCEV: " << *PtrScev << "\n");
4379 // The address calculation must not wrap. Otherwise, a dependence could be
4381 // An inbounds getelementptr that is a AddRec with a unit stride
4382 // cannot wrap per definition. The unit stride requirement is checked later.
4383 // An getelementptr without an inbounds attribute and unit stride would have
4384 // to access the pointer value "0" which is undefined behavior in address
4385 // space 0, therefore we can also vectorize this case.
4386 bool IsInBoundsGEP = isInBoundsGep(Ptr);
4387 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
4388 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
4389 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
4390 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
4391 << *Ptr << " SCEV: " << *PtrScev << "\n");
4395 // Check the step is constant.
4396 const SCEV *Step = AR->getStepRecurrence(*SE);
4398 // Calculate the pointer stride and check if it is consecutive.
4399 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4401 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
4402 " SCEV: " << *PtrScev << "\n");
4406 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
4407 const APInt &APStepVal = C->getValue()->getValue();
4409 // Huge step value - give up.
4410 if (APStepVal.getBitWidth() > 64)
4413 int64_t StepVal = APStepVal.getSExtValue();
4416 int64_t Stride = StepVal / Size;
4417 int64_t Rem = StepVal % Size;
4421 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
4422 // know we can't "wrap around the address space". In case of address space
4423 // zero we know that this won't happen without triggering undefined behavior.
4424 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
4425 Stride != 1 && Stride != -1)
4431 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
4432 unsigned TypeByteSize) {
4433 // If loads occur at a distance that is not a multiple of a feasible vector
4434 // factor store-load forwarding does not take place.
4435 // Positive dependences might cause troubles because vectorizing them might
4436 // prevent store-load forwarding making vectorized code run a lot slower.
4437 // a[i] = a[i-3] ^ a[i-8];
4438 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
4439 // hence on your typical architecture store-load forwarding does not take
4440 // place. Vectorizing in such cases does not make sense.
4441 // Store-load forwarding distance.
4442 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
4443 // Maximum vector factor.
4444 unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
4445 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
4446 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
4448 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
4450 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
4451 MaxVFWithoutSLForwardIssues = (vf >>=1);
4456 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4457 DEBUG(dbgs() << "LV: Distance " << Distance <<
4458 " that could cause a store-load forwarding conflict\n");
4462 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4463 MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4464 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4468 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4469 const MemAccessInfo &B, unsigned BIdx,
4470 ValueToValueMap &Strides) {
4471 assert (AIdx < BIdx && "Must pass arguments in program order");
4473 Value *APtr = A.getPointer();
4474 Value *BPtr = B.getPointer();
4475 bool AIsWrite = A.getInt();
4476 bool BIsWrite = B.getInt();
4478 // Two reads are independent.
4479 if (!AIsWrite && !BIsWrite)
4482 // We cannot check pointers in different address spaces.
4483 if (APtr->getType()->getPointerAddressSpace() !=
4484 BPtr->getType()->getPointerAddressSpace())
4487 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4488 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4490 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4491 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4493 const SCEV *Src = AScev;
4494 const SCEV *Sink = BScev;
4496 // If the induction step is negative we have to invert source and sink of the
4498 if (StrideAPtr < 0) {
4501 std::swap(APtr, BPtr);
4502 std::swap(Src, Sink);
4503 std::swap(AIsWrite, BIsWrite);
4504 std::swap(AIdx, BIdx);
4505 std::swap(StrideAPtr, StrideBPtr);
4508 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4510 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4511 << "(Induction step: " << StrideAPtr << ")\n");
4512 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4513 << *InstMap[BIdx] << ": " << *Dist << "\n");
4515 // Need consecutive accesses. We don't want to vectorize
4516 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4517 // the address space.
4518 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4519 DEBUG(dbgs() << "Non-consecutive pointer access\n");
4523 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4525 DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4526 ShouldRetryWithRuntimeCheck = true;
4530 Type *ATy = APtr->getType()->getPointerElementType();
4531 Type *BTy = BPtr->getType()->getPointerElementType();
4532 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4534 // Negative distances are not plausible dependencies.
4535 const APInt &Val = C->getValue()->getValue();
4536 if (Val.isNegative()) {
4537 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4538 if (IsTrueDataDependence &&
4539 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4543 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4547 // Write to the same location with the same size.
4548 // Could be improved to assert type sizes are the same (i32 == float, etc).
4552 DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4556 assert(Val.isStrictlyPositive() && "Expect a positive value");
4558 // Positive distance bigger than max vectorization factor.
4561 "LV: ReadWrite-Write positive dependency with different types\n");
4565 unsigned Distance = (unsigned) Val.getZExtValue();
4567 // Bail out early if passed-in parameters make vectorization not feasible.
4568 unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4569 unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
4571 // The distance must be bigger than the size needed for a vectorized version
4572 // of the operation and the size of the vectorized operation must not be
4573 // bigger than the currrent maximum size.
4574 if (Distance < 2*TypeByteSize ||
4575 2*TypeByteSize > MaxSafeDepDistBytes ||
4576 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4577 DEBUG(dbgs() << "LV: Failure because of Positive distance "
4578 << Val.getSExtValue() << '\n');
4582 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4583 Distance : MaxSafeDepDistBytes;
4585 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4586 if (IsTrueDataDependence &&
4587 couldPreventStoreLoadForward(Distance, TypeByteSize))
4590 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4591 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4596 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4597 MemAccessInfoSet &CheckDeps,
4598 ValueToValueMap &Strides) {
4600 MaxSafeDepDistBytes = -1U;
4601 while (!CheckDeps.empty()) {
4602 MemAccessInfo CurAccess = *CheckDeps.begin();
4604 // Get the relevant memory access set.
4605 EquivalenceClasses<MemAccessInfo>::iterator I =
4606 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4608 // Check accesses within this set.
4609 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4610 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4612 // Check every access pair.
4614 CheckDeps.erase(*AI);
4615 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
4617 // Check every accessing instruction pair in program order.
4618 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4619 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4620 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4621 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4622 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4624 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4635 bool LoopVectorizationLegality::canVectorizeMemory() {
4637 typedef SmallVector<Value*, 16> ValueVector;
4638 typedef SmallPtrSet<Value*, 16> ValueSet;
4640 // Holds the Load and Store *instructions*.
4644 // Holds all the different accesses in the loop.
4645 unsigned NumReads = 0;
4646 unsigned NumReadWrites = 0;
4648 PtrRtCheck.Pointers.clear();
4649 PtrRtCheck.Need = false;
4651 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4652 MemoryDepChecker DepChecker(SE, DL, TheLoop);
4655 for (Loop::block_iterator bb = TheLoop->block_begin(),
4656 be = TheLoop->block_end(); bb != be; ++bb) {
4658 // Scan the BB and collect legal loads and stores.
4659 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4662 // If this is a load, save it. If this instruction can read from memory
4663 // but is not a load, then we quit. Notice that we don't handle function
4664 // calls that read or write.
4665 if (it->mayReadFromMemory()) {
4666 // Many math library functions read the rounding mode. We will only
4667 // vectorize a loop if it contains known function calls that don't set
4668 // the flag. Therefore, it is safe to ignore this read from memory.
4669 CallInst *Call = dyn_cast<CallInst>(it);
4670 if (Call && getIntrinsicIDForCall(Call, TLI))
4673 LoadInst *Ld = dyn_cast<LoadInst>(it);
4674 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
4675 emitAnalysis(Report(Ld)
4676 << "read with atomic ordering or volatile read");
4677 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4681 Loads.push_back(Ld);
4682 DepChecker.addAccess(Ld);
4686 // Save 'store' instructions. Abort if other instructions write to memory.
4687 if (it->mayWriteToMemory()) {
4688 StoreInst *St = dyn_cast<StoreInst>(it);
4690 emitAnalysis(Report(it) << "instruction cannot be vectorized");
4693 if (!St->isSimple() && !IsAnnotatedParallel) {
4694 emitAnalysis(Report(St)
4695 << "write with atomic ordering or volatile write");
4696 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4700 Stores.push_back(St);
4701 DepChecker.addAccess(St);
4706 // Now we have two lists that hold the loads and the stores.
4707 // Next, we find the pointers that they use.
4709 // Check if we see any stores. If there are no stores, then we don't
4710 // care if the pointers are *restrict*.
4711 if (!Stores.size()) {
4712 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4716 AccessAnalysis::DepCandidates DependentAccesses;
4717 AccessAnalysis Accesses(DL, AA, DependentAccesses);
4719 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4720 // multiple times on the same object. If the ptr is accessed twice, once
4721 // for read and once for write, it will only appear once (on the write
4722 // list). This is okay, since we are going to check for conflicts between
4723 // writes and between reads and writes, but not between reads and reads.
4726 ValueVector::iterator I, IE;
4727 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4728 StoreInst *ST = cast<StoreInst>(*I);
4729 Value* Ptr = ST->getPointerOperand();
4731 if (isUniform(Ptr)) {
4734 << "write to a loop invariant address could not be vectorized");
4735 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4739 // If we did *not* see this pointer before, insert it to the read-write
4740 // list. At this phase it is only a 'write' list.
4741 if (Seen.insert(Ptr)) {
4744 AliasAnalysis::Location Loc = AA->getLocation(ST);
4745 // The TBAA metadata could have a control dependency on the predication
4746 // condition, so we cannot rely on it when determining whether or not we
4747 // need runtime pointer checks.
4748 if (blockNeedsPredication(ST->getParent()))
4749 Loc.AATags.TBAA = nullptr;
4751 Accesses.addStore(Loc);
4755 if (IsAnnotatedParallel) {
4757 << "LV: A loop annotated parallel, ignore memory dependency "
4762 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4763 LoadInst *LD = cast<LoadInst>(*I);
4764 Value* Ptr = LD->getPointerOperand();
4765 // If we did *not* see this pointer before, insert it to the
4766 // read list. If we *did* see it before, then it is already in
4767 // the read-write list. This allows us to vectorize expressions
4768 // such as A[i] += x; Because the address of A[i] is a read-write
4769 // pointer. This only works if the index of A[i] is consecutive.
4770 // If the address of i is unknown (for example A[B[i]]) then we may
4771 // read a few words, modify, and write a few words, and some of the
4772 // words may be written to the same address.
4773 bool IsReadOnlyPtr = false;
4774 if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4776 IsReadOnlyPtr = true;
4779 AliasAnalysis::Location Loc = AA->getLocation(LD);
4780 // The TBAA metadata could have a control dependency on the predication
4781 // condition, so we cannot rely on it when determining whether or not we
4782 // need runtime pointer checks.
4783 if (blockNeedsPredication(LD->getParent()))
4784 Loc.AATags.TBAA = nullptr;
4786 Accesses.addLoad(Loc, IsReadOnlyPtr);
4789 // If we write (or read-write) to a single destination and there are no
4790 // other reads in this loop then is it safe to vectorize.
4791 if (NumReadWrites == 1 && NumReads == 0) {
4792 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4796 // Build dependence sets and check whether we need a runtime pointer bounds
4798 Accesses.buildDependenceSets();
4799 bool NeedRTCheck = Accesses.isRTCheckNeeded();
4801 // Find pointers with computable bounds. We are going to use this information
4802 // to place a runtime bound check.
4803 unsigned NumComparisons = 0;
4804 bool CanDoRT = false;
4806 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4809 DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4810 " pointer comparisons.\n");
4812 // If we only have one set of dependences to check pointers among we don't
4813 // need a runtime check.
4814 if (NumComparisons == 0 && NeedRTCheck)
4815 NeedRTCheck = false;
4817 // Check that we did not collect too many pointers or found an unsizeable
4819 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4825 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4828 if (NeedRTCheck && !CanDoRT) {
4829 emitAnalysis(Report() << "cannot identify array bounds");
4830 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4831 "the array bounds.\n");
4836 PtrRtCheck.Need = NeedRTCheck;
4838 bool CanVecMem = true;
4839 if (Accesses.isDependencyCheckNeeded()) {
4840 DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4841 CanVecMem = DepChecker.areDepsSafe(
4842 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4843 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4845 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4846 DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4849 // Clear the dependency checks. We assume they are not needed.
4850 Accesses.resetDepChecks();
4853 PtrRtCheck.Need = true;
4855 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4856 TheLoop, Strides, true);
4857 // Check that we did not collect too many pointers or found an unsizeable
4859 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4860 if (!CanDoRT && NumComparisons > 0)
4861 emitAnalysis(Report()
4862 << "cannot check memory dependencies at runtime");
4864 emitAnalysis(Report()
4865 << NumComparisons << " exceeds limit of "
4866 << RuntimeMemoryCheckThreshold
4867 << " dependent memory operations checked at runtime");
4868 DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4878 emitAnalysis(Report() << "unsafe dependent memory operations in loop");
4880 DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4881 " need a runtime memory check.\n");
4886 static bool hasMultipleUsesOf(Instruction *I,
4887 SmallPtrSet<Instruction *, 8> &Insts) {
4888 unsigned NumUses = 0;
4889 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
4890 if (Insts.count(dyn_cast<Instruction>(*Use)))
4899 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
4900 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4901 if (!Set.count(dyn_cast<Instruction>(*Use)))
4906 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
4907 ReductionKind Kind) {
4908 if (Phi->getNumIncomingValues() != 2)
4911 // Reduction variables are only found in the loop header block.
4912 if (Phi->getParent() != TheLoop->getHeader())
4915 // Obtain the reduction start value from the value that comes from the loop
4917 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
4919 // ExitInstruction is the single value which is used outside the loop.
4920 // We only allow for a single reduction value to be used outside the loop.
4921 // This includes users of the reduction, variables (which form a cycle
4922 // which ends in the phi node).
4923 Instruction *ExitInstruction = nullptr;
4924 // Indicates that we found a reduction operation in our scan.
4925 bool FoundReduxOp = false;
4927 // We start with the PHI node and scan for all of the users of this
4928 // instruction. All users must be instructions that can be used as reduction
4929 // variables (such as ADD). We must have a single out-of-block user. The cycle
4930 // must include the original PHI.
4931 bool FoundStartPHI = false;
4933 // To recognize min/max patterns formed by a icmp select sequence, we store
4934 // the number of instruction we saw from the recognized min/max pattern,
4935 // to make sure we only see exactly the two instructions.
4936 unsigned NumCmpSelectPatternInst = 0;
4937 ReductionInstDesc ReduxDesc(false, nullptr);
4939 SmallPtrSet<Instruction *, 8> VisitedInsts;
4940 SmallVector<Instruction *, 8> Worklist;
4941 Worklist.push_back(Phi);
4942 VisitedInsts.insert(Phi);
4944 // A value in the reduction can be used:
4945 // - By the reduction:
4946 // - Reduction operation:
4947 // - One use of reduction value (safe).
4948 // - Multiple use of reduction value (not safe).
4950 // - All uses of the PHI must be the reduction (safe).
4951 // - Otherwise, not safe.
4952 // - By one instruction outside of the loop (safe).
4953 // - By further instructions outside of the loop (not safe).
4954 // - By an instruction that is not part of the reduction (not safe).
4956 // * An instruction type other than PHI or the reduction operation.
4957 // * A PHI in the header other than the initial PHI.
4958 while (!Worklist.empty()) {
4959 Instruction *Cur = Worklist.back();
4960 Worklist.pop_back();
4963 // If the instruction has no users then this is a broken chain and can't be
4964 // a reduction variable.
4965 if (Cur->use_empty())
4968 bool IsAPhi = isa<PHINode>(Cur);
4970 // A header PHI use other than the original PHI.
4971 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
4974 // Reductions of instructions such as Div, and Sub is only possible if the
4975 // LHS is the reduction variable.
4976 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
4977 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
4978 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
4981 // Any reduction instruction must be of one of the allowed kinds.
4982 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
4983 if (!ReduxDesc.IsReduction)
4986 // A reduction operation must only have one use of the reduction value.
4987 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
4988 hasMultipleUsesOf(Cur, VisitedInsts))
4991 // All inputs to a PHI node must be a reduction value.
4992 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4995 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4996 isa<SelectInst>(Cur)))
4997 ++NumCmpSelectPatternInst;
4998 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4999 isa<SelectInst>(Cur)))
5000 ++NumCmpSelectPatternInst;
5002 // Check whether we found a reduction operator.
5003 FoundReduxOp |= !IsAPhi;
5005 // Process users of current instruction. Push non-PHI nodes after PHI nodes
5006 // onto the stack. This way we are going to have seen all inputs to PHI
5007 // nodes once we get to them.
5008 SmallVector<Instruction *, 8> NonPHIs;
5009 SmallVector<Instruction *, 8> PHIs;
5010 for (User *U : Cur->users()) {
5011 Instruction *UI = cast<Instruction>(U);
5013 // Check if we found the exit user.
5014 BasicBlock *Parent = UI->getParent();
5015 if (!TheLoop->contains(Parent)) {
5016 // Exit if you find multiple outside users or if the header phi node is
5017 // being used. In this case the user uses the value of the previous
5018 // iteration, in which case we would loose "VF-1" iterations of the
5019 // reduction operation if we vectorize.
5020 if (ExitInstruction != nullptr || Cur == Phi)
5023 // The instruction used by an outside user must be the last instruction
5024 // before we feed back to the reduction phi. Otherwise, we loose VF-1
5025 // operations on the value.
5026 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
5029 ExitInstruction = Cur;
5033 // Process instructions only once (termination). Each reduction cycle
5034 // value must only be used once, except by phi nodes and min/max
5035 // reductions which are represented as a cmp followed by a select.
5036 ReductionInstDesc IgnoredVal(false, nullptr);
5037 if (VisitedInsts.insert(UI)) {
5038 if (isa<PHINode>(UI))
5041 NonPHIs.push_back(UI);
5042 } else if (!isa<PHINode>(UI) &&
5043 ((!isa<FCmpInst>(UI) &&
5044 !isa<ICmpInst>(UI) &&
5045 !isa<SelectInst>(UI)) ||
5046 !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
5049 // Remember that we completed the cycle.
5051 FoundStartPHI = true;
5053 Worklist.append(PHIs.begin(), PHIs.end());
5054 Worklist.append(NonPHIs.begin(), NonPHIs.end());
5057 // This means we have seen one but not the other instruction of the
5058 // pattern or more than just a select and cmp.
5059 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
5060 NumCmpSelectPatternInst != 2)
5063 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
5066 // We found a reduction var if we have reached the original phi node and we
5067 // only have a single instruction with out-of-loop users.
5069 // This instruction is allowed to have out-of-loop users.
5070 AllowedExit.insert(ExitInstruction);
5072 // Save the description of this reduction variable.
5073 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
5074 ReduxDesc.MinMaxKind);
5075 Reductions[Phi] = RD;
5076 // We've ended the cycle. This is a reduction variable if we have an
5077 // outside user and it has a binary op.
5082 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
5083 /// pattern corresponding to a min(X, Y) or max(X, Y).
5084 LoopVectorizationLegality::ReductionInstDesc
5085 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
5086 ReductionInstDesc &Prev) {
5088 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
5089 "Expect a select instruction");
5090 Instruction *Cmp = nullptr;
5091 SelectInst *Select = nullptr;
5093 // We must handle the select(cmp()) as a single instruction. Advance to the
5095 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
5096 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
5097 return ReductionInstDesc(false, I);
5098 return ReductionInstDesc(Select, Prev.MinMaxKind);
5101 // Only handle single use cases for now.
5102 if (!(Select = dyn_cast<SelectInst>(I)))
5103 return ReductionInstDesc(false, I);
5104 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
5105 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
5106 return ReductionInstDesc(false, I);
5107 if (!Cmp->hasOneUse())
5108 return ReductionInstDesc(false, I);
5113 // Look for a min/max pattern.
5114 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5115 return ReductionInstDesc(Select, MRK_UIntMin);
5116 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5117 return ReductionInstDesc(Select, MRK_UIntMax);
5118 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5119 return ReductionInstDesc(Select, MRK_SIntMax);
5120 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5121 return ReductionInstDesc(Select, MRK_SIntMin);
5122 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5123 return ReductionInstDesc(Select, MRK_FloatMin);
5124 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5125 return ReductionInstDesc(Select, MRK_FloatMax);
5126 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5127 return ReductionInstDesc(Select, MRK_FloatMin);
5128 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5129 return ReductionInstDesc(Select, MRK_FloatMax);
5131 return ReductionInstDesc(false, I);
5134 LoopVectorizationLegality::ReductionInstDesc
5135 LoopVectorizationLegality::isReductionInstr(Instruction *I,
5137 ReductionInstDesc &Prev) {
5138 bool FP = I->getType()->isFloatingPointTy();
5139 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
5140 switch (I->getOpcode()) {
5142 return ReductionInstDesc(false, I);
5143 case Instruction::PHI:
5144 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
5145 Kind != RK_FloatMinMax))
5146 return ReductionInstDesc(false, I);
5147 return ReductionInstDesc(I, Prev.MinMaxKind);
5148 case Instruction::Sub:
5149 case Instruction::Add:
5150 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
5151 case Instruction::Mul:
5152 return ReductionInstDesc(Kind == RK_IntegerMult, I);
5153 case Instruction::And:
5154 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
5155 case Instruction::Or:
5156 return ReductionInstDesc(Kind == RK_IntegerOr, I);
5157 case Instruction::Xor:
5158 return ReductionInstDesc(Kind == RK_IntegerXor, I);
5159 case Instruction::FMul:
5160 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
5161 case Instruction::FAdd:
5162 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
5163 case Instruction::FCmp:
5164 case Instruction::ICmp:
5165 case Instruction::Select:
5166 if (Kind != RK_IntegerMinMax &&
5167 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
5168 return ReductionInstDesc(false, I);
5169 return isMinMaxSelectCmpPattern(I, Prev);
5173 LoopVectorizationLegality::InductionKind
5174 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
5175 Type *PhiTy = Phi->getType();
5176 // We only handle integer and pointer inductions variables.
5177 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
5178 return IK_NoInduction;
5180 // Check that the PHI is consecutive.
5181 const SCEV *PhiScev = SE->getSCEV(Phi);
5182 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
5184 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
5185 return IK_NoInduction;
5187 const SCEV *Step = AR->getStepRecurrence(*SE);
5189 // Integer inductions need to have a stride of one.
5190 if (PhiTy->isIntegerTy()) {
5192 return IK_IntInduction;
5193 if (Step->isAllOnesValue())
5194 return IK_ReverseIntInduction;
5195 return IK_NoInduction;
5198 // Calculate the pointer stride and check if it is consecutive.
5199 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5201 return IK_NoInduction;
5203 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
5204 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
5205 if (C->getValue()->equalsInt(Size))
5206 return IK_PtrInduction;
5207 else if (C->getValue()->equalsInt(0 - Size))
5208 return IK_ReversePtrInduction;
5210 return IK_NoInduction;
5213 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
5214 Value *In0 = const_cast<Value*>(V);
5215 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
5219 return Inductions.count(PN);
5222 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
5223 assert(TheLoop->contains(BB) && "Unknown block used");
5225 // Blocks that do not dominate the latch need predication.
5226 BasicBlock* Latch = TheLoop->getLoopLatch();
5227 return !DT->dominates(BB, Latch);
5230 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
5231 SmallPtrSet<Value *, 8>& SafePtrs) {
5232 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5233 // We might be able to hoist the load.
5234 if (it->mayReadFromMemory()) {
5235 LoadInst *LI = dyn_cast<LoadInst>(it);
5236 if (!LI || !SafePtrs.count(LI->getPointerOperand()))
5240 // We don't predicate stores at the moment.
5241 if (it->mayWriteToMemory()) {
5242 StoreInst *SI = dyn_cast<StoreInst>(it);
5243 // We only support predication of stores in basic blocks with one
5245 if (!SI || ++NumPredStores > NumberOfStoresToPredicate ||
5246 !SafePtrs.count(SI->getPointerOperand()) ||
5247 !SI->getParent()->getSinglePredecessor())
5253 // Check that we don't have a constant expression that can trap as operand.
5254 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
5256 if (Constant *C = dyn_cast<Constant>(*OI))
5261 // The instructions below can trap.
5262 switch (it->getOpcode()) {
5264 case Instruction::UDiv:
5265 case Instruction::SDiv:
5266 case Instruction::URem:
5267 case Instruction::SRem:
5275 LoopVectorizationCostModel::VectorizationFactor
5276 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
5277 // Width 1 means no vectorize
5278 VectorizationFactor Factor = { 1U, 0U };
5279 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
5280 emitAnalysis(Report() << "runtime pointer checks needed. Enable vectorization of this loop with '#pragma clang loop vectorize(enable)' when compiling with -Os");
5281 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
5285 if (!EnableCondStoresVectorization && Legal->NumPredStores) {
5286 emitAnalysis(Report() << "store that is conditionally executed prevents vectorization");
5287 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
5291 // Find the trip count.
5292 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
5293 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5295 unsigned WidestType = getWidestType();
5296 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
5297 unsigned MaxSafeDepDist = -1U;
5298 if (Legal->getMaxSafeDepDistBytes() != -1U)
5299 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5300 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
5301 WidestRegister : MaxSafeDepDist);
5302 unsigned MaxVectorSize = WidestRegister / WidestType;
5303 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
5304 DEBUG(dbgs() << "LV: The Widest register is: "
5305 << WidestRegister << " bits.\n");
5307 if (MaxVectorSize == 0) {
5308 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5312 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
5313 " into one vector!");
5315 unsigned VF = MaxVectorSize;
5317 // If we optimize the program for size, avoid creating the tail loop.
5319 // If we are unable to calculate the trip count then don't try to vectorize.
5321 emitAnalysis(Report() << "unable to calculate the loop count due to complex control flow");
5322 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5326 // Find the maximum SIMD width that can fit within the trip count.
5327 VF = TC % MaxVectorSize;
5332 // If the trip count that we found modulo the vectorization factor is not
5333 // zero then we require a tail.
5335 emitAnalysis(Report() << "cannot optimize for size and vectorize at the same time. Enable vectorization of this loop with '#pragma clang loop vectorize(enable)' when compiling with -Os");
5336 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5341 int UserVF = Hints->getWidth();
5343 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
5344 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5346 Factor.Width = UserVF;
5350 float Cost = expectedCost(1);
5352 const float ScalarCost = Cost;
5355 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
5357 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5358 // Ignore scalar width, because the user explicitly wants vectorization.
5359 if (ForceVectorization && VF > 1) {
5361 Cost = expectedCost(Width) / (float)Width;
5364 for (unsigned i=2; i <= VF; i*=2) {
5365 // Notice that the vector loop needs to be executed less times, so
5366 // we need to divide the cost of the vector loops by the width of
5367 // the vector elements.
5368 float VectorCost = expectedCost(i) / (float)i;
5369 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
5370 (int)VectorCost << ".\n");
5371 if (VectorCost < Cost) {
5377 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
5378 << "LV: Vectorization seems to be not beneficial, "
5379 << "but was forced by a user.\n");
5380 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
5381 Factor.Width = Width;
5382 Factor.Cost = Width * Cost;
5386 unsigned LoopVectorizationCostModel::getWidestType() {
5387 unsigned MaxWidth = 8;
5390 for (Loop::block_iterator bb = TheLoop->block_begin(),
5391 be = TheLoop->block_end(); bb != be; ++bb) {
5392 BasicBlock *BB = *bb;
5394 // For each instruction in the loop.
5395 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5396 Type *T = it->getType();
5398 // Only examine Loads, Stores and PHINodes.
5399 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
5402 // Examine PHI nodes that are reduction variables.
5403 if (PHINode *PN = dyn_cast<PHINode>(it))
5404 if (!Legal->getReductionVars()->count(PN))
5407 // Examine the stored values.
5408 if (StoreInst *ST = dyn_cast<StoreInst>(it))
5409 T = ST->getValueOperand()->getType();
5411 // Ignore loaded pointer types and stored pointer types that are not
5412 // consecutive. However, we do want to take consecutive stores/loads of
5413 // pointer vectors into account.
5414 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
5417 MaxWidth = std::max(MaxWidth,
5418 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
5426 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
5428 unsigned LoopCost) {
5430 // -- The unroll heuristics --
5431 // We unroll the loop in order to expose ILP and reduce the loop overhead.
5432 // There are many micro-architectural considerations that we can't predict
5433 // at this level. For example frontend pressure (on decode or fetch) due to
5434 // code size, or the number and capabilities of the execution ports.
5436 // We use the following heuristics to select the unroll factor:
5437 // 1. If the code has reductions the we unroll in order to break the cross
5438 // iteration dependency.
5439 // 2. If the loop is really small then we unroll in order to reduce the loop
5441 // 3. We don't unroll if we think that we will spill registers to memory due
5442 // to the increased register pressure.
5444 // Use the user preference, unless 'auto' is selected.
5445 int UserUF = Hints->getUnroll();
5449 // When we optimize for size we don't unroll.
5453 // We used the distance for the unroll factor.
5454 if (Legal->getMaxSafeDepDistBytes() != -1U)
5457 // Do not unroll loops with a relatively small trip count.
5458 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
5459 TheLoop->getLoopLatch());
5460 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
5463 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5464 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
5468 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5469 TargetNumRegisters = ForceTargetNumScalarRegs;
5471 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5472 TargetNumRegisters = ForceTargetNumVectorRegs;
5475 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
5476 // We divide by these constants so assume that we have at least one
5477 // instruction that uses at least one register.
5478 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5479 R.NumInstructions = std::max(R.NumInstructions, 1U);
5481 // We calculate the unroll factor using the following formula.
5482 // Subtract the number of loop invariants from the number of available
5483 // registers. These registers are used by all of the unrolled instances.
5484 // Next, divide the remaining registers by the number of registers that is
5485 // required by the loop, in order to estimate how many parallel instances
5486 // fit without causing spills. All of this is rounded down if necessary to be
5487 // a power of two. We want power of two unroll factors to simplify any
5488 // addressing operations or alignment considerations.
5489 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5492 // Don't count the induction variable as unrolled.
5493 if (EnableIndVarRegisterHeur)
5494 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
5495 std::max(1U, (R.MaxLocalUsers - 1)));
5497 // Clamp the unroll factor ranges to reasonable factors.
5498 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
5500 // Check if the user has overridden the unroll max.
5502 if (ForceTargetMaxScalarUnrollFactor.getNumOccurrences() > 0)
5503 MaxUnrollSize = ForceTargetMaxScalarUnrollFactor;
5505 if (ForceTargetMaxVectorUnrollFactor.getNumOccurrences() > 0)
5506 MaxUnrollSize = ForceTargetMaxVectorUnrollFactor;
5509 // If we did not calculate the cost for VF (because the user selected the VF)
5510 // then we calculate the cost of VF here.
5512 LoopCost = expectedCost(VF);
5514 // Clamp the calculated UF to be between the 1 and the max unroll factor
5515 // that the target allows.
5516 if (UF > MaxUnrollSize)
5521 // Unroll if we vectorized this loop and there is a reduction that could
5522 // benefit from unrolling.
5523 if (VF > 1 && Legal->getReductionVars()->size()) {
5524 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
5528 // Note that if we've already vectorized the loop we will have done the
5529 // runtime check and so unrolling won't require further checks.
5530 bool UnrollingRequiresRuntimePointerCheck =
5531 (VF == 1 && Legal->getRuntimePointerCheck()->Need);
5533 // We want to unroll small loops in order to reduce the loop overhead and
5534 // potentially expose ILP opportunities.
5535 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5536 if (!UnrollingRequiresRuntimePointerCheck &&
5537 LoopCost < SmallLoopCost) {
5538 // We assume that the cost overhead is 1 and we use the cost model
5539 // to estimate the cost of the loop and unroll until the cost of the
5540 // loop overhead is about 5% of the cost of the loop.
5541 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5543 // Unroll until store/load ports (estimated by max unroll factor) are
5545 unsigned StoresUF = UF / (Legal->NumStores ? Legal->NumStores : 1);
5546 unsigned LoadsUF = UF / (Legal->NumLoads ? Legal->NumLoads : 1);
5548 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
5549 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
5550 return std::max(StoresUF, LoadsUF);
5553 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
5557 DEBUG(dbgs() << "LV: Not Unrolling.\n");
5561 LoopVectorizationCostModel::RegisterUsage
5562 LoopVectorizationCostModel::calculateRegisterUsage() {
5563 // This function calculates the register usage by measuring the highest number
5564 // of values that are alive at a single location. Obviously, this is a very
5565 // rough estimation. We scan the loop in a topological order in order and
5566 // assign a number to each instruction. We use RPO to ensure that defs are
5567 // met before their users. We assume that each instruction that has in-loop
5568 // users starts an interval. We record every time that an in-loop value is
5569 // used, so we have a list of the first and last occurrences of each
5570 // instruction. Next, we transpose this data structure into a multi map that
5571 // holds the list of intervals that *end* at a specific location. This multi
5572 // map allows us to perform a linear search. We scan the instructions linearly
5573 // and record each time that a new interval starts, by placing it in a set.
5574 // If we find this value in the multi-map then we remove it from the set.
5575 // The max register usage is the maximum size of the set.
5576 // We also search for instructions that are defined outside the loop, but are
5577 // used inside the loop. We need this number separately from the max-interval
5578 // usage number because when we unroll, loop-invariant values do not take
5580 LoopBlocksDFS DFS(TheLoop);
5584 R.NumInstructions = 0;
5586 // Each 'key' in the map opens a new interval. The values
5587 // of the map are the index of the 'last seen' usage of the
5588 // instruction that is the key.
5589 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5590 // Maps instruction to its index.
5591 DenseMap<unsigned, Instruction*> IdxToInstr;
5592 // Marks the end of each interval.
5593 IntervalMap EndPoint;
5594 // Saves the list of instruction indices that are used in the loop.
5595 SmallSet<Instruction*, 8> Ends;
5596 // Saves the list of values that are used in the loop but are
5597 // defined outside the loop, such as arguments and constants.
5598 SmallPtrSet<Value*, 8> LoopInvariants;
5601 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5602 be = DFS.endRPO(); bb != be; ++bb) {
5603 R.NumInstructions += (*bb)->size();
5604 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5606 Instruction *I = it;
5607 IdxToInstr[Index++] = I;
5609 // Save the end location of each USE.
5610 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5611 Value *U = I->getOperand(i);
5612 Instruction *Instr = dyn_cast<Instruction>(U);
5614 // Ignore non-instruction values such as arguments, constants, etc.
5615 if (!Instr) continue;
5617 // If this instruction is outside the loop then record it and continue.
5618 if (!TheLoop->contains(Instr)) {
5619 LoopInvariants.insert(Instr);
5623 // Overwrite previous end points.
5624 EndPoint[Instr] = Index;
5630 // Saves the list of intervals that end with the index in 'key'.
5631 typedef SmallVector<Instruction*, 2> InstrList;
5632 DenseMap<unsigned, InstrList> TransposeEnds;
5634 // Transpose the EndPoints to a list of values that end at each index.
5635 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5637 TransposeEnds[it->second].push_back(it->first);
5639 SmallSet<Instruction*, 8> OpenIntervals;
5640 unsigned MaxUsage = 0;
5643 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5644 for (unsigned int i = 0; i < Index; ++i) {
5645 Instruction *I = IdxToInstr[i];
5646 // Ignore instructions that are never used within the loop.
5647 if (!Ends.count(I)) continue;
5649 // Remove all of the instructions that end at this location.
5650 InstrList &List = TransposeEnds[i];
5651 for (unsigned int j=0, e = List.size(); j < e; ++j)
5652 OpenIntervals.erase(List[j]);
5654 // Count the number of live interals.
5655 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5657 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5658 OpenIntervals.size() << '\n');
5660 // Add the current instruction to the list of open intervals.
5661 OpenIntervals.insert(I);
5664 unsigned Invariant = LoopInvariants.size();
5665 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5666 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5667 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5669 R.LoopInvariantRegs = Invariant;
5670 R.MaxLocalUsers = MaxUsage;
5674 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5678 for (Loop::block_iterator bb = TheLoop->block_begin(),
5679 be = TheLoop->block_end(); bb != be; ++bb) {
5680 unsigned BlockCost = 0;
5681 BasicBlock *BB = *bb;
5683 // For each instruction in the old loop.
5684 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5685 // Skip dbg intrinsics.
5686 if (isa<DbgInfoIntrinsic>(it))
5689 unsigned C = getInstructionCost(it, VF);
5691 // Check if we should override the cost.
5692 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5693 C = ForceTargetInstructionCost;
5696 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5697 VF << " For instruction: " << *it << '\n');
5700 // We assume that if-converted blocks have a 50% chance of being executed.
5701 // When the code is scalar then some of the blocks are avoided due to CF.
5702 // When the code is vectorized we execute all code paths.
5703 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5712 /// \brief Check whether the address computation for a non-consecutive memory
5713 /// access looks like an unlikely candidate for being merged into the indexing
5716 /// We look for a GEP which has one index that is an induction variable and all
5717 /// other indices are loop invariant. If the stride of this access is also
5718 /// within a small bound we decide that this address computation can likely be
5719 /// merged into the addressing mode.
5720 /// In all other cases, we identify the address computation as complex.
5721 static bool isLikelyComplexAddressComputation(Value *Ptr,
5722 LoopVectorizationLegality *Legal,
5723 ScalarEvolution *SE,
5724 const Loop *TheLoop) {
5725 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5729 // We are looking for a gep with all loop invariant indices except for one
5730 // which should be an induction variable.
5731 unsigned NumOperands = Gep->getNumOperands();
5732 for (unsigned i = 1; i < NumOperands; ++i) {
5733 Value *Opd = Gep->getOperand(i);
5734 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5735 !Legal->isInductionVariable(Opd))
5739 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5740 // can likely be merged into the address computation.
5741 unsigned MaxMergeDistance = 64;
5743 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5747 // Check the step is constant.
5748 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5749 // Calculate the pointer stride and check if it is consecutive.
5750 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5754 const APInt &APStepVal = C->getValue()->getValue();
5756 // Huge step value - give up.
5757 if (APStepVal.getBitWidth() > 64)
5760 int64_t StepVal = APStepVal.getSExtValue();
5762 return StepVal > MaxMergeDistance;
5765 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5766 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5772 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5773 // If we know that this instruction will remain uniform, check the cost of
5774 // the scalar version.
5775 if (Legal->isUniformAfterVectorization(I))
5778 Type *RetTy = I->getType();
5779 Type *VectorTy = ToVectorTy(RetTy, VF);
5781 // TODO: We need to estimate the cost of intrinsic calls.
5782 switch (I->getOpcode()) {
5783 case Instruction::GetElementPtr:
5784 // We mark this instruction as zero-cost because the cost of GEPs in
5785 // vectorized code depends on whether the corresponding memory instruction
5786 // is scalarized or not. Therefore, we handle GEPs with the memory
5787 // instruction cost.
5789 case Instruction::Br: {
5790 return TTI.getCFInstrCost(I->getOpcode());
5792 case Instruction::PHI:
5793 //TODO: IF-converted IFs become selects.
5795 case Instruction::Add:
5796 case Instruction::FAdd:
5797 case Instruction::Sub:
5798 case Instruction::FSub:
5799 case Instruction::Mul:
5800 case Instruction::FMul:
5801 case Instruction::UDiv:
5802 case Instruction::SDiv:
5803 case Instruction::FDiv:
5804 case Instruction::URem:
5805 case Instruction::SRem:
5806 case Instruction::FRem:
5807 case Instruction::Shl:
5808 case Instruction::LShr:
5809 case Instruction::AShr:
5810 case Instruction::And:
5811 case Instruction::Or:
5812 case Instruction::Xor: {
5813 // Since we will replace the stride by 1 the multiplication should go away.
5814 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5816 // Certain instructions can be cheaper to vectorize if they have a constant
5817 // second vector operand. One example of this are shifts on x86.
5818 TargetTransformInfo::OperandValueKind Op1VK =
5819 TargetTransformInfo::OK_AnyValue;
5820 TargetTransformInfo::OperandValueKind Op2VK =
5821 TargetTransformInfo::OK_AnyValue;
5822 Value *Op2 = I->getOperand(1);
5824 // Check for a splat of a constant or for a non uniform vector of constants.
5825 if (isa<ConstantInt>(Op2))
5826 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5827 else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5828 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5829 if (cast<Constant>(Op2)->getSplatValue() != nullptr)
5830 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5833 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
5835 case Instruction::Select: {
5836 SelectInst *SI = cast<SelectInst>(I);
5837 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5838 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5839 Type *CondTy = SI->getCondition()->getType();
5841 CondTy = VectorType::get(CondTy, VF);
5843 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5845 case Instruction::ICmp:
5846 case Instruction::FCmp: {
5847 Type *ValTy = I->getOperand(0)->getType();
5848 VectorTy = ToVectorTy(ValTy, VF);
5849 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5851 case Instruction::Store:
5852 case Instruction::Load: {
5853 StoreInst *SI = dyn_cast<StoreInst>(I);
5854 LoadInst *LI = dyn_cast<LoadInst>(I);
5855 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5857 VectorTy = ToVectorTy(ValTy, VF);
5859 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5860 unsigned AS = SI ? SI->getPointerAddressSpace() :
5861 LI->getPointerAddressSpace();
5862 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5863 // We add the cost of address computation here instead of with the gep
5864 // instruction because only here we know whether the operation is
5867 return TTI.getAddressComputationCost(VectorTy) +
5868 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5870 // Scalarized loads/stores.
5871 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5872 bool Reverse = ConsecutiveStride < 0;
5873 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
5874 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
5875 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5876 bool IsComplexComputation =
5877 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5879 // The cost of extracting from the value vector and pointer vector.
5880 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5881 for (unsigned i = 0; i < VF; ++i) {
5882 // The cost of extracting the pointer operand.
5883 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5884 // In case of STORE, the cost of ExtractElement from the vector.
5885 // In case of LOAD, the cost of InsertElement into the returned
5887 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5888 Instruction::InsertElement,
5892 // The cost of the scalar loads/stores.
5893 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5894 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5899 // Wide load/stores.
5900 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5901 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5904 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5908 case Instruction::ZExt:
5909 case Instruction::SExt:
5910 case Instruction::FPToUI:
5911 case Instruction::FPToSI:
5912 case Instruction::FPExt:
5913 case Instruction::PtrToInt:
5914 case Instruction::IntToPtr:
5915 case Instruction::SIToFP:
5916 case Instruction::UIToFP:
5917 case Instruction::Trunc:
5918 case Instruction::FPTrunc:
5919 case Instruction::BitCast: {
5920 // We optimize the truncation of induction variable.
5921 // The cost of these is the same as the scalar operation.
5922 if (I->getOpcode() == Instruction::Trunc &&
5923 Legal->isInductionVariable(I->getOperand(0)))
5924 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5925 I->getOperand(0)->getType());
5927 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5928 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5930 case Instruction::Call: {
5931 CallInst *CI = cast<CallInst>(I);
5932 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5933 assert(ID && "Not an intrinsic call!");
5934 Type *RetTy = ToVectorTy(CI->getType(), VF);
5935 SmallVector<Type*, 4> Tys;
5936 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5937 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5938 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5941 // We are scalarizing the instruction. Return the cost of the scalar
5942 // instruction, plus the cost of insert and extract into vector
5943 // elements, times the vector width.
5946 if (!RetTy->isVoidTy() && VF != 1) {
5947 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5949 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5952 // The cost of inserting the results plus extracting each one of the
5954 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5957 // The cost of executing VF copies of the scalar instruction. This opcode
5958 // is unknown. Assume that it is the same as 'mul'.
5959 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5965 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
5966 if (Scalar->isVoidTy() || VF == 1)
5968 return VectorType::get(Scalar, VF);
5971 char LoopVectorize::ID = 0;
5972 static const char lv_name[] = "Loop Vectorization";
5973 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5974 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
5975 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
5976 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5977 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5978 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5979 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5980 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
5981 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5982 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5985 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5986 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5990 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5991 // Check for a store.
5992 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5993 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5995 // Check for a load.
5996 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5997 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
6003 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
6004 bool IfPredicateStore) {
6005 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
6006 // Holds vector parameters or scalars, in case of uniform vals.
6007 SmallVector<VectorParts, 4> Params;
6009 setDebugLocFromInst(Builder, Instr);
6011 // Find all of the vectorized parameters.
6012 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
6013 Value *SrcOp = Instr->getOperand(op);
6015 // If we are accessing the old induction variable, use the new one.
6016 if (SrcOp == OldInduction) {
6017 Params.push_back(getVectorValue(SrcOp));
6021 // Try using previously calculated values.
6022 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
6024 // If the src is an instruction that appeared earlier in the basic block
6025 // then it should already be vectorized.
6026 if (SrcInst && OrigLoop->contains(SrcInst)) {
6027 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
6028 // The parameter is a vector value from earlier.
6029 Params.push_back(WidenMap.get(SrcInst));
6031 // The parameter is a scalar from outside the loop. Maybe even a constant.
6032 VectorParts Scalars;
6033 Scalars.append(UF, SrcOp);
6034 Params.push_back(Scalars);
6038 assert(Params.size() == Instr->getNumOperands() &&
6039 "Invalid number of operands");
6041 // Does this instruction return a value ?
6042 bool IsVoidRetTy = Instr->getType()->isVoidTy();
6044 Value *UndefVec = IsVoidRetTy ? nullptr :
6045 UndefValue::get(Instr->getType());
6046 // Create a new entry in the WidenMap and initialize it to Undef or Null.
6047 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
6049 Instruction *InsertPt = Builder.GetInsertPoint();
6050 BasicBlock *IfBlock = Builder.GetInsertBlock();
6051 BasicBlock *CondBlock = nullptr;
6054 Loop *VectorLp = nullptr;
6055 if (IfPredicateStore) {
6056 assert(Instr->getParent()->getSinglePredecessor() &&
6057 "Only support single predecessor blocks");
6058 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
6059 Instr->getParent());
6060 VectorLp = LI->getLoopFor(IfBlock);
6061 assert(VectorLp && "Must have a loop for this block");
6064 // For each vector unroll 'part':
6065 for (unsigned Part = 0; Part < UF; ++Part) {
6066 // For each scalar that we create:
6068 // Start an "if (pred) a[i] = ..." block.
6069 Value *Cmp = nullptr;
6070 if (IfPredicateStore) {
6071 if (Cond[Part]->getType()->isVectorTy())
6073 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
6074 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
6075 ConstantInt::get(Cond[Part]->getType(), 1));
6076 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
6077 LoopVectorBody.push_back(CondBlock);
6078 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
6079 // Update Builder with newly created basic block.
6080 Builder.SetInsertPoint(InsertPt);
6083 Instruction *Cloned = Instr->clone();
6085 Cloned->setName(Instr->getName() + ".cloned");
6086 // Replace the operands of the cloned instructions with extracted scalars.
6087 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
6088 Value *Op = Params[op][Part];
6089 Cloned->setOperand(op, Op);
6092 // Place the cloned scalar in the new loop.
6093 Builder.Insert(Cloned);
6095 // If the original scalar returns a value we need to place it in a vector
6096 // so that future users will be able to use it.
6098 VecResults[Part] = Cloned;
6101 if (IfPredicateStore) {
6102 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
6103 LoopVectorBody.push_back(NewIfBlock);
6104 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
6105 Builder.SetInsertPoint(InsertPt);
6106 Instruction *OldBr = IfBlock->getTerminator();
6107 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
6108 OldBr->eraseFromParent();
6109 IfBlock = NewIfBlock;
6114 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
6115 StoreInst *SI = dyn_cast<StoreInst>(Instr);
6116 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
6118 return scalarizeInstruction(Instr, IfPredicateStore);
6121 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
6125 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
6129 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
6131 // When unrolling and the VF is 1, we only need to add a simple scalar.
6132 Type *ITy = Val->getType();
6133 assert(!ITy->isVectorTy() && "Val must be a scalar");
6134 Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
6135 return Builder.CreateAdd(Val, C, "induction");