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/BlockFrequencyInfo.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/LoopIterator.h"
60 #include "llvm/Analysis/LoopPass.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/ScalarEvolutionExpander.h"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Analysis/TargetTransformInfo.h"
65 #include "llvm/Analysis/ValueTracking.h"
66 #include "llvm/IR/Constants.h"
67 #include "llvm/IR/DataLayout.h"
68 #include "llvm/IR/DebugInfo.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/DiagnosticInfo.h"
71 #include "llvm/IR/Dominators.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/IRBuilder.h"
74 #include "llvm/IR/Instructions.h"
75 #include "llvm/IR/IntrinsicInst.h"
76 #include "llvm/IR/LLVMContext.h"
77 #include "llvm/IR/Module.h"
78 #include "llvm/IR/PatternMatch.h"
79 #include "llvm/IR/Type.h"
80 #include "llvm/IR/Value.h"
81 #include "llvm/IR/ValueHandle.h"
82 #include "llvm/IR/Verifier.h"
83 #include "llvm/Pass.h"
84 #include "llvm/Support/BranchProbability.h"
85 #include "llvm/Support/CommandLine.h"
86 #include "llvm/Support/Debug.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Scalar.h"
89 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
90 #include "llvm/Transforms/Utils/Local.h"
91 #include "llvm/Transforms/Utils/VectorUtils.h"
97 using namespace llvm::PatternMatch;
99 #define LV_NAME "loop-vectorize"
100 #define DEBUG_TYPE LV_NAME
102 STATISTIC(LoopsVectorized, "Number of loops vectorized");
103 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
105 static cl::opt<unsigned>
106 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
107 cl::desc("Sets the SIMD width. Zero is autoselect."));
109 static cl::opt<unsigned>
110 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
111 cl::desc("Sets the vectorization unroll count. "
112 "Zero is autoselect."));
115 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
116 cl::desc("Enable if-conversion during vectorization."));
118 /// We don't vectorize loops with a known constant trip count below this number.
119 static cl::opt<unsigned>
120 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
122 cl::desc("Don't vectorize loops with a constant "
123 "trip count that is smaller than this "
126 /// This enables versioning on the strides of symbolically striding memory
127 /// accesses in code like the following.
128 /// for (i = 0; i < N; ++i)
129 /// A[i * Stride1] += B[i * Stride2] ...
131 /// Will be roughly translated to
132 /// if (Stride1 == 1 && Stride2 == 1) {
133 /// for (i = 0; i < N; i+=4)
137 static cl::opt<bool> EnableMemAccessVersioning(
138 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
139 cl::desc("Enable symblic stride memory access versioning"));
141 /// We don't unroll loops with a known constant trip count below this number.
142 static const unsigned TinyTripCountUnrollThreshold = 128;
144 /// When performing memory disambiguation checks at runtime do not make more
145 /// than this number of comparisons.
146 static const unsigned RuntimeMemoryCheckThreshold = 8;
148 /// Maximum simd width.
149 static const unsigned MaxVectorWidth = 64;
151 static cl::opt<unsigned> ForceTargetNumScalarRegs(
152 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
153 cl::desc("A flag that overrides the target's number of scalar registers."));
155 static cl::opt<unsigned> ForceTargetNumVectorRegs(
156 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
157 cl::desc("A flag that overrides the target's number of vector registers."));
159 /// Maximum vectorization unroll count.
160 static const unsigned MaxUnrollFactor = 16;
162 static cl::opt<unsigned> ForceTargetMaxScalarUnrollFactor(
163 "force-target-max-scalar-unroll", cl::init(0), cl::Hidden,
164 cl::desc("A flag that overrides the target's max unroll factor for scalar "
167 static cl::opt<unsigned> ForceTargetMaxVectorUnrollFactor(
168 "force-target-max-vector-unroll", cl::init(0), cl::Hidden,
169 cl::desc("A flag that overrides the target's max unroll factor for "
170 "vectorized loops."));
172 static cl::opt<unsigned> ForceTargetInstructionCost(
173 "force-target-instruction-cost", cl::init(0), cl::Hidden,
174 cl::desc("A flag that overrides the target's expected cost for "
175 "an instruction to a single constant value. Mostly "
176 "useful for getting consistent testing."));
178 static cl::opt<unsigned> SmallLoopCost(
179 "small-loop-cost", cl::init(20), cl::Hidden,
180 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
182 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
183 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
184 cl::desc("Enable the use of the block frequency analysis to access PGO "
185 "heuristics minimizing code growth in cold regions and being more "
186 "aggressive in hot regions."));
188 // Runtime unroll loops for load/store throughput.
189 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
190 "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
191 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
193 /// The number of stores in a loop that are allowed to need predication.
194 static cl::opt<unsigned> NumberOfStoresToPredicate(
195 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
196 cl::desc("Max number of stores to be predicated behind an if."));
198 static cl::opt<bool> EnableIndVarRegisterHeur(
199 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
200 cl::desc("Count the induction variable only once when unrolling"));
202 static cl::opt<bool> EnableCondStoresVectorization(
203 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
204 cl::desc("Enable if predication of stores during vectorization."));
208 // Forward declarations.
209 class LoopVectorizationLegality;
210 class LoopVectorizationCostModel;
212 /// Optimization analysis message produced during vectorization. Messages inform
213 /// the user why vectorization did not occur.
216 raw_string_ostream Out;
220 Report(Instruction *I = nullptr) : Out(Message), Instr(I) {
221 Out << "loop not vectorized: ";
224 template <typename A> Report &operator<<(const A &Value) {
229 Instruction *getInstr() { return Instr; }
231 std::string &str() { return Out.str(); }
232 operator Twine() { return Out.str(); }
235 /// InnerLoopVectorizer vectorizes loops which contain only one basic
236 /// block to a specified vectorization factor (VF).
237 /// This class performs the widening of scalars into vectors, or multiple
238 /// scalars. This class also implements the following features:
239 /// * It inserts an epilogue loop for handling loops that don't have iteration
240 /// counts that are known to be a multiple of the vectorization factor.
241 /// * It handles the code generation for reduction variables.
242 /// * Scalarization (implementation using scalars) of un-vectorizable
244 /// InnerLoopVectorizer does not perform any vectorization-legality
245 /// checks, and relies on the caller to check for the different legality
246 /// aspects. The InnerLoopVectorizer relies on the
247 /// LoopVectorizationLegality class to provide information about the induction
248 /// and reduction variables that were found to a given vectorization factor.
249 class InnerLoopVectorizer {
251 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
252 DominatorTree *DT, const DataLayout *DL,
253 const TargetLibraryInfo *TLI, unsigned VecWidth,
254 unsigned UnrollFactor)
255 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
256 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
257 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
260 // Perform the actual loop widening (vectorization).
261 void vectorize(LoopVectorizationLegality *L) {
263 // Create a new empty loop. Unlink the old loop and connect the new one.
265 // Widen each instruction in the old loop to a new one in the new loop.
266 // Use the Legality module to find the induction and reduction variables.
268 // Register the new loop and update the analysis passes.
272 virtual ~InnerLoopVectorizer() {}
275 /// A small list of PHINodes.
276 typedef SmallVector<PHINode*, 4> PhiVector;
277 /// When we unroll loops we have multiple vector values for each scalar.
278 /// This data structure holds the unrolled and vectorized values that
279 /// originated from one scalar instruction.
280 typedef SmallVector<Value*, 2> VectorParts;
282 // When we if-convert we need create edge masks. We have to cache values so
283 // that we don't end up with exponential recursion/IR.
284 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
285 VectorParts> EdgeMaskCache;
287 /// \brief Add code that checks at runtime if the accessed arrays overlap.
289 /// Returns a pair of instructions where the first element is the first
290 /// instruction generated in possibly a sequence of instructions and the
291 /// second value is the final comparator value or NULL if no check is needed.
292 std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
294 /// \brief Add checks for strides that where assumed to be 1.
296 /// Returns the last check instruction and the first check instruction in the
297 /// pair as (first, last).
298 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
300 /// Create an empty loop, based on the loop ranges of the old loop.
301 void createEmptyLoop();
302 /// Copy and widen the instructions from the old loop.
303 virtual void vectorizeLoop();
305 /// \brief The Loop exit block may have single value PHI nodes where the
306 /// incoming value is 'Undef'. While vectorizing we only handled real values
307 /// that were defined inside the loop. Here we fix the 'undef case'.
311 /// A helper function that computes the predicate of the block BB, assuming
312 /// that the header block of the loop is set to True. It returns the *entry*
313 /// mask for the block BB.
314 VectorParts createBlockInMask(BasicBlock *BB);
315 /// A helper function that computes the predicate of the edge between SRC
317 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
319 /// A helper function to vectorize a single BB within the innermost loop.
320 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
322 /// Vectorize a single PHINode in a block. This method handles the induction
323 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
324 /// arbitrary length vectors.
325 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
326 unsigned UF, unsigned VF, PhiVector *PV);
328 /// Insert the new loop to the loop hierarchy and pass manager
329 /// and update the analysis passes.
330 void updateAnalysis();
332 /// This instruction is un-vectorizable. Implement it as a sequence
333 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
334 /// scalarized instruction behind an if block predicated on the control
335 /// dependence of the instruction.
336 virtual void scalarizeInstruction(Instruction *Instr,
337 bool IfPredicateStore=false);
339 /// Vectorize Load and Store instructions,
340 virtual void vectorizeMemoryInstruction(Instruction *Instr);
342 /// Create a broadcast instruction. This method generates a broadcast
343 /// instruction (shuffle) for loop invariant values and for the induction
344 /// value. If this is the induction variable then we extend it to N, N+1, ...
345 /// this is needed because each iteration in the loop corresponds to a SIMD
347 virtual Value *getBroadcastInstrs(Value *V);
349 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
350 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
351 /// The sequence starts at StartIndex.
352 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
354 /// When we go over instructions in the basic block we rely on previous
355 /// values within the current basic block or on loop invariant values.
356 /// When we widen (vectorize) values we place them in the map. If the values
357 /// are not within the map, they have to be loop invariant, so we simply
358 /// broadcast them into a vector.
359 VectorParts &getVectorValue(Value *V);
361 /// Generate a shuffle sequence that will reverse the vector Vec.
362 virtual Value *reverseVector(Value *Vec);
364 /// This is a helper class that holds the vectorizer state. It maps scalar
365 /// instructions to vector instructions. When the code is 'unrolled' then
366 /// then a single scalar value is mapped to multiple vector parts. The parts
367 /// are stored in the VectorPart type.
369 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
371 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
373 /// \return True if 'Key' is saved in the Value Map.
374 bool has(Value *Key) const { return MapStorage.count(Key); }
376 /// Initializes a new entry in the map. Sets all of the vector parts to the
377 /// save value in 'Val'.
378 /// \return A reference to a vector with splat values.
379 VectorParts &splat(Value *Key, Value *Val) {
380 VectorParts &Entry = MapStorage[Key];
381 Entry.assign(UF, Val);
385 ///\return A reference to the value that is stored at 'Key'.
386 VectorParts &get(Value *Key) {
387 VectorParts &Entry = MapStorage[Key];
390 assert(Entry.size() == UF);
395 /// The unroll factor. Each entry in the map stores this number of vector
399 /// Map storage. We use std::map and not DenseMap because insertions to a
400 /// dense map invalidates its iterators.
401 std::map<Value *, VectorParts> MapStorage;
404 /// The original loop.
406 /// Scev analysis to use.
413 const DataLayout *DL;
414 /// Target Library Info.
415 const TargetLibraryInfo *TLI;
417 /// The vectorization SIMD factor to use. Each vector will have this many
422 /// The vectorization unroll factor to use. Each scalar is vectorized to this
423 /// many different vector instructions.
426 /// The builder that we use
429 // --- Vectorization state ---
431 /// The vector-loop preheader.
432 BasicBlock *LoopVectorPreHeader;
433 /// The scalar-loop preheader.
434 BasicBlock *LoopScalarPreHeader;
435 /// Middle Block between the vector and the scalar.
436 BasicBlock *LoopMiddleBlock;
437 ///The ExitBlock of the scalar loop.
438 BasicBlock *LoopExitBlock;
439 ///The vector loop body.
440 SmallVector<BasicBlock *, 4> LoopVectorBody;
441 ///The scalar loop body.
442 BasicBlock *LoopScalarBody;
443 /// A list of all bypass blocks. The first block is the entry of the loop.
444 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
446 /// The new Induction variable which was added to the new block.
448 /// The induction variable of the old basic block.
449 PHINode *OldInduction;
450 /// Holds the extended (to the widest induction type) start index.
452 /// Maps scalars to widened vectors.
454 EdgeMaskCache MaskCache;
456 LoopVectorizationLegality *Legal;
459 class InnerLoopUnroller : public InnerLoopVectorizer {
461 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
462 DominatorTree *DT, const DataLayout *DL,
463 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
464 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
467 void scalarizeInstruction(Instruction *Instr,
468 bool IfPredicateStore = false) override;
469 void vectorizeMemoryInstruction(Instruction *Instr) override;
470 Value *getBroadcastInstrs(Value *V) override;
471 Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate) override;
472 Value *reverseVector(Value *Vec) override;
475 /// \brief Look for a meaningful debug location on the instruction or it's
477 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
482 if (I->getDebugLoc() != Empty)
485 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
486 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
487 if (OpInst->getDebugLoc() != Empty)
494 /// \brief Set the debug location in the builder using the debug location in the
496 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
497 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
498 B.SetCurrentDebugLocation(Inst->getDebugLoc());
500 B.SetCurrentDebugLocation(DebugLoc());
504 /// \return string containing a file name and a line # for the given loop.
505 static std::string getDebugLocString(const Loop *L) {
508 raw_string_ostream OS(Result);
509 const DebugLoc LoopDbgLoc = L->getStartLoc();
510 if (!LoopDbgLoc.isUnknown())
511 LoopDbgLoc.print(L->getHeader()->getContext(), OS);
513 // Just print the module name.
514 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
521 /// \brief Propagate known metadata from one instruction to another.
522 static void propagateMetadata(Instruction *To, const Instruction *From) {
523 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
524 From->getAllMetadataOtherThanDebugLoc(Metadata);
526 for (auto M : Metadata) {
527 unsigned Kind = M.first;
529 // These are safe to transfer (this is safe for TBAA, even when we
530 // if-convert, because should that metadata have had a control dependency
531 // on the condition, and thus actually aliased with some other
532 // non-speculated memory access when the condition was false, this would be
533 // caught by the runtime overlap checks).
534 if (Kind != LLVMContext::MD_tbaa &&
535 Kind != LLVMContext::MD_fpmath)
538 To->setMetadata(Kind, M.second);
542 /// \brief Propagate known metadata from one instruction to a vector of others.
543 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
545 if (Instruction *I = dyn_cast<Instruction>(V))
546 propagateMetadata(I, From);
549 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
550 /// to what vectorization factor.
551 /// This class does not look at the profitability of vectorization, only the
552 /// legality. This class has two main kinds of checks:
553 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
554 /// will change the order of memory accesses in a way that will change the
555 /// correctness of the program.
556 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
557 /// checks for a number of different conditions, such as the availability of a
558 /// single induction variable, that all types are supported and vectorize-able,
559 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
560 /// This class is also used by InnerLoopVectorizer for identifying
561 /// induction variable and the different reduction variables.
562 class LoopVectorizationLegality {
566 unsigned NumPredStores;
568 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
569 DominatorTree *DT, TargetLibraryInfo *TLI,
571 : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
572 DT(DT), TLI(TLI), TheFunction(F), Induction(nullptr),
573 WidestIndTy(nullptr), HasFunNoNaNAttr(false), MaxSafeDepDistBytes(-1U) {
576 /// This enum represents the kinds of reductions that we support.
578 RK_NoReduction, ///< Not a reduction.
579 RK_IntegerAdd, ///< Sum of integers.
580 RK_IntegerMult, ///< Product of integers.
581 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
582 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
583 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
584 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
585 RK_FloatAdd, ///< Sum of floats.
586 RK_FloatMult, ///< Product of floats.
587 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
590 /// This enum represents the kinds of inductions that we support.
592 IK_NoInduction, ///< Not an induction variable.
593 IK_IntInduction, ///< Integer induction variable. Step = 1.
594 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
595 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
596 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
599 // This enum represents the kind of minmax reduction.
600 enum MinMaxReductionKind {
610 /// This struct holds information about reduction variables.
611 struct ReductionDescriptor {
612 ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
613 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
615 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
616 MinMaxReductionKind MK)
617 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
619 // The starting value of the reduction.
620 // It does not have to be zero!
621 TrackingVH<Value> StartValue;
622 // The instruction who's value is used outside the loop.
623 Instruction *LoopExitInstr;
624 // The kind of the reduction.
626 // If this a min/max reduction the kind of reduction.
627 MinMaxReductionKind MinMaxKind;
630 /// This POD struct holds information about a potential reduction operation.
631 struct ReductionInstDesc {
632 ReductionInstDesc(bool IsRedux, Instruction *I) :
633 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
635 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
636 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
638 // Is this instruction a reduction candidate.
640 // The last instruction in a min/max pattern (select of the select(icmp())
641 // pattern), or the current reduction instruction otherwise.
642 Instruction *PatternLastInst;
643 // If this is a min/max pattern the comparison predicate.
644 MinMaxReductionKind MinMaxKind;
647 /// This struct holds information about the memory runtime legality
648 /// check that a group of pointers do not overlap.
649 struct RuntimePointerCheck {
650 RuntimePointerCheck() : Need(false) {}
652 /// Reset the state of the pointer runtime information.
659 DependencySetId.clear();
662 /// Insert a pointer and calculate the start and end SCEVs.
663 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
664 unsigned DepSetId, ValueToValueMap &Strides);
666 /// This flag indicates if we need to add the runtime check.
668 /// Holds the pointers that we need to check.
669 SmallVector<TrackingVH<Value>, 2> Pointers;
670 /// Holds the pointer value at the beginning of the loop.
671 SmallVector<const SCEV*, 2> Starts;
672 /// Holds the pointer value at the end of the loop.
673 SmallVector<const SCEV*, 2> Ends;
674 /// Holds the information if this pointer is used for writing to memory.
675 SmallVector<bool, 2> IsWritePtr;
676 /// Holds the id of the set of pointers that could be dependent because of a
677 /// shared underlying object.
678 SmallVector<unsigned, 2> DependencySetId;
681 /// A struct for saving information about induction variables.
682 struct InductionInfo {
683 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
684 InductionInfo() : StartValue(nullptr), IK(IK_NoInduction) {}
686 TrackingVH<Value> StartValue;
691 /// ReductionList contains the reduction descriptors for all
692 /// of the reductions that were found in the loop.
693 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
695 /// InductionList saves induction variables and maps them to the
696 /// induction descriptor.
697 typedef MapVector<PHINode*, InductionInfo> InductionList;
699 /// Returns true if it is legal to vectorize this loop.
700 /// This does not mean that it is profitable to vectorize this
701 /// loop, only that it is legal to do so.
704 /// Returns the Induction variable.
705 PHINode *getInduction() { return Induction; }
707 /// Returns the reduction variables found in the loop.
708 ReductionList *getReductionVars() { return &Reductions; }
710 /// Returns the induction variables found in the loop.
711 InductionList *getInductionVars() { return &Inductions; }
713 /// Returns the widest induction type.
714 Type *getWidestInductionType() { return WidestIndTy; }
716 /// Returns True if V is an induction variable in this loop.
717 bool isInductionVariable(const Value *V);
719 /// Return true if the block BB needs to be predicated in order for the loop
720 /// to be vectorized.
721 bool blockNeedsPredication(BasicBlock *BB);
723 /// Check if this pointer is consecutive when vectorizing. This happens
724 /// when the last index of the GEP is the induction variable, or that the
725 /// pointer itself is an induction variable.
726 /// This check allows us to vectorize A[idx] into a wide load/store.
728 /// 0 - Stride is unknown or non-consecutive.
729 /// 1 - Address is consecutive.
730 /// -1 - Address is consecutive, and decreasing.
731 int isConsecutivePtr(Value *Ptr);
733 /// Returns true if the value V is uniform within the loop.
734 bool isUniform(Value *V);
736 /// Returns true if this instruction will remain scalar after vectorization.
737 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
739 /// Returns the information that we collected about runtime memory check.
740 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
742 /// This function returns the identity element (or neutral element) for
744 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
746 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
748 bool hasStride(Value *V) { return StrideSet.count(V); }
749 bool mustCheckStrides() { return !StrideSet.empty(); }
750 SmallPtrSet<Value *, 8>::iterator strides_begin() {
751 return StrideSet.begin();
753 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
756 /// Check if a single basic block loop is vectorizable.
757 /// At this point we know that this is a loop with a constant trip count
758 /// and we only need to check individual instructions.
759 bool canVectorizeInstrs();
761 /// When we vectorize loops we may change the order in which
762 /// we read and write from memory. This method checks if it is
763 /// legal to vectorize the code, considering only memory constrains.
764 /// Returns true if the loop is vectorizable
765 bool canVectorizeMemory();
767 /// Return true if we can vectorize this loop using the IF-conversion
769 bool canVectorizeWithIfConvert();
771 /// Collect the variables that need to stay uniform after vectorization.
772 void collectLoopUniforms();
774 /// Return true if all of the instructions in the block can be speculatively
775 /// executed. \p SafePtrs is a list of addresses that are known to be legal
776 /// and we know that we can read from them without segfault.
777 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
779 /// Returns True, if 'Phi' is the kind of reduction variable for type
780 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
781 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
782 /// Returns a struct describing if the instruction 'I' can be a reduction
783 /// variable of type 'Kind'. If the reduction is a min/max pattern of
784 /// select(icmp()) this function advances the instruction pointer 'I' from the
785 /// compare instruction to the select instruction and stores this pointer in
786 /// 'PatternLastInst' member of the returned struct.
787 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
788 ReductionInstDesc &Desc);
789 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
790 /// pattern corresponding to a min(X, Y) or max(X, Y).
791 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
792 ReductionInstDesc &Prev);
793 /// Returns the induction kind of Phi. This function may return NoInduction
794 /// if the PHI is not an induction variable.
795 InductionKind isInductionVariable(PHINode *Phi);
797 /// \brief Collect memory access with loop invariant strides.
799 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
801 void collectStridedAcccess(Value *LoadOrStoreInst);
803 /// Report an analysis message to assist the user in diagnosing loops that are
805 void emitAnalysis(Report &Message) {
806 DebugLoc DL = TheLoop->getStartLoc();
807 if (Instruction *I = Message.getInstr())
808 DL = I->getDebugLoc();
809 emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
810 *TheFunction, DL, Message.str());
813 /// The loop that we evaluate.
817 /// DataLayout analysis.
818 const DataLayout *DL;
821 /// Target Library Info.
822 TargetLibraryInfo *TLI;
824 Function *TheFunction;
826 // --- vectorization state --- //
828 /// Holds the integer induction variable. This is the counter of the
831 /// Holds the reduction variables.
832 ReductionList Reductions;
833 /// Holds all of the induction variables that we found in the loop.
834 /// Notice that inductions don't need to start at zero and that induction
835 /// variables can be pointers.
836 InductionList Inductions;
837 /// Holds the widest induction type encountered.
840 /// Allowed outside users. This holds the reduction
841 /// vars which can be accessed from outside the loop.
842 SmallPtrSet<Value*, 4> AllowedExit;
843 /// This set holds the variables which are known to be uniform after
845 SmallPtrSet<Instruction*, 4> Uniforms;
846 /// We need to check that all of the pointers in this list are disjoint
848 RuntimePointerCheck PtrRtCheck;
849 /// Can we assume the absence of NaNs.
850 bool HasFunNoNaNAttr;
852 unsigned MaxSafeDepDistBytes;
854 ValueToValueMap Strides;
855 SmallPtrSet<Value *, 8> StrideSet;
858 /// LoopVectorizationCostModel - estimates the expected speedups due to
860 /// In many cases vectorization is not profitable. This can happen because of
861 /// a number of reasons. In this class we mainly attempt to predict the
862 /// expected speedup/slowdowns due to the supported instruction set. We use the
863 /// TargetTransformInfo to query the different backends for the cost of
864 /// different operations.
865 class LoopVectorizationCostModel {
867 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
868 LoopVectorizationLegality *Legal,
869 const TargetTransformInfo &TTI,
870 const DataLayout *DL, const TargetLibraryInfo *TLI)
871 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
873 /// Information about vectorization costs
874 struct VectorizationFactor {
875 unsigned Width; // Vector width with best cost
876 unsigned Cost; // Cost of the loop with that width
878 /// \return The most profitable vectorization factor and the cost of that VF.
879 /// This method checks every power of two up to VF. If UserVF is not ZERO
880 /// then this vectorization factor will be selected if vectorization is
882 VectorizationFactor selectVectorizationFactor(bool OptForSize,
884 bool ForceVectorization);
886 /// \return The size (in bits) of the widest type in the code that
887 /// needs to be vectorized. We ignore values that remain scalar such as
888 /// 64 bit loop indices.
889 unsigned getWidestType();
891 /// \return The most profitable unroll factor.
892 /// If UserUF is non-zero then this method finds the best unroll-factor
893 /// based on register pressure and other parameters.
894 /// VF and LoopCost are the selected vectorization factor and the cost of the
896 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
899 /// \brief A struct that represents some properties of the register usage
901 struct RegisterUsage {
902 /// Holds the number of loop invariant values that are used in the loop.
903 unsigned LoopInvariantRegs;
904 /// Holds the maximum number of concurrent live intervals in the loop.
905 unsigned MaxLocalUsers;
906 /// Holds the number of instructions in the loop.
907 unsigned NumInstructions;
910 /// \return information about the register usage of the loop.
911 RegisterUsage calculateRegisterUsage();
914 /// Returns the expected execution cost. The unit of the cost does
915 /// not matter because we use the 'cost' units to compare different
916 /// vector widths. The cost that is returned is *not* normalized by
917 /// the factor width.
918 unsigned expectedCost(unsigned VF);
920 /// Returns the execution time cost of an instruction for a given vector
921 /// width. Vector width of one means scalar.
922 unsigned getInstructionCost(Instruction *I, unsigned VF);
924 /// A helper function for converting Scalar types to vector types.
925 /// If the incoming type is void, we return void. If the VF is 1, we return
927 static Type* ToVectorTy(Type *Scalar, unsigned VF);
929 /// Returns whether the instruction is a load or store and will be a emitted
930 /// as a vector operation.
931 bool isConsecutiveLoadOrStore(Instruction *I);
933 /// The loop that we evaluate.
937 /// Loop Info analysis.
939 /// Vectorization legality.
940 LoopVectorizationLegality *Legal;
941 /// Vector target information.
942 const TargetTransformInfo &TTI;
943 /// Target data layout information.
944 const DataLayout *DL;
945 /// Target Library Info.
946 const TargetLibraryInfo *TLI;
949 /// Utility class for getting and setting loop vectorizer hints in the form
950 /// of loop metadata.
951 class LoopVectorizeHints {
954 FK_Undefined = -1, ///< Not selected.
955 FK_Disabled = 0, ///< Forcing disabled.
956 FK_Enabled = 1, ///< Forcing enabled.
959 LoopVectorizeHints(const Loop *L, bool DisableUnrolling)
960 : Width(VectorizationFactor),
961 Unroll(DisableUnrolling),
963 LoopID(L->getLoopID()) {
965 // force-vector-unroll overrides DisableUnrolling.
966 if (VectorizationUnroll.getNumOccurrences() > 0)
967 Unroll = VectorizationUnroll;
969 DEBUG(if (DisableUnrolling && Unroll == 1) dbgs()
970 << "LV: Unrolling disabled by the pass manager\n");
973 /// Return the loop vectorizer metadata prefix.
974 static StringRef Prefix() { return "llvm.loop.vectorize."; }
976 MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) const {
977 SmallVector<Value*, 2> Vals;
978 Vals.push_back(MDString::get(Context, Name));
979 Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
980 return MDNode::get(Context, Vals);
983 /// Mark the loop L as already vectorized by setting the width to 1.
984 void setAlreadyVectorized(Loop *L) {
985 LLVMContext &Context = L->getHeader()->getContext();
989 // Create a new loop id with one more operand for the already_vectorized
990 // hint. If the loop already has a loop id then copy the existing operands.
991 SmallVector<Value*, 4> Vals(1);
993 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
994 Vals.push_back(LoopID->getOperand(i));
996 Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
997 Vals.push_back(createHint(Context, Twine(Prefix(), "unroll").str(), 1));
999 MDNode *NewLoopID = MDNode::get(Context, Vals);
1000 // Set operand 0 to refer to the loop id itself.
1001 NewLoopID->replaceOperandWith(0, NewLoopID);
1003 L->setLoopID(NewLoopID);
1005 LoopID->replaceAllUsesWith(NewLoopID);
1010 std::string emitRemark() const {
1012 R << "vectorization ";
1014 case LoopVectorizeHints::FK_Disabled:
1015 R << "is explicitly disabled";
1017 case LoopVectorizeHints::FK_Enabled:
1018 R << "is explicitly enabled";
1019 if (Width != 0 && Unroll != 0)
1020 R << " with width " << Width << " and interleave count " << Unroll;
1021 else if (Width != 0)
1022 R << " with width " << Width;
1023 else if (Unroll != 0)
1024 R << " with interleave count " << Unroll;
1026 case LoopVectorizeHints::FK_Undefined:
1027 R << "was not specified";
1033 unsigned getWidth() const { return Width; }
1034 unsigned getUnroll() const { return Unroll; }
1035 enum ForceKind getForce() const { return Force; }
1036 MDNode *getLoopID() const { return LoopID; }
1039 /// Find hints specified in the loop metadata.
1040 void getHints(const Loop *L) {
1044 // First operand should refer to the loop id itself.
1045 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1046 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1048 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1049 const MDString *S = nullptr;
1050 SmallVector<Value*, 4> Args;
1052 // The expected hint is either a MDString or a MDNode with the first
1053 // operand a MDString.
1054 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1055 if (!MD || MD->getNumOperands() == 0)
1057 S = dyn_cast<MDString>(MD->getOperand(0));
1058 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1059 Args.push_back(MD->getOperand(i));
1061 S = dyn_cast<MDString>(LoopID->getOperand(i));
1062 assert(Args.size() == 0 && "too many arguments for MDString");
1068 // Check if the hint starts with the vectorizer prefix.
1069 StringRef Hint = S->getString();
1070 if (!Hint.startswith(Prefix()))
1072 // Remove the prefix.
1073 Hint = Hint.substr(Prefix().size(), StringRef::npos);
1075 if (Args.size() == 1)
1076 getHint(Hint, Args[0]);
1080 // Check string hint with one operand.
1081 void getHint(StringRef Hint, Value *Arg) {
1082 const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
1084 unsigned Val = C->getZExtValue();
1086 if (Hint == "width") {
1087 if (isPowerOf2_32(Val) && Val <= MaxVectorWidth)
1090 DEBUG(dbgs() << "LV: ignoring invalid width hint metadata\n");
1091 } else if (Hint == "unroll") {
1092 if (isPowerOf2_32(Val) && Val <= MaxUnrollFactor)
1095 DEBUG(dbgs() << "LV: ignoring invalid unroll hint metadata\n");
1096 } else if (Hint == "enable") {
1097 if (C->getBitWidth() == 1)
1098 Force = Val == 1 ? LoopVectorizeHints::FK_Enabled
1099 : LoopVectorizeHints::FK_Disabled;
1101 DEBUG(dbgs() << "LV: ignoring invalid enable hint metadata\n");
1103 DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint << '\n');
1107 /// Vectorization width.
1109 /// Vectorization unroll factor.
1111 /// Vectorization forced
1112 enum ForceKind Force;
1117 static void emitMissedWarning(Function *F, Loop *L,
1118 const LoopVectorizeHints &LH) {
1119 emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1120 L->getStartLoc(), LH.emitRemark());
1122 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1123 if (LH.getWidth() != 1)
1124 emitLoopVectorizeWarning(
1125 F->getContext(), *F, L->getStartLoc(),
1126 "failed explicitly specified loop vectorization");
1127 else if (LH.getUnroll() != 1)
1128 emitLoopInterleaveWarning(
1129 F->getContext(), *F, L->getStartLoc(),
1130 "failed explicitly specified loop interleaving");
1134 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1136 return V.push_back(&L);
1138 for (Loop *InnerL : L)
1139 addInnerLoop(*InnerL, V);
1142 /// The LoopVectorize Pass.
1143 struct LoopVectorize : public FunctionPass {
1144 /// Pass identification, replacement for typeid
1147 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1149 DisableUnrolling(NoUnrolling),
1150 AlwaysVectorize(AlwaysVectorize) {
1151 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1154 ScalarEvolution *SE;
1155 const DataLayout *DL;
1157 TargetTransformInfo *TTI;
1159 BlockFrequencyInfo *BFI;
1160 TargetLibraryInfo *TLI;
1161 bool DisableUnrolling;
1162 bool AlwaysVectorize;
1164 BlockFrequency ColdEntryFreq;
1166 bool runOnFunction(Function &F) override {
1167 SE = &getAnalysis<ScalarEvolution>();
1168 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1169 DL = DLP ? &DLP->getDataLayout() : nullptr;
1170 LI = &getAnalysis<LoopInfo>();
1171 TTI = &getAnalysis<TargetTransformInfo>();
1172 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1173 BFI = &getAnalysis<BlockFrequencyInfo>();
1174 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1176 // Compute some weights outside of the loop over the loops. Compute this
1177 // using a BranchProbability to re-use its scaling math.
1178 const BranchProbability ColdProb(1, 5); // 20%
1179 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1181 // If the target claims to have no vector registers don't attempt
1183 if (!TTI->getNumberOfRegisters(true))
1187 DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1188 << ": Missing data layout\n");
1192 // Build up a worklist of inner-loops to vectorize. This is necessary as
1193 // the act of vectorizing or partially unrolling a loop creates new loops
1194 // and can invalidate iterators across the loops.
1195 SmallVector<Loop *, 8> Worklist;
1198 addInnerLoop(*L, Worklist);
1200 LoopsAnalyzed += Worklist.size();
1202 // Now walk the identified inner loops.
1203 bool Changed = false;
1204 while (!Worklist.empty())
1205 Changed |= processLoop(Worklist.pop_back_val());
1207 // Process each loop nest in the function.
1211 bool processLoop(Loop *L) {
1212 assert(L->empty() && "Only process inner loops.");
1215 const std::string DebugLocStr = getDebugLocString(L);
1218 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1219 << L->getHeader()->getParent()->getName() << "\" from "
1220 << DebugLocStr << "\n");
1222 LoopVectorizeHints Hints(L, DisableUnrolling);
1224 DEBUG(dbgs() << "LV: Loop hints:"
1226 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1228 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1230 : "?")) << " width=" << Hints.getWidth()
1231 << " unroll=" << Hints.getUnroll() << "\n");
1233 // Function containing loop
1234 Function *F = L->getHeader()->getParent();
1236 // Looking at the diagnostic output is the only way to determine if a loop
1237 // was vectorized (other than looking at the IR or machine code), so it
1238 // is important to generate an optimization remark for each loop. Most of
1239 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1240 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1241 // less verbose reporting vectorized loops and unvectorized loops that may
1242 // benefit from vectorization, respectively.
1244 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1245 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1246 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1247 L->getStartLoc(), Hints.emitRemark());
1251 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1252 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1253 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1254 L->getStartLoc(), Hints.emitRemark());
1258 if (Hints.getWidth() == 1 && Hints.getUnroll() == 1) {
1259 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1260 emitOptimizationRemarkAnalysis(
1261 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1262 "loop not vectorized: vector width and interleave count are "
1263 "explicitly set to 1");
1267 // Check the loop for a trip count threshold:
1268 // do not vectorize loops with a tiny trip count.
1269 BasicBlock *Latch = L->getLoopLatch();
1270 const unsigned TC = SE->getSmallConstantTripCount(L, Latch);
1271 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1272 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1273 << "This loop is not worth vectorizing.");
1274 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1275 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1277 DEBUG(dbgs() << "\n");
1278 emitOptimizationRemarkAnalysis(
1279 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1280 "vectorization is not beneficial and is not explicitly forced");
1285 // Check if it is legal to vectorize the loop.
1286 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI, F);
1287 if (!LVL.canVectorize()) {
1288 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1289 emitMissedWarning(F, L, Hints);
1293 // Use the cost model.
1294 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
1296 // Check the function attributes to find out if this function should be
1297 // optimized for size.
1298 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1299 F->hasFnAttribute(Attribute::OptimizeForSize);
1301 // Compute the weighted frequency of this loop being executed and see if it
1302 // is less than 20% of the function entry baseline frequency. Note that we
1303 // always have a canonical loop here because we think we *can* vectoriez.
1304 // FIXME: This is hidden behind a flag due to pervasive problems with
1305 // exactly what block frequency models.
1306 if (LoopVectorizeWithBlockFrequency) {
1307 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1308 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1309 LoopEntryFreq < ColdEntryFreq)
1313 // Check the function attributes to see if implicit floats are allowed.a
1314 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1315 // an integer loop and the vector instructions selected are purely integer
1316 // vector instructions?
1317 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1318 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1319 "attribute is used.\n");
1320 emitOptimizationRemarkAnalysis(
1321 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1322 "loop not vectorized due to NoImplicitFloat attribute");
1323 emitMissedWarning(F, L, Hints);
1327 // Select the optimal vectorization factor.
1328 const LoopVectorizationCostModel::VectorizationFactor VF =
1329 CM.selectVectorizationFactor(OptForSize, Hints.getWidth(),
1331 LoopVectorizeHints::FK_Enabled);
1333 // Select the unroll factor.
1335 CM.selectUnrollFactor(OptForSize, Hints.getUnroll(), VF.Width, VF.Cost);
1337 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1338 << DebugLocStr << '\n');
1339 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1341 if (VF.Width == 1) {
1342 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
1345 emitOptimizationRemarkAnalysis(
1346 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1347 "not beneficial to vectorize and user disabled interleaving");
1350 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1352 // Report the unrolling decision.
1353 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1354 Twine("unrolled with interleaving factor " +
1356 " (vectorization not beneficial)"));
1358 // We decided not to vectorize, but we may want to unroll.
1360 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1361 Unroller.vectorize(&LVL);
1363 // If we decided that it is *legal* to vectorize the loop then do it.
1364 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1368 // Report the vectorization decision.
1369 emitOptimizationRemark(
1370 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1371 Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1372 ", unrolling interleave factor: " + Twine(UF) + ")");
1375 // Mark the loop as already vectorized to avoid vectorizing again.
1376 Hints.setAlreadyVectorized(L);
1378 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1382 void getAnalysisUsage(AnalysisUsage &AU) const override {
1383 AU.addRequiredID(LoopSimplifyID);
1384 AU.addRequiredID(LCSSAID);
1385 AU.addRequired<BlockFrequencyInfo>();
1386 AU.addRequired<DominatorTreeWrapperPass>();
1387 AU.addRequired<LoopInfo>();
1388 AU.addRequired<ScalarEvolution>();
1389 AU.addRequired<TargetTransformInfo>();
1390 AU.addPreserved<LoopInfo>();
1391 AU.addPreserved<DominatorTreeWrapperPass>();
1396 } // end anonymous namespace
1398 //===----------------------------------------------------------------------===//
1399 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1400 // LoopVectorizationCostModel.
1401 //===----------------------------------------------------------------------===//
1403 static Value *stripIntegerCast(Value *V) {
1404 if (CastInst *CI = dyn_cast<CastInst>(V))
1405 if (CI->getOperand(0)->getType()->isIntegerTy())
1406 return CI->getOperand(0);
1410 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1412 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1414 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1415 ValueToValueMap &PtrToStride,
1416 Value *Ptr, Value *OrigPtr = nullptr) {
1418 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1420 // If there is an entry in the map return the SCEV of the pointer with the
1421 // symbolic stride replaced by one.
1422 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1423 if (SI != PtrToStride.end()) {
1424 Value *StrideVal = SI->second;
1427 StrideVal = stripIntegerCast(StrideVal);
1429 // Replace symbolic stride by one.
1430 Value *One = ConstantInt::get(StrideVal->getType(), 1);
1431 ValueToValueMap RewriteMap;
1432 RewriteMap[StrideVal] = One;
1435 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1436 DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1441 // Otherwise, just return the SCEV of the original pointer.
1442 return SE->getSCEV(Ptr);
1445 void LoopVectorizationLegality::RuntimePointerCheck::insert(
1446 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
1447 ValueToValueMap &Strides) {
1448 // Get the stride replaced scev.
1449 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1450 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1451 assert(AR && "Invalid addrec expression");
1452 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1453 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1454 Pointers.push_back(Ptr);
1455 Starts.push_back(AR->getStart());
1456 Ends.push_back(ScEnd);
1457 IsWritePtr.push_back(WritePtr);
1458 DependencySetId.push_back(DepSetId);
1461 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1462 // We need to place the broadcast of invariant variables outside the loop.
1463 Instruction *Instr = dyn_cast<Instruction>(V);
1465 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1466 Instr->getParent()) != LoopVectorBody.end());
1467 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1469 // Place the code for broadcasting invariant variables in the new preheader.
1470 IRBuilder<>::InsertPointGuard Guard(Builder);
1472 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1474 // Broadcast the scalar into all locations in the vector.
1475 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1480 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1482 assert(Val->getType()->isVectorTy() && "Must be a vector");
1483 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1484 "Elem must be an integer");
1485 // Create the types.
1486 Type *ITy = Val->getType()->getScalarType();
1487 VectorType *Ty = cast<VectorType>(Val->getType());
1488 int VLen = Ty->getNumElements();
1489 SmallVector<Constant*, 8> Indices;
1491 // Create a vector of consecutive numbers from zero to VF.
1492 for (int i = 0; i < VLen; ++i) {
1493 int64_t Idx = Negate ? (-i) : i;
1494 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1497 // Add the consecutive indices to the vector value.
1498 Constant *Cv = ConstantVector::get(Indices);
1499 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1500 return Builder.CreateAdd(Val, Cv, "induction");
1503 /// \brief Find the operand of the GEP that should be checked for consecutive
1504 /// stores. This ignores trailing indices that have no effect on the final
1506 static unsigned getGEPInductionOperand(const DataLayout *DL,
1507 const GetElementPtrInst *Gep) {
1508 unsigned LastOperand = Gep->getNumOperands() - 1;
1509 unsigned GEPAllocSize = DL->getTypeAllocSize(
1510 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1512 // Walk backwards and try to peel off zeros.
1513 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1514 // Find the type we're currently indexing into.
1515 gep_type_iterator GEPTI = gep_type_begin(Gep);
1516 std::advance(GEPTI, LastOperand - 1);
1518 // If it's a type with the same allocation size as the result of the GEP we
1519 // can peel off the zero index.
1520 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1528 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1529 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1530 // Make sure that the pointer does not point to structs.
1531 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1534 // If this value is a pointer induction variable we know it is consecutive.
1535 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1536 if (Phi && Inductions.count(Phi)) {
1537 InductionInfo II = Inductions[Phi];
1538 if (IK_PtrInduction == II.IK)
1540 else if (IK_ReversePtrInduction == II.IK)
1544 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1548 unsigned NumOperands = Gep->getNumOperands();
1549 Value *GpPtr = Gep->getPointerOperand();
1550 // If this GEP value is a consecutive pointer induction variable and all of
1551 // the indices are constant then we know it is consecutive. We can
1552 Phi = dyn_cast<PHINode>(GpPtr);
1553 if (Phi && Inductions.count(Phi)) {
1555 // Make sure that the pointer does not point to structs.
1556 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1557 if (GepPtrType->getElementType()->isAggregateType())
1560 // Make sure that all of the index operands are loop invariant.
1561 for (unsigned i = 1; i < NumOperands; ++i)
1562 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1565 InductionInfo II = Inductions[Phi];
1566 if (IK_PtrInduction == II.IK)
1568 else if (IK_ReversePtrInduction == II.IK)
1572 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1574 // Check that all of the gep indices are uniform except for our induction
1576 for (unsigned i = 0; i != NumOperands; ++i)
1577 if (i != InductionOperand &&
1578 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1581 // We can emit wide load/stores only if the last non-zero index is the
1582 // induction variable.
1583 const SCEV *Last = nullptr;
1584 if (!Strides.count(Gep))
1585 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1587 // Because of the multiplication by a stride we can have a s/zext cast.
1588 // We are going to replace this stride by 1 so the cast is safe to ignore.
1590 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1591 // %0 = trunc i64 %indvars.iv to i32
1592 // %mul = mul i32 %0, %Stride1
1593 // %idxprom = zext i32 %mul to i64 << Safe cast.
1594 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1596 Last = replaceSymbolicStrideSCEV(SE, Strides,
1597 Gep->getOperand(InductionOperand), Gep);
1598 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1600 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1604 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1605 const SCEV *Step = AR->getStepRecurrence(*SE);
1607 // The memory is consecutive because the last index is consecutive
1608 // and all other indices are loop invariant.
1611 if (Step->isAllOnesValue())
1618 bool LoopVectorizationLegality::isUniform(Value *V) {
1619 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1622 InnerLoopVectorizer::VectorParts&
1623 InnerLoopVectorizer::getVectorValue(Value *V) {
1624 assert(V != Induction && "The new induction variable should not be used.");
1625 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1627 // If we have a stride that is replaced by one, do it here.
1628 if (Legal->hasStride(V))
1629 V = ConstantInt::get(V->getType(), 1);
1631 // If we have this scalar in the map, return it.
1632 if (WidenMap.has(V))
1633 return WidenMap.get(V);
1635 // If this scalar is unknown, assume that it is a constant or that it is
1636 // loop invariant. Broadcast V and save the value for future uses.
1637 Value *B = getBroadcastInstrs(V);
1638 return WidenMap.splat(V, B);
1641 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1642 assert(Vec->getType()->isVectorTy() && "Invalid type");
1643 SmallVector<Constant*, 8> ShuffleMask;
1644 for (unsigned i = 0; i < VF; ++i)
1645 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1647 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1648 ConstantVector::get(ShuffleMask),
1652 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1653 // Attempt to issue a wide load.
1654 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1655 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1657 assert((LI || SI) && "Invalid Load/Store instruction");
1659 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1660 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1661 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1662 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1663 // An alignment of 0 means target abi alignment. We need to use the scalar's
1664 // target abi alignment in such a case.
1666 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1667 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1668 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1669 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1671 if (SI && Legal->blockNeedsPredication(SI->getParent()))
1672 return scalarizeInstruction(Instr, true);
1674 if (ScalarAllocatedSize != VectorElementSize)
1675 return scalarizeInstruction(Instr);
1677 // If the pointer is loop invariant or if it is non-consecutive,
1678 // scalarize the load.
1679 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1680 bool Reverse = ConsecutiveStride < 0;
1681 bool UniformLoad = LI && Legal->isUniform(Ptr);
1682 if (!ConsecutiveStride || UniformLoad)
1683 return scalarizeInstruction(Instr);
1685 Constant *Zero = Builder.getInt32(0);
1686 VectorParts &Entry = WidenMap.get(Instr);
1688 // Handle consecutive loads/stores.
1689 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1690 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1691 setDebugLocFromInst(Builder, Gep);
1692 Value *PtrOperand = Gep->getPointerOperand();
1693 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1694 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1696 // Create the new GEP with the new induction variable.
1697 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1698 Gep2->setOperand(0, FirstBasePtr);
1699 Gep2->setName("gep.indvar.base");
1700 Ptr = Builder.Insert(Gep2);
1702 setDebugLocFromInst(Builder, Gep);
1703 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1704 OrigLoop) && "Base ptr must be invariant");
1706 // The last index does not have to be the induction. It can be
1707 // consecutive and be a function of the index. For example A[I+1];
1708 unsigned NumOperands = Gep->getNumOperands();
1709 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1710 // Create the new GEP with the new induction variable.
1711 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1713 for (unsigned i = 0; i < NumOperands; ++i) {
1714 Value *GepOperand = Gep->getOperand(i);
1715 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1717 // Update last index or loop invariant instruction anchored in loop.
1718 if (i == InductionOperand ||
1719 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1720 assert((i == InductionOperand ||
1721 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1722 "Must be last index or loop invariant");
1724 VectorParts &GEPParts = getVectorValue(GepOperand);
1725 Value *Index = GEPParts[0];
1726 Index = Builder.CreateExtractElement(Index, Zero);
1727 Gep2->setOperand(i, Index);
1728 Gep2->setName("gep.indvar.idx");
1731 Ptr = Builder.Insert(Gep2);
1733 // Use the induction element ptr.
1734 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1735 setDebugLocFromInst(Builder, Ptr);
1736 VectorParts &PtrVal = getVectorValue(Ptr);
1737 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1742 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1743 "We do not allow storing to uniform addresses");
1744 setDebugLocFromInst(Builder, SI);
1745 // We don't want to update the value in the map as it might be used in
1746 // another expression. So don't use a reference type for "StoredVal".
1747 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1749 for (unsigned Part = 0; Part < UF; ++Part) {
1750 // Calculate the pointer for the specific unroll-part.
1751 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1754 // If we store to reverse consecutive memory locations then we need
1755 // to reverse the order of elements in the stored value.
1756 StoredVal[Part] = reverseVector(StoredVal[Part]);
1757 // If the address is consecutive but reversed, then the
1758 // wide store needs to start at the last vector element.
1759 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1760 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1763 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1764 DataTy->getPointerTo(AddressSpace));
1766 Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
1767 propagateMetadata(NewSI, SI);
1773 assert(LI && "Must have a load instruction");
1774 setDebugLocFromInst(Builder, LI);
1775 for (unsigned Part = 0; Part < UF; ++Part) {
1776 // Calculate the pointer for the specific unroll-part.
1777 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
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));
1788 LoadInst *NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
1789 propagateMetadata(NewLI, LI);
1790 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
1794 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1795 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1796 // Holds vector parameters or scalars, in case of uniform vals.
1797 SmallVector<VectorParts, 4> Params;
1799 setDebugLocFromInst(Builder, Instr);
1801 // Find all of the vectorized parameters.
1802 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1803 Value *SrcOp = Instr->getOperand(op);
1805 // If we are accessing the old induction variable, use the new one.
1806 if (SrcOp == OldInduction) {
1807 Params.push_back(getVectorValue(SrcOp));
1811 // Try using previously calculated values.
1812 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1814 // If the src is an instruction that appeared earlier in the basic block
1815 // then it should already be vectorized.
1816 if (SrcInst && OrigLoop->contains(SrcInst)) {
1817 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1818 // The parameter is a vector value from earlier.
1819 Params.push_back(WidenMap.get(SrcInst));
1821 // The parameter is a scalar from outside the loop. Maybe even a constant.
1822 VectorParts Scalars;
1823 Scalars.append(UF, SrcOp);
1824 Params.push_back(Scalars);
1828 assert(Params.size() == Instr->getNumOperands() &&
1829 "Invalid number of operands");
1831 // Does this instruction return a value ?
1832 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1834 Value *UndefVec = IsVoidRetTy ? nullptr :
1835 UndefValue::get(VectorType::get(Instr->getType(), VF));
1836 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1837 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1839 Instruction *InsertPt = Builder.GetInsertPoint();
1840 BasicBlock *IfBlock = Builder.GetInsertBlock();
1841 BasicBlock *CondBlock = nullptr;
1844 Loop *VectorLp = nullptr;
1845 if (IfPredicateStore) {
1846 assert(Instr->getParent()->getSinglePredecessor() &&
1847 "Only support single predecessor blocks");
1848 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1849 Instr->getParent());
1850 VectorLp = LI->getLoopFor(IfBlock);
1851 assert(VectorLp && "Must have a loop for this block");
1854 // For each vector unroll 'part':
1855 for (unsigned Part = 0; Part < UF; ++Part) {
1856 // For each scalar that we create:
1857 for (unsigned Width = 0; Width < VF; ++Width) {
1860 Value *Cmp = nullptr;
1861 if (IfPredicateStore) {
1862 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1863 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1864 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1865 LoopVectorBody.push_back(CondBlock);
1866 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
1867 // Update Builder with newly created basic block.
1868 Builder.SetInsertPoint(InsertPt);
1871 Instruction *Cloned = Instr->clone();
1873 Cloned->setName(Instr->getName() + ".cloned");
1874 // Replace the operands of the cloned instructions with extracted scalars.
1875 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1876 Value *Op = Params[op][Part];
1877 // Param is a vector. Need to extract the right lane.
1878 if (Op->getType()->isVectorTy())
1879 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1880 Cloned->setOperand(op, Op);
1883 // Place the cloned scalar in the new loop.
1884 Builder.Insert(Cloned);
1886 // If the original scalar returns a value we need to place it in a vector
1887 // so that future users will be able to use it.
1889 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1890 Builder.getInt32(Width));
1892 if (IfPredicateStore) {
1893 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1894 LoopVectorBody.push_back(NewIfBlock);
1895 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
1896 Builder.SetInsertPoint(InsertPt);
1897 Instruction *OldBr = IfBlock->getTerminator();
1898 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1899 OldBr->eraseFromParent();
1900 IfBlock = NewIfBlock;
1906 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1910 if (Instruction *I = dyn_cast<Instruction>(V))
1911 return I->getParent() == Loc->getParent() ? I : nullptr;
1915 std::pair<Instruction *, Instruction *>
1916 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1917 Instruction *tnullptr = nullptr;
1918 if (!Legal->mustCheckStrides())
1919 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1921 IRBuilder<> ChkBuilder(Loc);
1924 Value *Check = nullptr;
1925 Instruction *FirstInst = nullptr;
1926 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1927 SE = Legal->strides_end();
1929 Value *Ptr = stripIntegerCast(*SI);
1930 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1932 // Store the first instruction we create.
1933 FirstInst = getFirstInst(FirstInst, C, Loc);
1935 Check = ChkBuilder.CreateOr(Check, C);
1940 // We have to do this trickery because the IRBuilder might fold the check to a
1941 // constant expression in which case there is no Instruction anchored in a
1943 LLVMContext &Ctx = Loc->getContext();
1944 Instruction *TheCheck =
1945 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
1946 ChkBuilder.Insert(TheCheck, "stride.not.one");
1947 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
1949 return std::make_pair(FirstInst, TheCheck);
1952 std::pair<Instruction *, Instruction *>
1953 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
1954 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1955 Legal->getRuntimePointerCheck();
1957 Instruction *tnullptr = nullptr;
1958 if (!PtrRtCheck->Need)
1959 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1961 unsigned NumPointers = PtrRtCheck->Pointers.size();
1962 SmallVector<TrackingVH<Value> , 2> Starts;
1963 SmallVector<TrackingVH<Value> , 2> Ends;
1965 LLVMContext &Ctx = Loc->getContext();
1966 SCEVExpander Exp(*SE, "induction");
1967 Instruction *FirstInst = nullptr;
1969 for (unsigned i = 0; i < NumPointers; ++i) {
1970 Value *Ptr = PtrRtCheck->Pointers[i];
1971 const SCEV *Sc = SE->getSCEV(Ptr);
1973 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1974 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1976 Starts.push_back(Ptr);
1977 Ends.push_back(Ptr);
1979 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
1980 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1982 // Use this type for pointer arithmetic.
1983 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1985 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1986 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1987 Starts.push_back(Start);
1988 Ends.push_back(End);
1992 IRBuilder<> ChkBuilder(Loc);
1993 // Our instructions might fold to a constant.
1994 Value *MemoryRuntimeCheck = nullptr;
1995 for (unsigned i = 0; i < NumPointers; ++i) {
1996 for (unsigned j = i+1; j < NumPointers; ++j) {
1997 // No need to check if two readonly pointers intersect.
1998 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
2001 // Only need to check pointers between two different dependency sets.
2002 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
2005 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
2006 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
2008 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
2009 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
2010 "Trying to bounds check pointers with different address spaces");
2012 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
2013 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
2015 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
2016 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
2017 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
2018 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
2020 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
2021 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
2022 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
2023 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
2024 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
2025 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2026 if (MemoryRuntimeCheck) {
2027 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
2029 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2031 MemoryRuntimeCheck = IsConflict;
2035 // We have to do this trickery because the IRBuilder might fold the check to a
2036 // constant expression in which case there is no Instruction anchored in a
2038 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
2039 ConstantInt::getTrue(Ctx));
2040 ChkBuilder.Insert(Check, "memcheck.conflict");
2041 FirstInst = getFirstInst(FirstInst, Check, Loc);
2042 return std::make_pair(FirstInst, Check);
2045 void InnerLoopVectorizer::createEmptyLoop() {
2047 In this function we generate a new loop. The new loop will contain
2048 the vectorized instructions while the old loop will continue to run the
2051 [ ] <-- Back-edge taken count overflow check.
2054 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2057 || [ ] <-- vector pre header.
2061 || [ ]_| <-- vector loop.
2064 | >[ ] <--- middle-block.
2067 -|- >[ ] <--- new preheader.
2071 | [ ]_| <-- old scalar loop to handle remainder.
2074 >[ ] <-- exit block.
2078 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2079 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
2080 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2081 assert(BypassBlock && "Invalid loop structure");
2082 assert(ExitBlock && "Must have an exit block");
2084 // Some loops have a single integer induction variable, while other loops
2085 // don't. One example is c++ iterators that often have multiple pointer
2086 // induction variables. In the code below we also support a case where we
2087 // don't have a single induction variable.
2088 OldInduction = Legal->getInduction();
2089 Type *IdxTy = Legal->getWidestInductionType();
2091 // Find the loop boundaries.
2092 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2093 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2095 // The exit count might have the type of i64 while the phi is i32. This can
2096 // happen if we have an induction variable that is sign extended before the
2097 // compare. The only way that we get a backedge taken count is that the
2098 // induction variable was signed and as such will not overflow. In such a case
2099 // truncation is legal.
2100 if (ExitCount->getType()->getPrimitiveSizeInBits() >
2101 IdxTy->getPrimitiveSizeInBits())
2102 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2104 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2105 // Get the total trip count from the count by adding 1.
2106 ExitCount = SE->getAddExpr(BackedgeTakeCount,
2107 SE->getConstant(BackedgeTakeCount->getType(), 1));
2109 // Expand the trip count and place the new instructions in the preheader.
2110 // Notice that the pre-header does not change, only the loop body.
2111 SCEVExpander Exp(*SE, "induction");
2113 // We need to test whether the backedge-taken count is uint##_max. Adding one
2114 // to it will cause overflow and an incorrect loop trip count in the vector
2115 // body. In case of overflow we want to directly jump to the scalar remainder
2117 Value *BackedgeCount =
2118 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2119 BypassBlock->getTerminator());
2120 if (BackedgeCount->getType()->isPointerTy())
2121 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2122 "backedge.ptrcnt.to.int",
2123 BypassBlock->getTerminator());
2124 Instruction *CheckBCOverflow =
2125 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2126 Constant::getAllOnesValue(BackedgeCount->getType()),
2127 "backedge.overflow", BypassBlock->getTerminator());
2129 // The loop index does not have to start at Zero. Find the original start
2130 // value from the induction PHI node. If we don't have an induction variable
2131 // then we know that it starts at zero.
2132 Builder.SetInsertPoint(BypassBlock->getTerminator());
2133 Value *StartIdx = ExtendedIdx = OldInduction ?
2134 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2136 ConstantInt::get(IdxTy, 0);
2138 // We need an instruction to anchor the overflow check on. StartIdx needs to
2139 // be defined before the overflow check branch. Because the scalar preheader
2140 // is going to merge the start index and so the overflow branch block needs to
2141 // contain a definition of the start index.
2142 Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
2143 StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
2144 BypassBlock->getTerminator());
2146 // Count holds the overall loop count (N).
2147 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2148 BypassBlock->getTerminator());
2150 LoopBypassBlocks.push_back(BypassBlock);
2152 // Split the single block loop into the two loop structure described above.
2153 BasicBlock *VectorPH =
2154 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2155 BasicBlock *VecBody =
2156 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2157 BasicBlock *MiddleBlock =
2158 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2159 BasicBlock *ScalarPH =
2160 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2162 // Create and register the new vector loop.
2163 Loop* Lp = new Loop();
2164 Loop *ParentLoop = OrigLoop->getParentLoop();
2166 // Insert the new loop into the loop nest and register the new basic blocks
2167 // before calling any utilities such as SCEV that require valid LoopInfo.
2169 ParentLoop->addChildLoop(Lp);
2170 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
2171 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
2172 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
2174 LI->addTopLevelLoop(Lp);
2176 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
2178 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2180 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2182 // Generate the induction variable.
2183 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2184 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2185 // The loop step is equal to the vectorization factor (num of SIMD elements)
2186 // times the unroll factor (num of SIMD instructions).
2187 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2189 // This is the IR builder that we use to add all of the logic for bypassing
2190 // the new vector loop.
2191 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2192 setDebugLocFromInst(BypassBuilder,
2193 getDebugLocFromInstOrOperands(OldInduction));
2195 // We may need to extend the index in case there is a type mismatch.
2196 // We know that the count starts at zero and does not overflow.
2197 if (Count->getType() != IdxTy) {
2198 // The exit count can be of pointer type. Convert it to the correct
2200 if (ExitCount->getType()->isPointerTy())
2201 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2203 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2206 // Add the start index to the loop count to get the new end index.
2207 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2209 // Now we need to generate the expression for N - (N % VF), which is
2210 // the part that the vectorized body will execute.
2211 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2212 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2213 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2214 "end.idx.rnd.down");
2216 // Now, compare the new count to zero. If it is zero skip the vector loop and
2217 // jump to the scalar loop.
2219 BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2221 BasicBlock *LastBypassBlock = BypassBlock;
2223 // Generate code to check that the loops trip count that we computed by adding
2224 // one to the backedge-taken count will not overflow.
2226 auto PastOverflowCheck =
2227 std::next(BasicBlock::iterator(OverflowCheckAnchor));
2228 BasicBlock *CheckBlock =
2229 LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2231 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2232 LoopBypassBlocks.push_back(CheckBlock);
2233 Instruction *OldTerm = LastBypassBlock->getTerminator();
2234 BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2235 OldTerm->eraseFromParent();
2236 LastBypassBlock = CheckBlock;
2239 // Generate the code to check that the strides we assumed to be one are really
2240 // one. We want the new basic block to start at the first instruction in a
2241 // sequence of instructions that form a check.
2242 Instruction *StrideCheck;
2243 Instruction *FirstCheckInst;
2244 std::tie(FirstCheckInst, StrideCheck) =
2245 addStrideCheck(LastBypassBlock->getTerminator());
2247 // Create a new block containing the stride check.
2248 BasicBlock *CheckBlock =
2249 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2251 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2252 LoopBypassBlocks.push_back(CheckBlock);
2254 // Replace the branch into the memory check block with a conditional branch
2255 // for the "few elements case".
2256 Instruction *OldTerm = LastBypassBlock->getTerminator();
2257 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2258 OldTerm->eraseFromParent();
2261 LastBypassBlock = CheckBlock;
2264 // Generate the code that checks in runtime if arrays overlap. We put the
2265 // checks into a separate block to make the more common case of few elements
2267 Instruction *MemRuntimeCheck;
2268 std::tie(FirstCheckInst, MemRuntimeCheck) =
2269 addRuntimeCheck(LastBypassBlock->getTerminator());
2270 if (MemRuntimeCheck) {
2271 // Create a new block containing the memory check.
2272 BasicBlock *CheckBlock =
2273 LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
2275 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2276 LoopBypassBlocks.push_back(CheckBlock);
2278 // Replace the branch into the memory check block with a conditional branch
2279 // for the "few elements case".
2280 Instruction *OldTerm = LastBypassBlock->getTerminator();
2281 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2282 OldTerm->eraseFromParent();
2284 Cmp = MemRuntimeCheck;
2285 LastBypassBlock = CheckBlock;
2288 LastBypassBlock->getTerminator()->eraseFromParent();
2289 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2292 // We are going to resume the execution of the scalar loop.
2293 // Go over all of the induction variables that we found and fix the
2294 // PHIs that are left in the scalar version of the loop.
2295 // The starting values of PHI nodes depend on the counter of the last
2296 // iteration in the vectorized loop.
2297 // If we come from a bypass edge then we need to start from the original
2300 // This variable saves the new starting index for the scalar loop.
2301 PHINode *ResumeIndex = nullptr;
2302 LoopVectorizationLegality::InductionList::iterator I, E;
2303 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2304 // Set builder to point to last bypass block.
2305 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2306 for (I = List->begin(), E = List->end(); I != E; ++I) {
2307 PHINode *OrigPhi = I->first;
2308 LoopVectorizationLegality::InductionInfo II = I->second;
2310 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2311 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2312 MiddleBlock->getTerminator());
2313 // We might have extended the type of the induction variable but we need a
2314 // truncated version for the scalar loop.
2315 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2316 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2317 MiddleBlock->getTerminator()) : nullptr;
2319 // Create phi nodes to merge from the backedge-taken check block.
2320 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2321 ScalarPH->getTerminator());
2322 BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2324 PHINode *BCTruncResumeVal = nullptr;
2325 if (OrigPhi == OldInduction) {
2327 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2328 ScalarPH->getTerminator());
2329 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2332 Value *EndValue = nullptr;
2334 case LoopVectorizationLegality::IK_NoInduction:
2335 llvm_unreachable("Unknown induction");
2336 case LoopVectorizationLegality::IK_IntInduction: {
2337 // Handle the integer induction counter.
2338 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2340 // We have the canonical induction variable.
2341 if (OrigPhi == OldInduction) {
2342 // Create a truncated version of the resume value for the scalar loop,
2343 // we might have promoted the type to a larger width.
2345 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2346 // The new PHI merges the original incoming value, in case of a bypass,
2347 // or the value at the end of the vectorized loop.
2348 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2349 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2350 TruncResumeVal->addIncoming(EndValue, VecBody);
2352 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2354 // We know what the end value is.
2355 EndValue = IdxEndRoundDown;
2356 // We also know which PHI node holds it.
2357 ResumeIndex = ResumeVal;
2361 // Not the canonical induction variable - add the vector loop count to the
2363 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2364 II.StartValue->getType(),
2366 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
2369 case LoopVectorizationLegality::IK_ReverseIntInduction: {
2370 // Convert the CountRoundDown variable to the PHI size.
2371 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2372 II.StartValue->getType(),
2374 // Handle reverse integer induction counter.
2375 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
2378 case LoopVectorizationLegality::IK_PtrInduction: {
2379 // For pointer induction variables, calculate the offset using
2381 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2385 case LoopVectorizationLegality::IK_ReversePtrInduction: {
2386 // The value at the end of the loop for the reverse pointer is calculated
2387 // by creating a GEP with a negative index starting from the start value.
2388 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2389 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2391 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2397 // The new PHI merges the original incoming value, in case of a bypass,
2398 // or the value at the end of the vectorized loop.
2399 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2400 if (OrigPhi == OldInduction)
2401 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2403 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2405 ResumeVal->addIncoming(EndValue, VecBody);
2407 // Fix the scalar body counter (PHI node).
2408 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2410 // The old induction's phi node in the scalar body needs the truncated
2412 if (OrigPhi == OldInduction) {
2413 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2414 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2416 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2417 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2421 // If we are generating a new induction variable then we also need to
2422 // generate the code that calculates the exit value. This value is not
2423 // simply the end of the counter because we may skip the vectorized body
2424 // in case of a runtime check.
2426 assert(!ResumeIndex && "Unexpected resume value found");
2427 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2428 MiddleBlock->getTerminator());
2429 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2430 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2431 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2434 // Make sure that we found the index where scalar loop needs to continue.
2435 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2436 "Invalid resume Index");
2438 // Add a check in the middle block to see if we have completed
2439 // all of the iterations in the first vector loop.
2440 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2441 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2442 ResumeIndex, "cmp.n",
2443 MiddleBlock->getTerminator());
2445 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2446 // Remove the old terminator.
2447 MiddleBlock->getTerminator()->eraseFromParent();
2449 // Create i+1 and fill the PHINode.
2450 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2451 Induction->addIncoming(StartIdx, VectorPH);
2452 Induction->addIncoming(NextIdx, VecBody);
2453 // Create the compare.
2454 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2455 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2457 // Now we have two terminators. Remove the old one from the block.
2458 VecBody->getTerminator()->eraseFromParent();
2460 // Get ready to start creating new instructions into the vectorized body.
2461 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2464 LoopVectorPreHeader = VectorPH;
2465 LoopScalarPreHeader = ScalarPH;
2466 LoopMiddleBlock = MiddleBlock;
2467 LoopExitBlock = ExitBlock;
2468 LoopVectorBody.push_back(VecBody);
2469 LoopScalarBody = OldBasicBlock;
2471 LoopVectorizeHints Hints(Lp, true);
2472 Hints.setAlreadyVectorized(Lp);
2475 /// This function returns the identity element (or neutral element) for
2476 /// the operation K.
2478 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2483 // Adding, Xoring, Oring zero to a number does not change it.
2484 return ConstantInt::get(Tp, 0);
2485 case RK_IntegerMult:
2486 // Multiplying a number by 1 does not change it.
2487 return ConstantInt::get(Tp, 1);
2489 // AND-ing a number with an all-1 value does not change it.
2490 return ConstantInt::get(Tp, -1, true);
2492 // Multiplying a number by 1 does not change it.
2493 return ConstantFP::get(Tp, 1.0L);
2495 // Adding zero to a number does not change it.
2496 return ConstantFP::get(Tp, 0.0L);
2498 llvm_unreachable("Unknown reduction kind");
2502 /// This function translates the reduction kind to an LLVM binary operator.
2504 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2506 case LoopVectorizationLegality::RK_IntegerAdd:
2507 return Instruction::Add;
2508 case LoopVectorizationLegality::RK_IntegerMult:
2509 return Instruction::Mul;
2510 case LoopVectorizationLegality::RK_IntegerOr:
2511 return Instruction::Or;
2512 case LoopVectorizationLegality::RK_IntegerAnd:
2513 return Instruction::And;
2514 case LoopVectorizationLegality::RK_IntegerXor:
2515 return Instruction::Xor;
2516 case LoopVectorizationLegality::RK_FloatMult:
2517 return Instruction::FMul;
2518 case LoopVectorizationLegality::RK_FloatAdd:
2519 return Instruction::FAdd;
2520 case LoopVectorizationLegality::RK_IntegerMinMax:
2521 return Instruction::ICmp;
2522 case LoopVectorizationLegality::RK_FloatMinMax:
2523 return Instruction::FCmp;
2525 llvm_unreachable("Unknown reduction operation");
2529 Value *createMinMaxOp(IRBuilder<> &Builder,
2530 LoopVectorizationLegality::MinMaxReductionKind RK,
2533 CmpInst::Predicate P = CmpInst::ICMP_NE;
2536 llvm_unreachable("Unknown min/max reduction kind");
2537 case LoopVectorizationLegality::MRK_UIntMin:
2538 P = CmpInst::ICMP_ULT;
2540 case LoopVectorizationLegality::MRK_UIntMax:
2541 P = CmpInst::ICMP_UGT;
2543 case LoopVectorizationLegality::MRK_SIntMin:
2544 P = CmpInst::ICMP_SLT;
2546 case LoopVectorizationLegality::MRK_SIntMax:
2547 P = CmpInst::ICMP_SGT;
2549 case LoopVectorizationLegality::MRK_FloatMin:
2550 P = CmpInst::FCMP_OLT;
2552 case LoopVectorizationLegality::MRK_FloatMax:
2553 P = CmpInst::FCMP_OGT;
2558 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2559 RK == LoopVectorizationLegality::MRK_FloatMax)
2560 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2562 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2564 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2569 struct CSEDenseMapInfo {
2570 static bool canHandle(Instruction *I) {
2571 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2572 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2574 static inline Instruction *getEmptyKey() {
2575 return DenseMapInfo<Instruction *>::getEmptyKey();
2577 static inline Instruction *getTombstoneKey() {
2578 return DenseMapInfo<Instruction *>::getTombstoneKey();
2580 static unsigned getHashValue(Instruction *I) {
2581 assert(canHandle(I) && "Unknown instruction!");
2582 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2583 I->value_op_end()));
2585 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2586 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2587 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2589 return LHS->isIdenticalTo(RHS);
2594 /// \brief Check whether this block is a predicated block.
2595 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2596 /// = ...; " blocks. We start with one vectorized basic block. For every
2597 /// conditional block we split this vectorized block. Therefore, every second
2598 /// block will be a predicated one.
2599 static bool isPredicatedBlock(unsigned BlockNum) {
2600 return BlockNum % 2;
2603 ///\brief Perform cse of induction variable instructions.
2604 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2605 // Perform simple cse.
2606 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2607 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2608 BasicBlock *BB = BBs[i];
2609 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2610 Instruction *In = I++;
2612 if (!CSEDenseMapInfo::canHandle(In))
2615 // Check if we can replace this instruction with any of the
2616 // visited instructions.
2617 if (Instruction *V = CSEMap.lookup(In)) {
2618 In->replaceAllUsesWith(V);
2619 In->eraseFromParent();
2622 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2623 // ...;" blocks for predicated stores. Every second block is a predicated
2625 if (isPredicatedBlock(i))
2633 /// \brief Adds a 'fast' flag to floating point operations.
2634 static Value *addFastMathFlag(Value *V) {
2635 if (isa<FPMathOperator>(V)){
2636 FastMathFlags Flags;
2637 Flags.setUnsafeAlgebra();
2638 cast<Instruction>(V)->setFastMathFlags(Flags);
2643 void InnerLoopVectorizer::vectorizeLoop() {
2644 //===------------------------------------------------===//
2646 // Notice: any optimization or new instruction that go
2647 // into the code below should be also be implemented in
2650 //===------------------------------------------------===//
2651 Constant *Zero = Builder.getInt32(0);
2653 // In order to support reduction variables we need to be able to vectorize
2654 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2655 // stages. First, we create a new vector PHI node with no incoming edges.
2656 // We use this value when we vectorize all of the instructions that use the
2657 // PHI. Next, after all of the instructions in the block are complete we
2658 // add the new incoming edges to the PHI. At this point all of the
2659 // instructions in the basic block are vectorized, so we can use them to
2660 // construct the PHI.
2661 PhiVector RdxPHIsToFix;
2663 // Scan the loop in a topological order to ensure that defs are vectorized
2665 LoopBlocksDFS DFS(OrigLoop);
2668 // Vectorize all of the blocks in the original loop.
2669 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2670 be = DFS.endRPO(); bb != be; ++bb)
2671 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2673 // At this point every instruction in the original loop is widened to
2674 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2675 // that we vectorized. The PHI nodes are currently empty because we did
2676 // not want to introduce cycles. Notice that the remaining PHI nodes
2677 // that we need to fix are reduction variables.
2679 // Create the 'reduced' values for each of the induction vars.
2680 // The reduced values are the vector values that we scalarize and combine
2681 // after the loop is finished.
2682 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2684 PHINode *RdxPhi = *it;
2685 assert(RdxPhi && "Unable to recover vectorized PHI");
2687 // Find the reduction variable descriptor.
2688 assert(Legal->getReductionVars()->count(RdxPhi) &&
2689 "Unable to find the reduction variable");
2690 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2691 (*Legal->getReductionVars())[RdxPhi];
2693 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2695 // We need to generate a reduction vector from the incoming scalar.
2696 // To do so, we need to generate the 'identity' vector and override
2697 // one of the elements with the incoming scalar reduction. We need
2698 // to do it in the vector-loop preheader.
2699 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2701 // This is the vector-clone of the value that leaves the loop.
2702 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2703 Type *VecTy = VectorExit[0]->getType();
2705 // Find the reduction identity variable. Zero for addition, or, xor,
2706 // one for multiplication, -1 for And.
2709 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2710 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2711 // MinMax reduction have the start value as their identify.
2713 VectorStart = Identity = RdxDesc.StartValue;
2715 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2720 // Handle other reduction kinds:
2722 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2723 VecTy->getScalarType());
2726 // This vector is the Identity vector where the first element is the
2727 // incoming scalar reduction.
2728 VectorStart = RdxDesc.StartValue;
2730 Identity = ConstantVector::getSplat(VF, Iden);
2732 // This vector is the Identity vector where the first element is the
2733 // incoming scalar reduction.
2734 VectorStart = Builder.CreateInsertElement(Identity,
2735 RdxDesc.StartValue, Zero);
2739 // Fix the vector-loop phi.
2740 // We created the induction variable so we know that the
2741 // preheader is the first entry.
2742 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2744 // Reductions do not have to start at zero. They can start with
2745 // any loop invariant values.
2746 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2747 BasicBlock *Latch = OrigLoop->getLoopLatch();
2748 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2749 VectorParts &Val = getVectorValue(LoopVal);
2750 for (unsigned part = 0; part < UF; ++part) {
2751 // Make sure to add the reduction stat value only to the
2752 // first unroll part.
2753 Value *StartVal = (part == 0) ? VectorStart : Identity;
2754 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2755 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2756 LoopVectorBody.back());
2759 // Before each round, move the insertion point right between
2760 // the PHIs and the values we are going to write.
2761 // This allows us to write both PHINodes and the extractelement
2763 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2765 VectorParts RdxParts;
2766 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2767 for (unsigned part = 0; part < UF; ++part) {
2768 // This PHINode contains the vectorized reduction variable, or
2769 // the initial value vector, if we bypass the vector loop.
2770 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2771 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2772 Value *StartVal = (part == 0) ? VectorStart : Identity;
2773 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2774 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2775 NewPhi->addIncoming(RdxExitVal[part],
2776 LoopVectorBody.back());
2777 RdxParts.push_back(NewPhi);
2780 // Reduce all of the unrolled parts into a single vector.
2781 Value *ReducedPartRdx = RdxParts[0];
2782 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2783 setDebugLocFromInst(Builder, ReducedPartRdx);
2784 for (unsigned part = 1; part < UF; ++part) {
2785 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2786 // Floating point operations had to be 'fast' to enable the reduction.
2787 ReducedPartRdx = addFastMathFlag(
2788 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2789 ReducedPartRdx, "bin.rdx"));
2791 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2792 ReducedPartRdx, RdxParts[part]);
2796 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2797 // and vector ops, reducing the set of values being computed by half each
2799 assert(isPowerOf2_32(VF) &&
2800 "Reduction emission only supported for pow2 vectors!");
2801 Value *TmpVec = ReducedPartRdx;
2802 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2803 for (unsigned i = VF; i != 1; i >>= 1) {
2804 // Move the upper half of the vector to the lower half.
2805 for (unsigned j = 0; j != i/2; ++j)
2806 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2808 // Fill the rest of the mask with undef.
2809 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2810 UndefValue::get(Builder.getInt32Ty()));
2813 Builder.CreateShuffleVector(TmpVec,
2814 UndefValue::get(TmpVec->getType()),
2815 ConstantVector::get(ShuffleMask),
2818 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2819 // Floating point operations had to be 'fast' to enable the reduction.
2820 TmpVec = addFastMathFlag(Builder.CreateBinOp(
2821 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2823 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2826 // The result is in the first element of the vector.
2827 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2828 Builder.getInt32(0));
2831 // Create a phi node that merges control-flow from the backedge-taken check
2832 // block and the middle block.
2833 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2834 LoopScalarPreHeader->getTerminator());
2835 BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
2836 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2838 // Now, we need to fix the users of the reduction variable
2839 // inside and outside of the scalar remainder loop.
2840 // We know that the loop is in LCSSA form. We need to update the
2841 // PHI nodes in the exit blocks.
2842 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2843 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2844 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2845 if (!LCSSAPhi) break;
2847 // All PHINodes need to have a single entry edge, or two if
2848 // we already fixed them.
2849 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2851 // We found our reduction value exit-PHI. Update it with the
2852 // incoming bypass edge.
2853 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2854 // Add an edge coming from the bypass.
2855 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2858 }// end of the LCSSA phi scan.
2860 // Fix the scalar loop reduction variable with the incoming reduction sum
2861 // from the vector body and from the backedge value.
2862 int IncomingEdgeBlockIdx =
2863 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2864 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2865 // Pick the other block.
2866 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2867 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
2868 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2869 }// end of for each redux variable.
2873 // Remove redundant induction instructions.
2874 cse(LoopVectorBody);
2877 void InnerLoopVectorizer::fixLCSSAPHIs() {
2878 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2879 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2880 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2881 if (!LCSSAPhi) break;
2882 if (LCSSAPhi->getNumIncomingValues() == 1)
2883 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2888 InnerLoopVectorizer::VectorParts
2889 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2890 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2893 // Look for cached value.
2894 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2895 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2896 if (ECEntryIt != MaskCache.end())
2897 return ECEntryIt->second;
2899 VectorParts SrcMask = createBlockInMask(Src);
2901 // The terminator has to be a branch inst!
2902 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2903 assert(BI && "Unexpected terminator found");
2905 if (BI->isConditional()) {
2906 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2908 if (BI->getSuccessor(0) != Dst)
2909 for (unsigned part = 0; part < UF; ++part)
2910 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2912 for (unsigned part = 0; part < UF; ++part)
2913 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2915 MaskCache[Edge] = EdgeMask;
2919 MaskCache[Edge] = SrcMask;
2923 InnerLoopVectorizer::VectorParts
2924 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2925 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2927 // Loop incoming mask is all-one.
2928 if (OrigLoop->getHeader() == BB) {
2929 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2930 return getVectorValue(C);
2933 // This is the block mask. We OR all incoming edges, and with zero.
2934 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2935 VectorParts BlockMask = getVectorValue(Zero);
2938 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2939 VectorParts EM = createEdgeMask(*it, BB);
2940 for (unsigned part = 0; part < UF; ++part)
2941 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2947 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2948 InnerLoopVectorizer::VectorParts &Entry,
2949 unsigned UF, unsigned VF, PhiVector *PV) {
2950 PHINode* P = cast<PHINode>(PN);
2951 // Handle reduction variables:
2952 if (Legal->getReductionVars()->count(P)) {
2953 for (unsigned part = 0; part < UF; ++part) {
2954 // This is phase one of vectorizing PHIs.
2955 Type *VecTy = (VF == 1) ? PN->getType() :
2956 VectorType::get(PN->getType(), VF);
2957 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2958 LoopVectorBody.back()-> getFirstInsertionPt());
2964 setDebugLocFromInst(Builder, P);
2965 // Check for PHI nodes that are lowered to vector selects.
2966 if (P->getParent() != OrigLoop->getHeader()) {
2967 // We know that all PHIs in non-header blocks are converted into
2968 // selects, so we don't have to worry about the insertion order and we
2969 // can just use the builder.
2970 // At this point we generate the predication tree. There may be
2971 // duplications since this is a simple recursive scan, but future
2972 // optimizations will clean it up.
2974 unsigned NumIncoming = P->getNumIncomingValues();
2976 // Generate a sequence of selects of the form:
2977 // SELECT(Mask3, In3,
2978 // SELECT(Mask2, In2,
2980 for (unsigned In = 0; In < NumIncoming; In++) {
2981 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2983 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2985 for (unsigned part = 0; part < UF; ++part) {
2986 // We might have single edge PHIs (blocks) - use an identity
2987 // 'select' for the first PHI operand.
2989 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2992 // Select between the current value and the previous incoming edge
2993 // based on the incoming mask.
2994 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2995 Entry[part], "predphi");
3001 // This PHINode must be an induction variable.
3002 // Make sure that we know about it.
3003 assert(Legal->getInductionVars()->count(P) &&
3004 "Not an induction variable");
3006 LoopVectorizationLegality::InductionInfo II =
3007 Legal->getInductionVars()->lookup(P);
3010 case LoopVectorizationLegality::IK_NoInduction:
3011 llvm_unreachable("Unknown induction");
3012 case LoopVectorizationLegality::IK_IntInduction: {
3013 assert(P->getType() == II.StartValue->getType() && "Types must match");
3014 Type *PhiTy = P->getType();
3016 if (P == OldInduction) {
3017 // Handle the canonical induction variable. We might have had to
3019 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
3021 // Handle other induction variables that are now based on the
3023 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
3025 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
3026 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
3029 Broadcasted = getBroadcastInstrs(Broadcasted);
3030 // After broadcasting the induction variable we need to make the vector
3031 // consecutive by adding 0, 1, 2, etc.
3032 for (unsigned part = 0; part < UF; ++part)
3033 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
3036 case LoopVectorizationLegality::IK_ReverseIntInduction:
3037 case LoopVectorizationLegality::IK_PtrInduction:
3038 case LoopVectorizationLegality::IK_ReversePtrInduction:
3039 // Handle reverse integer and pointer inductions.
3040 Value *StartIdx = ExtendedIdx;
3041 // This is the normalized GEP that starts counting at zero.
3042 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
3045 // Handle the reverse integer induction variable case.
3046 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
3047 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
3048 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
3050 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
3053 // This is a new value so do not hoist it out.
3054 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
3055 // After broadcasting the induction variable we need to make the
3056 // vector consecutive by adding ... -3, -2, -1, 0.
3057 for (unsigned part = 0; part < UF; ++part)
3058 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
3063 // Handle the pointer induction variable case.
3064 assert(P->getType()->isPointerTy() && "Unexpected type.");
3066 // Is this a reverse induction ptr or a consecutive induction ptr.
3067 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
3070 // This is the vector of results. Notice that we don't generate
3071 // vector geps because scalar geps result in better code.
3072 for (unsigned part = 0; part < UF; ++part) {
3074 int EltIndex = (part) * (Reverse ? -1 : 1);
3075 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3078 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
3080 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
3082 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
3084 Entry[part] = SclrGep;
3088 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3089 for (unsigned int i = 0; i < VF; ++i) {
3090 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
3091 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3094 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
3096 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
3098 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
3100 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3101 Builder.getInt32(i),
3104 Entry[part] = VecVal;
3110 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3111 // For each instruction in the old loop.
3112 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3113 VectorParts &Entry = WidenMap.get(it);
3114 switch (it->getOpcode()) {
3115 case Instruction::Br:
3116 // Nothing to do for PHIs and BR, since we already took care of the
3117 // loop control flow instructions.
3119 case Instruction::PHI:{
3120 // Vectorize PHINodes.
3121 widenPHIInstruction(it, Entry, UF, VF, PV);
3125 case Instruction::Add:
3126 case Instruction::FAdd:
3127 case Instruction::Sub:
3128 case Instruction::FSub:
3129 case Instruction::Mul:
3130 case Instruction::FMul:
3131 case Instruction::UDiv:
3132 case Instruction::SDiv:
3133 case Instruction::FDiv:
3134 case Instruction::URem:
3135 case Instruction::SRem:
3136 case Instruction::FRem:
3137 case Instruction::Shl:
3138 case Instruction::LShr:
3139 case Instruction::AShr:
3140 case Instruction::And:
3141 case Instruction::Or:
3142 case Instruction::Xor: {
3143 // Just widen binops.
3144 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3145 setDebugLocFromInst(Builder, BinOp);
3146 VectorParts &A = getVectorValue(it->getOperand(0));
3147 VectorParts &B = getVectorValue(it->getOperand(1));
3149 // Use this vector value for all users of the original instruction.
3150 for (unsigned Part = 0; Part < UF; ++Part) {
3151 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3153 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
3154 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
3155 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
3156 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
3157 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
3159 if (VecOp && isa<PossiblyExactOperator>(VecOp))
3160 VecOp->setIsExact(BinOp->isExact());
3162 // Copy the fast-math flags.
3163 if (VecOp && isa<FPMathOperator>(V))
3164 VecOp->setFastMathFlags(it->getFastMathFlags());
3169 propagateMetadata(Entry, it);
3172 case Instruction::Select: {
3174 // If the selector is loop invariant we can create a select
3175 // instruction with a scalar condition. Otherwise, use vector-select.
3176 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3178 setDebugLocFromInst(Builder, it);
3180 // The condition can be loop invariant but still defined inside the
3181 // loop. This means that we can't just use the original 'cond' value.
3182 // We have to take the 'vectorized' value and pick the first lane.
3183 // Instcombine will make this a no-op.
3184 VectorParts &Cond = getVectorValue(it->getOperand(0));
3185 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3186 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3188 Value *ScalarCond = (VF == 1) ? Cond[0] :
3189 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3191 for (unsigned Part = 0; Part < UF; ++Part) {
3192 Entry[Part] = Builder.CreateSelect(
3193 InvariantCond ? ScalarCond : Cond[Part],
3198 propagateMetadata(Entry, it);
3202 case Instruction::ICmp:
3203 case Instruction::FCmp: {
3204 // Widen compares. Generate vector compares.
3205 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3206 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3207 setDebugLocFromInst(Builder, it);
3208 VectorParts &A = getVectorValue(it->getOperand(0));
3209 VectorParts &B = getVectorValue(it->getOperand(1));
3210 for (unsigned Part = 0; Part < UF; ++Part) {
3213 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3215 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3219 propagateMetadata(Entry, it);
3223 case Instruction::Store:
3224 case Instruction::Load:
3225 vectorizeMemoryInstruction(it);
3227 case Instruction::ZExt:
3228 case Instruction::SExt:
3229 case Instruction::FPToUI:
3230 case Instruction::FPToSI:
3231 case Instruction::FPExt:
3232 case Instruction::PtrToInt:
3233 case Instruction::IntToPtr:
3234 case Instruction::SIToFP:
3235 case Instruction::UIToFP:
3236 case Instruction::Trunc:
3237 case Instruction::FPTrunc:
3238 case Instruction::BitCast: {
3239 CastInst *CI = dyn_cast<CastInst>(it);
3240 setDebugLocFromInst(Builder, it);
3241 /// Optimize the special case where the source is the induction
3242 /// variable. Notice that we can only optimize the 'trunc' case
3243 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3244 /// c. other casts depend on pointer size.
3245 if (CI->getOperand(0) == OldInduction &&
3246 it->getOpcode() == Instruction::Trunc) {
3247 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3249 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3250 for (unsigned Part = 0; Part < UF; ++Part)
3251 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
3252 propagateMetadata(Entry, it);
3255 /// Vectorize casts.
3256 Type *DestTy = (VF == 1) ? CI->getType() :
3257 VectorType::get(CI->getType(), VF);
3259 VectorParts &A = getVectorValue(it->getOperand(0));
3260 for (unsigned Part = 0; Part < UF; ++Part)
3261 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3262 propagateMetadata(Entry, it);
3266 case Instruction::Call: {
3267 // Ignore dbg intrinsics.
3268 if (isa<DbgInfoIntrinsic>(it))
3270 setDebugLocFromInst(Builder, it);
3272 Module *M = BB->getParent()->getParent();
3273 CallInst *CI = cast<CallInst>(it);
3274 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3275 assert(ID && "Not an intrinsic call!");
3277 case Intrinsic::lifetime_end:
3278 case Intrinsic::lifetime_start:
3279 scalarizeInstruction(it);
3282 bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
3283 for (unsigned Part = 0; Part < UF; ++Part) {
3284 SmallVector<Value *, 4> Args;
3285 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3286 if (HasScalarOpd && i == 1) {
3287 Args.push_back(CI->getArgOperand(i));
3290 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3291 Args.push_back(Arg[Part]);
3293 Type *Tys[] = {CI->getType()};
3295 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3297 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3298 Entry[Part] = Builder.CreateCall(F, Args);
3301 propagateMetadata(Entry, it);
3308 // All other instructions are unsupported. Scalarize them.
3309 scalarizeInstruction(it);
3312 }// end of for_each instr.
3315 void InnerLoopVectorizer::updateAnalysis() {
3316 // Forget the original basic block.
3317 SE->forgetLoop(OrigLoop);
3319 // Update the dominator tree information.
3320 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3321 "Entry does not dominate exit.");
3323 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3324 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3325 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3327 // Due to if predication of stores we might create a sequence of "if(pred)
3328 // a[i] = ...; " blocks.
3329 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3331 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3332 else if (isPredicatedBlock(i)) {
3333 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3335 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3339 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3340 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3341 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3342 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3344 DEBUG(DT->verifyDomTree());
3347 /// \brief Check whether it is safe to if-convert this phi node.
3349 /// Phi nodes with constant expressions that can trap are not safe to if
3351 static bool canIfConvertPHINodes(BasicBlock *BB) {
3352 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3353 PHINode *Phi = dyn_cast<PHINode>(I);
3356 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3357 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3364 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3365 if (!EnableIfConversion) {
3366 emitAnalysis(Report() << "if-conversion is disabled");
3370 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3372 // A list of pointers that we can safely read and write to.
3373 SmallPtrSet<Value *, 8> SafePointes;
3375 // Collect safe addresses.
3376 for (Loop::block_iterator BI = TheLoop->block_begin(),
3377 BE = TheLoop->block_end(); BI != BE; ++BI) {
3378 BasicBlock *BB = *BI;
3380 if (blockNeedsPredication(BB))
3383 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3384 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3385 SafePointes.insert(LI->getPointerOperand());
3386 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3387 SafePointes.insert(SI->getPointerOperand());
3391 // Collect the blocks that need predication.
3392 BasicBlock *Header = TheLoop->getHeader();
3393 for (Loop::block_iterator BI = TheLoop->block_begin(),
3394 BE = TheLoop->block_end(); BI != BE; ++BI) {
3395 BasicBlock *BB = *BI;
3397 // We don't support switch statements inside loops.
3398 if (!isa<BranchInst>(BB->getTerminator())) {
3399 emitAnalysis(Report(BB->getTerminator())
3400 << "loop contains a switch statement");
3404 // We must be able to predicate all blocks that need to be predicated.
3405 if (blockNeedsPredication(BB)) {
3406 if (!blockCanBePredicated(BB, SafePointes)) {
3407 emitAnalysis(Report(BB->getTerminator())
3408 << "control flow cannot be substituted for a select");
3411 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3412 emitAnalysis(Report(BB->getTerminator())
3413 << "control flow cannot be substituted for a select");
3418 // We can if-convert this loop.
3422 bool LoopVectorizationLegality::canVectorize() {
3423 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3424 // be canonicalized.
3425 if (!TheLoop->getLoopPreheader()) {
3427 Report() << "loop control flow is not understood by vectorizer");
3431 // We can only vectorize innermost loops.
3432 if (TheLoop->getSubLoopsVector().size()) {
3433 emitAnalysis(Report() << "loop is not the innermost loop");
3437 // We must have a single backedge.
3438 if (TheLoop->getNumBackEdges() != 1) {
3440 Report() << "loop control flow is not understood by vectorizer");
3444 // We must have a single exiting block.
3445 if (!TheLoop->getExitingBlock()) {
3447 Report() << "loop control flow is not understood by vectorizer");
3451 // We need to have a loop header.
3452 DEBUG(dbgs() << "LV: Found a loop: " <<
3453 TheLoop->getHeader()->getName() << '\n');
3455 // Check if we can if-convert non-single-bb loops.
3456 unsigned NumBlocks = TheLoop->getNumBlocks();
3457 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3458 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3462 // ScalarEvolution needs to be able to find the exit count.
3463 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3464 if (ExitCount == SE->getCouldNotCompute()) {
3465 emitAnalysis(Report() << "could not determine number of loop iterations");
3466 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3470 // Check if we can vectorize the instructions and CFG in this loop.
3471 if (!canVectorizeInstrs()) {
3472 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3476 // Go over each instruction and look at memory deps.
3477 if (!canVectorizeMemory()) {
3478 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3482 // Collect all of the variables that remain uniform after vectorization.
3483 collectLoopUniforms();
3485 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3486 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3489 // Okay! We can vectorize. At this point we don't have any other mem analysis
3490 // which may limit our maximum vectorization factor, so just return true with
3495 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3496 if (Ty->isPointerTy())
3497 return DL.getIntPtrType(Ty);
3499 // It is possible that char's or short's overflow when we ask for the loop's
3500 // trip count, work around this by changing the type size.
3501 if (Ty->getScalarSizeInBits() < 32)
3502 return Type::getInt32Ty(Ty->getContext());
3507 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3508 Ty0 = convertPointerToIntegerType(DL, Ty0);
3509 Ty1 = convertPointerToIntegerType(DL, Ty1);
3510 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3515 /// \brief Check that the instruction has outside loop users and is not an
3516 /// identified reduction variable.
3517 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3518 SmallPtrSet<Value *, 4> &Reductions) {
3519 // Reduction instructions are allowed to have exit users. All other
3520 // instructions must not have external users.
3521 if (!Reductions.count(Inst))
3522 //Check that all of the users of the loop are inside the BB.
3523 for (User *U : Inst->users()) {
3524 Instruction *UI = cast<Instruction>(U);
3525 // This user may be a reduction exit value.
3526 if (!TheLoop->contains(UI)) {
3527 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3534 bool LoopVectorizationLegality::canVectorizeInstrs() {
3535 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3536 BasicBlock *Header = TheLoop->getHeader();
3538 // Look for the attribute signaling the absence of NaNs.
3539 Function &F = *Header->getParent();
3540 if (F.hasFnAttribute("no-nans-fp-math"))
3541 HasFunNoNaNAttr = F.getAttributes().getAttribute(
3542 AttributeSet::FunctionIndex,
3543 "no-nans-fp-math").getValueAsString() == "true";
3545 // For each block in the loop.
3546 for (Loop::block_iterator bb = TheLoop->block_begin(),
3547 be = TheLoop->block_end(); bb != be; ++bb) {
3549 // Scan the instructions in the block and look for hazards.
3550 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3553 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3554 Type *PhiTy = Phi->getType();
3555 // Check that this PHI type is allowed.
3556 if (!PhiTy->isIntegerTy() &&
3557 !PhiTy->isFloatingPointTy() &&
3558 !PhiTy->isPointerTy()) {
3559 emitAnalysis(Report(it)
3560 << "loop control flow is not understood by vectorizer");
3561 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3565 // If this PHINode is not in the header block, then we know that we
3566 // can convert it to select during if-conversion. No need to check if
3567 // the PHIs in this block are induction or reduction variables.
3568 if (*bb != Header) {
3569 // Check that this instruction has no outside users or is an
3570 // identified reduction value with an outside user.
3571 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3573 emitAnalysis(Report(it) << "value that could not be identified as "
3574 "reduction is used outside the loop");
3578 // We only allow if-converted PHIs with more than two incoming values.
3579 if (Phi->getNumIncomingValues() != 2) {
3580 emitAnalysis(Report(it)
3581 << "control flow not understood by vectorizer");
3582 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3586 // This is the value coming from the preheader.
3587 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3588 // Check if this is an induction variable.
3589 InductionKind IK = isInductionVariable(Phi);
3591 if (IK_NoInduction != IK) {
3592 // Get the widest type.
3594 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3596 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3598 // Int inductions are special because we only allow one IV.
3599 if (IK == IK_IntInduction) {
3600 // Use the phi node with the widest type as induction. Use the last
3601 // one if there are multiple (no good reason for doing this other
3602 // than it is expedient).
3603 if (!Induction || PhiTy == WidestIndTy)
3607 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3608 Inductions[Phi] = InductionInfo(StartValue, IK);
3610 // Until we explicitly handle the case of an induction variable with
3611 // an outside loop user we have to give up vectorizing this loop.
3612 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3613 emitAnalysis(Report(it) << "use of induction value outside of the "
3614 "loop is not handled by vectorizer");
3621 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3622 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3625 if (AddReductionVar(Phi, RK_IntegerMult)) {
3626 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3629 if (AddReductionVar(Phi, RK_IntegerOr)) {
3630 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3633 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3634 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3637 if (AddReductionVar(Phi, RK_IntegerXor)) {
3638 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3641 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3642 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3645 if (AddReductionVar(Phi, RK_FloatMult)) {
3646 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3649 if (AddReductionVar(Phi, RK_FloatAdd)) {
3650 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3653 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3654 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3659 emitAnalysis(Report(it) << "unvectorizable operation");
3660 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3662 }// end of PHI handling
3664 // We still don't handle functions. However, we can ignore dbg intrinsic
3665 // calls and we do handle certain intrinsic and libm functions.
3666 CallInst *CI = dyn_cast<CallInst>(it);
3667 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3668 emitAnalysis(Report(it) << "call instruction cannot be vectorized");
3669 DEBUG(dbgs() << "LV: Found a call site.\n");
3673 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
3674 // second argument is the same (i.e. loop invariant)
3676 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
3677 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
3678 emitAnalysis(Report(it)
3679 << "intrinsic instruction cannot be vectorized");
3680 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
3685 // Check that the instruction return type is vectorizable.
3686 // Also, we can't vectorize extractelement instructions.
3687 if ((!VectorType::isValidElementType(it->getType()) &&
3688 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3689 emitAnalysis(Report(it)
3690 << "instruction return type cannot be vectorized");
3691 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3695 // Check that the stored type is vectorizable.
3696 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3697 Type *T = ST->getValueOperand()->getType();
3698 if (!VectorType::isValidElementType(T)) {
3699 emitAnalysis(Report(ST) << "store instruction cannot be vectorized");
3702 if (EnableMemAccessVersioning)
3703 collectStridedAcccess(ST);
3706 if (EnableMemAccessVersioning)
3707 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3708 collectStridedAcccess(LI);
3710 // Reduction instructions are allowed to have exit users.
3711 // All other instructions must not have external users.
3712 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3713 emitAnalysis(Report(it) << "value cannot be used outside the loop");
3722 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3723 if (Inductions.empty()) {
3724 emitAnalysis(Report()
3725 << "loop induction variable could not be identified");
3733 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3734 /// return the induction operand of the gep pointer.
3735 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3736 const DataLayout *DL, Loop *Lp) {
3737 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3741 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3743 // Check that all of the gep indices are uniform except for our induction
3745 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3746 if (i != InductionOperand &&
3747 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3749 return GEP->getOperand(InductionOperand);
3752 ///\brief Look for a cast use of the passed value.
3753 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3754 Value *UniqueCast = nullptr;
3755 for (User *U : Ptr->users()) {
3756 CastInst *CI = dyn_cast<CastInst>(U);
3757 if (CI && CI->getType() == Ty) {
3767 ///\brief Get the stride of a pointer access in a loop.
3768 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3769 /// pointer to the Value, or null otherwise.
3770 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3771 const DataLayout *DL, Loop *Lp) {
3772 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3773 if (!PtrTy || PtrTy->isAggregateType())
3776 // Try to remove a gep instruction to make the pointer (actually index at this
3777 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3778 // pointer, otherwise, we are analyzing the index.
3779 Value *OrigPtr = Ptr;
3781 // The size of the pointer access.
3782 int64_t PtrAccessSize = 1;
3784 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3785 const SCEV *V = SE->getSCEV(Ptr);
3789 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3790 V = C->getOperand();
3792 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3796 V = S->getStepRecurrence(*SE);
3800 // Strip off the size of access multiplication if we are still analyzing the
3802 if (OrigPtr == Ptr) {
3803 DL->getTypeAllocSize(PtrTy->getElementType());
3804 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3805 if (M->getOperand(0)->getSCEVType() != scConstant)
3808 const APInt &APStepVal =
3809 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3811 // Huge step value - give up.
3812 if (APStepVal.getBitWidth() > 64)
3815 int64_t StepVal = APStepVal.getSExtValue();
3816 if (PtrAccessSize != StepVal)
3818 V = M->getOperand(1);
3823 Type *StripedOffRecurrenceCast = nullptr;
3824 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3825 StripedOffRecurrenceCast = C->getType();
3826 V = C->getOperand();
3829 // Look for the loop invariant symbolic value.
3830 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3834 Value *Stride = U->getValue();
3835 if (!Lp->isLoopInvariant(Stride))
3838 // If we have stripped off the recurrence cast we have to make sure that we
3839 // return the value that is used in this loop so that we can replace it later.
3840 if (StripedOffRecurrenceCast)
3841 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3846 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
3847 Value *Ptr = nullptr;
3848 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3849 Ptr = LI->getPointerOperand();
3850 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3851 Ptr = SI->getPointerOperand();
3855 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3859 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3860 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3861 Strides[Ptr] = Stride;
3862 StrideSet.insert(Stride);
3865 void LoopVectorizationLegality::collectLoopUniforms() {
3866 // We now know that the loop is vectorizable!
3867 // Collect variables that will remain uniform after vectorization.
3868 std::vector<Value*> Worklist;
3869 BasicBlock *Latch = TheLoop->getLoopLatch();
3871 // Start with the conditional branch and walk up the block.
3872 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3874 // Also add all consecutive pointer values; these values will be uniform
3875 // after vectorization (and subsequent cleanup) and, until revectorization is
3876 // supported, all dependencies must also be uniform.
3877 for (Loop::block_iterator B = TheLoop->block_begin(),
3878 BE = TheLoop->block_end(); B != BE; ++B)
3879 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3881 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3882 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3884 while (Worklist.size()) {
3885 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3886 Worklist.pop_back();
3888 // Look at instructions inside this loop.
3889 // Stop when reaching PHI nodes.
3890 // TODO: we need to follow values all over the loop, not only in this block.
3891 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3894 // This is a known uniform.
3897 // Insert all operands.
3898 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3903 /// \brief Analyses memory accesses in a loop.
3905 /// Checks whether run time pointer checks are needed and builds sets for data
3906 /// dependence checking.
3907 class AccessAnalysis {
3909 /// \brief Read or write access location.
3910 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3911 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3913 /// \brief Set of potential dependent memory accesses.
3914 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
3916 AccessAnalysis(const DataLayout *Dl, DepCandidates &DA) :
3917 DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
3918 AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
3920 /// \brief Register a load and whether it is only read from.
3921 void addLoad(Value *Ptr, bool IsReadOnly) {
3922 Accesses.insert(MemAccessInfo(Ptr, false));
3924 ReadOnlyPtr.insert(Ptr);
3927 /// \brief Register a store.
3928 void addStore(Value *Ptr) {
3929 Accesses.insert(MemAccessInfo(Ptr, true));
3932 /// \brief Check whether we can check the pointers at runtime for
3933 /// non-intersection.
3934 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3935 unsigned &NumComparisons, ScalarEvolution *SE,
3936 Loop *TheLoop, ValueToValueMap &Strides,
3937 bool ShouldCheckStride = false);
3939 /// \brief Goes over all memory accesses, checks whether a RT check is needed
3940 /// and builds sets of dependent accesses.
3941 void buildDependenceSets() {
3942 // Process read-write pointers first.
3943 processMemAccesses(false);
3944 // Next, process read pointers.
3945 processMemAccesses(true);
3948 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
3950 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
3951 void resetDepChecks() { CheckDeps.clear(); }
3953 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
3956 typedef SetVector<MemAccessInfo> PtrAccessSet;
3957 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
3959 /// \brief Go over all memory access or only the deferred ones if
3960 /// \p UseDeferred is true and check whether runtime pointer checks are needed
3961 /// and build sets of dependency check candidates.
3962 void processMemAccesses(bool UseDeferred);
3964 /// Set of all accesses.
3965 PtrAccessSet Accesses;
3967 /// Set of access to check after all writes have been processed.
3968 PtrAccessSet DeferredAccesses;
3970 /// Map of pointers to last access encountered.
3971 UnderlyingObjToAccessMap ObjToLastAccess;
3973 /// Set of accesses that need a further dependence check.
3974 MemAccessInfoSet CheckDeps;
3976 /// Set of pointers that are read only.
3977 SmallPtrSet<Value*, 16> ReadOnlyPtr;
3979 /// Set of underlying objects already written to.
3980 SmallPtrSet<Value*, 16> WriteObjects;
3982 const DataLayout *DL;
3984 /// Sets of potentially dependent accesses - members of one set share an
3985 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
3986 /// dependence check.
3987 DepCandidates &DepCands;
3989 bool AreAllWritesIdentified;
3990 bool AreAllReadsIdentified;
3991 bool IsRTCheckNeeded;
3994 } // end anonymous namespace
3996 /// \brief Check whether a pointer can participate in a runtime bounds check.
3997 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
3999 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
4000 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4004 return AR->isAffine();
4007 /// \brief Check the stride of the pointer and ensure that it does not wrap in
4008 /// the address space.
4009 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
4010 const Loop *Lp, ValueToValueMap &StridesMap);
4012 bool AccessAnalysis::canCheckPtrAtRT(
4013 LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
4014 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
4015 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
4016 // Find pointers with computable bounds. We are going to use this information
4017 // to place a runtime bound check.
4018 unsigned NumReadPtrChecks = 0;
4019 unsigned NumWritePtrChecks = 0;
4020 bool CanDoRT = true;
4022 bool IsDepCheckNeeded = isDependencyCheckNeeded();
4023 // We assign consecutive id to access from different dependence sets.
4024 // Accesses within the same set don't need a runtime check.
4025 unsigned RunningDepId = 1;
4026 DenseMap<Value *, unsigned> DepSetId;
4028 for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
4030 const MemAccessInfo &Access = *AI;
4031 Value *Ptr = Access.getPointer();
4032 bool IsWrite = Access.getInt();
4034 // Just add write checks if we have both.
4035 if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
4039 ++NumWritePtrChecks;
4043 if (hasComputableBounds(SE, StridesMap, Ptr) &&
4044 // When we run after a failing dependency check we have to make sure we
4045 // don't have wrapping pointers.
4046 (!ShouldCheckStride ||
4047 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
4048 // The id of the dependence set.
4051 if (IsDepCheckNeeded) {
4052 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
4053 unsigned &LeaderId = DepSetId[Leader];
4055 LeaderId = RunningDepId++;
4058 // Each access has its own dependence set.
4059 DepId = RunningDepId++;
4061 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, StridesMap);
4063 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
4069 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
4070 NumComparisons = 0; // Only one dependence set.
4072 NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
4073 NumWritePtrChecks - 1));
4076 // If the pointers that we would use for the bounds comparison have different
4077 // address spaces, assume the values aren't directly comparable, so we can't
4078 // use them for the runtime check. We also have to assume they could
4079 // overlap. In the future there should be metadata for whether address spaces
4081 unsigned NumPointers = RtCheck.Pointers.size();
4082 for (unsigned i = 0; i < NumPointers; ++i) {
4083 for (unsigned j = i + 1; j < NumPointers; ++j) {
4084 // Only need to check pointers between two different dependency sets.
4085 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
4088 Value *PtrI = RtCheck.Pointers[i];
4089 Value *PtrJ = RtCheck.Pointers[j];
4091 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
4092 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
4094 DEBUG(dbgs() << "LV: Runtime check would require comparison between"
4095 " different address spaces\n");
4104 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
4105 return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
4108 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
4109 // We process the set twice: first we process read-write pointers, last we
4110 // process read-only pointers. This allows us to skip dependence tests for
4111 // read-only pointers.
4113 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
4114 for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
4115 const MemAccessInfo &Access = *AI;
4116 Value *Ptr = Access.getPointer();
4117 bool IsWrite = Access.getInt();
4119 DepCands.insert(Access);
4121 // Memorize read-only pointers for later processing and skip them in the
4122 // first round (they need to be checked after we have seen all write
4123 // pointers). Note: we also mark pointer that are not consecutive as
4124 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
4125 // second check for "!IsWrite".
4126 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
4127 if (!UseDeferred && IsReadOnlyPtr) {
4128 DeferredAccesses.insert(Access);
4132 bool NeedDepCheck = false;
4133 // Check whether there is the possibility of dependency because of
4134 // underlying objects being the same.
4135 typedef SmallVector<Value*, 16> ValueVector;
4136 ValueVector TempObjects;
4137 GetUnderlyingObjects(Ptr, TempObjects, DL);
4138 for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
4140 Value *UnderlyingObj = *UI;
4142 // If this is a write then it needs to be an identified object. If this a
4143 // read and all writes (so far) are identified function scope objects we
4144 // don't need an identified underlying object but only an Argument (the
4145 // next write is going to invalidate this assumption if it is
4147 // This is a micro-optimization for the case where all writes are
4148 // identified and we have one argument pointer.
4149 // Otherwise, we do need a runtime check.
4150 if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
4151 (!IsWrite && (!AreAllWritesIdentified ||
4152 !isa<Argument>(UnderlyingObj)) &&
4153 !isIdentifiedObject(UnderlyingObj))) {
4154 DEBUG(dbgs() << "LV: Found an unidentified " <<
4155 (IsWrite ? "write" : "read" ) << " ptr: " << *UnderlyingObj <<
4157 IsRTCheckNeeded = (IsRTCheckNeeded ||
4158 !isIdentifiedObject(UnderlyingObj) ||
4159 !AreAllReadsIdentified);
4162 AreAllWritesIdentified = false;
4164 AreAllReadsIdentified = false;
4167 // If this is a write - check other reads and writes for conflicts. If
4168 // this is a read only check other writes for conflicts (but only if there
4169 // is no other write to the ptr - this is an optimization to catch "a[i] =
4170 // a[i] + " without having to do a dependence check).
4171 if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
4172 NeedDepCheck = true;
4175 WriteObjects.insert(UnderlyingObj);
4177 // Create sets of pointers connected by shared underlying objects.
4178 UnderlyingObjToAccessMap::iterator Prev =
4179 ObjToLastAccess.find(UnderlyingObj);
4180 if (Prev != ObjToLastAccess.end())
4181 DepCands.unionSets(Access, Prev->second);
4183 ObjToLastAccess[UnderlyingObj] = Access;
4187 CheckDeps.insert(Access);
4192 /// \brief Checks memory dependences among accesses to the same underlying
4193 /// object to determine whether there vectorization is legal or not (and at
4194 /// which vectorization factor).
4196 /// This class works under the assumption that we already checked that memory
4197 /// locations with different underlying pointers are "must-not alias".
4198 /// We use the ScalarEvolution framework to symbolically evalutate access
4199 /// functions pairs. Since we currently don't restructure the loop we can rely
4200 /// on the program order of memory accesses to determine their safety.
4201 /// At the moment we will only deem accesses as safe for:
4202 /// * A negative constant distance assuming program order.
4204 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
4205 /// a[i] = tmp; y = a[i];
4207 /// The latter case is safe because later checks guarantuee that there can't
4208 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
4209 /// the same variable: a header phi can only be an induction or a reduction, a
4210 /// reduction can't have a memory sink, an induction can't have a memory
4211 /// source). This is important and must not be violated (or we have to
4212 /// resort to checking for cycles through memory).
4214 /// * A positive constant distance assuming program order that is bigger
4215 /// than the biggest memory access.
4217 /// tmp = a[i] OR b[i] = x
4218 /// a[i+2] = tmp y = b[i+2];
4220 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
4222 /// * Zero distances and all accesses have the same size.
4224 class MemoryDepChecker {
4226 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
4227 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
4229 MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
4230 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
4231 ShouldRetryWithRuntimeCheck(false) {}
4233 /// \brief Register the location (instructions are given increasing numbers)
4234 /// of a write access.
4235 void addAccess(StoreInst *SI) {
4236 Value *Ptr = SI->getPointerOperand();
4237 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
4238 InstMap.push_back(SI);
4242 /// \brief Register the location (instructions are given increasing numbers)
4243 /// of a write access.
4244 void addAccess(LoadInst *LI) {
4245 Value *Ptr = LI->getPointerOperand();
4246 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
4247 InstMap.push_back(LI);
4251 /// \brief Check whether the dependencies between the accesses are safe.
4253 /// Only checks sets with elements in \p CheckDeps.
4254 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4255 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
4257 /// \brief The maximum number of bytes of a vector register we can vectorize
4258 /// the accesses safely with.
4259 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
4261 /// \brief In same cases when the dependency check fails we can still
4262 /// vectorize the loop with a dynamic array access check.
4263 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
4266 ScalarEvolution *SE;
4267 const DataLayout *DL;
4268 const Loop *InnermostLoop;
4270 /// \brief Maps access locations (ptr, read/write) to program order.
4271 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
4273 /// \brief Memory access instructions in program order.
4274 SmallVector<Instruction *, 16> InstMap;
4276 /// \brief The program order index to be used for the next instruction.
4279 // We can access this many bytes in parallel safely.
4280 unsigned MaxSafeDepDistBytes;
4282 /// \brief If we see a non-constant dependence distance we can still try to
4283 /// vectorize this loop with runtime checks.
4284 bool ShouldRetryWithRuntimeCheck;
4286 /// \brief Check whether there is a plausible dependence between the two
4289 /// Access \p A must happen before \p B in program order. The two indices
4290 /// identify the index into the program order map.
4292 /// This function checks whether there is a plausible dependence (or the
4293 /// absence of such can't be proved) between the two accesses. If there is a
4294 /// plausible dependence but the dependence distance is bigger than one
4295 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
4296 /// distance is smaller than any other distance encountered so far).
4297 /// Otherwise, this function returns true signaling a possible dependence.
4298 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
4299 const MemAccessInfo &B, unsigned BIdx,
4300 ValueToValueMap &Strides);
4302 /// \brief Check whether the data dependence could prevent store-load
4304 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
4307 } // end anonymous namespace
4309 static bool isInBoundsGep(Value *Ptr) {
4310 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
4311 return GEP->isInBounds();
4315 /// \brief Check whether the access through \p Ptr has a constant stride.
4316 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
4317 const Loop *Lp, ValueToValueMap &StridesMap) {
4318 const Type *Ty = Ptr->getType();
4319 assert(Ty->isPointerTy() && "Unexpected non-ptr");
4321 // Make sure that the pointer does not point to aggregate types.
4322 const PointerType *PtrTy = cast<PointerType>(Ty);
4323 if (PtrTy->getElementType()->isAggregateType()) {
4324 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
4329 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
4331 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4333 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
4334 << *Ptr << " SCEV: " << *PtrScev << "\n");
4338 // The accesss function must stride over the innermost loop.
4339 if (Lp != AR->getLoop()) {
4340 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
4341 *Ptr << " SCEV: " << *PtrScev << "\n");
4344 // The address calculation must not wrap. Otherwise, a dependence could be
4346 // An inbounds getelementptr that is a AddRec with a unit stride
4347 // cannot wrap per definition. The unit stride requirement is checked later.
4348 // An getelementptr without an inbounds attribute and unit stride would have
4349 // to access the pointer value "0" which is undefined behavior in address
4350 // space 0, therefore we can also vectorize this case.
4351 bool IsInBoundsGEP = isInBoundsGep(Ptr);
4352 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
4353 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
4354 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
4355 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
4356 << *Ptr << " SCEV: " << *PtrScev << "\n");
4360 // Check the step is constant.
4361 const SCEV *Step = AR->getStepRecurrence(*SE);
4363 // Calculate the pointer stride and check if it is consecutive.
4364 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4366 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
4367 " SCEV: " << *PtrScev << "\n");
4371 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
4372 const APInt &APStepVal = C->getValue()->getValue();
4374 // Huge step value - give up.
4375 if (APStepVal.getBitWidth() > 64)
4378 int64_t StepVal = APStepVal.getSExtValue();
4381 int64_t Stride = StepVal / Size;
4382 int64_t Rem = StepVal % Size;
4386 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
4387 // know we can't "wrap around the address space". In case of address space
4388 // zero we know that this won't happen without triggering undefined behavior.
4389 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
4390 Stride != 1 && Stride != -1)
4396 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
4397 unsigned TypeByteSize) {
4398 // If loads occur at a distance that is not a multiple of a feasible vector
4399 // factor store-load forwarding does not take place.
4400 // Positive dependences might cause troubles because vectorizing them might
4401 // prevent store-load forwarding making vectorized code run a lot slower.
4402 // a[i] = a[i-3] ^ a[i-8];
4403 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
4404 // hence on your typical architecture store-load forwarding does not take
4405 // place. Vectorizing in such cases does not make sense.
4406 // Store-load forwarding distance.
4407 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
4408 // Maximum vector factor.
4409 unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
4410 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
4411 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
4413 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
4415 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
4416 MaxVFWithoutSLForwardIssues = (vf >>=1);
4421 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4422 DEBUG(dbgs() << "LV: Distance " << Distance <<
4423 " that could cause a store-load forwarding conflict\n");
4427 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4428 MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4429 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4433 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4434 const MemAccessInfo &B, unsigned BIdx,
4435 ValueToValueMap &Strides) {
4436 assert (AIdx < BIdx && "Must pass arguments in program order");
4438 Value *APtr = A.getPointer();
4439 Value *BPtr = B.getPointer();
4440 bool AIsWrite = A.getInt();
4441 bool BIsWrite = B.getInt();
4443 // Two reads are independent.
4444 if (!AIsWrite && !BIsWrite)
4447 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4448 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4450 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4451 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4453 const SCEV *Src = AScev;
4454 const SCEV *Sink = BScev;
4456 // If the induction step is negative we have to invert source and sink of the
4458 if (StrideAPtr < 0) {
4461 std::swap(APtr, BPtr);
4462 std::swap(Src, Sink);
4463 std::swap(AIsWrite, BIsWrite);
4464 std::swap(AIdx, BIdx);
4465 std::swap(StrideAPtr, StrideBPtr);
4468 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4470 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4471 << "(Induction step: " << StrideAPtr << ")\n");
4472 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4473 << *InstMap[BIdx] << ": " << *Dist << "\n");
4475 // Need consecutive accesses. We don't want to vectorize
4476 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4477 // the address space.
4478 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4479 DEBUG(dbgs() << "Non-consecutive pointer access\n");
4483 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4485 DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4486 ShouldRetryWithRuntimeCheck = true;
4490 Type *ATy = APtr->getType()->getPointerElementType();
4491 Type *BTy = BPtr->getType()->getPointerElementType();
4492 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4494 // Negative distances are not plausible dependencies.
4495 const APInt &Val = C->getValue()->getValue();
4496 if (Val.isNegative()) {
4497 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4498 if (IsTrueDataDependence &&
4499 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4503 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4507 // Write to the same location with the same size.
4508 // Could be improved to assert type sizes are the same (i32 == float, etc).
4512 DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4516 assert(Val.isStrictlyPositive() && "Expect a positive value");
4518 // Positive distance bigger than max vectorization factor.
4521 "LV: ReadWrite-Write positive dependency with different types\n");
4525 unsigned Distance = (unsigned) Val.getZExtValue();
4527 // Bail out early if passed-in parameters make vectorization not feasible.
4528 unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4529 unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
4531 // The distance must be bigger than the size needed for a vectorized version
4532 // of the operation and the size of the vectorized operation must not be
4533 // bigger than the currrent maximum size.
4534 if (Distance < 2*TypeByteSize ||
4535 2*TypeByteSize > MaxSafeDepDistBytes ||
4536 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4537 DEBUG(dbgs() << "LV: Failure because of Positive distance "
4538 << Val.getSExtValue() << '\n');
4542 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4543 Distance : MaxSafeDepDistBytes;
4545 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4546 if (IsTrueDataDependence &&
4547 couldPreventStoreLoadForward(Distance, TypeByteSize))
4550 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4551 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4556 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4557 MemAccessInfoSet &CheckDeps,
4558 ValueToValueMap &Strides) {
4560 MaxSafeDepDistBytes = -1U;
4561 while (!CheckDeps.empty()) {
4562 MemAccessInfo CurAccess = *CheckDeps.begin();
4564 // Get the relevant memory access set.
4565 EquivalenceClasses<MemAccessInfo>::iterator I =
4566 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4568 // Check accesses within this set.
4569 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4570 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4572 // Check every access pair.
4574 CheckDeps.erase(*AI);
4575 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
4577 // Check every accessing instruction pair in program order.
4578 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4579 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4580 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4581 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4582 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4584 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4595 bool LoopVectorizationLegality::canVectorizeMemory() {
4597 typedef SmallVector<Value*, 16> ValueVector;
4598 typedef SmallPtrSet<Value*, 16> ValueSet;
4600 // Holds the Load and Store *instructions*.
4604 // Holds all the different accesses in the loop.
4605 unsigned NumReads = 0;
4606 unsigned NumReadWrites = 0;
4608 PtrRtCheck.Pointers.clear();
4609 PtrRtCheck.Need = false;
4611 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4612 MemoryDepChecker DepChecker(SE, DL, TheLoop);
4615 for (Loop::block_iterator bb = TheLoop->block_begin(),
4616 be = TheLoop->block_end(); bb != be; ++bb) {
4618 // Scan the BB and collect legal loads and stores.
4619 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4622 // If this is a load, save it. If this instruction can read from memory
4623 // but is not a load, then we quit. Notice that we don't handle function
4624 // calls that read or write.
4625 if (it->mayReadFromMemory()) {
4626 // Many math library functions read the rounding mode. We will only
4627 // vectorize a loop if it contains known function calls that don't set
4628 // the flag. Therefore, it is safe to ignore this read from memory.
4629 CallInst *Call = dyn_cast<CallInst>(it);
4630 if (Call && getIntrinsicIDForCall(Call, TLI))
4633 LoadInst *Ld = dyn_cast<LoadInst>(it);
4634 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
4635 emitAnalysis(Report(Ld)
4636 << "read with atomic ordering or volatile read");
4637 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4641 Loads.push_back(Ld);
4642 DepChecker.addAccess(Ld);
4646 // Save 'store' instructions. Abort if other instructions write to memory.
4647 if (it->mayWriteToMemory()) {
4648 StoreInst *St = dyn_cast<StoreInst>(it);
4650 emitAnalysis(Report(it) << "instruction cannot be vectorized");
4653 if (!St->isSimple() && !IsAnnotatedParallel) {
4654 emitAnalysis(Report(St)
4655 << "write with atomic ordering or volatile write");
4656 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4660 Stores.push_back(St);
4661 DepChecker.addAccess(St);
4666 // Now we have two lists that hold the loads and the stores.
4667 // Next, we find the pointers that they use.
4669 // Check if we see any stores. If there are no stores, then we don't
4670 // care if the pointers are *restrict*.
4671 if (!Stores.size()) {
4672 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4676 AccessAnalysis::DepCandidates DependentAccesses;
4677 AccessAnalysis Accesses(DL, DependentAccesses);
4679 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4680 // multiple times on the same object. If the ptr is accessed twice, once
4681 // for read and once for write, it will only appear once (on the write
4682 // list). This is okay, since we are going to check for conflicts between
4683 // writes and between reads and writes, but not between reads and reads.
4686 ValueVector::iterator I, IE;
4687 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4688 StoreInst *ST = cast<StoreInst>(*I);
4689 Value* Ptr = ST->getPointerOperand();
4691 if (isUniform(Ptr)) {
4694 << "write to a loop invariant address could not be vectorized");
4695 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4699 // If we did *not* see this pointer before, insert it to the read-write
4700 // list. At this phase it is only a 'write' list.
4701 if (Seen.insert(Ptr)) {
4703 Accesses.addStore(Ptr);
4707 if (IsAnnotatedParallel) {
4709 << "LV: A loop annotated parallel, ignore memory dependency "
4714 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4715 LoadInst *LD = cast<LoadInst>(*I);
4716 Value* Ptr = LD->getPointerOperand();
4717 // If we did *not* see this pointer before, insert it to the
4718 // read list. If we *did* see it before, then it is already in
4719 // the read-write list. This allows us to vectorize expressions
4720 // such as A[i] += x; Because the address of A[i] is a read-write
4721 // pointer. This only works if the index of A[i] is consecutive.
4722 // If the address of i is unknown (for example A[B[i]]) then we may
4723 // read a few words, modify, and write a few words, and some of the
4724 // words may be written to the same address.
4725 bool IsReadOnlyPtr = false;
4726 if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4728 IsReadOnlyPtr = true;
4730 Accesses.addLoad(Ptr, IsReadOnlyPtr);
4733 // If we write (or read-write) to a single destination and there are no
4734 // other reads in this loop then is it safe to vectorize.
4735 if (NumReadWrites == 1 && NumReads == 0) {
4736 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4740 // Build dependence sets and check whether we need a runtime pointer bounds
4742 Accesses.buildDependenceSets();
4743 bool NeedRTCheck = Accesses.isRTCheckNeeded();
4745 // Find pointers with computable bounds. We are going to use this information
4746 // to place a runtime bound check.
4747 unsigned NumComparisons = 0;
4748 bool CanDoRT = false;
4750 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4753 DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4754 " pointer comparisons.\n");
4756 // If we only have one set of dependences to check pointers among we don't
4757 // need a runtime check.
4758 if (NumComparisons == 0 && NeedRTCheck)
4759 NeedRTCheck = false;
4761 // Check that we did not collect too many pointers or found an unsizeable
4763 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4769 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4772 if (NeedRTCheck && !CanDoRT) {
4773 emitAnalysis(Report() << "cannot identify array bounds");
4774 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4775 "the array bounds.\n");
4780 PtrRtCheck.Need = NeedRTCheck;
4782 bool CanVecMem = true;
4783 if (Accesses.isDependencyCheckNeeded()) {
4784 DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4785 CanVecMem = DepChecker.areDepsSafe(
4786 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4787 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4789 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4790 DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4793 // Clear the dependency checks. We assume they are not needed.
4794 Accesses.resetDepChecks();
4797 PtrRtCheck.Need = true;
4799 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4800 TheLoop, Strides, true);
4801 // Check that we did not collect too many pointers or found an unsizeable
4803 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4804 if (!CanDoRT && NumComparisons > 0)
4805 emitAnalysis(Report()
4806 << "cannot check memory dependencies at runtime");
4808 emitAnalysis(Report()
4809 << NumComparisons << " exceeds limit of "
4810 << RuntimeMemoryCheckThreshold
4811 << " dependent memory operations checked at runtime");
4812 DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4822 emitAnalysis(Report() << "unsafe dependent memory operations in loop");
4824 DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4825 " need a runtime memory check.\n");
4830 static bool hasMultipleUsesOf(Instruction *I,
4831 SmallPtrSet<Instruction *, 8> &Insts) {
4832 unsigned NumUses = 0;
4833 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
4834 if (Insts.count(dyn_cast<Instruction>(*Use)))
4843 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
4844 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4845 if (!Set.count(dyn_cast<Instruction>(*Use)))
4850 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
4851 ReductionKind Kind) {
4852 if (Phi->getNumIncomingValues() != 2)
4855 // Reduction variables are only found in the loop header block.
4856 if (Phi->getParent() != TheLoop->getHeader())
4859 // Obtain the reduction start value from the value that comes from the loop
4861 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
4863 // ExitInstruction is the single value which is used outside the loop.
4864 // We only allow for a single reduction value to be used outside the loop.
4865 // This includes users of the reduction, variables (which form a cycle
4866 // which ends in the phi node).
4867 Instruction *ExitInstruction = nullptr;
4868 // Indicates that we found a reduction operation in our scan.
4869 bool FoundReduxOp = false;
4871 // We start with the PHI node and scan for all of the users of this
4872 // instruction. All users must be instructions that can be used as reduction
4873 // variables (such as ADD). We must have a single out-of-block user. The cycle
4874 // must include the original PHI.
4875 bool FoundStartPHI = false;
4877 // To recognize min/max patterns formed by a icmp select sequence, we store
4878 // the number of instruction we saw from the recognized min/max pattern,
4879 // to make sure we only see exactly the two instructions.
4880 unsigned NumCmpSelectPatternInst = 0;
4881 ReductionInstDesc ReduxDesc(false, nullptr);
4883 SmallPtrSet<Instruction *, 8> VisitedInsts;
4884 SmallVector<Instruction *, 8> Worklist;
4885 Worklist.push_back(Phi);
4886 VisitedInsts.insert(Phi);
4888 // A value in the reduction can be used:
4889 // - By the reduction:
4890 // - Reduction operation:
4891 // - One use of reduction value (safe).
4892 // - Multiple use of reduction value (not safe).
4894 // - All uses of the PHI must be the reduction (safe).
4895 // - Otherwise, not safe.
4896 // - By one instruction outside of the loop (safe).
4897 // - By further instructions outside of the loop (not safe).
4898 // - By an instruction that is not part of the reduction (not safe).
4900 // * An instruction type other than PHI or the reduction operation.
4901 // * A PHI in the header other than the initial PHI.
4902 while (!Worklist.empty()) {
4903 Instruction *Cur = Worklist.back();
4904 Worklist.pop_back();
4907 // If the instruction has no users then this is a broken chain and can't be
4908 // a reduction variable.
4909 if (Cur->use_empty())
4912 bool IsAPhi = isa<PHINode>(Cur);
4914 // A header PHI use other than the original PHI.
4915 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
4918 // Reductions of instructions such as Div, and Sub is only possible if the
4919 // LHS is the reduction variable.
4920 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
4921 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
4922 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
4925 // Any reduction instruction must be of one of the allowed kinds.
4926 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
4927 if (!ReduxDesc.IsReduction)
4930 // A reduction operation must only have one use of the reduction value.
4931 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
4932 hasMultipleUsesOf(Cur, VisitedInsts))
4935 // All inputs to a PHI node must be a reduction value.
4936 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4939 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4940 isa<SelectInst>(Cur)))
4941 ++NumCmpSelectPatternInst;
4942 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4943 isa<SelectInst>(Cur)))
4944 ++NumCmpSelectPatternInst;
4946 // Check whether we found a reduction operator.
4947 FoundReduxOp |= !IsAPhi;
4949 // Process users of current instruction. Push non-PHI nodes after PHI nodes
4950 // onto the stack. This way we are going to have seen all inputs to PHI
4951 // nodes once we get to them.
4952 SmallVector<Instruction *, 8> NonPHIs;
4953 SmallVector<Instruction *, 8> PHIs;
4954 for (User *U : Cur->users()) {
4955 Instruction *UI = cast<Instruction>(U);
4957 // Check if we found the exit user.
4958 BasicBlock *Parent = UI->getParent();
4959 if (!TheLoop->contains(Parent)) {
4960 // Exit if you find multiple outside users or if the header phi node is
4961 // being used. In this case the user uses the value of the previous
4962 // iteration, in which case we would loose "VF-1" iterations of the
4963 // reduction operation if we vectorize.
4964 if (ExitInstruction != nullptr || Cur == Phi)
4967 // The instruction used by an outside user must be the last instruction
4968 // before we feed back to the reduction phi. Otherwise, we loose VF-1
4969 // operations on the value.
4970 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
4973 ExitInstruction = Cur;
4977 // Process instructions only once (termination). Each reduction cycle
4978 // value must only be used once, except by phi nodes and min/max
4979 // reductions which are represented as a cmp followed by a select.
4980 ReductionInstDesc IgnoredVal(false, nullptr);
4981 if (VisitedInsts.insert(UI)) {
4982 if (isa<PHINode>(UI))
4985 NonPHIs.push_back(UI);
4986 } else if (!isa<PHINode>(UI) &&
4987 ((!isa<FCmpInst>(UI) &&
4988 !isa<ICmpInst>(UI) &&
4989 !isa<SelectInst>(UI)) ||
4990 !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
4993 // Remember that we completed the cycle.
4995 FoundStartPHI = true;
4997 Worklist.append(PHIs.begin(), PHIs.end());
4998 Worklist.append(NonPHIs.begin(), NonPHIs.end());
5001 // This means we have seen one but not the other instruction of the
5002 // pattern or more than just a select and cmp.
5003 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
5004 NumCmpSelectPatternInst != 2)
5007 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
5010 // We found a reduction var if we have reached the original phi node and we
5011 // only have a single instruction with out-of-loop users.
5013 // This instruction is allowed to have out-of-loop users.
5014 AllowedExit.insert(ExitInstruction);
5016 // Save the description of this reduction variable.
5017 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
5018 ReduxDesc.MinMaxKind);
5019 Reductions[Phi] = RD;
5020 // We've ended the cycle. This is a reduction variable if we have an
5021 // outside user and it has a binary op.
5026 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
5027 /// pattern corresponding to a min(X, Y) or max(X, Y).
5028 LoopVectorizationLegality::ReductionInstDesc
5029 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
5030 ReductionInstDesc &Prev) {
5032 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
5033 "Expect a select instruction");
5034 Instruction *Cmp = nullptr;
5035 SelectInst *Select = nullptr;
5037 // We must handle the select(cmp()) as a single instruction. Advance to the
5039 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
5040 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
5041 return ReductionInstDesc(false, I);
5042 return ReductionInstDesc(Select, Prev.MinMaxKind);
5045 // Only handle single use cases for now.
5046 if (!(Select = dyn_cast<SelectInst>(I)))
5047 return ReductionInstDesc(false, I);
5048 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
5049 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
5050 return ReductionInstDesc(false, I);
5051 if (!Cmp->hasOneUse())
5052 return ReductionInstDesc(false, I);
5057 // Look for a min/max pattern.
5058 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5059 return ReductionInstDesc(Select, MRK_UIntMin);
5060 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5061 return ReductionInstDesc(Select, MRK_UIntMax);
5062 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5063 return ReductionInstDesc(Select, MRK_SIntMax);
5064 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5065 return ReductionInstDesc(Select, MRK_SIntMin);
5066 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5067 return ReductionInstDesc(Select, MRK_FloatMin);
5068 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5069 return ReductionInstDesc(Select, MRK_FloatMax);
5070 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5071 return ReductionInstDesc(Select, MRK_FloatMin);
5072 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5073 return ReductionInstDesc(Select, MRK_FloatMax);
5075 return ReductionInstDesc(false, I);
5078 LoopVectorizationLegality::ReductionInstDesc
5079 LoopVectorizationLegality::isReductionInstr(Instruction *I,
5081 ReductionInstDesc &Prev) {
5082 bool FP = I->getType()->isFloatingPointTy();
5083 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
5084 switch (I->getOpcode()) {
5086 return ReductionInstDesc(false, I);
5087 case Instruction::PHI:
5088 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
5089 Kind != RK_FloatMinMax))
5090 return ReductionInstDesc(false, I);
5091 return ReductionInstDesc(I, Prev.MinMaxKind);
5092 case Instruction::Sub:
5093 case Instruction::Add:
5094 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
5095 case Instruction::Mul:
5096 return ReductionInstDesc(Kind == RK_IntegerMult, I);
5097 case Instruction::And:
5098 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
5099 case Instruction::Or:
5100 return ReductionInstDesc(Kind == RK_IntegerOr, I);
5101 case Instruction::Xor:
5102 return ReductionInstDesc(Kind == RK_IntegerXor, I);
5103 case Instruction::FMul:
5104 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
5105 case Instruction::FAdd:
5106 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
5107 case Instruction::FCmp:
5108 case Instruction::ICmp:
5109 case Instruction::Select:
5110 if (Kind != RK_IntegerMinMax &&
5111 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
5112 return ReductionInstDesc(false, I);
5113 return isMinMaxSelectCmpPattern(I, Prev);
5117 LoopVectorizationLegality::InductionKind
5118 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
5119 Type *PhiTy = Phi->getType();
5120 // We only handle integer and pointer inductions variables.
5121 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
5122 return IK_NoInduction;
5124 // Check that the PHI is consecutive.
5125 const SCEV *PhiScev = SE->getSCEV(Phi);
5126 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
5128 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
5129 return IK_NoInduction;
5131 const SCEV *Step = AR->getStepRecurrence(*SE);
5133 // Integer inductions need to have a stride of one.
5134 if (PhiTy->isIntegerTy()) {
5136 return IK_IntInduction;
5137 if (Step->isAllOnesValue())
5138 return IK_ReverseIntInduction;
5139 return IK_NoInduction;
5142 // Calculate the pointer stride and check if it is consecutive.
5143 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5145 return IK_NoInduction;
5147 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
5148 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
5149 if (C->getValue()->equalsInt(Size))
5150 return IK_PtrInduction;
5151 else if (C->getValue()->equalsInt(0 - Size))
5152 return IK_ReversePtrInduction;
5154 return IK_NoInduction;
5157 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
5158 Value *In0 = const_cast<Value*>(V);
5159 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
5163 return Inductions.count(PN);
5166 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
5167 assert(TheLoop->contains(BB) && "Unknown block used");
5169 // Blocks that do not dominate the latch need predication.
5170 BasicBlock* Latch = TheLoop->getLoopLatch();
5171 return !DT->dominates(BB, Latch);
5174 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
5175 SmallPtrSet<Value *, 8>& SafePtrs) {
5176 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5177 // We might be able to hoist the load.
5178 if (it->mayReadFromMemory()) {
5179 LoadInst *LI = dyn_cast<LoadInst>(it);
5180 if (!LI || !SafePtrs.count(LI->getPointerOperand()))
5184 // We don't predicate stores at the moment.
5185 if (it->mayWriteToMemory()) {
5186 StoreInst *SI = dyn_cast<StoreInst>(it);
5187 // We only support predication of stores in basic blocks with one
5189 if (!SI || ++NumPredStores > NumberOfStoresToPredicate ||
5190 !SafePtrs.count(SI->getPointerOperand()) ||
5191 !SI->getParent()->getSinglePredecessor())
5197 // Check that we don't have a constant expression that can trap as operand.
5198 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
5200 if (Constant *C = dyn_cast<Constant>(*OI))
5205 // The instructions below can trap.
5206 switch (it->getOpcode()) {
5208 case Instruction::UDiv:
5209 case Instruction::SDiv:
5210 case Instruction::URem:
5211 case Instruction::SRem:
5219 LoopVectorizationCostModel::VectorizationFactor
5220 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
5222 bool ForceVectorization) {
5223 // Width 1 means no vectorize
5224 VectorizationFactor Factor = { 1U, 0U };
5225 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
5226 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
5230 if (!EnableCondStoresVectorization && Legal->NumPredStores) {
5231 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
5235 // Find the trip count.
5236 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
5237 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5239 unsigned WidestType = getWidestType();
5240 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
5241 unsigned MaxSafeDepDist = -1U;
5242 if (Legal->getMaxSafeDepDistBytes() != -1U)
5243 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5244 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
5245 WidestRegister : MaxSafeDepDist);
5246 unsigned MaxVectorSize = WidestRegister / WidestType;
5247 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
5248 DEBUG(dbgs() << "LV: The Widest register is: "
5249 << WidestRegister << " bits.\n");
5251 if (MaxVectorSize == 0) {
5252 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5256 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
5257 " into one vector!");
5259 unsigned VF = MaxVectorSize;
5261 // If we optimize the program for size, avoid creating the tail loop.
5263 // If we are unable to calculate the trip count then don't try to vectorize.
5265 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5269 // Find the maximum SIMD width that can fit within the trip count.
5270 VF = TC % MaxVectorSize;
5275 // If the trip count that we found modulo the vectorization factor is not
5276 // zero then we require a tail.
5278 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5284 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
5285 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5287 Factor.Width = UserVF;
5291 float Cost = expectedCost(1);
5293 const float ScalarCost = Cost;
5296 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
5298 // Ignore scalar width, because the user explicitly wants vectorization.
5299 if (ForceVectorization && VF > 1) {
5301 Cost = expectedCost(Width) / (float)Width;
5304 for (unsigned i=2; i <= VF; i*=2) {
5305 // Notice that the vector loop needs to be executed less times, so
5306 // we need to divide the cost of the vector loops by the width of
5307 // the vector elements.
5308 float VectorCost = expectedCost(i) / (float)i;
5309 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
5310 (int)VectorCost << ".\n");
5311 if (VectorCost < Cost) {
5317 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
5318 << "LV: Vectorization seems to be not beneficial, "
5319 << "but was forced by a user.\n");
5320 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
5321 Factor.Width = Width;
5322 Factor.Cost = Width * Cost;
5326 unsigned LoopVectorizationCostModel::getWidestType() {
5327 unsigned MaxWidth = 8;
5330 for (Loop::block_iterator bb = TheLoop->block_begin(),
5331 be = TheLoop->block_end(); bb != be; ++bb) {
5332 BasicBlock *BB = *bb;
5334 // For each instruction in the loop.
5335 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5336 Type *T = it->getType();
5338 // Only examine Loads, Stores and PHINodes.
5339 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
5342 // Examine PHI nodes that are reduction variables.
5343 if (PHINode *PN = dyn_cast<PHINode>(it))
5344 if (!Legal->getReductionVars()->count(PN))
5347 // Examine the stored values.
5348 if (StoreInst *ST = dyn_cast<StoreInst>(it))
5349 T = ST->getValueOperand()->getType();
5351 // Ignore loaded pointer types and stored pointer types that are not
5352 // consecutive. However, we do want to take consecutive stores/loads of
5353 // pointer vectors into account.
5354 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
5357 MaxWidth = std::max(MaxWidth,
5358 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
5366 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
5369 unsigned LoopCost) {
5371 // -- The unroll heuristics --
5372 // We unroll the loop in order to expose ILP and reduce the loop overhead.
5373 // There are many micro-architectural considerations that we can't predict
5374 // at this level. For example frontend pressure (on decode or fetch) due to
5375 // code size, or the number and capabilities of the execution ports.
5377 // We use the following heuristics to select the unroll factor:
5378 // 1. If the code has reductions the we unroll in order to break the cross
5379 // iteration dependency.
5380 // 2. If the loop is really small then we unroll in order to reduce the loop
5382 // 3. We don't unroll if we think that we will spill registers to memory due
5383 // to the increased register pressure.
5385 // Use the user preference, unless 'auto' is selected.
5389 // When we optimize for size we don't unroll.
5393 // We used the distance for the unroll factor.
5394 if (Legal->getMaxSafeDepDistBytes() != -1U)
5397 // Do not unroll loops with a relatively small trip count.
5398 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
5399 TheLoop->getLoopLatch());
5400 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
5403 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5404 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
5408 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5409 TargetNumRegisters = ForceTargetNumScalarRegs;
5411 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5412 TargetNumRegisters = ForceTargetNumVectorRegs;
5415 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
5416 // We divide by these constants so assume that we have at least one
5417 // instruction that uses at least one register.
5418 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5419 R.NumInstructions = std::max(R.NumInstructions, 1U);
5421 // We calculate the unroll factor using the following formula.
5422 // Subtract the number of loop invariants from the number of available
5423 // registers. These registers are used by all of the unrolled instances.
5424 // Next, divide the remaining registers by the number of registers that is
5425 // required by the loop, in order to estimate how many parallel instances
5426 // fit without causing spills. All of this is rounded down if necessary to be
5427 // a power of two. We want power of two unroll factors to simplify any
5428 // addressing operations or alignment considerations.
5429 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5432 // Don't count the induction variable as unrolled.
5433 if (EnableIndVarRegisterHeur)
5434 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
5435 std::max(1U, (R.MaxLocalUsers - 1)));
5437 // Clamp the unroll factor ranges to reasonable factors.
5438 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
5440 // Check if the user has overridden the unroll max.
5442 if (ForceTargetMaxScalarUnrollFactor.getNumOccurrences() > 0)
5443 MaxUnrollSize = ForceTargetMaxScalarUnrollFactor;
5445 if (ForceTargetMaxVectorUnrollFactor.getNumOccurrences() > 0)
5446 MaxUnrollSize = ForceTargetMaxVectorUnrollFactor;
5449 // If we did not calculate the cost for VF (because the user selected the VF)
5450 // then we calculate the cost of VF here.
5452 LoopCost = expectedCost(VF);
5454 // Clamp the calculated UF to be between the 1 and the max unroll factor
5455 // that the target allows.
5456 if (UF > MaxUnrollSize)
5461 // Unroll if we vectorized this loop and there is a reduction that could
5462 // benefit from unrolling.
5463 if (VF > 1 && Legal->getReductionVars()->size()) {
5464 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
5468 // Note that if we've already vectorized the loop we will have done the
5469 // runtime check and so unrolling won't require further checks.
5470 bool UnrollingRequiresRuntimePointerCheck =
5471 (VF == 1 && Legal->getRuntimePointerCheck()->Need);
5473 // We want to unroll small loops in order to reduce the loop overhead and
5474 // potentially expose ILP opportunities.
5475 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5476 if (!UnrollingRequiresRuntimePointerCheck &&
5477 LoopCost < SmallLoopCost) {
5478 // We assume that the cost overhead is 1 and we use the cost model
5479 // to estimate the cost of the loop and unroll until the cost of the
5480 // loop overhead is about 5% of the cost of the loop.
5481 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5483 // Unroll until store/load ports (estimated by max unroll factor) are
5485 unsigned StoresUF = UF / (Legal->NumStores ? Legal->NumStores : 1);
5486 unsigned LoadsUF = UF / (Legal->NumLoads ? Legal->NumLoads : 1);
5488 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
5489 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
5490 return std::max(StoresUF, LoadsUF);
5493 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
5497 DEBUG(dbgs() << "LV: Not Unrolling.\n");
5501 LoopVectorizationCostModel::RegisterUsage
5502 LoopVectorizationCostModel::calculateRegisterUsage() {
5503 // This function calculates the register usage by measuring the highest number
5504 // of values that are alive at a single location. Obviously, this is a very
5505 // rough estimation. We scan the loop in a topological order in order and
5506 // assign a number to each instruction. We use RPO to ensure that defs are
5507 // met before their users. We assume that each instruction that has in-loop
5508 // users starts an interval. We record every time that an in-loop value is
5509 // used, so we have a list of the first and last occurrences of each
5510 // instruction. Next, we transpose this data structure into a multi map that
5511 // holds the list of intervals that *end* at a specific location. This multi
5512 // map allows us to perform a linear search. We scan the instructions linearly
5513 // and record each time that a new interval starts, by placing it in a set.
5514 // If we find this value in the multi-map then we remove it from the set.
5515 // The max register usage is the maximum size of the set.
5516 // We also search for instructions that are defined outside the loop, but are
5517 // used inside the loop. We need this number separately from the max-interval
5518 // usage number because when we unroll, loop-invariant values do not take
5520 LoopBlocksDFS DFS(TheLoop);
5524 R.NumInstructions = 0;
5526 // Each 'key' in the map opens a new interval. The values
5527 // of the map are the index of the 'last seen' usage of the
5528 // instruction that is the key.
5529 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5530 // Maps instruction to its index.
5531 DenseMap<unsigned, Instruction*> IdxToInstr;
5532 // Marks the end of each interval.
5533 IntervalMap EndPoint;
5534 // Saves the list of instruction indices that are used in the loop.
5535 SmallSet<Instruction*, 8> Ends;
5536 // Saves the list of values that are used in the loop but are
5537 // defined outside the loop, such as arguments and constants.
5538 SmallPtrSet<Value*, 8> LoopInvariants;
5541 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5542 be = DFS.endRPO(); bb != be; ++bb) {
5543 R.NumInstructions += (*bb)->size();
5544 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5546 Instruction *I = it;
5547 IdxToInstr[Index++] = I;
5549 // Save the end location of each USE.
5550 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5551 Value *U = I->getOperand(i);
5552 Instruction *Instr = dyn_cast<Instruction>(U);
5554 // Ignore non-instruction values such as arguments, constants, etc.
5555 if (!Instr) continue;
5557 // If this instruction is outside the loop then record it and continue.
5558 if (!TheLoop->contains(Instr)) {
5559 LoopInvariants.insert(Instr);
5563 // Overwrite previous end points.
5564 EndPoint[Instr] = Index;
5570 // Saves the list of intervals that end with the index in 'key'.
5571 typedef SmallVector<Instruction*, 2> InstrList;
5572 DenseMap<unsigned, InstrList> TransposeEnds;
5574 // Transpose the EndPoints to a list of values that end at each index.
5575 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5577 TransposeEnds[it->second].push_back(it->first);
5579 SmallSet<Instruction*, 8> OpenIntervals;
5580 unsigned MaxUsage = 0;
5583 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5584 for (unsigned int i = 0; i < Index; ++i) {
5585 Instruction *I = IdxToInstr[i];
5586 // Ignore instructions that are never used within the loop.
5587 if (!Ends.count(I)) continue;
5589 // Remove all of the instructions that end at this location.
5590 InstrList &List = TransposeEnds[i];
5591 for (unsigned int j=0, e = List.size(); j < e; ++j)
5592 OpenIntervals.erase(List[j]);
5594 // Count the number of live interals.
5595 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5597 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5598 OpenIntervals.size() << '\n');
5600 // Add the current instruction to the list of open intervals.
5601 OpenIntervals.insert(I);
5604 unsigned Invariant = LoopInvariants.size();
5605 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5606 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5607 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5609 R.LoopInvariantRegs = Invariant;
5610 R.MaxLocalUsers = MaxUsage;
5614 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5618 for (Loop::block_iterator bb = TheLoop->block_begin(),
5619 be = TheLoop->block_end(); bb != be; ++bb) {
5620 unsigned BlockCost = 0;
5621 BasicBlock *BB = *bb;
5623 // For each instruction in the old loop.
5624 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5625 // Skip dbg intrinsics.
5626 if (isa<DbgInfoIntrinsic>(it))
5629 unsigned C = getInstructionCost(it, VF);
5631 // Check if we should override the cost.
5632 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5633 C = ForceTargetInstructionCost;
5636 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5637 VF << " For instruction: " << *it << '\n');
5640 // We assume that if-converted blocks have a 50% chance of being executed.
5641 // When the code is scalar then some of the blocks are avoided due to CF.
5642 // When the code is vectorized we execute all code paths.
5643 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5652 /// \brief Check whether the address computation for a non-consecutive memory
5653 /// access looks like an unlikely candidate for being merged into the indexing
5656 /// We look for a GEP which has one index that is an induction variable and all
5657 /// other indices are loop invariant. If the stride of this access is also
5658 /// within a small bound we decide that this address computation can likely be
5659 /// merged into the addressing mode.
5660 /// In all other cases, we identify the address computation as complex.
5661 static bool isLikelyComplexAddressComputation(Value *Ptr,
5662 LoopVectorizationLegality *Legal,
5663 ScalarEvolution *SE,
5664 const Loop *TheLoop) {
5665 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5669 // We are looking for a gep with all loop invariant indices except for one
5670 // which should be an induction variable.
5671 unsigned NumOperands = Gep->getNumOperands();
5672 for (unsigned i = 1; i < NumOperands; ++i) {
5673 Value *Opd = Gep->getOperand(i);
5674 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5675 !Legal->isInductionVariable(Opd))
5679 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5680 // can likely be merged into the address computation.
5681 unsigned MaxMergeDistance = 64;
5683 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5687 // Check the step is constant.
5688 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5689 // Calculate the pointer stride and check if it is consecutive.
5690 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5694 const APInt &APStepVal = C->getValue()->getValue();
5696 // Huge step value - give up.
5697 if (APStepVal.getBitWidth() > 64)
5700 int64_t StepVal = APStepVal.getSExtValue();
5702 return StepVal > MaxMergeDistance;
5705 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5706 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5712 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5713 // If we know that this instruction will remain uniform, check the cost of
5714 // the scalar version.
5715 if (Legal->isUniformAfterVectorization(I))
5718 Type *RetTy = I->getType();
5719 Type *VectorTy = ToVectorTy(RetTy, VF);
5721 // TODO: We need to estimate the cost of intrinsic calls.
5722 switch (I->getOpcode()) {
5723 case Instruction::GetElementPtr:
5724 // We mark this instruction as zero-cost because the cost of GEPs in
5725 // vectorized code depends on whether the corresponding memory instruction
5726 // is scalarized or not. Therefore, we handle GEPs with the memory
5727 // instruction cost.
5729 case Instruction::Br: {
5730 return TTI.getCFInstrCost(I->getOpcode());
5732 case Instruction::PHI:
5733 //TODO: IF-converted IFs become selects.
5735 case Instruction::Add:
5736 case Instruction::FAdd:
5737 case Instruction::Sub:
5738 case Instruction::FSub:
5739 case Instruction::Mul:
5740 case Instruction::FMul:
5741 case Instruction::UDiv:
5742 case Instruction::SDiv:
5743 case Instruction::FDiv:
5744 case Instruction::URem:
5745 case Instruction::SRem:
5746 case Instruction::FRem:
5747 case Instruction::Shl:
5748 case Instruction::LShr:
5749 case Instruction::AShr:
5750 case Instruction::And:
5751 case Instruction::Or:
5752 case Instruction::Xor: {
5753 // Since we will replace the stride by 1 the multiplication should go away.
5754 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5756 // Certain instructions can be cheaper to vectorize if they have a constant
5757 // second vector operand. One example of this are shifts on x86.
5758 TargetTransformInfo::OperandValueKind Op1VK =
5759 TargetTransformInfo::OK_AnyValue;
5760 TargetTransformInfo::OperandValueKind Op2VK =
5761 TargetTransformInfo::OK_AnyValue;
5762 Value *Op2 = I->getOperand(1);
5764 // Check for a splat of a constant or for a non uniform vector of constants.
5765 if (isa<ConstantInt>(Op2))
5766 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5767 else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5768 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5769 if (cast<Constant>(Op2)->getSplatValue() != nullptr)
5770 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5773 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
5775 case Instruction::Select: {
5776 SelectInst *SI = cast<SelectInst>(I);
5777 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5778 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5779 Type *CondTy = SI->getCondition()->getType();
5781 CondTy = VectorType::get(CondTy, VF);
5783 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5785 case Instruction::ICmp:
5786 case Instruction::FCmp: {
5787 Type *ValTy = I->getOperand(0)->getType();
5788 VectorTy = ToVectorTy(ValTy, VF);
5789 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5791 case Instruction::Store:
5792 case Instruction::Load: {
5793 StoreInst *SI = dyn_cast<StoreInst>(I);
5794 LoadInst *LI = dyn_cast<LoadInst>(I);
5795 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5797 VectorTy = ToVectorTy(ValTy, VF);
5799 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5800 unsigned AS = SI ? SI->getPointerAddressSpace() :
5801 LI->getPointerAddressSpace();
5802 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5803 // We add the cost of address computation here instead of with the gep
5804 // instruction because only here we know whether the operation is
5807 return TTI.getAddressComputationCost(VectorTy) +
5808 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5810 // Scalarized loads/stores.
5811 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5812 bool Reverse = ConsecutiveStride < 0;
5813 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
5814 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
5815 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5816 bool IsComplexComputation =
5817 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5819 // The cost of extracting from the value vector and pointer vector.
5820 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5821 for (unsigned i = 0; i < VF; ++i) {
5822 // The cost of extracting the pointer operand.
5823 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5824 // In case of STORE, the cost of ExtractElement from the vector.
5825 // In case of LOAD, the cost of InsertElement into the returned
5827 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5828 Instruction::InsertElement,
5832 // The cost of the scalar loads/stores.
5833 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5834 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5839 // Wide load/stores.
5840 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5841 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5844 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5848 case Instruction::ZExt:
5849 case Instruction::SExt:
5850 case Instruction::FPToUI:
5851 case Instruction::FPToSI:
5852 case Instruction::FPExt:
5853 case Instruction::PtrToInt:
5854 case Instruction::IntToPtr:
5855 case Instruction::SIToFP:
5856 case Instruction::UIToFP:
5857 case Instruction::Trunc:
5858 case Instruction::FPTrunc:
5859 case Instruction::BitCast: {
5860 // We optimize the truncation of induction variable.
5861 // The cost of these is the same as the scalar operation.
5862 if (I->getOpcode() == Instruction::Trunc &&
5863 Legal->isInductionVariable(I->getOperand(0)))
5864 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5865 I->getOperand(0)->getType());
5867 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5868 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5870 case Instruction::Call: {
5871 CallInst *CI = cast<CallInst>(I);
5872 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5873 assert(ID && "Not an intrinsic call!");
5874 Type *RetTy = ToVectorTy(CI->getType(), VF);
5875 SmallVector<Type*, 4> Tys;
5876 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5877 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5878 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5881 // We are scalarizing the instruction. Return the cost of the scalar
5882 // instruction, plus the cost of insert and extract into vector
5883 // elements, times the vector width.
5886 if (!RetTy->isVoidTy() && VF != 1) {
5887 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5889 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5892 // The cost of inserting the results plus extracting each one of the
5894 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5897 // The cost of executing VF copies of the scalar instruction. This opcode
5898 // is unknown. Assume that it is the same as 'mul'.
5899 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5905 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
5906 if (Scalar->isVoidTy() || VF == 1)
5908 return VectorType::get(Scalar, VF);
5911 char LoopVectorize::ID = 0;
5912 static const char lv_name[] = "Loop Vectorization";
5913 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5914 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
5915 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5916 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5917 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5918 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5919 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
5920 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5921 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5924 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5925 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5929 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5930 // Check for a store.
5931 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5932 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5934 // Check for a load.
5935 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5936 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5942 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5943 bool IfPredicateStore) {
5944 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5945 // Holds vector parameters or scalars, in case of uniform vals.
5946 SmallVector<VectorParts, 4> Params;
5948 setDebugLocFromInst(Builder, Instr);
5950 // Find all of the vectorized parameters.
5951 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5952 Value *SrcOp = Instr->getOperand(op);
5954 // If we are accessing the old induction variable, use the new one.
5955 if (SrcOp == OldInduction) {
5956 Params.push_back(getVectorValue(SrcOp));
5960 // Try using previously calculated values.
5961 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5963 // If the src is an instruction that appeared earlier in the basic block
5964 // then it should already be vectorized.
5965 if (SrcInst && OrigLoop->contains(SrcInst)) {
5966 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5967 // The parameter is a vector value from earlier.
5968 Params.push_back(WidenMap.get(SrcInst));
5970 // The parameter is a scalar from outside the loop. Maybe even a constant.
5971 VectorParts Scalars;
5972 Scalars.append(UF, SrcOp);
5973 Params.push_back(Scalars);
5977 assert(Params.size() == Instr->getNumOperands() &&
5978 "Invalid number of operands");
5980 // Does this instruction return a value ?
5981 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5983 Value *UndefVec = IsVoidRetTy ? nullptr :
5984 UndefValue::get(Instr->getType());
5985 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5986 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5988 Instruction *InsertPt = Builder.GetInsertPoint();
5989 BasicBlock *IfBlock = Builder.GetInsertBlock();
5990 BasicBlock *CondBlock = nullptr;
5993 Loop *VectorLp = nullptr;
5994 if (IfPredicateStore) {
5995 assert(Instr->getParent()->getSinglePredecessor() &&
5996 "Only support single predecessor blocks");
5997 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5998 Instr->getParent());
5999 VectorLp = LI->getLoopFor(IfBlock);
6000 assert(VectorLp && "Must have a loop for this block");
6003 // For each vector unroll 'part':
6004 for (unsigned Part = 0; Part < UF; ++Part) {
6005 // For each scalar that we create:
6007 // Start an "if (pred) a[i] = ..." block.
6008 Value *Cmp = nullptr;
6009 if (IfPredicateStore) {
6010 if (Cond[Part]->getType()->isVectorTy())
6012 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
6013 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
6014 ConstantInt::get(Cond[Part]->getType(), 1));
6015 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
6016 LoopVectorBody.push_back(CondBlock);
6017 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
6018 // Update Builder with newly created basic block.
6019 Builder.SetInsertPoint(InsertPt);
6022 Instruction *Cloned = Instr->clone();
6024 Cloned->setName(Instr->getName() + ".cloned");
6025 // Replace the operands of the cloned instructions with extracted scalars.
6026 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
6027 Value *Op = Params[op][Part];
6028 Cloned->setOperand(op, Op);
6031 // Place the cloned scalar in the new loop.
6032 Builder.Insert(Cloned);
6034 // If the original scalar returns a value we need to place it in a vector
6035 // so that future users will be able to use it.
6037 VecResults[Part] = Cloned;
6040 if (IfPredicateStore) {
6041 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
6042 LoopVectorBody.push_back(NewIfBlock);
6043 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
6044 Builder.SetInsertPoint(InsertPt);
6045 Instruction *OldBr = IfBlock->getTerminator();
6046 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
6047 OldBr->eraseFromParent();
6048 IfBlock = NewIfBlock;
6053 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
6054 StoreInst *SI = dyn_cast<StoreInst>(Instr);
6055 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
6057 return scalarizeInstruction(Instr, IfPredicateStore);
6060 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
6064 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
6068 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
6070 // When unrolling and the VF is 1, we only need to add a simple scalar.
6071 Type *ITy = Val->getType();
6072 assert(!ITy->isVectorTy() && "Val must be a scalar");
6073 Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
6074 return Builder.CreateAdd(Val, C, "induction");