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/Dominators.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/IRBuilder.h"
73 #include "llvm/IR/Instructions.h"
74 #include "llvm/IR/IntrinsicInst.h"
75 #include "llvm/IR/LLVMContext.h"
76 #include "llvm/IR/Module.h"
77 #include "llvm/IR/PatternMatch.h"
78 #include "llvm/IR/Type.h"
79 #include "llvm/IR/Value.h"
80 #include "llvm/IR/ValueHandle.h"
81 #include "llvm/IR/Verifier.h"
82 #include "llvm/Pass.h"
83 #include "llvm/Support/BranchProbability.h"
84 #include "llvm/Support/CommandLine.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Target/TargetLibraryInfo.h"
89 #include "llvm/Transforms/Scalar.h"
90 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
91 #include "llvm/Transforms/Utils/Local.h"
92 #include "llvm/Transforms/Utils/VectorUtils.h"
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 /// InnerLoopVectorizer vectorizes loops which contain only one basic
213 /// block to a specified vectorization factor (VF).
214 /// This class performs the widening of scalars into vectors, or multiple
215 /// scalars. This class also implements the following features:
216 /// * It inserts an epilogue loop for handling loops that don't have iteration
217 /// counts that are known to be a multiple of the vectorization factor.
218 /// * It handles the code generation for reduction variables.
219 /// * Scalarization (implementation using scalars) of un-vectorizable
221 /// InnerLoopVectorizer does not perform any vectorization-legality
222 /// checks, and relies on the caller to check for the different legality
223 /// aspects. The InnerLoopVectorizer relies on the
224 /// LoopVectorizationLegality class to provide information about the induction
225 /// and reduction variables that were found to a given vectorization factor.
226 class InnerLoopVectorizer {
228 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
229 DominatorTree *DT, const DataLayout *DL,
230 const TargetLibraryInfo *TLI, unsigned VecWidth,
231 unsigned UnrollFactor)
232 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
233 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
234 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
237 // Perform the actual loop widening (vectorization).
238 void vectorize(LoopVectorizationLegality *L) {
240 // Create a new empty loop. Unlink the old loop and connect the new one.
242 // Widen each instruction in the old loop to a new one in the new loop.
243 // Use the Legality module to find the induction and reduction variables.
245 // Register the new loop and update the analysis passes.
249 virtual ~InnerLoopVectorizer() {}
252 /// A small list of PHINodes.
253 typedef SmallVector<PHINode*, 4> PhiVector;
254 /// When we unroll loops we have multiple vector values for each scalar.
255 /// This data structure holds the unrolled and vectorized values that
256 /// originated from one scalar instruction.
257 typedef SmallVector<Value*, 2> VectorParts;
259 // When we if-convert we need create edge masks. We have to cache values so
260 // that we don't end up with exponential recursion/IR.
261 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
262 VectorParts> EdgeMaskCache;
264 /// \brief Add code that checks at runtime if the accessed arrays overlap.
266 /// Returns a pair of instructions where the first element is the first
267 /// instruction generated in possibly a sequence of instructions and the
268 /// second value is the final comparator value or NULL if no check is needed.
269 std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
271 /// \brief Add checks for strides that where assumed to be 1.
273 /// Returns the last check instruction and the first check instruction in the
274 /// pair as (first, last).
275 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
277 /// Create an empty loop, based on the loop ranges of the old loop.
278 void createEmptyLoop();
279 /// Copy and widen the instructions from the old loop.
280 virtual void vectorizeLoop();
282 /// \brief The Loop exit block may have single value PHI nodes where the
283 /// incoming value is 'Undef'. While vectorizing we only handled real values
284 /// that were defined inside the loop. Here we fix the 'undef case'.
288 /// A helper function that computes the predicate of the block BB, assuming
289 /// that the header block of the loop is set to True. It returns the *entry*
290 /// mask for the block BB.
291 VectorParts createBlockInMask(BasicBlock *BB);
292 /// A helper function that computes the predicate of the edge between SRC
294 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
296 /// A helper function to vectorize a single BB within the innermost loop.
297 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
299 /// Vectorize a single PHINode in a block. This method handles the induction
300 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
301 /// arbitrary length vectors.
302 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
303 unsigned UF, unsigned VF, PhiVector *PV);
305 /// Insert the new loop to the loop hierarchy and pass manager
306 /// and update the analysis passes.
307 void updateAnalysis();
309 /// This instruction is un-vectorizable. Implement it as a sequence
310 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
311 /// scalarized instruction behind an if block predicated on the control
312 /// dependence of the instruction.
313 virtual void scalarizeInstruction(Instruction *Instr,
314 bool IfPredicateStore=false);
316 /// Vectorize Load and Store instructions,
317 virtual void vectorizeMemoryInstruction(Instruction *Instr);
319 /// Create a broadcast instruction. This method generates a broadcast
320 /// instruction (shuffle) for loop invariant values and for the induction
321 /// value. If this is the induction variable then we extend it to N, N+1, ...
322 /// this is needed because each iteration in the loop corresponds to a SIMD
324 virtual Value *getBroadcastInstrs(Value *V);
326 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
327 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
328 /// The sequence starts at StartIndex.
329 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
331 /// When we go over instructions in the basic block we rely on previous
332 /// values within the current basic block or on loop invariant values.
333 /// When we widen (vectorize) values we place them in the map. If the values
334 /// are not within the map, they have to be loop invariant, so we simply
335 /// broadcast them into a vector.
336 VectorParts &getVectorValue(Value *V);
338 /// Generate a shuffle sequence that will reverse the vector Vec.
339 virtual Value *reverseVector(Value *Vec);
341 /// This is a helper class that holds the vectorizer state. It maps scalar
342 /// instructions to vector instructions. When the code is 'unrolled' then
343 /// then a single scalar value is mapped to multiple vector parts. The parts
344 /// are stored in the VectorPart type.
346 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
348 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
350 /// \return True if 'Key' is saved in the Value Map.
351 bool has(Value *Key) const { return MapStorage.count(Key); }
353 /// Initializes a new entry in the map. Sets all of the vector parts to the
354 /// save value in 'Val'.
355 /// \return A reference to a vector with splat values.
356 VectorParts &splat(Value *Key, Value *Val) {
357 VectorParts &Entry = MapStorage[Key];
358 Entry.assign(UF, Val);
362 ///\return A reference to the value that is stored at 'Key'.
363 VectorParts &get(Value *Key) {
364 VectorParts &Entry = MapStorage[Key];
367 assert(Entry.size() == UF);
372 /// The unroll factor. Each entry in the map stores this number of vector
376 /// Map storage. We use std::map and not DenseMap because insertions to a
377 /// dense map invalidates its iterators.
378 std::map<Value *, VectorParts> MapStorage;
381 /// The original loop.
383 /// Scev analysis to use.
390 const DataLayout *DL;
391 /// Target Library Info.
392 const TargetLibraryInfo *TLI;
394 /// The vectorization SIMD factor to use. Each vector will have this many
399 /// The vectorization unroll factor to use. Each scalar is vectorized to this
400 /// many different vector instructions.
403 /// The builder that we use
406 // --- Vectorization state ---
408 /// The vector-loop preheader.
409 BasicBlock *LoopVectorPreHeader;
410 /// The scalar-loop preheader.
411 BasicBlock *LoopScalarPreHeader;
412 /// Middle Block between the vector and the scalar.
413 BasicBlock *LoopMiddleBlock;
414 ///The ExitBlock of the scalar loop.
415 BasicBlock *LoopExitBlock;
416 ///The vector loop body.
417 SmallVector<BasicBlock *, 4> LoopVectorBody;
418 ///The scalar loop body.
419 BasicBlock *LoopScalarBody;
420 /// A list of all bypass blocks. The first block is the entry of the loop.
421 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
423 /// The new Induction variable which was added to the new block.
425 /// The induction variable of the old basic block.
426 PHINode *OldInduction;
427 /// Holds the extended (to the widest induction type) start index.
429 /// Maps scalars to widened vectors.
431 EdgeMaskCache MaskCache;
433 LoopVectorizationLegality *Legal;
436 class InnerLoopUnroller : public InnerLoopVectorizer {
438 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
439 DominatorTree *DT, const DataLayout *DL,
440 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
441 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
444 void scalarizeInstruction(Instruction *Instr,
445 bool IfPredicateStore = false) override;
446 void vectorizeMemoryInstruction(Instruction *Instr) override;
447 Value *getBroadcastInstrs(Value *V) override;
448 Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate) override;
449 Value *reverseVector(Value *Vec) override;
452 /// \brief Look for a meaningful debug location on the instruction or it's
454 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
459 if (I->getDebugLoc() != Empty)
462 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
463 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
464 if (OpInst->getDebugLoc() != Empty)
471 /// \brief Set the debug location in the builder using the debug location in the
473 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
474 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
475 B.SetCurrentDebugLocation(Inst->getDebugLoc());
477 B.SetCurrentDebugLocation(DebugLoc());
481 /// \return string containing a file name and a line # for the given
483 static format_object3<const char *, const char *, unsigned>
484 getDebugLocString(const Instruction *I) {
486 return format<const char *, const char *, unsigned>("", "", "", 0U);
487 MDNode *N = I->getMetadata("dbg");
489 const StringRef ModuleName =
490 I->getParent()->getParent()->getParent()->getModuleIdentifier();
491 return format<const char *, const char *, unsigned>("%s", ModuleName.data(),
494 const DILocation Loc(N);
495 const unsigned LineNo = Loc.getLineNumber();
496 const char *DirName = Loc.getDirectory().data();
497 const char *FileName = Loc.getFilename().data();
498 return format("%s/%s:%u", DirName, FileName, LineNo);
502 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
503 /// to what vectorization factor.
504 /// This class does not look at the profitability of vectorization, only the
505 /// legality. This class has two main kinds of checks:
506 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
507 /// will change the order of memory accesses in a way that will change the
508 /// correctness of the program.
509 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
510 /// checks for a number of different conditions, such as the availability of a
511 /// single induction variable, that all types are supported and vectorize-able,
512 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
513 /// This class is also used by InnerLoopVectorizer for identifying
514 /// induction variable and the different reduction variables.
515 class LoopVectorizationLegality {
519 unsigned NumPredStores;
521 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
522 DominatorTree *DT, TargetLibraryInfo *TLI)
523 : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
524 DT(DT), TLI(TLI), Induction(nullptr), WidestIndTy(nullptr),
525 HasFunNoNaNAttr(false), MaxSafeDepDistBytes(-1U) {}
527 /// This enum represents the kinds of reductions that we support.
529 RK_NoReduction, ///< Not a reduction.
530 RK_IntegerAdd, ///< Sum of integers.
531 RK_IntegerMult, ///< Product of integers.
532 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
533 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
534 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
535 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
536 RK_FloatAdd, ///< Sum of floats.
537 RK_FloatMult, ///< Product of floats.
538 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
541 /// This enum represents the kinds of inductions that we support.
543 IK_NoInduction, ///< Not an induction variable.
544 IK_IntInduction, ///< Integer induction variable. Step = 1.
545 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
546 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
547 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
550 // This enum represents the kind of minmax reduction.
551 enum MinMaxReductionKind {
561 /// This struct holds information about reduction variables.
562 struct ReductionDescriptor {
563 ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
564 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
566 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
567 MinMaxReductionKind MK)
568 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
570 // The starting value of the reduction.
571 // It does not have to be zero!
572 TrackingVH<Value> StartValue;
573 // The instruction who's value is used outside the loop.
574 Instruction *LoopExitInstr;
575 // The kind of the reduction.
577 // If this a min/max reduction the kind of reduction.
578 MinMaxReductionKind MinMaxKind;
581 /// This POD struct holds information about a potential reduction operation.
582 struct ReductionInstDesc {
583 ReductionInstDesc(bool IsRedux, Instruction *I) :
584 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
586 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
587 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
589 // Is this instruction a reduction candidate.
591 // The last instruction in a min/max pattern (select of the select(icmp())
592 // pattern), or the current reduction instruction otherwise.
593 Instruction *PatternLastInst;
594 // If this is a min/max pattern the comparison predicate.
595 MinMaxReductionKind MinMaxKind;
598 /// This struct holds information about the memory runtime legality
599 /// check that a group of pointers do not overlap.
600 struct RuntimePointerCheck {
601 RuntimePointerCheck() : Need(false) {}
603 /// Reset the state of the pointer runtime information.
610 DependencySetId.clear();
613 /// Insert a pointer and calculate the start and end SCEVs.
614 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
615 unsigned DepSetId, ValueToValueMap &Strides);
617 /// This flag indicates if we need to add the runtime check.
619 /// Holds the pointers that we need to check.
620 SmallVector<TrackingVH<Value>, 2> Pointers;
621 /// Holds the pointer value at the beginning of the loop.
622 SmallVector<const SCEV*, 2> Starts;
623 /// Holds the pointer value at the end of the loop.
624 SmallVector<const SCEV*, 2> Ends;
625 /// Holds the information if this pointer is used for writing to memory.
626 SmallVector<bool, 2> IsWritePtr;
627 /// Holds the id of the set of pointers that could be dependent because of a
628 /// shared underlying object.
629 SmallVector<unsigned, 2> DependencySetId;
632 /// A struct for saving information about induction variables.
633 struct InductionInfo {
634 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
635 InductionInfo() : StartValue(nullptr), IK(IK_NoInduction) {}
637 TrackingVH<Value> StartValue;
642 /// ReductionList contains the reduction descriptors for all
643 /// of the reductions that were found in the loop.
644 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
646 /// InductionList saves induction variables and maps them to the
647 /// induction descriptor.
648 typedef MapVector<PHINode*, InductionInfo> InductionList;
650 /// Returns true if it is legal to vectorize this loop.
651 /// This does not mean that it is profitable to vectorize this
652 /// loop, only that it is legal to do so.
655 /// Returns the Induction variable.
656 PHINode *getInduction() { return Induction; }
658 /// Returns the reduction variables found in the loop.
659 ReductionList *getReductionVars() { return &Reductions; }
661 /// Returns the induction variables found in the loop.
662 InductionList *getInductionVars() { return &Inductions; }
664 /// Returns the widest induction type.
665 Type *getWidestInductionType() { return WidestIndTy; }
667 /// Returns True if V is an induction variable in this loop.
668 bool isInductionVariable(const Value *V);
670 /// Return true if the block BB needs to be predicated in order for the loop
671 /// to be vectorized.
672 bool blockNeedsPredication(BasicBlock *BB);
674 /// Check if this pointer is consecutive when vectorizing. This happens
675 /// when the last index of the GEP is the induction variable, or that the
676 /// pointer itself is an induction variable.
677 /// This check allows us to vectorize A[idx] into a wide load/store.
679 /// 0 - Stride is unknown or non-consecutive.
680 /// 1 - Address is consecutive.
681 /// -1 - Address is consecutive, and decreasing.
682 int isConsecutivePtr(Value *Ptr);
684 /// Returns true if the value V is uniform within the loop.
685 bool isUniform(Value *V);
687 /// Returns true if this instruction will remain scalar after vectorization.
688 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
690 /// Returns the information that we collected about runtime memory check.
691 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
693 /// This function returns the identity element (or neutral element) for
695 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
697 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
699 bool hasStride(Value *V) { return StrideSet.count(V); }
700 bool mustCheckStrides() { return !StrideSet.empty(); }
701 SmallPtrSet<Value *, 8>::iterator strides_begin() {
702 return StrideSet.begin();
704 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
707 /// Check if a single basic block loop is vectorizable.
708 /// At this point we know that this is a loop with a constant trip count
709 /// and we only need to check individual instructions.
710 bool canVectorizeInstrs();
712 /// When we vectorize loops we may change the order in which
713 /// we read and write from memory. This method checks if it is
714 /// legal to vectorize the code, considering only memory constrains.
715 /// Returns true if the loop is vectorizable
716 bool canVectorizeMemory();
718 /// Return true if we can vectorize this loop using the IF-conversion
720 bool canVectorizeWithIfConvert();
722 /// Collect the variables that need to stay uniform after vectorization.
723 void collectLoopUniforms();
725 /// Return true if all of the instructions in the block can be speculatively
726 /// executed. \p SafePtrs is a list of addresses that are known to be legal
727 /// and we know that we can read from them without segfault.
728 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
730 /// Returns True, if 'Phi' is the kind of reduction variable for type
731 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
732 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
733 /// Returns a struct describing if the instruction 'I' can be a reduction
734 /// variable of type 'Kind'. If the reduction is a min/max pattern of
735 /// select(icmp()) this function advances the instruction pointer 'I' from the
736 /// compare instruction to the select instruction and stores this pointer in
737 /// 'PatternLastInst' member of the returned struct.
738 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
739 ReductionInstDesc &Desc);
740 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
741 /// pattern corresponding to a min(X, Y) or max(X, Y).
742 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
743 ReductionInstDesc &Prev);
744 /// Returns the induction kind of Phi. This function may return NoInduction
745 /// if the PHI is not an induction variable.
746 InductionKind isInductionVariable(PHINode *Phi);
748 /// \brief Collect memory access with loop invariant strides.
750 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
752 void collectStridedAcccess(Value *LoadOrStoreInst);
754 /// The loop that we evaluate.
758 /// DataLayout analysis.
759 const DataLayout *DL;
762 /// Target Library Info.
763 TargetLibraryInfo *TLI;
765 // --- vectorization state --- //
767 /// Holds the integer induction variable. This is the counter of the
770 /// Holds the reduction variables.
771 ReductionList Reductions;
772 /// Holds all of the induction variables that we found in the loop.
773 /// Notice that inductions don't need to start at zero and that induction
774 /// variables can be pointers.
775 InductionList Inductions;
776 /// Holds the widest induction type encountered.
779 /// Allowed outside users. This holds the reduction
780 /// vars which can be accessed from outside the loop.
781 SmallPtrSet<Value*, 4> AllowedExit;
782 /// This set holds the variables which are known to be uniform after
784 SmallPtrSet<Instruction*, 4> Uniforms;
785 /// We need to check that all of the pointers in this list are disjoint
787 RuntimePointerCheck PtrRtCheck;
788 /// Can we assume the absence of NaNs.
789 bool HasFunNoNaNAttr;
791 unsigned MaxSafeDepDistBytes;
793 ValueToValueMap Strides;
794 SmallPtrSet<Value *, 8> StrideSet;
797 /// LoopVectorizationCostModel - estimates the expected speedups due to
799 /// In many cases vectorization is not profitable. This can happen because of
800 /// a number of reasons. In this class we mainly attempt to predict the
801 /// expected speedup/slowdowns due to the supported instruction set. We use the
802 /// TargetTransformInfo to query the different backends for the cost of
803 /// different operations.
804 class LoopVectorizationCostModel {
806 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
807 LoopVectorizationLegality *Legal,
808 const TargetTransformInfo &TTI,
809 const DataLayout *DL, const TargetLibraryInfo *TLI)
810 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
812 /// Information about vectorization costs
813 struct VectorizationFactor {
814 unsigned Width; // Vector width with best cost
815 unsigned Cost; // Cost of the loop with that width
817 /// \return The most profitable vectorization factor and the cost of that VF.
818 /// This method checks every power of two up to VF. If UserVF is not ZERO
819 /// then this vectorization factor will be selected if vectorization is
821 VectorizationFactor selectVectorizationFactor(bool OptForSize,
824 /// \return The size (in bits) of the widest type in the code that
825 /// needs to be vectorized. We ignore values that remain scalar such as
826 /// 64 bit loop indices.
827 unsigned getWidestType();
829 /// \return The most profitable unroll factor.
830 /// If UserUF is non-zero then this method finds the best unroll-factor
831 /// based on register pressure and other parameters.
832 /// VF and LoopCost are the selected vectorization factor and the cost of the
834 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
837 /// \brief A struct that represents some properties of the register usage
839 struct RegisterUsage {
840 /// Holds the number of loop invariant values that are used in the loop.
841 unsigned LoopInvariantRegs;
842 /// Holds the maximum number of concurrent live intervals in the loop.
843 unsigned MaxLocalUsers;
844 /// Holds the number of instructions in the loop.
845 unsigned NumInstructions;
848 /// \return information about the register usage of the loop.
849 RegisterUsage calculateRegisterUsage();
852 /// Returns the expected execution cost. The unit of the cost does
853 /// not matter because we use the 'cost' units to compare different
854 /// vector widths. The cost that is returned is *not* normalized by
855 /// the factor width.
856 unsigned expectedCost(unsigned VF);
858 /// Returns the execution time cost of an instruction for a given vector
859 /// width. Vector width of one means scalar.
860 unsigned getInstructionCost(Instruction *I, unsigned VF);
862 /// A helper function for converting Scalar types to vector types.
863 /// If the incoming type is void, we return void. If the VF is 1, we return
865 static Type* ToVectorTy(Type *Scalar, unsigned VF);
867 /// Returns whether the instruction is a load or store and will be a emitted
868 /// as a vector operation.
869 bool isConsecutiveLoadOrStore(Instruction *I);
871 /// The loop that we evaluate.
875 /// Loop Info analysis.
877 /// Vectorization legality.
878 LoopVectorizationLegality *Legal;
879 /// Vector target information.
880 const TargetTransformInfo &TTI;
881 /// Target data layout information.
882 const DataLayout *DL;
883 /// Target Library Info.
884 const TargetLibraryInfo *TLI;
887 /// Utility class for getting and setting loop vectorizer hints in the form
888 /// of loop metadata.
889 struct LoopVectorizeHints {
890 /// Vectorization width.
892 /// Vectorization unroll factor.
894 /// Vectorization forced (-1 not selected, 0 force disabled, 1 force enabled)
897 LoopVectorizeHints(const Loop *L, bool DisableUnrolling)
898 : Width(VectorizationFactor)
899 , Unroll(DisableUnrolling ? 1 : VectorizationUnroll)
901 , LoopID(L->getLoopID()) {
903 // The command line options override any loop metadata except for when
904 // width == 1 which is used to indicate the loop is already vectorized.
905 if (VectorizationFactor.getNumOccurrences() > 0 && Width != 1)
906 Width = VectorizationFactor;
907 if (VectorizationUnroll.getNumOccurrences() > 0)
908 Unroll = VectorizationUnroll;
910 DEBUG(if (DisableUnrolling && Unroll == 1)
911 dbgs() << "LV: Unrolling disabled by the pass manager\n");
914 /// Return the loop vectorizer metadata prefix.
915 static StringRef Prefix() { return "llvm.vectorizer."; }
917 MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) {
918 SmallVector<Value*, 2> Vals;
919 Vals.push_back(MDString::get(Context, Name));
920 Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
921 return MDNode::get(Context, Vals);
924 /// Mark the loop L as already vectorized by setting the width to 1.
925 void setAlreadyVectorized(Loop *L) {
926 LLVMContext &Context = L->getHeader()->getContext();
930 // Create a new loop id with one more operand for the already_vectorized
931 // hint. If the loop already has a loop id then copy the existing operands.
932 SmallVector<Value*, 4> Vals(1);
934 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
935 Vals.push_back(LoopID->getOperand(i));
937 Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
938 Vals.push_back(createHint(Context, Twine(Prefix(), "unroll").str(), 1));
940 MDNode *NewLoopID = MDNode::get(Context, Vals);
941 // Set operand 0 to refer to the loop id itself.
942 NewLoopID->replaceOperandWith(0, NewLoopID);
944 L->setLoopID(NewLoopID);
946 LoopID->replaceAllUsesWith(NewLoopID);
954 /// Find hints specified in the loop metadata.
955 void getHints(const Loop *L) {
959 // First operand should refer to the loop id itself.
960 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
961 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
963 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
964 const MDString *S = nullptr;
965 SmallVector<Value*, 4> Args;
967 // The expected hint is either a MDString or a MDNode with the first
968 // operand a MDString.
969 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
970 if (!MD || MD->getNumOperands() == 0)
972 S = dyn_cast<MDString>(MD->getOperand(0));
973 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
974 Args.push_back(MD->getOperand(i));
976 S = dyn_cast<MDString>(LoopID->getOperand(i));
977 assert(Args.size() == 0 && "too many arguments for MDString");
983 // Check if the hint starts with the vectorizer prefix.
984 StringRef Hint = S->getString();
985 if (!Hint.startswith(Prefix()))
987 // Remove the prefix.
988 Hint = Hint.substr(Prefix().size(), StringRef::npos);
990 if (Args.size() == 1)
991 getHint(Hint, Args[0]);
995 // Check string hint with one operand.
996 void getHint(StringRef Hint, Value *Arg) {
997 const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
999 unsigned Val = C->getZExtValue();
1001 if (Hint == "width") {
1002 if (isPowerOf2_32(Val) && Val <= MaxVectorWidth)
1005 DEBUG(dbgs() << "LV: ignoring invalid width hint metadata\n");
1006 } else if (Hint == "unroll") {
1007 if (isPowerOf2_32(Val) && Val <= MaxUnrollFactor)
1010 DEBUG(dbgs() << "LV: ignoring invalid unroll hint metadata\n");
1011 } else if (Hint == "enable") {
1012 if (C->getBitWidth() == 1)
1015 DEBUG(dbgs() << "LV: ignoring invalid enable hint metadata\n");
1017 DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint << '\n');
1022 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1024 return V.push_back(&L);
1026 for (Loop *InnerL : L)
1027 addInnerLoop(*InnerL, V);
1030 /// The LoopVectorize Pass.
1031 struct LoopVectorize : public FunctionPass {
1032 /// Pass identification, replacement for typeid
1035 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1037 DisableUnrolling(NoUnrolling),
1038 AlwaysVectorize(AlwaysVectorize) {
1039 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1042 ScalarEvolution *SE;
1043 const DataLayout *DL;
1045 TargetTransformInfo *TTI;
1047 BlockFrequencyInfo *BFI;
1048 TargetLibraryInfo *TLI;
1049 bool DisableUnrolling;
1050 bool AlwaysVectorize;
1052 BlockFrequency ColdEntryFreq;
1054 bool runOnFunction(Function &F) override {
1055 SE = &getAnalysis<ScalarEvolution>();
1056 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1057 DL = DLP ? &DLP->getDataLayout() : nullptr;
1058 LI = &getAnalysis<LoopInfo>();
1059 TTI = &getAnalysis<TargetTransformInfo>();
1060 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1061 BFI = &getAnalysis<BlockFrequencyInfo>();
1062 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1064 // Compute some weights outside of the loop over the loops. Compute this
1065 // using a BranchProbability to re-use its scaling math.
1066 const BranchProbability ColdProb(1, 5); // 20%
1067 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1069 // If the target claims to have no vector registers don't attempt
1071 if (!TTI->getNumberOfRegisters(true))
1075 DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1076 << ": Missing data layout\n");
1080 // Build up a worklist of inner-loops to vectorize. This is necessary as
1081 // the act of vectorizing or partially unrolling a loop creates new loops
1082 // and can invalidate iterators across the loops.
1083 SmallVector<Loop *, 8> Worklist;
1086 addInnerLoop(*L, Worklist);
1088 LoopsAnalyzed += Worklist.size();
1090 // Now walk the identified inner loops.
1091 bool Changed = false;
1092 while (!Worklist.empty())
1093 Changed |= processLoop(Worklist.pop_back_val());
1095 // Process each loop nest in the function.
1099 bool processLoop(Loop *L) {
1100 assert(L->empty() && "Only process inner loops.");
1101 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1102 << L->getHeader()->getParent()->getName() << "\" from "
1103 << getDebugLocString(L->getHeader()->getFirstNonPHIOrDbg())
1106 LoopVectorizeHints Hints(L, DisableUnrolling);
1108 DEBUG(dbgs() << "LV: Loop hints:"
1109 << " force=" << (Hints.Force == 0
1111 : (Hints.Force == 1 ? "enabled" : "?"))
1112 << " width=" << Hints.Width << " unroll=" << Hints.Unroll
1115 if (Hints.Force == 0) {
1116 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1120 if (!AlwaysVectorize && Hints.Force != 1) {
1121 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1125 if (Hints.Width == 1 && Hints.Unroll == 1) {
1126 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1130 // Check if it is legal to vectorize the loop.
1131 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI);
1132 if (!LVL.canVectorize()) {
1133 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1137 // Use the cost model.
1138 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
1140 // Check the function attributes to find out if this function should be
1141 // optimized for size.
1142 Function *F = L->getHeader()->getParent();
1144 Hints.Force != 1 && F->hasFnAttribute(Attribute::OptimizeForSize);
1146 // Compute the weighted frequency of this loop being executed and see if it
1147 // is less than 20% of the function entry baseline frequency. Note that we
1148 // always have a canonical loop here because we think we *can* vectoriez.
1149 // FIXME: This is hidden behind a flag due to pervasive problems with
1150 // exactly what block frequency models.
1151 if (LoopVectorizeWithBlockFrequency) {
1152 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1153 if (Hints.Force != 1 && LoopEntryFreq < ColdEntryFreq)
1157 // Check the function attributes to see if implicit floats are allowed.a
1158 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1159 // an integer loop and the vector instructions selected are purely integer
1160 // vector instructions?
1161 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1162 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1163 "attribute is used.\n");
1167 // Select the optimal vectorization factor.
1168 const LoopVectorizationCostModel::VectorizationFactor VF =
1169 CM.selectVectorizationFactor(OptForSize, Hints.Width);
1170 // Select the unroll factor.
1171 const unsigned UF = CM.selectUnrollFactor(OptForSize, Hints.Unroll, VF.Width,
1174 DEBUG(dbgs() << "LV: Found a vectorizable loop ("
1175 << VF.Width << ") in "
1176 << getDebugLocString(L->getHeader()->getFirstNonPHIOrDbg())
1178 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1180 if (VF.Width == 1) {
1181 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1184 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1185 // We decided not to vectorize, but we may want to unroll.
1186 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1187 Unroller.vectorize(&LVL);
1189 // If we decided that it is *legal* to vectorize the loop then do it.
1190 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1195 // Mark the loop as already vectorized to avoid vectorizing again.
1196 Hints.setAlreadyVectorized(L);
1198 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1202 void getAnalysisUsage(AnalysisUsage &AU) const override {
1203 AU.addRequiredID(LoopSimplifyID);
1204 AU.addRequiredID(LCSSAID);
1205 AU.addRequired<BlockFrequencyInfo>();
1206 AU.addRequired<DominatorTreeWrapperPass>();
1207 AU.addRequired<LoopInfo>();
1208 AU.addRequired<ScalarEvolution>();
1209 AU.addRequired<TargetTransformInfo>();
1210 AU.addPreserved<LoopInfo>();
1211 AU.addPreserved<DominatorTreeWrapperPass>();
1216 } // end anonymous namespace
1218 //===----------------------------------------------------------------------===//
1219 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1220 // LoopVectorizationCostModel.
1221 //===----------------------------------------------------------------------===//
1223 static Value *stripIntegerCast(Value *V) {
1224 if (CastInst *CI = dyn_cast<CastInst>(V))
1225 if (CI->getOperand(0)->getType()->isIntegerTy())
1226 return CI->getOperand(0);
1230 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1232 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1234 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1235 ValueToValueMap &PtrToStride,
1236 Value *Ptr, Value *OrigPtr = nullptr) {
1238 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1240 // If there is an entry in the map return the SCEV of the pointer with the
1241 // symbolic stride replaced by one.
1242 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1243 if (SI != PtrToStride.end()) {
1244 Value *StrideVal = SI->second;
1247 StrideVal = stripIntegerCast(StrideVal);
1249 // Replace symbolic stride by one.
1250 Value *One = ConstantInt::get(StrideVal->getType(), 1);
1251 ValueToValueMap RewriteMap;
1252 RewriteMap[StrideVal] = One;
1255 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1256 DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1261 // Otherwise, just return the SCEV of the original pointer.
1262 return SE->getSCEV(Ptr);
1265 void LoopVectorizationLegality::RuntimePointerCheck::insert(
1266 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
1267 ValueToValueMap &Strides) {
1268 // Get the stride replaced scev.
1269 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1270 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1271 assert(AR && "Invalid addrec expression");
1272 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1273 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1274 Pointers.push_back(Ptr);
1275 Starts.push_back(AR->getStart());
1276 Ends.push_back(ScEnd);
1277 IsWritePtr.push_back(WritePtr);
1278 DependencySetId.push_back(DepSetId);
1281 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1282 // We need to place the broadcast of invariant variables outside the loop.
1283 Instruction *Instr = dyn_cast<Instruction>(V);
1285 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1286 Instr->getParent()) != LoopVectorBody.end());
1287 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1289 // Place the code for broadcasting invariant variables in the new preheader.
1290 IRBuilder<>::InsertPointGuard Guard(Builder);
1292 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1294 // Broadcast the scalar into all locations in the vector.
1295 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1300 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1302 assert(Val->getType()->isVectorTy() && "Must be a vector");
1303 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1304 "Elem must be an integer");
1305 // Create the types.
1306 Type *ITy = Val->getType()->getScalarType();
1307 VectorType *Ty = cast<VectorType>(Val->getType());
1308 int VLen = Ty->getNumElements();
1309 SmallVector<Constant*, 8> Indices;
1311 // Create a vector of consecutive numbers from zero to VF.
1312 for (int i = 0; i < VLen; ++i) {
1313 int64_t Idx = Negate ? (-i) : i;
1314 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1317 // Add the consecutive indices to the vector value.
1318 Constant *Cv = ConstantVector::get(Indices);
1319 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1320 return Builder.CreateAdd(Val, Cv, "induction");
1323 /// \brief Find the operand of the GEP that should be checked for consecutive
1324 /// stores. This ignores trailing indices that have no effect on the final
1326 static unsigned getGEPInductionOperand(const DataLayout *DL,
1327 const GetElementPtrInst *Gep) {
1328 unsigned LastOperand = Gep->getNumOperands() - 1;
1329 unsigned GEPAllocSize = DL->getTypeAllocSize(
1330 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1332 // Walk backwards and try to peel off zeros.
1333 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1334 // Find the type we're currently indexing into.
1335 gep_type_iterator GEPTI = gep_type_begin(Gep);
1336 std::advance(GEPTI, LastOperand - 1);
1338 // If it's a type with the same allocation size as the result of the GEP we
1339 // can peel off the zero index.
1340 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1348 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1349 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1350 // Make sure that the pointer does not point to structs.
1351 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1354 // If this value is a pointer induction variable we know it is consecutive.
1355 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1356 if (Phi && Inductions.count(Phi)) {
1357 InductionInfo II = Inductions[Phi];
1358 if (IK_PtrInduction == II.IK)
1360 else if (IK_ReversePtrInduction == II.IK)
1364 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1368 unsigned NumOperands = Gep->getNumOperands();
1369 Value *GpPtr = Gep->getPointerOperand();
1370 // If this GEP value is a consecutive pointer induction variable and all of
1371 // the indices are constant then we know it is consecutive. We can
1372 Phi = dyn_cast<PHINode>(GpPtr);
1373 if (Phi && Inductions.count(Phi)) {
1375 // Make sure that the pointer does not point to structs.
1376 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1377 if (GepPtrType->getElementType()->isAggregateType())
1380 // Make sure that all of the index operands are loop invariant.
1381 for (unsigned i = 1; i < NumOperands; ++i)
1382 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1385 InductionInfo II = Inductions[Phi];
1386 if (IK_PtrInduction == II.IK)
1388 else if (IK_ReversePtrInduction == II.IK)
1392 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1394 // Check that all of the gep indices are uniform except for our induction
1396 for (unsigned i = 0; i != NumOperands; ++i)
1397 if (i != InductionOperand &&
1398 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1401 // We can emit wide load/stores only if the last non-zero index is the
1402 // induction variable.
1403 const SCEV *Last = nullptr;
1404 if (!Strides.count(Gep))
1405 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1407 // Because of the multiplication by a stride we can have a s/zext cast.
1408 // We are going to replace this stride by 1 so the cast is safe to ignore.
1410 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1411 // %0 = trunc i64 %indvars.iv to i32
1412 // %mul = mul i32 %0, %Stride1
1413 // %idxprom = zext i32 %mul to i64 << Safe cast.
1414 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1416 Last = replaceSymbolicStrideSCEV(SE, Strides,
1417 Gep->getOperand(InductionOperand), Gep);
1418 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1420 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1424 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1425 const SCEV *Step = AR->getStepRecurrence(*SE);
1427 // The memory is consecutive because the last index is consecutive
1428 // and all other indices are loop invariant.
1431 if (Step->isAllOnesValue())
1438 bool LoopVectorizationLegality::isUniform(Value *V) {
1439 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1442 InnerLoopVectorizer::VectorParts&
1443 InnerLoopVectorizer::getVectorValue(Value *V) {
1444 assert(V != Induction && "The new induction variable should not be used.");
1445 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1447 // If we have a stride that is replaced by one, do it here.
1448 if (Legal->hasStride(V))
1449 V = ConstantInt::get(V->getType(), 1);
1451 // If we have this scalar in the map, return it.
1452 if (WidenMap.has(V))
1453 return WidenMap.get(V);
1455 // If this scalar is unknown, assume that it is a constant or that it is
1456 // loop invariant. Broadcast V and save the value for future uses.
1457 Value *B = getBroadcastInstrs(V);
1458 return WidenMap.splat(V, B);
1461 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1462 assert(Vec->getType()->isVectorTy() && "Invalid type");
1463 SmallVector<Constant*, 8> ShuffleMask;
1464 for (unsigned i = 0; i < VF; ++i)
1465 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1467 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1468 ConstantVector::get(ShuffleMask),
1472 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1473 // Attempt to issue a wide load.
1474 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1475 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1477 assert((LI || SI) && "Invalid Load/Store instruction");
1479 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1480 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1481 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1482 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1483 // An alignment of 0 means target abi alignment. We need to use the scalar's
1484 // target abi alignment in such a case.
1486 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1487 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1488 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1489 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1491 if (SI && Legal->blockNeedsPredication(SI->getParent()))
1492 return scalarizeInstruction(Instr, true);
1494 if (ScalarAllocatedSize != VectorElementSize)
1495 return scalarizeInstruction(Instr);
1497 // If the pointer is loop invariant or if it is non-consecutive,
1498 // scalarize the load.
1499 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1500 bool Reverse = ConsecutiveStride < 0;
1501 bool UniformLoad = LI && Legal->isUniform(Ptr);
1502 if (!ConsecutiveStride || UniformLoad)
1503 return scalarizeInstruction(Instr);
1505 Constant *Zero = Builder.getInt32(0);
1506 VectorParts &Entry = WidenMap.get(Instr);
1508 // Handle consecutive loads/stores.
1509 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1510 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1511 setDebugLocFromInst(Builder, Gep);
1512 Value *PtrOperand = Gep->getPointerOperand();
1513 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1514 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1516 // Create the new GEP with the new induction variable.
1517 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1518 Gep2->setOperand(0, FirstBasePtr);
1519 Gep2->setName("gep.indvar.base");
1520 Ptr = Builder.Insert(Gep2);
1522 setDebugLocFromInst(Builder, Gep);
1523 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1524 OrigLoop) && "Base ptr must be invariant");
1526 // The last index does not have to be the induction. It can be
1527 // consecutive and be a function of the index. For example A[I+1];
1528 unsigned NumOperands = Gep->getNumOperands();
1529 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1530 // Create the new GEP with the new induction variable.
1531 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1533 for (unsigned i = 0; i < NumOperands; ++i) {
1534 Value *GepOperand = Gep->getOperand(i);
1535 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1537 // Update last index or loop invariant instruction anchored in loop.
1538 if (i == InductionOperand ||
1539 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1540 assert((i == InductionOperand ||
1541 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1542 "Must be last index or loop invariant");
1544 VectorParts &GEPParts = getVectorValue(GepOperand);
1545 Value *Index = GEPParts[0];
1546 Index = Builder.CreateExtractElement(Index, Zero);
1547 Gep2->setOperand(i, Index);
1548 Gep2->setName("gep.indvar.idx");
1551 Ptr = Builder.Insert(Gep2);
1553 // Use the induction element ptr.
1554 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1555 setDebugLocFromInst(Builder, Ptr);
1556 VectorParts &PtrVal = getVectorValue(Ptr);
1557 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1562 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1563 "We do not allow storing to uniform addresses");
1564 setDebugLocFromInst(Builder, SI);
1565 // We don't want to update the value in the map as it might be used in
1566 // another expression. So don't use a reference type for "StoredVal".
1567 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1569 for (unsigned Part = 0; Part < UF; ++Part) {
1570 // Calculate the pointer for the specific unroll-part.
1571 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1574 // If we store to reverse consecutive memory locations then we need
1575 // to reverse the order of elements in the stored value.
1576 StoredVal[Part] = reverseVector(StoredVal[Part]);
1577 // If the address is consecutive but reversed, then the
1578 // wide store needs to start at the last vector element.
1579 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1580 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1583 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1584 DataTy->getPointerTo(AddressSpace));
1585 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1591 assert(LI && "Must have a load instruction");
1592 setDebugLocFromInst(Builder, LI);
1593 for (unsigned Part = 0; Part < UF; ++Part) {
1594 // Calculate the pointer for the specific unroll-part.
1595 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1598 // If the address is consecutive but reversed, then the
1599 // wide store needs to start at the last vector element.
1600 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1601 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1604 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1605 DataTy->getPointerTo(AddressSpace));
1606 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1607 cast<LoadInst>(LI)->setAlignment(Alignment);
1608 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1612 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1613 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1614 // Holds vector parameters or scalars, in case of uniform vals.
1615 SmallVector<VectorParts, 4> Params;
1617 setDebugLocFromInst(Builder, Instr);
1619 // Find all of the vectorized parameters.
1620 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1621 Value *SrcOp = Instr->getOperand(op);
1623 // If we are accessing the old induction variable, use the new one.
1624 if (SrcOp == OldInduction) {
1625 Params.push_back(getVectorValue(SrcOp));
1629 // Try using previously calculated values.
1630 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1632 // If the src is an instruction that appeared earlier in the basic block
1633 // then it should already be vectorized.
1634 if (SrcInst && OrigLoop->contains(SrcInst)) {
1635 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1636 // The parameter is a vector value from earlier.
1637 Params.push_back(WidenMap.get(SrcInst));
1639 // The parameter is a scalar from outside the loop. Maybe even a constant.
1640 VectorParts Scalars;
1641 Scalars.append(UF, SrcOp);
1642 Params.push_back(Scalars);
1646 assert(Params.size() == Instr->getNumOperands() &&
1647 "Invalid number of operands");
1649 // Does this instruction return a value ?
1650 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1652 Value *UndefVec = IsVoidRetTy ? nullptr :
1653 UndefValue::get(VectorType::get(Instr->getType(), VF));
1654 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1655 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1657 Instruction *InsertPt = Builder.GetInsertPoint();
1658 BasicBlock *IfBlock = Builder.GetInsertBlock();
1659 BasicBlock *CondBlock = nullptr;
1662 Loop *VectorLp = nullptr;
1663 if (IfPredicateStore) {
1664 assert(Instr->getParent()->getSinglePredecessor() &&
1665 "Only support single predecessor blocks");
1666 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1667 Instr->getParent());
1668 VectorLp = LI->getLoopFor(IfBlock);
1669 assert(VectorLp && "Must have a loop for this block");
1672 // For each vector unroll 'part':
1673 for (unsigned Part = 0; Part < UF; ++Part) {
1674 // For each scalar that we create:
1675 for (unsigned Width = 0; Width < VF; ++Width) {
1678 Value *Cmp = nullptr;
1679 if (IfPredicateStore) {
1680 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1681 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1682 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1683 LoopVectorBody.push_back(CondBlock);
1684 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
1685 // Update Builder with newly created basic block.
1686 Builder.SetInsertPoint(InsertPt);
1689 Instruction *Cloned = Instr->clone();
1691 Cloned->setName(Instr->getName() + ".cloned");
1692 // Replace the operands of the cloned instructions with extracted scalars.
1693 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1694 Value *Op = Params[op][Part];
1695 // Param is a vector. Need to extract the right lane.
1696 if (Op->getType()->isVectorTy())
1697 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1698 Cloned->setOperand(op, Op);
1701 // Place the cloned scalar in the new loop.
1702 Builder.Insert(Cloned);
1704 // If the original scalar returns a value we need to place it in a vector
1705 // so that future users will be able to use it.
1707 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1708 Builder.getInt32(Width));
1710 if (IfPredicateStore) {
1711 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1712 LoopVectorBody.push_back(NewIfBlock);
1713 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
1714 Builder.SetInsertPoint(InsertPt);
1715 Instruction *OldBr = IfBlock->getTerminator();
1716 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1717 OldBr->eraseFromParent();
1718 IfBlock = NewIfBlock;
1724 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1728 if (Instruction *I = dyn_cast<Instruction>(V))
1729 return I->getParent() == Loc->getParent() ? I : nullptr;
1733 std::pair<Instruction *, Instruction *>
1734 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1735 Instruction *tnullptr = nullptr;
1736 if (!Legal->mustCheckStrides())
1737 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1739 IRBuilder<> ChkBuilder(Loc);
1742 Value *Check = nullptr;
1743 Instruction *FirstInst = nullptr;
1744 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1745 SE = Legal->strides_end();
1747 Value *Ptr = stripIntegerCast(*SI);
1748 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1750 // Store the first instruction we create.
1751 FirstInst = getFirstInst(FirstInst, C, Loc);
1753 Check = ChkBuilder.CreateOr(Check, C);
1758 // We have to do this trickery because the IRBuilder might fold the check to a
1759 // constant expression in which case there is no Instruction anchored in a
1761 LLVMContext &Ctx = Loc->getContext();
1762 Instruction *TheCheck =
1763 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
1764 ChkBuilder.Insert(TheCheck, "stride.not.one");
1765 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
1767 return std::make_pair(FirstInst, TheCheck);
1770 std::pair<Instruction *, Instruction *>
1771 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
1772 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1773 Legal->getRuntimePointerCheck();
1775 Instruction *tnullptr = nullptr;
1776 if (!PtrRtCheck->Need)
1777 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1779 unsigned NumPointers = PtrRtCheck->Pointers.size();
1780 SmallVector<TrackingVH<Value> , 2> Starts;
1781 SmallVector<TrackingVH<Value> , 2> Ends;
1783 LLVMContext &Ctx = Loc->getContext();
1784 SCEVExpander Exp(*SE, "induction");
1785 Instruction *FirstInst = nullptr;
1787 for (unsigned i = 0; i < NumPointers; ++i) {
1788 Value *Ptr = PtrRtCheck->Pointers[i];
1789 const SCEV *Sc = SE->getSCEV(Ptr);
1791 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1792 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1794 Starts.push_back(Ptr);
1795 Ends.push_back(Ptr);
1797 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
1798 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1800 // Use this type for pointer arithmetic.
1801 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1803 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1804 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1805 Starts.push_back(Start);
1806 Ends.push_back(End);
1810 IRBuilder<> ChkBuilder(Loc);
1811 // Our instructions might fold to a constant.
1812 Value *MemoryRuntimeCheck = nullptr;
1813 for (unsigned i = 0; i < NumPointers; ++i) {
1814 for (unsigned j = i+1; j < NumPointers; ++j) {
1815 // No need to check if two readonly pointers intersect.
1816 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1819 // Only need to check pointers between two different dependency sets.
1820 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
1823 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1824 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1826 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1827 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1828 "Trying to bounds check pointers with different address spaces");
1830 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1831 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1833 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1834 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1835 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1836 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1838 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1839 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1840 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1841 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1842 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1843 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1844 if (MemoryRuntimeCheck) {
1845 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1847 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1849 MemoryRuntimeCheck = IsConflict;
1853 // We have to do this trickery because the IRBuilder might fold the check to a
1854 // constant expression in which case there is no Instruction anchored in a
1856 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1857 ConstantInt::getTrue(Ctx));
1858 ChkBuilder.Insert(Check, "memcheck.conflict");
1859 FirstInst = getFirstInst(FirstInst, Check, Loc);
1860 return std::make_pair(FirstInst, Check);
1863 void InnerLoopVectorizer::createEmptyLoop() {
1865 In this function we generate a new loop. The new loop will contain
1866 the vectorized instructions while the old loop will continue to run the
1869 [ ] <-- vector loop bypass (may consist of multiple blocks).
1872 | [ ] <-- vector pre header.
1876 | [ ]_| <-- vector loop.
1879 >[ ] <--- middle-block.
1882 | [ ] <--- new preheader.
1886 | [ ]_| <-- old scalar loop to handle remainder.
1889 >[ ] <-- exit block.
1893 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1894 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1895 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1896 assert(ExitBlock && "Must have an exit block");
1898 // Some loops have a single integer induction variable, while other loops
1899 // don't. One example is c++ iterators that often have multiple pointer
1900 // induction variables. In the code below we also support a case where we
1901 // don't have a single induction variable.
1902 OldInduction = Legal->getInduction();
1903 Type *IdxTy = Legal->getWidestInductionType();
1905 // Find the loop boundaries.
1906 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
1907 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1909 // The exit count might have the type of i64 while the phi is i32. This can
1910 // happen if we have an induction variable that is sign extended before the
1911 // compare. The only way that we get a backedge taken count is that the
1912 // induction variable was signed and as such will not overflow. In such a case
1913 // truncation is legal.
1914 if (ExitCount->getType()->getPrimitiveSizeInBits() >
1915 IdxTy->getPrimitiveSizeInBits())
1916 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
1918 ExitCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
1919 // Get the total trip count from the count by adding 1.
1920 ExitCount = SE->getAddExpr(ExitCount,
1921 SE->getConstant(ExitCount->getType(), 1));
1923 // Expand the trip count and place the new instructions in the preheader.
1924 // Notice that the pre-header does not change, only the loop body.
1925 SCEVExpander Exp(*SE, "induction");
1927 // Count holds the overall loop count (N).
1928 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1929 BypassBlock->getTerminator());
1931 // The loop index does not have to start at Zero. Find the original start
1932 // value from the induction PHI node. If we don't have an induction variable
1933 // then we know that it starts at zero.
1934 Builder.SetInsertPoint(BypassBlock->getTerminator());
1935 Value *StartIdx = ExtendedIdx = OldInduction ?
1936 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1938 ConstantInt::get(IdxTy, 0);
1940 assert(BypassBlock && "Invalid loop structure");
1941 LoopBypassBlocks.push_back(BypassBlock);
1943 // Split the single block loop into the two loop structure described above.
1944 BasicBlock *VectorPH =
1945 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1946 BasicBlock *VecBody =
1947 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1948 BasicBlock *MiddleBlock =
1949 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1950 BasicBlock *ScalarPH =
1951 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1953 // Create and register the new vector loop.
1954 Loop* Lp = new Loop();
1955 Loop *ParentLoop = OrigLoop->getParentLoop();
1957 // Insert the new loop into the loop nest and register the new basic blocks
1958 // before calling any utilities such as SCEV that require valid LoopInfo.
1960 ParentLoop->addChildLoop(Lp);
1961 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1962 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1963 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1965 LI->addTopLevelLoop(Lp);
1967 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1969 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1971 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
1973 // Generate the induction variable.
1974 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
1975 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1976 // The loop step is equal to the vectorization factor (num of SIMD elements)
1977 // times the unroll factor (num of SIMD instructions).
1978 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1980 // This is the IR builder that we use to add all of the logic for bypassing
1981 // the new vector loop.
1982 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1983 setDebugLocFromInst(BypassBuilder,
1984 getDebugLocFromInstOrOperands(OldInduction));
1986 // We may need to extend the index in case there is a type mismatch.
1987 // We know that the count starts at zero and does not overflow.
1988 if (Count->getType() != IdxTy) {
1989 // The exit count can be of pointer type. Convert it to the correct
1991 if (ExitCount->getType()->isPointerTy())
1992 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1994 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1997 // Add the start index to the loop count to get the new end index.
1998 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2000 // Now we need to generate the expression for N - (N % VF), which is
2001 // the part that the vectorized body will execute.
2002 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2003 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2004 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2005 "end.idx.rnd.down");
2007 // Now, compare the new count to zero. If it is zero skip the vector loop and
2008 // jump to the scalar loop.
2009 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
2012 BasicBlock *LastBypassBlock = BypassBlock;
2014 // Generate the code to check that the strides we assumed to be one are really
2015 // one. We want the new basic block to start at the first instruction in a
2016 // sequence of instructions that form a check.
2017 Instruction *StrideCheck;
2018 Instruction *FirstCheckInst;
2019 std::tie(FirstCheckInst, StrideCheck) =
2020 addStrideCheck(BypassBlock->getTerminator());
2022 // Create a new block containing the stride check.
2023 BasicBlock *CheckBlock =
2024 BypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2026 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2027 LoopBypassBlocks.push_back(CheckBlock);
2029 // Replace the branch into the memory check block with a conditional branch
2030 // for the "few elements case".
2031 Instruction *OldTerm = BypassBlock->getTerminator();
2032 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2033 OldTerm->eraseFromParent();
2036 LastBypassBlock = CheckBlock;
2039 // Generate the code that checks in runtime if arrays overlap. We put the
2040 // checks into a separate block to make the more common case of few elements
2042 Instruction *MemRuntimeCheck;
2043 std::tie(FirstCheckInst, MemRuntimeCheck) =
2044 addRuntimeCheck(LastBypassBlock->getTerminator());
2045 if (MemRuntimeCheck) {
2046 // Create a new block containing the memory check.
2047 BasicBlock *CheckBlock =
2048 LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
2050 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2051 LoopBypassBlocks.push_back(CheckBlock);
2053 // Replace the branch into the memory check block with a conditional branch
2054 // for the "few elements case".
2055 Instruction *OldTerm = LastBypassBlock->getTerminator();
2056 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2057 OldTerm->eraseFromParent();
2059 Cmp = MemRuntimeCheck;
2060 LastBypassBlock = CheckBlock;
2063 LastBypassBlock->getTerminator()->eraseFromParent();
2064 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2067 // We are going to resume the execution of the scalar loop.
2068 // Go over all of the induction variables that we found and fix the
2069 // PHIs that are left in the scalar version of the loop.
2070 // The starting values of PHI nodes depend on the counter of the last
2071 // iteration in the vectorized loop.
2072 // If we come from a bypass edge then we need to start from the original
2075 // This variable saves the new starting index for the scalar loop.
2076 PHINode *ResumeIndex = nullptr;
2077 LoopVectorizationLegality::InductionList::iterator I, E;
2078 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2079 // Set builder to point to last bypass block.
2080 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2081 for (I = List->begin(), E = List->end(); I != E; ++I) {
2082 PHINode *OrigPhi = I->first;
2083 LoopVectorizationLegality::InductionInfo II = I->second;
2085 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2086 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2087 MiddleBlock->getTerminator());
2088 // We might have extended the type of the induction variable but we need a
2089 // truncated version for the scalar loop.
2090 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2091 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2092 MiddleBlock->getTerminator()) : nullptr;
2094 Value *EndValue = nullptr;
2096 case LoopVectorizationLegality::IK_NoInduction:
2097 llvm_unreachable("Unknown induction");
2098 case LoopVectorizationLegality::IK_IntInduction: {
2099 // Handle the integer induction counter.
2100 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2102 // We have the canonical induction variable.
2103 if (OrigPhi == OldInduction) {
2104 // Create a truncated version of the resume value for the scalar loop,
2105 // we might have promoted the type to a larger width.
2107 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2108 // The new PHI merges the original incoming value, in case of a bypass,
2109 // or the value at the end of the vectorized loop.
2110 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2111 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2112 TruncResumeVal->addIncoming(EndValue, VecBody);
2114 // We know what the end value is.
2115 EndValue = IdxEndRoundDown;
2116 // We also know which PHI node holds it.
2117 ResumeIndex = ResumeVal;
2121 // Not the canonical induction variable - add the vector loop count to the
2123 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2124 II.StartValue->getType(),
2126 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
2129 case LoopVectorizationLegality::IK_ReverseIntInduction: {
2130 // Convert the CountRoundDown variable to the PHI size.
2131 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2132 II.StartValue->getType(),
2134 // Handle reverse integer induction counter.
2135 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
2138 case LoopVectorizationLegality::IK_PtrInduction: {
2139 // For pointer induction variables, calculate the offset using
2141 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2145 case LoopVectorizationLegality::IK_ReversePtrInduction: {
2146 // The value at the end of the loop for the reverse pointer is calculated
2147 // by creating a GEP with a negative index starting from the start value.
2148 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2149 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2151 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2157 // The new PHI merges the original incoming value, in case of a bypass,
2158 // or the value at the end of the vectorized loop.
2159 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
2160 if (OrigPhi == OldInduction)
2161 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2163 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2165 ResumeVal->addIncoming(EndValue, VecBody);
2167 // Fix the scalar body counter (PHI node).
2168 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2169 // The old inductions phi node in the scalar body needs the truncated value.
2170 if (OrigPhi == OldInduction)
2171 OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
2173 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
2176 // If we are generating a new induction variable then we also need to
2177 // generate the code that calculates the exit value. This value is not
2178 // simply the end of the counter because we may skip the vectorized body
2179 // in case of a runtime check.
2181 assert(!ResumeIndex && "Unexpected resume value found");
2182 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2183 MiddleBlock->getTerminator());
2184 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2185 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2186 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2189 // Make sure that we found the index where scalar loop needs to continue.
2190 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2191 "Invalid resume Index");
2193 // Add a check in the middle block to see if we have completed
2194 // all of the iterations in the first vector loop.
2195 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2196 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2197 ResumeIndex, "cmp.n",
2198 MiddleBlock->getTerminator());
2200 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2201 // Remove the old terminator.
2202 MiddleBlock->getTerminator()->eraseFromParent();
2204 // Create i+1 and fill the PHINode.
2205 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2206 Induction->addIncoming(StartIdx, VectorPH);
2207 Induction->addIncoming(NextIdx, VecBody);
2208 // Create the compare.
2209 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2210 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2212 // Now we have two terminators. Remove the old one from the block.
2213 VecBody->getTerminator()->eraseFromParent();
2215 // Get ready to start creating new instructions into the vectorized body.
2216 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2219 LoopVectorPreHeader = VectorPH;
2220 LoopScalarPreHeader = ScalarPH;
2221 LoopMiddleBlock = MiddleBlock;
2222 LoopExitBlock = ExitBlock;
2223 LoopVectorBody.push_back(VecBody);
2224 LoopScalarBody = OldBasicBlock;
2226 LoopVectorizeHints Hints(Lp, true);
2227 Hints.setAlreadyVectorized(Lp);
2230 /// This function returns the identity element (or neutral element) for
2231 /// the operation K.
2233 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2238 // Adding, Xoring, Oring zero to a number does not change it.
2239 return ConstantInt::get(Tp, 0);
2240 case RK_IntegerMult:
2241 // Multiplying a number by 1 does not change it.
2242 return ConstantInt::get(Tp, 1);
2244 // AND-ing a number with an all-1 value does not change it.
2245 return ConstantInt::get(Tp, -1, true);
2247 // Multiplying a number by 1 does not change it.
2248 return ConstantFP::get(Tp, 1.0L);
2250 // Adding zero to a number does not change it.
2251 return ConstantFP::get(Tp, 0.0L);
2253 llvm_unreachable("Unknown reduction kind");
2257 static Intrinsic::ID checkUnaryFloatSignature(const CallInst &I,
2258 Intrinsic::ID ValidIntrinsicID) {
2259 if (I.getNumArgOperands() != 1 ||
2260 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2261 I.getType() != I.getArgOperand(0)->getType() ||
2262 !I.onlyReadsMemory())
2263 return Intrinsic::not_intrinsic;
2265 return ValidIntrinsicID;
2268 static Intrinsic::ID checkBinaryFloatSignature(const CallInst &I,
2269 Intrinsic::ID ValidIntrinsicID) {
2270 if (I.getNumArgOperands() != 2 ||
2271 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2272 !I.getArgOperand(1)->getType()->isFloatingPointTy() ||
2273 I.getType() != I.getArgOperand(0)->getType() ||
2274 I.getType() != I.getArgOperand(1)->getType() ||
2275 !I.onlyReadsMemory())
2276 return Intrinsic::not_intrinsic;
2278 return ValidIntrinsicID;
2282 static Intrinsic::ID
2283 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
2284 // If we have an intrinsic call, check if it is trivially vectorizable.
2285 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2286 Intrinsic::ID ID = II->getIntrinsicID();
2287 if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
2288 ID == Intrinsic::lifetime_end)
2291 return Intrinsic::not_intrinsic;
2295 return Intrinsic::not_intrinsic;
2298 Function *F = CI->getCalledFunction();
2299 // We're going to make assumptions on the semantics of the functions, check
2300 // that the target knows that it's available in this environment and it does
2301 // not have local linkage.
2302 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(F->getName(), Func))
2303 return Intrinsic::not_intrinsic;
2305 // Otherwise check if we have a call to a function that can be turned into a
2306 // vector intrinsic.
2313 return checkUnaryFloatSignature(*CI, Intrinsic::sin);
2317 return checkUnaryFloatSignature(*CI, Intrinsic::cos);
2321 return checkUnaryFloatSignature(*CI, Intrinsic::exp);
2323 case LibFunc::exp2f:
2324 case LibFunc::exp2l:
2325 return checkUnaryFloatSignature(*CI, Intrinsic::exp2);
2329 return checkUnaryFloatSignature(*CI, Intrinsic::log);
2330 case LibFunc::log10:
2331 case LibFunc::log10f:
2332 case LibFunc::log10l:
2333 return checkUnaryFloatSignature(*CI, Intrinsic::log10);
2335 case LibFunc::log2f:
2336 case LibFunc::log2l:
2337 return checkUnaryFloatSignature(*CI, Intrinsic::log2);
2339 case LibFunc::fabsf:
2340 case LibFunc::fabsl:
2341 return checkUnaryFloatSignature(*CI, Intrinsic::fabs);
2342 case LibFunc::copysign:
2343 case LibFunc::copysignf:
2344 case LibFunc::copysignl:
2345 return checkBinaryFloatSignature(*CI, Intrinsic::copysign);
2346 case LibFunc::floor:
2347 case LibFunc::floorf:
2348 case LibFunc::floorl:
2349 return checkUnaryFloatSignature(*CI, Intrinsic::floor);
2351 case LibFunc::ceilf:
2352 case LibFunc::ceill:
2353 return checkUnaryFloatSignature(*CI, Intrinsic::ceil);
2354 case LibFunc::trunc:
2355 case LibFunc::truncf:
2356 case LibFunc::truncl:
2357 return checkUnaryFloatSignature(*CI, Intrinsic::trunc);
2359 case LibFunc::rintf:
2360 case LibFunc::rintl:
2361 return checkUnaryFloatSignature(*CI, Intrinsic::rint);
2362 case LibFunc::nearbyint:
2363 case LibFunc::nearbyintf:
2364 case LibFunc::nearbyintl:
2365 return checkUnaryFloatSignature(*CI, Intrinsic::nearbyint);
2366 case LibFunc::round:
2367 case LibFunc::roundf:
2368 case LibFunc::roundl:
2369 return checkUnaryFloatSignature(*CI, Intrinsic::round);
2373 return checkBinaryFloatSignature(*CI, Intrinsic::pow);
2376 return Intrinsic::not_intrinsic;
2379 /// This function translates the reduction kind to an LLVM binary operator.
2381 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2383 case LoopVectorizationLegality::RK_IntegerAdd:
2384 return Instruction::Add;
2385 case LoopVectorizationLegality::RK_IntegerMult:
2386 return Instruction::Mul;
2387 case LoopVectorizationLegality::RK_IntegerOr:
2388 return Instruction::Or;
2389 case LoopVectorizationLegality::RK_IntegerAnd:
2390 return Instruction::And;
2391 case LoopVectorizationLegality::RK_IntegerXor:
2392 return Instruction::Xor;
2393 case LoopVectorizationLegality::RK_FloatMult:
2394 return Instruction::FMul;
2395 case LoopVectorizationLegality::RK_FloatAdd:
2396 return Instruction::FAdd;
2397 case LoopVectorizationLegality::RK_IntegerMinMax:
2398 return Instruction::ICmp;
2399 case LoopVectorizationLegality::RK_FloatMinMax:
2400 return Instruction::FCmp;
2402 llvm_unreachable("Unknown reduction operation");
2406 Value *createMinMaxOp(IRBuilder<> &Builder,
2407 LoopVectorizationLegality::MinMaxReductionKind RK,
2410 CmpInst::Predicate P = CmpInst::ICMP_NE;
2413 llvm_unreachable("Unknown min/max reduction kind");
2414 case LoopVectorizationLegality::MRK_UIntMin:
2415 P = CmpInst::ICMP_ULT;
2417 case LoopVectorizationLegality::MRK_UIntMax:
2418 P = CmpInst::ICMP_UGT;
2420 case LoopVectorizationLegality::MRK_SIntMin:
2421 P = CmpInst::ICMP_SLT;
2423 case LoopVectorizationLegality::MRK_SIntMax:
2424 P = CmpInst::ICMP_SGT;
2426 case LoopVectorizationLegality::MRK_FloatMin:
2427 P = CmpInst::FCMP_OLT;
2429 case LoopVectorizationLegality::MRK_FloatMax:
2430 P = CmpInst::FCMP_OGT;
2435 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2436 RK == LoopVectorizationLegality::MRK_FloatMax)
2437 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2439 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2441 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2446 struct CSEDenseMapInfo {
2447 static bool canHandle(Instruction *I) {
2448 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2449 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2451 static inline Instruction *getEmptyKey() {
2452 return DenseMapInfo<Instruction *>::getEmptyKey();
2454 static inline Instruction *getTombstoneKey() {
2455 return DenseMapInfo<Instruction *>::getTombstoneKey();
2457 static unsigned getHashValue(Instruction *I) {
2458 assert(canHandle(I) && "Unknown instruction!");
2459 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2460 I->value_op_end()));
2462 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2463 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2464 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2466 return LHS->isIdenticalTo(RHS);
2471 /// \brief Check whether this block is a predicated block.
2472 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2473 /// = ...; " blocks. We start with one vectorized basic block. For every
2474 /// conditional block we split this vectorized block. Therefore, every second
2475 /// block will be a predicated one.
2476 static bool isPredicatedBlock(unsigned BlockNum) {
2477 return BlockNum % 2;
2480 ///\brief Perform cse of induction variable instructions.
2481 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2482 // Perform simple cse.
2483 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2484 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2485 BasicBlock *BB = BBs[i];
2486 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2487 Instruction *In = I++;
2489 if (!CSEDenseMapInfo::canHandle(In))
2492 // Check if we can replace this instruction with any of the
2493 // visited instructions.
2494 if (Instruction *V = CSEMap.lookup(In)) {
2495 In->replaceAllUsesWith(V);
2496 In->eraseFromParent();
2499 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2500 // ...;" blocks for predicated stores. Every second block is a predicated
2502 if (isPredicatedBlock(i))
2510 /// \brief Adds a 'fast' flag to floating point operations.
2511 static Value *addFastMathFlag(Value *V) {
2512 if (isa<FPMathOperator>(V)){
2513 FastMathFlags Flags;
2514 Flags.setUnsafeAlgebra();
2515 cast<Instruction>(V)->setFastMathFlags(Flags);
2520 void InnerLoopVectorizer::vectorizeLoop() {
2521 //===------------------------------------------------===//
2523 // Notice: any optimization or new instruction that go
2524 // into the code below should be also be implemented in
2527 //===------------------------------------------------===//
2528 Constant *Zero = Builder.getInt32(0);
2530 // In order to support reduction variables we need to be able to vectorize
2531 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2532 // stages. First, we create a new vector PHI node with no incoming edges.
2533 // We use this value when we vectorize all of the instructions that use the
2534 // PHI. Next, after all of the instructions in the block are complete we
2535 // add the new incoming edges to the PHI. At this point all of the
2536 // instructions in the basic block are vectorized, so we can use them to
2537 // construct the PHI.
2538 PhiVector RdxPHIsToFix;
2540 // Scan the loop in a topological order to ensure that defs are vectorized
2542 LoopBlocksDFS DFS(OrigLoop);
2545 // Vectorize all of the blocks in the original loop.
2546 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2547 be = DFS.endRPO(); bb != be; ++bb)
2548 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2550 // At this point every instruction in the original loop is widened to
2551 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2552 // that we vectorized. The PHI nodes are currently empty because we did
2553 // not want to introduce cycles. Notice that the remaining PHI nodes
2554 // that we need to fix are reduction variables.
2556 // Create the 'reduced' values for each of the induction vars.
2557 // The reduced values are the vector values that we scalarize and combine
2558 // after the loop is finished.
2559 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2561 PHINode *RdxPhi = *it;
2562 assert(RdxPhi && "Unable to recover vectorized PHI");
2564 // Find the reduction variable descriptor.
2565 assert(Legal->getReductionVars()->count(RdxPhi) &&
2566 "Unable to find the reduction variable");
2567 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2568 (*Legal->getReductionVars())[RdxPhi];
2570 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2572 // We need to generate a reduction vector from the incoming scalar.
2573 // To do so, we need to generate the 'identity' vector and override
2574 // one of the elements with the incoming scalar reduction. We need
2575 // to do it in the vector-loop preheader.
2576 Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
2578 // This is the vector-clone of the value that leaves the loop.
2579 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2580 Type *VecTy = VectorExit[0]->getType();
2582 // Find the reduction identity variable. Zero for addition, or, xor,
2583 // one for multiplication, -1 for And.
2586 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2587 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2588 // MinMax reduction have the start value as their identify.
2590 VectorStart = Identity = RdxDesc.StartValue;
2592 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2597 // Handle other reduction kinds:
2599 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2600 VecTy->getScalarType());
2603 // This vector is the Identity vector where the first element is the
2604 // incoming scalar reduction.
2605 VectorStart = RdxDesc.StartValue;
2607 Identity = ConstantVector::getSplat(VF, Iden);
2609 // This vector is the Identity vector where the first element is the
2610 // incoming scalar reduction.
2611 VectorStart = Builder.CreateInsertElement(Identity,
2612 RdxDesc.StartValue, Zero);
2616 // Fix the vector-loop phi.
2617 // We created the induction variable so we know that the
2618 // preheader is the first entry.
2619 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2621 // Reductions do not have to start at zero. They can start with
2622 // any loop invariant values.
2623 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2624 BasicBlock *Latch = OrigLoop->getLoopLatch();
2625 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2626 VectorParts &Val = getVectorValue(LoopVal);
2627 for (unsigned part = 0; part < UF; ++part) {
2628 // Make sure to add the reduction stat value only to the
2629 // first unroll part.
2630 Value *StartVal = (part == 0) ? VectorStart : Identity;
2631 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2632 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2633 LoopVectorBody.back());
2636 // Before each round, move the insertion point right between
2637 // the PHIs and the values we are going to write.
2638 // This allows us to write both PHINodes and the extractelement
2640 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2642 VectorParts RdxParts;
2643 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2644 for (unsigned part = 0; part < UF; ++part) {
2645 // This PHINode contains the vectorized reduction variable, or
2646 // the initial value vector, if we bypass the vector loop.
2647 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2648 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2649 Value *StartVal = (part == 0) ? VectorStart : Identity;
2650 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2651 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2652 NewPhi->addIncoming(RdxExitVal[part],
2653 LoopVectorBody.back());
2654 RdxParts.push_back(NewPhi);
2657 // Reduce all of the unrolled parts into a single vector.
2658 Value *ReducedPartRdx = RdxParts[0];
2659 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2660 setDebugLocFromInst(Builder, ReducedPartRdx);
2661 for (unsigned part = 1; part < UF; ++part) {
2662 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2663 // Floating point operations had to be 'fast' to enable the reduction.
2664 ReducedPartRdx = addFastMathFlag(
2665 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2666 ReducedPartRdx, "bin.rdx"));
2668 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2669 ReducedPartRdx, RdxParts[part]);
2673 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2674 // and vector ops, reducing the set of values being computed by half each
2676 assert(isPowerOf2_32(VF) &&
2677 "Reduction emission only supported for pow2 vectors!");
2678 Value *TmpVec = ReducedPartRdx;
2679 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2680 for (unsigned i = VF; i != 1; i >>= 1) {
2681 // Move the upper half of the vector to the lower half.
2682 for (unsigned j = 0; j != i/2; ++j)
2683 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2685 // Fill the rest of the mask with undef.
2686 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2687 UndefValue::get(Builder.getInt32Ty()));
2690 Builder.CreateShuffleVector(TmpVec,
2691 UndefValue::get(TmpVec->getType()),
2692 ConstantVector::get(ShuffleMask),
2695 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2696 // Floating point operations had to be 'fast' to enable the reduction.
2697 TmpVec = addFastMathFlag(Builder.CreateBinOp(
2698 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2700 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2703 // The result is in the first element of the vector.
2704 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2705 Builder.getInt32(0));
2708 // Now, we need to fix the users of the reduction variable
2709 // inside and outside of the scalar remainder loop.
2710 // We know that the loop is in LCSSA form. We need to update the
2711 // PHI nodes in the exit blocks.
2712 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2713 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2714 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2715 if (!LCSSAPhi) break;
2717 // All PHINodes need to have a single entry edge, or two if
2718 // we already fixed them.
2719 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2721 // We found our reduction value exit-PHI. Update it with the
2722 // incoming bypass edge.
2723 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2724 // Add an edge coming from the bypass.
2725 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2728 }// end of the LCSSA phi scan.
2730 // Fix the scalar loop reduction variable with the incoming reduction sum
2731 // from the vector body and from the backedge value.
2732 int IncomingEdgeBlockIdx =
2733 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2734 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2735 // Pick the other block.
2736 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2737 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, ReducedPartRdx);
2738 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2739 }// end of for each redux variable.
2743 // Remove redundant induction instructions.
2744 cse(LoopVectorBody);
2747 void InnerLoopVectorizer::fixLCSSAPHIs() {
2748 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2749 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2750 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2751 if (!LCSSAPhi) break;
2752 if (LCSSAPhi->getNumIncomingValues() == 1)
2753 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2758 InnerLoopVectorizer::VectorParts
2759 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2760 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2763 // Look for cached value.
2764 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2765 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2766 if (ECEntryIt != MaskCache.end())
2767 return ECEntryIt->second;
2769 VectorParts SrcMask = createBlockInMask(Src);
2771 // The terminator has to be a branch inst!
2772 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2773 assert(BI && "Unexpected terminator found");
2775 if (BI->isConditional()) {
2776 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2778 if (BI->getSuccessor(0) != Dst)
2779 for (unsigned part = 0; part < UF; ++part)
2780 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2782 for (unsigned part = 0; part < UF; ++part)
2783 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2785 MaskCache[Edge] = EdgeMask;
2789 MaskCache[Edge] = SrcMask;
2793 InnerLoopVectorizer::VectorParts
2794 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2795 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2797 // Loop incoming mask is all-one.
2798 if (OrigLoop->getHeader() == BB) {
2799 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2800 return getVectorValue(C);
2803 // This is the block mask. We OR all incoming edges, and with zero.
2804 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2805 VectorParts BlockMask = getVectorValue(Zero);
2808 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2809 VectorParts EM = createEdgeMask(*it, BB);
2810 for (unsigned part = 0; part < UF; ++part)
2811 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2817 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2818 InnerLoopVectorizer::VectorParts &Entry,
2819 unsigned UF, unsigned VF, PhiVector *PV) {
2820 PHINode* P = cast<PHINode>(PN);
2821 // Handle reduction variables:
2822 if (Legal->getReductionVars()->count(P)) {
2823 for (unsigned part = 0; part < UF; ++part) {
2824 // This is phase one of vectorizing PHIs.
2825 Type *VecTy = (VF == 1) ? PN->getType() :
2826 VectorType::get(PN->getType(), VF);
2827 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2828 LoopVectorBody.back()-> getFirstInsertionPt());
2834 setDebugLocFromInst(Builder, P);
2835 // Check for PHI nodes that are lowered to vector selects.
2836 if (P->getParent() != OrigLoop->getHeader()) {
2837 // We know that all PHIs in non-header blocks are converted into
2838 // selects, so we don't have to worry about the insertion order and we
2839 // can just use the builder.
2840 // At this point we generate the predication tree. There may be
2841 // duplications since this is a simple recursive scan, but future
2842 // optimizations will clean it up.
2844 unsigned NumIncoming = P->getNumIncomingValues();
2846 // Generate a sequence of selects of the form:
2847 // SELECT(Mask3, In3,
2848 // SELECT(Mask2, In2,
2850 for (unsigned In = 0; In < NumIncoming; In++) {
2851 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2853 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2855 for (unsigned part = 0; part < UF; ++part) {
2856 // We might have single edge PHIs (blocks) - use an identity
2857 // 'select' for the first PHI operand.
2859 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2862 // Select between the current value and the previous incoming edge
2863 // based on the incoming mask.
2864 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2865 Entry[part], "predphi");
2871 // This PHINode must be an induction variable.
2872 // Make sure that we know about it.
2873 assert(Legal->getInductionVars()->count(P) &&
2874 "Not an induction variable");
2876 LoopVectorizationLegality::InductionInfo II =
2877 Legal->getInductionVars()->lookup(P);
2880 case LoopVectorizationLegality::IK_NoInduction:
2881 llvm_unreachable("Unknown induction");
2882 case LoopVectorizationLegality::IK_IntInduction: {
2883 assert(P->getType() == II.StartValue->getType() && "Types must match");
2884 Type *PhiTy = P->getType();
2886 if (P == OldInduction) {
2887 // Handle the canonical induction variable. We might have had to
2889 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2891 // Handle other induction variables that are now based on the
2893 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2895 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2896 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2899 Broadcasted = getBroadcastInstrs(Broadcasted);
2900 // After broadcasting the induction variable we need to make the vector
2901 // consecutive by adding 0, 1, 2, etc.
2902 for (unsigned part = 0; part < UF; ++part)
2903 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2906 case LoopVectorizationLegality::IK_ReverseIntInduction:
2907 case LoopVectorizationLegality::IK_PtrInduction:
2908 case LoopVectorizationLegality::IK_ReversePtrInduction:
2909 // Handle reverse integer and pointer inductions.
2910 Value *StartIdx = ExtendedIdx;
2911 // This is the normalized GEP that starts counting at zero.
2912 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2915 // Handle the reverse integer induction variable case.
2916 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2917 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2918 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2920 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
2923 // This is a new value so do not hoist it out.
2924 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2925 // After broadcasting the induction variable we need to make the
2926 // vector consecutive by adding ... -3, -2, -1, 0.
2927 for (unsigned part = 0; part < UF; ++part)
2928 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2933 // Handle the pointer induction variable case.
2934 assert(P->getType()->isPointerTy() && "Unexpected type.");
2936 // Is this a reverse induction ptr or a consecutive induction ptr.
2937 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2940 // This is the vector of results. Notice that we don't generate
2941 // vector geps because scalar geps result in better code.
2942 for (unsigned part = 0; part < UF; ++part) {
2944 int EltIndex = (part) * (Reverse ? -1 : 1);
2945 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2948 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2950 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2952 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2954 Entry[part] = SclrGep;
2958 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2959 for (unsigned int i = 0; i < VF; ++i) {
2960 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2961 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2964 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2966 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2968 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2970 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2971 Builder.getInt32(i),
2974 Entry[part] = VecVal;
2980 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
2981 // For each instruction in the old loop.
2982 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2983 VectorParts &Entry = WidenMap.get(it);
2984 switch (it->getOpcode()) {
2985 case Instruction::Br:
2986 // Nothing to do for PHIs and BR, since we already took care of the
2987 // loop control flow instructions.
2989 case Instruction::PHI:{
2990 // Vectorize PHINodes.
2991 widenPHIInstruction(it, Entry, UF, VF, PV);
2995 case Instruction::Add:
2996 case Instruction::FAdd:
2997 case Instruction::Sub:
2998 case Instruction::FSub:
2999 case Instruction::Mul:
3000 case Instruction::FMul:
3001 case Instruction::UDiv:
3002 case Instruction::SDiv:
3003 case Instruction::FDiv:
3004 case Instruction::URem:
3005 case Instruction::SRem:
3006 case Instruction::FRem:
3007 case Instruction::Shl:
3008 case Instruction::LShr:
3009 case Instruction::AShr:
3010 case Instruction::And:
3011 case Instruction::Or:
3012 case Instruction::Xor: {
3013 // Just widen binops.
3014 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3015 setDebugLocFromInst(Builder, BinOp);
3016 VectorParts &A = getVectorValue(it->getOperand(0));
3017 VectorParts &B = getVectorValue(it->getOperand(1));
3019 // Use this vector value for all users of the original instruction.
3020 for (unsigned Part = 0; Part < UF; ++Part) {
3021 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3023 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
3024 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
3025 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
3026 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
3027 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
3029 if (VecOp && isa<PossiblyExactOperator>(VecOp))
3030 VecOp->setIsExact(BinOp->isExact());
3032 // Copy the fast-math flags.
3033 if (VecOp && isa<FPMathOperator>(V))
3034 VecOp->setFastMathFlags(it->getFastMathFlags());
3040 case Instruction::Select: {
3042 // If the selector is loop invariant we can create a select
3043 // instruction with a scalar condition. Otherwise, use vector-select.
3044 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3046 setDebugLocFromInst(Builder, it);
3048 // The condition can be loop invariant but still defined inside the
3049 // loop. This means that we can't just use the original 'cond' value.
3050 // We have to take the 'vectorized' value and pick the first lane.
3051 // Instcombine will make this a no-op.
3052 VectorParts &Cond = getVectorValue(it->getOperand(0));
3053 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3054 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3056 Value *ScalarCond = (VF == 1) ? Cond[0] :
3057 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3059 for (unsigned Part = 0; Part < UF; ++Part) {
3060 Entry[Part] = Builder.CreateSelect(
3061 InvariantCond ? ScalarCond : Cond[Part],
3068 case Instruction::ICmp:
3069 case Instruction::FCmp: {
3070 // Widen compares. Generate vector compares.
3071 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3072 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3073 setDebugLocFromInst(Builder, it);
3074 VectorParts &A = getVectorValue(it->getOperand(0));
3075 VectorParts &B = getVectorValue(it->getOperand(1));
3076 for (unsigned Part = 0; Part < UF; ++Part) {
3079 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3081 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3087 case Instruction::Store:
3088 case Instruction::Load:
3089 vectorizeMemoryInstruction(it);
3091 case Instruction::ZExt:
3092 case Instruction::SExt:
3093 case Instruction::FPToUI:
3094 case Instruction::FPToSI:
3095 case Instruction::FPExt:
3096 case Instruction::PtrToInt:
3097 case Instruction::IntToPtr:
3098 case Instruction::SIToFP:
3099 case Instruction::UIToFP:
3100 case Instruction::Trunc:
3101 case Instruction::FPTrunc:
3102 case Instruction::BitCast: {
3103 CastInst *CI = dyn_cast<CastInst>(it);
3104 setDebugLocFromInst(Builder, it);
3105 /// Optimize the special case where the source is the induction
3106 /// variable. Notice that we can only optimize the 'trunc' case
3107 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3108 /// c. other casts depend on pointer size.
3109 if (CI->getOperand(0) == OldInduction &&
3110 it->getOpcode() == Instruction::Trunc) {
3111 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3113 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3114 for (unsigned Part = 0; Part < UF; ++Part)
3115 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
3118 /// Vectorize casts.
3119 Type *DestTy = (VF == 1) ? CI->getType() :
3120 VectorType::get(CI->getType(), VF);
3122 VectorParts &A = getVectorValue(it->getOperand(0));
3123 for (unsigned Part = 0; Part < UF; ++Part)
3124 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3128 case Instruction::Call: {
3129 // Ignore dbg intrinsics.
3130 if (isa<DbgInfoIntrinsic>(it))
3132 setDebugLocFromInst(Builder, it);
3134 Module *M = BB->getParent()->getParent();
3135 CallInst *CI = cast<CallInst>(it);
3136 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3137 assert(ID && "Not an intrinsic call!");
3139 case Intrinsic::lifetime_end:
3140 case Intrinsic::lifetime_start:
3141 scalarizeInstruction(it);
3144 for (unsigned Part = 0; Part < UF; ++Part) {
3145 SmallVector<Value *, 4> Args;
3146 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3147 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3148 Args.push_back(Arg[Part]);
3150 Type *Tys[] = {CI->getType()};
3152 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3154 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3155 Entry[Part] = Builder.CreateCall(F, Args);
3163 // All other instructions are unsupported. Scalarize them.
3164 scalarizeInstruction(it);
3167 }// end of for_each instr.
3170 void InnerLoopVectorizer::updateAnalysis() {
3171 // Forget the original basic block.
3172 SE->forgetLoop(OrigLoop);
3174 // Update the dominator tree information.
3175 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3176 "Entry does not dominate exit.");
3178 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3179 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3180 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3182 // Due to if predication of stores we might create a sequence of "if(pred)
3183 // a[i] = ...; " blocks.
3184 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3186 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3187 else if (isPredicatedBlock(i)) {
3188 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3190 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3194 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
3195 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
3196 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3197 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3199 DEBUG(DT->verifyDomTree());
3202 /// \brief Check whether it is safe to if-convert this phi node.
3204 /// Phi nodes with constant expressions that can trap are not safe to if
3206 static bool canIfConvertPHINodes(BasicBlock *BB) {
3207 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3208 PHINode *Phi = dyn_cast<PHINode>(I);
3211 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3212 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3219 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3220 if (!EnableIfConversion)
3223 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3225 // A list of pointers that we can safely read and write to.
3226 SmallPtrSet<Value *, 8> SafePointes;
3228 // Collect safe addresses.
3229 for (Loop::block_iterator BI = TheLoop->block_begin(),
3230 BE = TheLoop->block_end(); BI != BE; ++BI) {
3231 BasicBlock *BB = *BI;
3233 if (blockNeedsPredication(BB))
3236 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3237 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3238 SafePointes.insert(LI->getPointerOperand());
3239 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3240 SafePointes.insert(SI->getPointerOperand());
3244 // Collect the blocks that need predication.
3245 BasicBlock *Header = TheLoop->getHeader();
3246 for (Loop::block_iterator BI = TheLoop->block_begin(),
3247 BE = TheLoop->block_end(); BI != BE; ++BI) {
3248 BasicBlock *BB = *BI;
3250 // We don't support switch statements inside loops.
3251 if (!isa<BranchInst>(BB->getTerminator()))
3254 // We must be able to predicate all blocks that need to be predicated.
3255 if (blockNeedsPredication(BB)) {
3256 if (!blockCanBePredicated(BB, SafePointes))
3258 } else if (BB != Header && !canIfConvertPHINodes(BB))
3263 // We can if-convert this loop.
3267 bool LoopVectorizationLegality::canVectorize() {
3268 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3269 // be canonicalized.
3270 if (!TheLoop->getLoopPreheader())
3273 // We can only vectorize innermost loops.
3274 if (TheLoop->getSubLoopsVector().size())
3277 // We must have a single backedge.
3278 if (TheLoop->getNumBackEdges() != 1)
3281 // We must have a single exiting block.
3282 if (!TheLoop->getExitingBlock())
3285 // We need to have a loop header.
3286 DEBUG(dbgs() << "LV: Found a loop: " <<
3287 TheLoop->getHeader()->getName() << '\n');
3289 // Check if we can if-convert non-single-bb loops.
3290 unsigned NumBlocks = TheLoop->getNumBlocks();
3291 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3292 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3296 // ScalarEvolution needs to be able to find the exit count.
3297 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3298 if (ExitCount == SE->getCouldNotCompute()) {
3299 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3303 // Do not loop-vectorize loops with a tiny trip count.
3304 BasicBlock *Latch = TheLoop->getLoopLatch();
3305 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
3306 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
3307 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
3308 "This loop is not worth vectorizing.\n");
3312 // Check if we can vectorize the instructions and CFG in this loop.
3313 if (!canVectorizeInstrs()) {
3314 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3318 // Go over each instruction and look at memory deps.
3319 if (!canVectorizeMemory()) {
3320 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3324 // Collect all of the variables that remain uniform after vectorization.
3325 collectLoopUniforms();
3327 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3328 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3331 // Okay! We can vectorize. At this point we don't have any other mem analysis
3332 // which may limit our maximum vectorization factor, so just return true with
3337 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3338 if (Ty->isPointerTy())
3339 return DL.getIntPtrType(Ty);
3341 // It is possible that char's or short's overflow when we ask for the loop's
3342 // trip count, work around this by changing the type size.
3343 if (Ty->getScalarSizeInBits() < 32)
3344 return Type::getInt32Ty(Ty->getContext());
3349 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3350 Ty0 = convertPointerToIntegerType(DL, Ty0);
3351 Ty1 = convertPointerToIntegerType(DL, Ty1);
3352 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3357 /// \brief Check that the instruction has outside loop users and is not an
3358 /// identified reduction variable.
3359 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3360 SmallPtrSet<Value *, 4> &Reductions) {
3361 // Reduction instructions are allowed to have exit users. All other
3362 // instructions must not have external users.
3363 if (!Reductions.count(Inst))
3364 //Check that all of the users of the loop are inside the BB.
3365 for (User *U : Inst->users()) {
3366 Instruction *UI = cast<Instruction>(U);
3367 // This user may be a reduction exit value.
3368 if (!TheLoop->contains(UI)) {
3369 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3376 bool LoopVectorizationLegality::canVectorizeInstrs() {
3377 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3378 BasicBlock *Header = TheLoop->getHeader();
3380 // Look for the attribute signaling the absence of NaNs.
3381 Function &F = *Header->getParent();
3382 if (F.hasFnAttribute("no-nans-fp-math"))
3383 HasFunNoNaNAttr = F.getAttributes().getAttribute(
3384 AttributeSet::FunctionIndex,
3385 "no-nans-fp-math").getValueAsString() == "true";
3387 // For each block in the loop.
3388 for (Loop::block_iterator bb = TheLoop->block_begin(),
3389 be = TheLoop->block_end(); bb != be; ++bb) {
3391 // Scan the instructions in the block and look for hazards.
3392 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3395 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3396 Type *PhiTy = Phi->getType();
3397 // Check that this PHI type is allowed.
3398 if (!PhiTy->isIntegerTy() &&
3399 !PhiTy->isFloatingPointTy() &&
3400 !PhiTy->isPointerTy()) {
3401 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3405 // If this PHINode is not in the header block, then we know that we
3406 // can convert it to select during if-conversion. No need to check if
3407 // the PHIs in this block are induction or reduction variables.
3408 if (*bb != Header) {
3409 // Check that this instruction has no outside users or is an
3410 // identified reduction value with an outside user.
3411 if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3416 // We only allow if-converted PHIs with more than two incoming values.
3417 if (Phi->getNumIncomingValues() != 2) {
3418 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3422 // This is the value coming from the preheader.
3423 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3424 // Check if this is an induction variable.
3425 InductionKind IK = isInductionVariable(Phi);
3427 if (IK_NoInduction != IK) {
3428 // Get the widest type.
3430 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3432 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3434 // Int inductions are special because we only allow one IV.
3435 if (IK == IK_IntInduction) {
3436 // Use the phi node with the widest type as induction. Use the last
3437 // one if there are multiple (no good reason for doing this other
3438 // than it is expedient).
3439 if (!Induction || PhiTy == WidestIndTy)
3443 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3444 Inductions[Phi] = InductionInfo(StartValue, IK);
3446 // Until we explicitly handle the case of an induction variable with
3447 // an outside loop user we have to give up vectorizing this loop.
3448 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3454 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3455 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3458 if (AddReductionVar(Phi, RK_IntegerMult)) {
3459 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3462 if (AddReductionVar(Phi, RK_IntegerOr)) {
3463 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3466 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3467 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3470 if (AddReductionVar(Phi, RK_IntegerXor)) {
3471 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3474 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3475 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3478 if (AddReductionVar(Phi, RK_FloatMult)) {
3479 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3482 if (AddReductionVar(Phi, RK_FloatAdd)) {
3483 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3486 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3487 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3492 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3494 }// end of PHI handling
3496 // We still don't handle functions. However, we can ignore dbg intrinsic
3497 // calls and we do handle certain intrinsic and libm functions.
3498 CallInst *CI = dyn_cast<CallInst>(it);
3499 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3500 DEBUG(dbgs() << "LV: Found a call site.\n");
3504 // Check that the instruction return type is vectorizable.
3505 // Also, we can't vectorize extractelement instructions.
3506 if ((!VectorType::isValidElementType(it->getType()) &&
3507 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3508 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3512 // Check that the stored type is vectorizable.
3513 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3514 Type *T = ST->getValueOperand()->getType();
3515 if (!VectorType::isValidElementType(T))
3517 if (EnableMemAccessVersioning)
3518 collectStridedAcccess(ST);
3521 if (EnableMemAccessVersioning)
3522 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3523 collectStridedAcccess(LI);
3525 // Reduction instructions are allowed to have exit users.
3526 // All other instructions must not have external users.
3527 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3535 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3536 if (Inductions.empty())
3543 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3544 /// return the induction operand of the gep pointer.
3545 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3546 const DataLayout *DL, Loop *Lp) {
3547 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3551 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3553 // Check that all of the gep indices are uniform except for our induction
3555 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3556 if (i != InductionOperand &&
3557 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3559 return GEP->getOperand(InductionOperand);
3562 ///\brief Look for a cast use of the passed value.
3563 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3564 Value *UniqueCast = nullptr;
3565 for (User *U : Ptr->users()) {
3566 CastInst *CI = dyn_cast<CastInst>(U);
3567 if (CI && CI->getType() == Ty) {
3577 ///\brief Get the stride of a pointer access in a loop.
3578 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3579 /// pointer to the Value, or null otherwise.
3580 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3581 const DataLayout *DL, Loop *Lp) {
3582 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3583 if (!PtrTy || PtrTy->isAggregateType())
3586 // Try to remove a gep instruction to make the pointer (actually index at this
3587 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3588 // pointer, otherwise, we are analyzing the index.
3589 Value *OrigPtr = Ptr;
3591 // The size of the pointer access.
3592 int64_t PtrAccessSize = 1;
3594 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3595 const SCEV *V = SE->getSCEV(Ptr);
3599 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3600 V = C->getOperand();
3602 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3606 V = S->getStepRecurrence(*SE);
3610 // Strip off the size of access multiplication if we are still analyzing the
3612 if (OrigPtr == Ptr) {
3613 DL->getTypeAllocSize(PtrTy->getElementType());
3614 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3615 if (M->getOperand(0)->getSCEVType() != scConstant)
3618 const APInt &APStepVal =
3619 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3621 // Huge step value - give up.
3622 if (APStepVal.getBitWidth() > 64)
3625 int64_t StepVal = APStepVal.getSExtValue();
3626 if (PtrAccessSize != StepVal)
3628 V = M->getOperand(1);
3633 Type *StripedOffRecurrenceCast = nullptr;
3634 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3635 StripedOffRecurrenceCast = C->getType();
3636 V = C->getOperand();
3639 // Look for the loop invariant symbolic value.
3640 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3644 Value *Stride = U->getValue();
3645 if (!Lp->isLoopInvariant(Stride))
3648 // If we have stripped off the recurrence cast we have to make sure that we
3649 // return the value that is used in this loop so that we can replace it later.
3650 if (StripedOffRecurrenceCast)
3651 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3656 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
3657 Value *Ptr = nullptr;
3658 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3659 Ptr = LI->getPointerOperand();
3660 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3661 Ptr = SI->getPointerOperand();
3665 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3669 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3670 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3671 Strides[Ptr] = Stride;
3672 StrideSet.insert(Stride);
3675 void LoopVectorizationLegality::collectLoopUniforms() {
3676 // We now know that the loop is vectorizable!
3677 // Collect variables that will remain uniform after vectorization.
3678 std::vector<Value*> Worklist;
3679 BasicBlock *Latch = TheLoop->getLoopLatch();
3681 // Start with the conditional branch and walk up the block.
3682 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3684 // Also add all consecutive pointer values; these values will be uniform
3685 // after vectorization (and subsequent cleanup) and, until revectorization is
3686 // supported, all dependencies must also be uniform.
3687 for (Loop::block_iterator B = TheLoop->block_begin(),
3688 BE = TheLoop->block_end(); B != BE; ++B)
3689 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3691 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3692 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3694 while (Worklist.size()) {
3695 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3696 Worklist.pop_back();
3698 // Look at instructions inside this loop.
3699 // Stop when reaching PHI nodes.
3700 // TODO: we need to follow values all over the loop, not only in this block.
3701 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3704 // This is a known uniform.
3707 // Insert all operands.
3708 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3713 /// \brief Analyses memory accesses in a loop.
3715 /// Checks whether run time pointer checks are needed and builds sets for data
3716 /// dependence checking.
3717 class AccessAnalysis {
3719 /// \brief Read or write access location.
3720 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3721 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3723 /// \brief Set of potential dependent memory accesses.
3724 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
3726 AccessAnalysis(const DataLayout *Dl, DepCandidates &DA) :
3727 DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
3728 AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
3730 /// \brief Register a load and whether it is only read from.
3731 void addLoad(Value *Ptr, bool IsReadOnly) {
3732 Accesses.insert(MemAccessInfo(Ptr, false));
3734 ReadOnlyPtr.insert(Ptr);
3737 /// \brief Register a store.
3738 void addStore(Value *Ptr) {
3739 Accesses.insert(MemAccessInfo(Ptr, true));
3742 /// \brief Check whether we can check the pointers at runtime for
3743 /// non-intersection.
3744 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3745 unsigned &NumComparisons, ScalarEvolution *SE,
3746 Loop *TheLoop, ValueToValueMap &Strides,
3747 bool ShouldCheckStride = false);
3749 /// \brief Goes over all memory accesses, checks whether a RT check is needed
3750 /// and builds sets of dependent accesses.
3751 void buildDependenceSets() {
3752 // Process read-write pointers first.
3753 processMemAccesses(false);
3754 // Next, process read pointers.
3755 processMemAccesses(true);
3758 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
3760 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
3761 void resetDepChecks() { CheckDeps.clear(); }
3763 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
3766 typedef SetVector<MemAccessInfo> PtrAccessSet;
3767 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
3769 /// \brief Go over all memory access or only the deferred ones if
3770 /// \p UseDeferred is true and check whether runtime pointer checks are needed
3771 /// and build sets of dependency check candidates.
3772 void processMemAccesses(bool UseDeferred);
3774 /// Set of all accesses.
3775 PtrAccessSet Accesses;
3777 /// Set of access to check after all writes have been processed.
3778 PtrAccessSet DeferredAccesses;
3780 /// Map of pointers to last access encountered.
3781 UnderlyingObjToAccessMap ObjToLastAccess;
3783 /// Set of accesses that need a further dependence check.
3784 MemAccessInfoSet CheckDeps;
3786 /// Set of pointers that are read only.
3787 SmallPtrSet<Value*, 16> ReadOnlyPtr;
3789 /// Set of underlying objects already written to.
3790 SmallPtrSet<Value*, 16> WriteObjects;
3792 const DataLayout *DL;
3794 /// Sets of potentially dependent accesses - members of one set share an
3795 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
3796 /// dependence check.
3797 DepCandidates &DepCands;
3799 bool AreAllWritesIdentified;
3800 bool AreAllReadsIdentified;
3801 bool IsRTCheckNeeded;
3804 } // end anonymous namespace
3806 /// \brief Check whether a pointer can participate in a runtime bounds check.
3807 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
3809 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
3810 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3814 return AR->isAffine();
3817 /// \brief Check the stride of the pointer and ensure that it does not wrap in
3818 /// the address space.
3819 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
3820 const Loop *Lp, ValueToValueMap &StridesMap);
3822 bool AccessAnalysis::canCheckPtrAtRT(
3823 LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3824 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
3825 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
3826 // Find pointers with computable bounds. We are going to use this information
3827 // to place a runtime bound check.
3828 unsigned NumReadPtrChecks = 0;
3829 unsigned NumWritePtrChecks = 0;
3830 bool CanDoRT = true;
3832 bool IsDepCheckNeeded = isDependencyCheckNeeded();
3833 // We assign consecutive id to access from different dependence sets.
3834 // Accesses within the same set don't need a runtime check.
3835 unsigned RunningDepId = 1;
3836 DenseMap<Value *, unsigned> DepSetId;
3838 for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
3840 const MemAccessInfo &Access = *AI;
3841 Value *Ptr = Access.getPointer();
3842 bool IsWrite = Access.getInt();
3844 // Just add write checks if we have both.
3845 if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
3849 ++NumWritePtrChecks;
3853 if (hasComputableBounds(SE, StridesMap, Ptr) &&
3854 // When we run after a failing dependency check we have to make sure we
3855 // don't have wrapping pointers.
3856 (!ShouldCheckStride ||
3857 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
3858 // The id of the dependence set.
3861 if (IsDepCheckNeeded) {
3862 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
3863 unsigned &LeaderId = DepSetId[Leader];
3865 LeaderId = RunningDepId++;
3868 // Each access has its own dependence set.
3869 DepId = RunningDepId++;
3871 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, StridesMap);
3873 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
3879 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
3880 NumComparisons = 0; // Only one dependence set.
3882 NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
3883 NumWritePtrChecks - 1));
3886 // If the pointers that we would use for the bounds comparison have different
3887 // address spaces, assume the values aren't directly comparable, so we can't
3888 // use them for the runtime check. We also have to assume they could
3889 // overlap. In the future there should be metadata for whether address spaces
3891 unsigned NumPointers = RtCheck.Pointers.size();
3892 for (unsigned i = 0; i < NumPointers; ++i) {
3893 for (unsigned j = i + 1; j < NumPointers; ++j) {
3894 // Only need to check pointers between two different dependency sets.
3895 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
3898 Value *PtrI = RtCheck.Pointers[i];
3899 Value *PtrJ = RtCheck.Pointers[j];
3901 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
3902 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
3904 DEBUG(dbgs() << "LV: Runtime check would require comparison between"
3905 " different address spaces\n");
3914 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
3915 return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
3918 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
3919 // We process the set twice: first we process read-write pointers, last we
3920 // process read-only pointers. This allows us to skip dependence tests for
3921 // read-only pointers.
3923 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
3924 for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
3925 const MemAccessInfo &Access = *AI;
3926 Value *Ptr = Access.getPointer();
3927 bool IsWrite = Access.getInt();
3929 DepCands.insert(Access);
3931 // Memorize read-only pointers for later processing and skip them in the
3932 // first round (they need to be checked after we have seen all write
3933 // pointers). Note: we also mark pointer that are not consecutive as
3934 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
3935 // second check for "!IsWrite".
3936 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
3937 if (!UseDeferred && IsReadOnlyPtr) {
3938 DeferredAccesses.insert(Access);
3942 bool NeedDepCheck = false;
3943 // Check whether there is the possibility of dependency because of
3944 // underlying objects being the same.
3945 typedef SmallVector<Value*, 16> ValueVector;
3946 ValueVector TempObjects;
3947 GetUnderlyingObjects(Ptr, TempObjects, DL);
3948 for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
3950 Value *UnderlyingObj = *UI;
3952 // If this is a write then it needs to be an identified object. If this a
3953 // read and all writes (so far) are identified function scope objects we
3954 // don't need an identified underlying object but only an Argument (the
3955 // next write is going to invalidate this assumption if it is
3957 // This is a micro-optimization for the case where all writes are
3958 // identified and we have one argument pointer.
3959 // Otherwise, we do need a runtime check.
3960 if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
3961 (!IsWrite && (!AreAllWritesIdentified ||
3962 !isa<Argument>(UnderlyingObj)) &&
3963 !isIdentifiedObject(UnderlyingObj))) {
3964 DEBUG(dbgs() << "LV: Found an unidentified " <<
3965 (IsWrite ? "write" : "read" ) << " ptr: " << *UnderlyingObj <<
3967 IsRTCheckNeeded = (IsRTCheckNeeded ||
3968 !isIdentifiedObject(UnderlyingObj) ||
3969 !AreAllReadsIdentified);
3972 AreAllWritesIdentified = false;
3974 AreAllReadsIdentified = false;
3977 // If this is a write - check other reads and writes for conflicts. If
3978 // this is a read only check other writes for conflicts (but only if there
3979 // is no other write to the ptr - this is an optimization to catch "a[i] =
3980 // a[i] + " without having to do a dependence check).
3981 if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
3982 NeedDepCheck = true;
3985 WriteObjects.insert(UnderlyingObj);
3987 // Create sets of pointers connected by shared underlying objects.
3988 UnderlyingObjToAccessMap::iterator Prev =
3989 ObjToLastAccess.find(UnderlyingObj);
3990 if (Prev != ObjToLastAccess.end())
3991 DepCands.unionSets(Access, Prev->second);
3993 ObjToLastAccess[UnderlyingObj] = Access;
3997 CheckDeps.insert(Access);
4002 /// \brief Checks memory dependences among accesses to the same underlying
4003 /// object to determine whether there vectorization is legal or not (and at
4004 /// which vectorization factor).
4006 /// This class works under the assumption that we already checked that memory
4007 /// locations with different underlying pointers are "must-not alias".
4008 /// We use the ScalarEvolution framework to symbolically evalutate access
4009 /// functions pairs. Since we currently don't restructure the loop we can rely
4010 /// on the program order of memory accesses to determine their safety.
4011 /// At the moment we will only deem accesses as safe for:
4012 /// * A negative constant distance assuming program order.
4014 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
4015 /// a[i] = tmp; y = a[i];
4017 /// The latter case is safe because later checks guarantuee that there can't
4018 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
4019 /// the same variable: a header phi can only be an induction or a reduction, a
4020 /// reduction can't have a memory sink, an induction can't have a memory
4021 /// source). This is important and must not be violated (or we have to
4022 /// resort to checking for cycles through memory).
4024 /// * A positive constant distance assuming program order that is bigger
4025 /// than the biggest memory access.
4027 /// tmp = a[i] OR b[i] = x
4028 /// a[i+2] = tmp y = b[i+2];
4030 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
4032 /// * Zero distances and all accesses have the same size.
4034 class MemoryDepChecker {
4036 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
4037 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
4039 MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
4040 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
4041 ShouldRetryWithRuntimeCheck(false) {}
4043 /// \brief Register the location (instructions are given increasing numbers)
4044 /// of a write access.
4045 void addAccess(StoreInst *SI) {
4046 Value *Ptr = SI->getPointerOperand();
4047 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
4048 InstMap.push_back(SI);
4052 /// \brief Register the location (instructions are given increasing numbers)
4053 /// of a write access.
4054 void addAccess(LoadInst *LI) {
4055 Value *Ptr = LI->getPointerOperand();
4056 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
4057 InstMap.push_back(LI);
4061 /// \brief Check whether the dependencies between the accesses are safe.
4063 /// Only checks sets with elements in \p CheckDeps.
4064 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4065 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
4067 /// \brief The maximum number of bytes of a vector register we can vectorize
4068 /// the accesses safely with.
4069 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
4071 /// \brief In same cases when the dependency check fails we can still
4072 /// vectorize the loop with a dynamic array access check.
4073 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
4076 ScalarEvolution *SE;
4077 const DataLayout *DL;
4078 const Loop *InnermostLoop;
4080 /// \brief Maps access locations (ptr, read/write) to program order.
4081 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
4083 /// \brief Memory access instructions in program order.
4084 SmallVector<Instruction *, 16> InstMap;
4086 /// \brief The program order index to be used for the next instruction.
4089 // We can access this many bytes in parallel safely.
4090 unsigned MaxSafeDepDistBytes;
4092 /// \brief If we see a non-constant dependence distance we can still try to
4093 /// vectorize this loop with runtime checks.
4094 bool ShouldRetryWithRuntimeCheck;
4096 /// \brief Check whether there is a plausible dependence between the two
4099 /// Access \p A must happen before \p B in program order. The two indices
4100 /// identify the index into the program order map.
4102 /// This function checks whether there is a plausible dependence (or the
4103 /// absence of such can't be proved) between the two accesses. If there is a
4104 /// plausible dependence but the dependence distance is bigger than one
4105 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
4106 /// distance is smaller than any other distance encountered so far).
4107 /// Otherwise, this function returns true signaling a possible dependence.
4108 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
4109 const MemAccessInfo &B, unsigned BIdx,
4110 ValueToValueMap &Strides);
4112 /// \brief Check whether the data dependence could prevent store-load
4114 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
4117 } // end anonymous namespace
4119 static bool isInBoundsGep(Value *Ptr) {
4120 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
4121 return GEP->isInBounds();
4125 /// \brief Check whether the access through \p Ptr has a constant stride.
4126 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
4127 const Loop *Lp, ValueToValueMap &StridesMap) {
4128 const Type *Ty = Ptr->getType();
4129 assert(Ty->isPointerTy() && "Unexpected non-ptr");
4131 // Make sure that the pointer does not point to aggregate types.
4132 const PointerType *PtrTy = cast<PointerType>(Ty);
4133 if (PtrTy->getElementType()->isAggregateType()) {
4134 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
4139 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
4141 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4143 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
4144 << *Ptr << " SCEV: " << *PtrScev << "\n");
4148 // The accesss function must stride over the innermost loop.
4149 if (Lp != AR->getLoop()) {
4150 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
4151 *Ptr << " SCEV: " << *PtrScev << "\n");
4154 // The address calculation must not wrap. Otherwise, a dependence could be
4156 // An inbounds getelementptr that is a AddRec with a unit stride
4157 // cannot wrap per definition. The unit stride requirement is checked later.
4158 // An getelementptr without an inbounds attribute and unit stride would have
4159 // to access the pointer value "0" which is undefined behavior in address
4160 // space 0, therefore we can also vectorize this case.
4161 bool IsInBoundsGEP = isInBoundsGep(Ptr);
4162 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
4163 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
4164 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
4165 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
4166 << *Ptr << " SCEV: " << *PtrScev << "\n");
4170 // Check the step is constant.
4171 const SCEV *Step = AR->getStepRecurrence(*SE);
4173 // Calculate the pointer stride and check if it is consecutive.
4174 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4176 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
4177 " SCEV: " << *PtrScev << "\n");
4181 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
4182 const APInt &APStepVal = C->getValue()->getValue();
4184 // Huge step value - give up.
4185 if (APStepVal.getBitWidth() > 64)
4188 int64_t StepVal = APStepVal.getSExtValue();
4191 int64_t Stride = StepVal / Size;
4192 int64_t Rem = StepVal % Size;
4196 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
4197 // know we can't "wrap around the address space". In case of address space
4198 // zero we know that this won't happen without triggering undefined behavior.
4199 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
4200 Stride != 1 && Stride != -1)
4206 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
4207 unsigned TypeByteSize) {
4208 // If loads occur at a distance that is not a multiple of a feasible vector
4209 // factor store-load forwarding does not take place.
4210 // Positive dependences might cause troubles because vectorizing them might
4211 // prevent store-load forwarding making vectorized code run a lot slower.
4212 // a[i] = a[i-3] ^ a[i-8];
4213 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
4214 // hence on your typical architecture store-load forwarding does not take
4215 // place. Vectorizing in such cases does not make sense.
4216 // Store-load forwarding distance.
4217 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
4218 // Maximum vector factor.
4219 unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
4220 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
4221 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
4223 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
4225 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
4226 MaxVFWithoutSLForwardIssues = (vf >>=1);
4231 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4232 DEBUG(dbgs() << "LV: Distance " << Distance <<
4233 " that could cause a store-load forwarding conflict\n");
4237 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4238 MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4239 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4243 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4244 const MemAccessInfo &B, unsigned BIdx,
4245 ValueToValueMap &Strides) {
4246 assert (AIdx < BIdx && "Must pass arguments in program order");
4248 Value *APtr = A.getPointer();
4249 Value *BPtr = B.getPointer();
4250 bool AIsWrite = A.getInt();
4251 bool BIsWrite = B.getInt();
4253 // Two reads are independent.
4254 if (!AIsWrite && !BIsWrite)
4257 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4258 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4260 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4261 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4263 const SCEV *Src = AScev;
4264 const SCEV *Sink = BScev;
4266 // If the induction step is negative we have to invert source and sink of the
4268 if (StrideAPtr < 0) {
4271 std::swap(APtr, BPtr);
4272 std::swap(Src, Sink);
4273 std::swap(AIsWrite, BIsWrite);
4274 std::swap(AIdx, BIdx);
4275 std::swap(StrideAPtr, StrideBPtr);
4278 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4280 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4281 << "(Induction step: " << StrideAPtr << ")\n");
4282 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4283 << *InstMap[BIdx] << ": " << *Dist << "\n");
4285 // Need consecutive accesses. We don't want to vectorize
4286 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4287 // the address space.
4288 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4289 DEBUG(dbgs() << "Non-consecutive pointer access\n");
4293 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4295 DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4296 ShouldRetryWithRuntimeCheck = true;
4300 Type *ATy = APtr->getType()->getPointerElementType();
4301 Type *BTy = BPtr->getType()->getPointerElementType();
4302 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4304 // Negative distances are not plausible dependencies.
4305 const APInt &Val = C->getValue()->getValue();
4306 if (Val.isNegative()) {
4307 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4308 if (IsTrueDataDependence &&
4309 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4313 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4317 // Write to the same location with the same size.
4318 // Could be improved to assert type sizes are the same (i32 == float, etc).
4322 DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4326 assert(Val.isStrictlyPositive() && "Expect a positive value");
4328 // Positive distance bigger than max vectorization factor.
4331 "LV: ReadWrite-Write positive dependency with different types\n");
4335 unsigned Distance = (unsigned) Val.getZExtValue();
4337 // Bail out early if passed-in parameters make vectorization not feasible.
4338 unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4339 unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
4341 // The distance must be bigger than the size needed for a vectorized version
4342 // of the operation and the size of the vectorized operation must not be
4343 // bigger than the currrent maximum size.
4344 if (Distance < 2*TypeByteSize ||
4345 2*TypeByteSize > MaxSafeDepDistBytes ||
4346 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4347 DEBUG(dbgs() << "LV: Failure because of Positive distance "
4348 << Val.getSExtValue() << '\n');
4352 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4353 Distance : MaxSafeDepDistBytes;
4355 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4356 if (IsTrueDataDependence &&
4357 couldPreventStoreLoadForward(Distance, TypeByteSize))
4360 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4361 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4366 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4367 MemAccessInfoSet &CheckDeps,
4368 ValueToValueMap &Strides) {
4370 MaxSafeDepDistBytes = -1U;
4371 while (!CheckDeps.empty()) {
4372 MemAccessInfo CurAccess = *CheckDeps.begin();
4374 // Get the relevant memory access set.
4375 EquivalenceClasses<MemAccessInfo>::iterator I =
4376 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4378 // Check accesses within this set.
4379 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4380 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4382 // Check every access pair.
4384 CheckDeps.erase(*AI);
4385 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
4387 // Check every accessing instruction pair in program order.
4388 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4389 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4390 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4391 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4392 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4394 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4405 bool LoopVectorizationLegality::canVectorizeMemory() {
4407 typedef SmallVector<Value*, 16> ValueVector;
4408 typedef SmallPtrSet<Value*, 16> ValueSet;
4410 // Holds the Load and Store *instructions*.
4414 // Holds all the different accesses in the loop.
4415 unsigned NumReads = 0;
4416 unsigned NumReadWrites = 0;
4418 PtrRtCheck.Pointers.clear();
4419 PtrRtCheck.Need = false;
4421 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4422 MemoryDepChecker DepChecker(SE, DL, TheLoop);
4425 for (Loop::block_iterator bb = TheLoop->block_begin(),
4426 be = TheLoop->block_end(); bb != be; ++bb) {
4428 // Scan the BB and collect legal loads and stores.
4429 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4432 // If this is a load, save it. If this instruction can read from memory
4433 // but is not a load, then we quit. Notice that we don't handle function
4434 // calls that read or write.
4435 if (it->mayReadFromMemory()) {
4436 // Many math library functions read the rounding mode. We will only
4437 // vectorize a loop if it contains known function calls that don't set
4438 // the flag. Therefore, it is safe to ignore this read from memory.
4439 CallInst *Call = dyn_cast<CallInst>(it);
4440 if (Call && getIntrinsicIDForCall(Call, TLI))
4443 LoadInst *Ld = dyn_cast<LoadInst>(it);
4444 if (!Ld) return false;
4445 if (!Ld->isSimple() && !IsAnnotatedParallel) {
4446 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4450 Loads.push_back(Ld);
4451 DepChecker.addAccess(Ld);
4455 // Save 'store' instructions. Abort if other instructions write to memory.
4456 if (it->mayWriteToMemory()) {
4457 StoreInst *St = dyn_cast<StoreInst>(it);
4458 if (!St) return false;
4459 if (!St->isSimple() && !IsAnnotatedParallel) {
4460 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4464 Stores.push_back(St);
4465 DepChecker.addAccess(St);
4470 // Now we have two lists that hold the loads and the stores.
4471 // Next, we find the pointers that they use.
4473 // Check if we see any stores. If there are no stores, then we don't
4474 // care if the pointers are *restrict*.
4475 if (!Stores.size()) {
4476 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4480 AccessAnalysis::DepCandidates DependentAccesses;
4481 AccessAnalysis Accesses(DL, DependentAccesses);
4483 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4484 // multiple times on the same object. If the ptr is accessed twice, once
4485 // for read and once for write, it will only appear once (on the write
4486 // list). This is okay, since we are going to check for conflicts between
4487 // writes and between reads and writes, but not between reads and reads.
4490 ValueVector::iterator I, IE;
4491 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4492 StoreInst *ST = cast<StoreInst>(*I);
4493 Value* Ptr = ST->getPointerOperand();
4495 if (isUniform(Ptr)) {
4496 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4500 // If we did *not* see this pointer before, insert it to the read-write
4501 // list. At this phase it is only a 'write' list.
4502 if (Seen.insert(Ptr)) {
4504 Accesses.addStore(Ptr);
4508 if (IsAnnotatedParallel) {
4510 << "LV: A loop annotated parallel, ignore memory dependency "
4515 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4516 LoadInst *LD = cast<LoadInst>(*I);
4517 Value* Ptr = LD->getPointerOperand();
4518 // If we did *not* see this pointer before, insert it to the
4519 // read list. If we *did* see it before, then it is already in
4520 // the read-write list. This allows us to vectorize expressions
4521 // such as A[i] += x; Because the address of A[i] is a read-write
4522 // pointer. This only works if the index of A[i] is consecutive.
4523 // If the address of i is unknown (for example A[B[i]]) then we may
4524 // read a few words, modify, and write a few words, and some of the
4525 // words may be written to the same address.
4526 bool IsReadOnlyPtr = false;
4527 if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4529 IsReadOnlyPtr = true;
4531 Accesses.addLoad(Ptr, IsReadOnlyPtr);
4534 // If we write (or read-write) to a single destination and there are no
4535 // other reads in this loop then is it safe to vectorize.
4536 if (NumReadWrites == 1 && NumReads == 0) {
4537 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4541 // Build dependence sets and check whether we need a runtime pointer bounds
4543 Accesses.buildDependenceSets();
4544 bool NeedRTCheck = Accesses.isRTCheckNeeded();
4546 // Find pointers with computable bounds. We are going to use this information
4547 // to place a runtime bound check.
4548 unsigned NumComparisons = 0;
4549 bool CanDoRT = false;
4551 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4554 DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4555 " pointer comparisons.\n");
4557 // If we only have one set of dependences to check pointers among we don't
4558 // need a runtime check.
4559 if (NumComparisons == 0 && NeedRTCheck)
4560 NeedRTCheck = false;
4562 // Check that we did not collect too many pointers or found an unsizeable
4564 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4570 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4573 if (NeedRTCheck && !CanDoRT) {
4574 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4575 "the array bounds.\n");
4580 PtrRtCheck.Need = NeedRTCheck;
4582 bool CanVecMem = true;
4583 if (Accesses.isDependencyCheckNeeded()) {
4584 DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4585 CanVecMem = DepChecker.areDepsSafe(
4586 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4587 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4589 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4590 DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4593 // Clear the dependency checks. We assume they are not needed.
4594 Accesses.resetDepChecks();
4597 PtrRtCheck.Need = true;
4599 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4600 TheLoop, Strides, true);
4601 // Check that we did not collect too many pointers or found an unsizeable
4603 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4604 DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4613 DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4614 " need a runtime memory check.\n");
4619 static bool hasMultipleUsesOf(Instruction *I,
4620 SmallPtrSet<Instruction *, 8> &Insts) {
4621 unsigned NumUses = 0;
4622 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
4623 if (Insts.count(dyn_cast<Instruction>(*Use)))
4632 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
4633 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4634 if (!Set.count(dyn_cast<Instruction>(*Use)))
4639 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
4640 ReductionKind Kind) {
4641 if (Phi->getNumIncomingValues() != 2)
4644 // Reduction variables are only found in the loop header block.
4645 if (Phi->getParent() != TheLoop->getHeader())
4648 // Obtain the reduction start value from the value that comes from the loop
4650 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
4652 // ExitInstruction is the single value which is used outside the loop.
4653 // We only allow for a single reduction value to be used outside the loop.
4654 // This includes users of the reduction, variables (which form a cycle
4655 // which ends in the phi node).
4656 Instruction *ExitInstruction = nullptr;
4657 // Indicates that we found a reduction operation in our scan.
4658 bool FoundReduxOp = false;
4660 // We start with the PHI node and scan for all of the users of this
4661 // instruction. All users must be instructions that can be used as reduction
4662 // variables (such as ADD). We must have a single out-of-block user. The cycle
4663 // must include the original PHI.
4664 bool FoundStartPHI = false;
4666 // To recognize min/max patterns formed by a icmp select sequence, we store
4667 // the number of instruction we saw from the recognized min/max pattern,
4668 // to make sure we only see exactly the two instructions.
4669 unsigned NumCmpSelectPatternInst = 0;
4670 ReductionInstDesc ReduxDesc(false, nullptr);
4672 SmallPtrSet<Instruction *, 8> VisitedInsts;
4673 SmallVector<Instruction *, 8> Worklist;
4674 Worklist.push_back(Phi);
4675 VisitedInsts.insert(Phi);
4677 // A value in the reduction can be used:
4678 // - By the reduction:
4679 // - Reduction operation:
4680 // - One use of reduction value (safe).
4681 // - Multiple use of reduction value (not safe).
4683 // - All uses of the PHI must be the reduction (safe).
4684 // - Otherwise, not safe.
4685 // - By one instruction outside of the loop (safe).
4686 // - By further instructions outside of the loop (not safe).
4687 // - By an instruction that is not part of the reduction (not safe).
4689 // * An instruction type other than PHI or the reduction operation.
4690 // * A PHI in the header other than the initial PHI.
4691 while (!Worklist.empty()) {
4692 Instruction *Cur = Worklist.back();
4693 Worklist.pop_back();
4696 // If the instruction has no users then this is a broken chain and can't be
4697 // a reduction variable.
4698 if (Cur->use_empty())
4701 bool IsAPhi = isa<PHINode>(Cur);
4703 // A header PHI use other than the original PHI.
4704 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
4707 // Reductions of instructions such as Div, and Sub is only possible if the
4708 // LHS is the reduction variable.
4709 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
4710 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
4711 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
4714 // Any reduction instruction must be of one of the allowed kinds.
4715 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
4716 if (!ReduxDesc.IsReduction)
4719 // A reduction operation must only have one use of the reduction value.
4720 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
4721 hasMultipleUsesOf(Cur, VisitedInsts))
4724 // All inputs to a PHI node must be a reduction value.
4725 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4728 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4729 isa<SelectInst>(Cur)))
4730 ++NumCmpSelectPatternInst;
4731 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4732 isa<SelectInst>(Cur)))
4733 ++NumCmpSelectPatternInst;
4735 // Check whether we found a reduction operator.
4736 FoundReduxOp |= !IsAPhi;
4738 // Process users of current instruction. Push non-PHI nodes after PHI nodes
4739 // onto the stack. This way we are going to have seen all inputs to PHI
4740 // nodes once we get to them.
4741 SmallVector<Instruction *, 8> NonPHIs;
4742 SmallVector<Instruction *, 8> PHIs;
4743 for (User *U : Cur->users()) {
4744 Instruction *UI = cast<Instruction>(U);
4746 // Check if we found the exit user.
4747 BasicBlock *Parent = UI->getParent();
4748 if (!TheLoop->contains(Parent)) {
4749 // Exit if you find multiple outside users or if the header phi node is
4750 // being used. In this case the user uses the value of the previous
4751 // iteration, in which case we would loose "VF-1" iterations of the
4752 // reduction operation if we vectorize.
4753 if (ExitInstruction != nullptr || Cur == Phi)
4756 // The instruction used by an outside user must be the last instruction
4757 // before we feed back to the reduction phi. Otherwise, we loose VF-1
4758 // operations on the value.
4759 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
4762 ExitInstruction = Cur;
4766 // Process instructions only once (termination). Each reduction cycle
4767 // value must only be used once, except by phi nodes and min/max
4768 // reductions which are represented as a cmp followed by a select.
4769 ReductionInstDesc IgnoredVal(false, nullptr);
4770 if (VisitedInsts.insert(UI)) {
4771 if (isa<PHINode>(UI))
4774 NonPHIs.push_back(UI);
4775 } else if (!isa<PHINode>(UI) &&
4776 ((!isa<FCmpInst>(UI) &&
4777 !isa<ICmpInst>(UI) &&
4778 !isa<SelectInst>(UI)) ||
4779 !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
4782 // Remember that we completed the cycle.
4784 FoundStartPHI = true;
4786 Worklist.append(PHIs.begin(), PHIs.end());
4787 Worklist.append(NonPHIs.begin(), NonPHIs.end());
4790 // This means we have seen one but not the other instruction of the
4791 // pattern or more than just a select and cmp.
4792 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4793 NumCmpSelectPatternInst != 2)
4796 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4799 // We found a reduction var if we have reached the original phi node and we
4800 // only have a single instruction with out-of-loop users.
4802 // This instruction is allowed to have out-of-loop users.
4803 AllowedExit.insert(ExitInstruction);
4805 // Save the description of this reduction variable.
4806 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4807 ReduxDesc.MinMaxKind);
4808 Reductions[Phi] = RD;
4809 // We've ended the cycle. This is a reduction variable if we have an
4810 // outside user and it has a binary op.
4815 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4816 /// pattern corresponding to a min(X, Y) or max(X, Y).
4817 LoopVectorizationLegality::ReductionInstDesc
4818 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4819 ReductionInstDesc &Prev) {
4821 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4822 "Expect a select instruction");
4823 Instruction *Cmp = nullptr;
4824 SelectInst *Select = nullptr;
4826 // We must handle the select(cmp()) as a single instruction. Advance to the
4828 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4829 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
4830 return ReductionInstDesc(false, I);
4831 return ReductionInstDesc(Select, Prev.MinMaxKind);
4834 // Only handle single use cases for now.
4835 if (!(Select = dyn_cast<SelectInst>(I)))
4836 return ReductionInstDesc(false, I);
4837 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4838 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4839 return ReductionInstDesc(false, I);
4840 if (!Cmp->hasOneUse())
4841 return ReductionInstDesc(false, I);
4846 // Look for a min/max pattern.
4847 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4848 return ReductionInstDesc(Select, MRK_UIntMin);
4849 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4850 return ReductionInstDesc(Select, MRK_UIntMax);
4851 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4852 return ReductionInstDesc(Select, MRK_SIntMax);
4853 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4854 return ReductionInstDesc(Select, MRK_SIntMin);
4855 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4856 return ReductionInstDesc(Select, MRK_FloatMin);
4857 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4858 return ReductionInstDesc(Select, MRK_FloatMax);
4859 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4860 return ReductionInstDesc(Select, MRK_FloatMin);
4861 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4862 return ReductionInstDesc(Select, MRK_FloatMax);
4864 return ReductionInstDesc(false, I);
4867 LoopVectorizationLegality::ReductionInstDesc
4868 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4870 ReductionInstDesc &Prev) {
4871 bool FP = I->getType()->isFloatingPointTy();
4872 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
4873 switch (I->getOpcode()) {
4875 return ReductionInstDesc(false, I);
4876 case Instruction::PHI:
4877 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4878 Kind != RK_FloatMinMax))
4879 return ReductionInstDesc(false, I);
4880 return ReductionInstDesc(I, Prev.MinMaxKind);
4881 case Instruction::Sub:
4882 case Instruction::Add:
4883 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4884 case Instruction::Mul:
4885 return ReductionInstDesc(Kind == RK_IntegerMult, I);
4886 case Instruction::And:
4887 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4888 case Instruction::Or:
4889 return ReductionInstDesc(Kind == RK_IntegerOr, I);
4890 case Instruction::Xor:
4891 return ReductionInstDesc(Kind == RK_IntegerXor, I);
4892 case Instruction::FMul:
4893 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4894 case Instruction::FAdd:
4895 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4896 case Instruction::FCmp:
4897 case Instruction::ICmp:
4898 case Instruction::Select:
4899 if (Kind != RK_IntegerMinMax &&
4900 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4901 return ReductionInstDesc(false, I);
4902 return isMinMaxSelectCmpPattern(I, Prev);
4906 LoopVectorizationLegality::InductionKind
4907 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
4908 Type *PhiTy = Phi->getType();
4909 // We only handle integer and pointer inductions variables.
4910 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4911 return IK_NoInduction;
4913 // Check that the PHI is consecutive.
4914 const SCEV *PhiScev = SE->getSCEV(Phi);
4915 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4917 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4918 return IK_NoInduction;
4920 const SCEV *Step = AR->getStepRecurrence(*SE);
4922 // Integer inductions need to have a stride of one.
4923 if (PhiTy->isIntegerTy()) {
4925 return IK_IntInduction;
4926 if (Step->isAllOnesValue())
4927 return IK_ReverseIntInduction;
4928 return IK_NoInduction;
4931 // Calculate the pointer stride and check if it is consecutive.
4932 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4934 return IK_NoInduction;
4936 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4937 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
4938 if (C->getValue()->equalsInt(Size))
4939 return IK_PtrInduction;
4940 else if (C->getValue()->equalsInt(0 - Size))
4941 return IK_ReversePtrInduction;
4943 return IK_NoInduction;
4946 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4947 Value *In0 = const_cast<Value*>(V);
4948 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4952 return Inductions.count(PN);
4955 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4956 assert(TheLoop->contains(BB) && "Unknown block used");
4958 // Blocks that do not dominate the latch need predication.
4959 BasicBlock* Latch = TheLoop->getLoopLatch();
4960 return !DT->dominates(BB, Latch);
4963 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4964 SmallPtrSet<Value *, 8>& SafePtrs) {
4965 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4966 // We might be able to hoist the load.
4967 if (it->mayReadFromMemory()) {
4968 LoadInst *LI = dyn_cast<LoadInst>(it);
4969 if (!LI || !SafePtrs.count(LI->getPointerOperand()))
4973 // We don't predicate stores at the moment.
4974 if (it->mayWriteToMemory()) {
4975 StoreInst *SI = dyn_cast<StoreInst>(it);
4976 // We only support predication of stores in basic blocks with one
4978 if (!SI || ++NumPredStores > NumberOfStoresToPredicate ||
4979 !SafePtrs.count(SI->getPointerOperand()) ||
4980 !SI->getParent()->getSinglePredecessor())
4986 // Check that we don't have a constant expression that can trap as operand.
4987 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4989 if (Constant *C = dyn_cast<Constant>(*OI))
4994 // The instructions below can trap.
4995 switch (it->getOpcode()) {
4997 case Instruction::UDiv:
4998 case Instruction::SDiv:
4999 case Instruction::URem:
5000 case Instruction::SRem:
5008 LoopVectorizationCostModel::VectorizationFactor
5009 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
5011 // Width 1 means no vectorize
5012 VectorizationFactor Factor = { 1U, 0U };
5013 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
5014 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
5018 if (!EnableCondStoresVectorization && Legal->NumPredStores) {
5019 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
5023 // Find the trip count.
5024 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
5025 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5027 unsigned WidestType = getWidestType();
5028 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
5029 unsigned MaxSafeDepDist = -1U;
5030 if (Legal->getMaxSafeDepDistBytes() != -1U)
5031 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5032 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
5033 WidestRegister : MaxSafeDepDist);
5034 unsigned MaxVectorSize = WidestRegister / WidestType;
5035 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
5036 DEBUG(dbgs() << "LV: The Widest register is: "
5037 << WidestRegister << " bits.\n");
5039 if (MaxVectorSize == 0) {
5040 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5044 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
5045 " into one vector!");
5047 unsigned VF = MaxVectorSize;
5049 // If we optimize the program for size, avoid creating the tail loop.
5051 // If we are unable to calculate the trip count then don't try to vectorize.
5053 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5057 // Find the maximum SIMD width that can fit within the trip count.
5058 VF = TC % MaxVectorSize;
5063 // If the trip count that we found modulo the vectorization factor is not
5064 // zero then we require a tail.
5066 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5072 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
5073 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5075 Factor.Width = UserVF;
5079 float Cost = expectedCost(1);
5081 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)Cost << ".\n");
5082 for (unsigned i=2; i <= VF; i*=2) {
5083 // Notice that the vector loop needs to be executed less times, so
5084 // we need to divide the cost of the vector loops by the width of
5085 // the vector elements.
5086 float VectorCost = expectedCost(i) / (float)i;
5087 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
5088 (int)VectorCost << ".\n");
5089 if (VectorCost < Cost) {
5095 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
5096 Factor.Width = Width;
5097 Factor.Cost = Width * Cost;
5101 unsigned LoopVectorizationCostModel::getWidestType() {
5102 unsigned MaxWidth = 8;
5105 for (Loop::block_iterator bb = TheLoop->block_begin(),
5106 be = TheLoop->block_end(); bb != be; ++bb) {
5107 BasicBlock *BB = *bb;
5109 // For each instruction in the loop.
5110 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5111 Type *T = it->getType();
5113 // Only examine Loads, Stores and PHINodes.
5114 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
5117 // Examine PHI nodes that are reduction variables.
5118 if (PHINode *PN = dyn_cast<PHINode>(it))
5119 if (!Legal->getReductionVars()->count(PN))
5122 // Examine the stored values.
5123 if (StoreInst *ST = dyn_cast<StoreInst>(it))
5124 T = ST->getValueOperand()->getType();
5126 // Ignore loaded pointer types and stored pointer types that are not
5127 // consecutive. However, we do want to take consecutive stores/loads of
5128 // pointer vectors into account.
5129 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
5132 MaxWidth = std::max(MaxWidth,
5133 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
5141 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
5144 unsigned LoopCost) {
5146 // -- The unroll heuristics --
5147 // We unroll the loop in order to expose ILP and reduce the loop overhead.
5148 // There are many micro-architectural considerations that we can't predict
5149 // at this level. For example frontend pressure (on decode or fetch) due to
5150 // code size, or the number and capabilities of the execution ports.
5152 // We use the following heuristics to select the unroll factor:
5153 // 1. If the code has reductions the we unroll in order to break the cross
5154 // iteration dependency.
5155 // 2. If the loop is really small then we unroll in order to reduce the loop
5157 // 3. We don't unroll if we think that we will spill registers to memory due
5158 // to the increased register pressure.
5160 // Use the user preference, unless 'auto' is selected.
5164 // When we optimize for size we don't unroll.
5168 // We used the distance for the unroll factor.
5169 if (Legal->getMaxSafeDepDistBytes() != -1U)
5172 // Do not unroll loops with a relatively small trip count.
5173 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
5174 TheLoop->getLoopLatch());
5175 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
5178 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5179 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
5183 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5184 TargetNumRegisters = ForceTargetNumScalarRegs;
5186 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5187 TargetNumRegisters = ForceTargetNumVectorRegs;
5190 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
5191 // We divide by these constants so assume that we have at least one
5192 // instruction that uses at least one register.
5193 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5194 R.NumInstructions = std::max(R.NumInstructions, 1U);
5196 // We calculate the unroll factor using the following formula.
5197 // Subtract the number of loop invariants from the number of available
5198 // registers. These registers are used by all of the unrolled instances.
5199 // Next, divide the remaining registers by the number of registers that is
5200 // required by the loop, in order to estimate how many parallel instances
5201 // fit without causing spills. All of this is rounded down if necessary to be
5202 // a power of two. We want power of two unroll factors to simplify any
5203 // addressing operations or alignment considerations.
5204 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5207 // Don't count the induction variable as unrolled.
5208 if (EnableIndVarRegisterHeur)
5209 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
5210 std::max(1U, (R.MaxLocalUsers - 1)));
5212 // Clamp the unroll factor ranges to reasonable factors.
5213 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
5215 // Check if the user has overridden the unroll max.
5217 if (ForceTargetMaxScalarUnrollFactor.getNumOccurrences() > 0)
5218 MaxUnrollSize = ForceTargetMaxScalarUnrollFactor;
5220 if (ForceTargetMaxVectorUnrollFactor.getNumOccurrences() > 0)
5221 MaxUnrollSize = ForceTargetMaxVectorUnrollFactor;
5224 // If we did not calculate the cost for VF (because the user selected the VF)
5225 // then we calculate the cost of VF here.
5227 LoopCost = expectedCost(VF);
5229 // Clamp the calculated UF to be between the 1 and the max unroll factor
5230 // that the target allows.
5231 if (UF > MaxUnrollSize)
5236 // Unroll if we vectorized this loop and there is a reduction that could
5237 // benefit from unrolling.
5238 if (VF > 1 && Legal->getReductionVars()->size()) {
5239 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
5243 // Note that if we've already vectorized the loop we will have done the
5244 // runtime check and so unrolling won't require further checks.
5245 bool UnrollingRequiresRuntimePointerCheck =
5246 (VF == 1 && Legal->getRuntimePointerCheck()->Need);
5248 // We want to unroll small loops in order to reduce the loop overhead and
5249 // potentially expose ILP opportunities.
5250 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5251 if (!UnrollingRequiresRuntimePointerCheck &&
5252 LoopCost < SmallLoopCost) {
5253 // We assume that the cost overhead is 1 and we use the cost model
5254 // to estimate the cost of the loop and unroll until the cost of the
5255 // loop overhead is about 5% of the cost of the loop.
5256 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5258 // Unroll until store/load ports (estimated by max unroll factor) are
5260 unsigned StoresUF = UF / (Legal->NumStores ? Legal->NumStores : 1);
5261 unsigned LoadsUF = UF / (Legal->NumLoads ? Legal->NumLoads : 1);
5263 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
5264 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
5265 return std::max(StoresUF, LoadsUF);
5268 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
5272 DEBUG(dbgs() << "LV: Not Unrolling.\n");
5276 LoopVectorizationCostModel::RegisterUsage
5277 LoopVectorizationCostModel::calculateRegisterUsage() {
5278 // This function calculates the register usage by measuring the highest number
5279 // of values that are alive at a single location. Obviously, this is a very
5280 // rough estimation. We scan the loop in a topological order in order and
5281 // assign a number to each instruction. We use RPO to ensure that defs are
5282 // met before their users. We assume that each instruction that has in-loop
5283 // users starts an interval. We record every time that an in-loop value is
5284 // used, so we have a list of the first and last occurrences of each
5285 // instruction. Next, we transpose this data structure into a multi map that
5286 // holds the list of intervals that *end* at a specific location. This multi
5287 // map allows us to perform a linear search. We scan the instructions linearly
5288 // and record each time that a new interval starts, by placing it in a set.
5289 // If we find this value in the multi-map then we remove it from the set.
5290 // The max register usage is the maximum size of the set.
5291 // We also search for instructions that are defined outside the loop, but are
5292 // used inside the loop. We need this number separately from the max-interval
5293 // usage number because when we unroll, loop-invariant values do not take
5295 LoopBlocksDFS DFS(TheLoop);
5299 R.NumInstructions = 0;
5301 // Each 'key' in the map opens a new interval. The values
5302 // of the map are the index of the 'last seen' usage of the
5303 // instruction that is the key.
5304 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5305 // Maps instruction to its index.
5306 DenseMap<unsigned, Instruction*> IdxToInstr;
5307 // Marks the end of each interval.
5308 IntervalMap EndPoint;
5309 // Saves the list of instruction indices that are used in the loop.
5310 SmallSet<Instruction*, 8> Ends;
5311 // Saves the list of values that are used in the loop but are
5312 // defined outside the loop, such as arguments and constants.
5313 SmallPtrSet<Value*, 8> LoopInvariants;
5316 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5317 be = DFS.endRPO(); bb != be; ++bb) {
5318 R.NumInstructions += (*bb)->size();
5319 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5321 Instruction *I = it;
5322 IdxToInstr[Index++] = I;
5324 // Save the end location of each USE.
5325 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5326 Value *U = I->getOperand(i);
5327 Instruction *Instr = dyn_cast<Instruction>(U);
5329 // Ignore non-instruction values such as arguments, constants, etc.
5330 if (!Instr) continue;
5332 // If this instruction is outside the loop then record it and continue.
5333 if (!TheLoop->contains(Instr)) {
5334 LoopInvariants.insert(Instr);
5338 // Overwrite previous end points.
5339 EndPoint[Instr] = Index;
5345 // Saves the list of intervals that end with the index in 'key'.
5346 typedef SmallVector<Instruction*, 2> InstrList;
5347 DenseMap<unsigned, InstrList> TransposeEnds;
5349 // Transpose the EndPoints to a list of values that end at each index.
5350 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5352 TransposeEnds[it->second].push_back(it->first);
5354 SmallSet<Instruction*, 8> OpenIntervals;
5355 unsigned MaxUsage = 0;
5358 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5359 for (unsigned int i = 0; i < Index; ++i) {
5360 Instruction *I = IdxToInstr[i];
5361 // Ignore instructions that are never used within the loop.
5362 if (!Ends.count(I)) continue;
5364 // Remove all of the instructions that end at this location.
5365 InstrList &List = TransposeEnds[i];
5366 for (unsigned int j=0, e = List.size(); j < e; ++j)
5367 OpenIntervals.erase(List[j]);
5369 // Count the number of live interals.
5370 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5372 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5373 OpenIntervals.size() << '\n');
5375 // Add the current instruction to the list of open intervals.
5376 OpenIntervals.insert(I);
5379 unsigned Invariant = LoopInvariants.size();
5380 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5381 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5382 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5384 R.LoopInvariantRegs = Invariant;
5385 R.MaxLocalUsers = MaxUsage;
5389 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5393 for (Loop::block_iterator bb = TheLoop->block_begin(),
5394 be = TheLoop->block_end(); bb != be; ++bb) {
5395 unsigned BlockCost = 0;
5396 BasicBlock *BB = *bb;
5398 // For each instruction in the old loop.
5399 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5400 // Skip dbg intrinsics.
5401 if (isa<DbgInfoIntrinsic>(it))
5404 unsigned C = getInstructionCost(it, VF);
5406 // Check if we should override the cost.
5407 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5408 C = ForceTargetInstructionCost;
5411 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5412 VF << " For instruction: " << *it << '\n');
5415 // We assume that if-converted blocks have a 50% chance of being executed.
5416 // When the code is scalar then some of the blocks are avoided due to CF.
5417 // When the code is vectorized we execute all code paths.
5418 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5427 /// \brief Check whether the address computation for a non-consecutive memory
5428 /// access looks like an unlikely candidate for being merged into the indexing
5431 /// We look for a GEP which has one index that is an induction variable and all
5432 /// other indices are loop invariant. If the stride of this access is also
5433 /// within a small bound we decide that this address computation can likely be
5434 /// merged into the addressing mode.
5435 /// In all other cases, we identify the address computation as complex.
5436 static bool isLikelyComplexAddressComputation(Value *Ptr,
5437 LoopVectorizationLegality *Legal,
5438 ScalarEvolution *SE,
5439 const Loop *TheLoop) {
5440 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5444 // We are looking for a gep with all loop invariant indices except for one
5445 // which should be an induction variable.
5446 unsigned NumOperands = Gep->getNumOperands();
5447 for (unsigned i = 1; i < NumOperands; ++i) {
5448 Value *Opd = Gep->getOperand(i);
5449 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5450 !Legal->isInductionVariable(Opd))
5454 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5455 // can likely be merged into the address computation.
5456 unsigned MaxMergeDistance = 64;
5458 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5462 // Check the step is constant.
5463 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5464 // Calculate the pointer stride and check if it is consecutive.
5465 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5469 const APInt &APStepVal = C->getValue()->getValue();
5471 // Huge step value - give up.
5472 if (APStepVal.getBitWidth() > 64)
5475 int64_t StepVal = APStepVal.getSExtValue();
5477 return StepVal > MaxMergeDistance;
5480 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5481 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5487 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5488 // If we know that this instruction will remain uniform, check the cost of
5489 // the scalar version.
5490 if (Legal->isUniformAfterVectorization(I))
5493 Type *RetTy = I->getType();
5494 Type *VectorTy = ToVectorTy(RetTy, VF);
5496 // TODO: We need to estimate the cost of intrinsic calls.
5497 switch (I->getOpcode()) {
5498 case Instruction::GetElementPtr:
5499 // We mark this instruction as zero-cost because the cost of GEPs in
5500 // vectorized code depends on whether the corresponding memory instruction
5501 // is scalarized or not. Therefore, we handle GEPs with the memory
5502 // instruction cost.
5504 case Instruction::Br: {
5505 return TTI.getCFInstrCost(I->getOpcode());
5507 case Instruction::PHI:
5508 //TODO: IF-converted IFs become selects.
5510 case Instruction::Add:
5511 case Instruction::FAdd:
5512 case Instruction::Sub:
5513 case Instruction::FSub:
5514 case Instruction::Mul:
5515 case Instruction::FMul:
5516 case Instruction::UDiv:
5517 case Instruction::SDiv:
5518 case Instruction::FDiv:
5519 case Instruction::URem:
5520 case Instruction::SRem:
5521 case Instruction::FRem:
5522 case Instruction::Shl:
5523 case Instruction::LShr:
5524 case Instruction::AShr:
5525 case Instruction::And:
5526 case Instruction::Or:
5527 case Instruction::Xor: {
5528 // Since we will replace the stride by 1 the multiplication should go away.
5529 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5531 // Certain instructions can be cheaper to vectorize if they have a constant
5532 // second vector operand. One example of this are shifts on x86.
5533 TargetTransformInfo::OperandValueKind Op1VK =
5534 TargetTransformInfo::OK_AnyValue;
5535 TargetTransformInfo::OperandValueKind Op2VK =
5536 TargetTransformInfo::OK_AnyValue;
5537 Value *Op2 = I->getOperand(1);
5539 // Check for a splat of a constant or for a non uniform vector of constants.
5540 if (isa<ConstantInt>(Op2))
5541 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5542 else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5543 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5544 if (cast<Constant>(Op2)->getSplatValue() != nullptr)
5545 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5548 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
5550 case Instruction::Select: {
5551 SelectInst *SI = cast<SelectInst>(I);
5552 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5553 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5554 Type *CondTy = SI->getCondition()->getType();
5556 CondTy = VectorType::get(CondTy, VF);
5558 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5560 case Instruction::ICmp:
5561 case Instruction::FCmp: {
5562 Type *ValTy = I->getOperand(0)->getType();
5563 VectorTy = ToVectorTy(ValTy, VF);
5564 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5566 case Instruction::Store:
5567 case Instruction::Load: {
5568 StoreInst *SI = dyn_cast<StoreInst>(I);
5569 LoadInst *LI = dyn_cast<LoadInst>(I);
5570 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5572 VectorTy = ToVectorTy(ValTy, VF);
5574 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5575 unsigned AS = SI ? SI->getPointerAddressSpace() :
5576 LI->getPointerAddressSpace();
5577 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5578 // We add the cost of address computation here instead of with the gep
5579 // instruction because only here we know whether the operation is
5582 return TTI.getAddressComputationCost(VectorTy) +
5583 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5585 // Scalarized loads/stores.
5586 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5587 bool Reverse = ConsecutiveStride < 0;
5588 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
5589 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
5590 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5591 bool IsComplexComputation =
5592 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5594 // The cost of extracting from the value vector and pointer vector.
5595 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5596 for (unsigned i = 0; i < VF; ++i) {
5597 // The cost of extracting the pointer operand.
5598 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5599 // In case of STORE, the cost of ExtractElement from the vector.
5600 // In case of LOAD, the cost of InsertElement into the returned
5602 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5603 Instruction::InsertElement,
5607 // The cost of the scalar loads/stores.
5608 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5609 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5614 // Wide load/stores.
5615 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5616 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5619 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5623 case Instruction::ZExt:
5624 case Instruction::SExt:
5625 case Instruction::FPToUI:
5626 case Instruction::FPToSI:
5627 case Instruction::FPExt:
5628 case Instruction::PtrToInt:
5629 case Instruction::IntToPtr:
5630 case Instruction::SIToFP:
5631 case Instruction::UIToFP:
5632 case Instruction::Trunc:
5633 case Instruction::FPTrunc:
5634 case Instruction::BitCast: {
5635 // We optimize the truncation of induction variable.
5636 // The cost of these is the same as the scalar operation.
5637 if (I->getOpcode() == Instruction::Trunc &&
5638 Legal->isInductionVariable(I->getOperand(0)))
5639 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5640 I->getOperand(0)->getType());
5642 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5643 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5645 case Instruction::Call: {
5646 CallInst *CI = cast<CallInst>(I);
5647 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5648 assert(ID && "Not an intrinsic call!");
5649 Type *RetTy = ToVectorTy(CI->getType(), VF);
5650 SmallVector<Type*, 4> Tys;
5651 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5652 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5653 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5656 // We are scalarizing the instruction. Return the cost of the scalar
5657 // instruction, plus the cost of insert and extract into vector
5658 // elements, times the vector width.
5661 if (!RetTy->isVoidTy() && VF != 1) {
5662 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5664 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5667 // The cost of inserting the results plus extracting each one of the
5669 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5672 // The cost of executing VF copies of the scalar instruction. This opcode
5673 // is unknown. Assume that it is the same as 'mul'.
5674 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5680 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
5681 if (Scalar->isVoidTy() || VF == 1)
5683 return VectorType::get(Scalar, VF);
5686 char LoopVectorize::ID = 0;
5687 static const char lv_name[] = "Loop Vectorization";
5688 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5689 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
5690 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5691 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5692 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5693 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5694 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
5695 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5696 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5699 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5700 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5704 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5705 // Check for a store.
5706 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5707 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5709 // Check for a load.
5710 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5711 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5717 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5718 bool IfPredicateStore) {
5719 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5720 // Holds vector parameters or scalars, in case of uniform vals.
5721 SmallVector<VectorParts, 4> Params;
5723 setDebugLocFromInst(Builder, Instr);
5725 // Find all of the vectorized parameters.
5726 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5727 Value *SrcOp = Instr->getOperand(op);
5729 // If we are accessing the old induction variable, use the new one.
5730 if (SrcOp == OldInduction) {
5731 Params.push_back(getVectorValue(SrcOp));
5735 // Try using previously calculated values.
5736 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5738 // If the src is an instruction that appeared earlier in the basic block
5739 // then it should already be vectorized.
5740 if (SrcInst && OrigLoop->contains(SrcInst)) {
5741 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5742 // The parameter is a vector value from earlier.
5743 Params.push_back(WidenMap.get(SrcInst));
5745 // The parameter is a scalar from outside the loop. Maybe even a constant.
5746 VectorParts Scalars;
5747 Scalars.append(UF, SrcOp);
5748 Params.push_back(Scalars);
5752 assert(Params.size() == Instr->getNumOperands() &&
5753 "Invalid number of operands");
5755 // Does this instruction return a value ?
5756 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5758 Value *UndefVec = IsVoidRetTy ? nullptr :
5759 UndefValue::get(Instr->getType());
5760 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5761 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5763 Instruction *InsertPt = Builder.GetInsertPoint();
5764 BasicBlock *IfBlock = Builder.GetInsertBlock();
5765 BasicBlock *CondBlock = nullptr;
5768 Loop *VectorLp = nullptr;
5769 if (IfPredicateStore) {
5770 assert(Instr->getParent()->getSinglePredecessor() &&
5771 "Only support single predecessor blocks");
5772 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5773 Instr->getParent());
5774 VectorLp = LI->getLoopFor(IfBlock);
5775 assert(VectorLp && "Must have a loop for this block");
5778 // For each vector unroll 'part':
5779 for (unsigned Part = 0; Part < UF; ++Part) {
5780 // For each scalar that we create:
5782 // Start an "if (pred) a[i] = ..." block.
5783 Value *Cmp = nullptr;
5784 if (IfPredicateStore) {
5785 if (Cond[Part]->getType()->isVectorTy())
5787 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5788 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5789 ConstantInt::get(Cond[Part]->getType(), 1));
5790 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5791 LoopVectorBody.push_back(CondBlock);
5792 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
5793 // Update Builder with newly created basic block.
5794 Builder.SetInsertPoint(InsertPt);
5797 Instruction *Cloned = Instr->clone();
5799 Cloned->setName(Instr->getName() + ".cloned");
5800 // Replace the operands of the cloned instructions with extracted scalars.
5801 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5802 Value *Op = Params[op][Part];
5803 Cloned->setOperand(op, Op);
5806 // Place the cloned scalar in the new loop.
5807 Builder.Insert(Cloned);
5809 // If the original scalar returns a value we need to place it in a vector
5810 // so that future users will be able to use it.
5812 VecResults[Part] = Cloned;
5815 if (IfPredicateStore) {
5816 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5817 LoopVectorBody.push_back(NewIfBlock);
5818 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
5819 Builder.SetInsertPoint(InsertPt);
5820 Instruction *OldBr = IfBlock->getTerminator();
5821 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
5822 OldBr->eraseFromParent();
5823 IfBlock = NewIfBlock;
5828 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5829 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5830 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5832 return scalarizeInstruction(Instr, IfPredicateStore);
5835 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5839 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5843 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
5845 // When unrolling and the VF is 1, we only need to add a simple scalar.
5846 Type *ITy = Val->getType();
5847 assert(!ITy->isVectorTy() && "Val must be a scalar");
5848 Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
5849 return Builder.CreateAdd(Val, C, "induction");