1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR.
12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
13 // of instructions in order to estimate the profitability of vectorization.
15 // The loop vectorizer combines consecutive loop iterations into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A unit that checks for the legality
22 // of the vectorization.
23 // 3. InnerLoopVectorizer - A unit that performs the actual
24 // widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 // of vectorization. It decides on the optimal vector width, which
27 // can be one, if vectorization is not profitable.
29 //===----------------------------------------------------------------------===//
31 // The reduction-variable vectorization is based on the paper:
32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
37 // Other ideas/concepts are from:
38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
41 // Vectorizing Compilers.
43 //===----------------------------------------------------------------------===//
45 #include "llvm/Transforms/Vectorize.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/EquivalenceClasses.h"
48 #include "llvm/ADT/Hashing.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/ADT/StringExtras.h"
56 #include "llvm/Analysis/AliasAnalysis.h"
57 #include "llvm/Analysis/AliasSetTracker.h"
58 #include "llvm/Analysis/AssumptionCache.h"
59 #include "llvm/Analysis/BlockFrequencyInfo.h"
60 #include "llvm/Analysis/CodeMetrics.h"
61 #include "llvm/Analysis/LoopAccessAnalysis.h"
62 #include "llvm/Analysis/LoopInfo.h"
63 #include "llvm/Analysis/LoopIterator.h"
64 #include "llvm/Analysis/LoopPass.h"
65 #include "llvm/Analysis/ScalarEvolution.h"
66 #include "llvm/Analysis/ScalarEvolutionExpander.h"
67 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
68 #include "llvm/Analysis/TargetTransformInfo.h"
69 #include "llvm/Analysis/ValueTracking.h"
70 #include "llvm/IR/Constants.h"
71 #include "llvm/IR/DataLayout.h"
72 #include "llvm/IR/DebugInfo.h"
73 #include "llvm/IR/DerivedTypes.h"
74 #include "llvm/IR/DiagnosticInfo.h"
75 #include "llvm/IR/Dominators.h"
76 #include "llvm/IR/Function.h"
77 #include "llvm/IR/IRBuilder.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/LLVMContext.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/Value.h"
85 #include "llvm/IR/ValueHandle.h"
86 #include "llvm/IR/Verifier.h"
87 #include "llvm/Pass.h"
88 #include "llvm/Support/BranchProbability.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Transforms/Scalar.h"
93 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
94 #include "llvm/Transforms/Utils/Local.h"
95 #include "llvm/Transforms/Utils/VectorUtils.h"
100 using namespace llvm;
101 using namespace llvm::PatternMatch;
103 #define LV_NAME "loop-vectorize"
104 #define DEBUG_TYPE LV_NAME
106 STATISTIC(LoopsVectorized, "Number of loops vectorized");
107 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
109 static cl::opt<unsigned>
110 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
111 cl::desc("Sets the SIMD width. Zero is autoselect."));
113 static cl::opt<unsigned>
114 VectorizationInterleave("force-vector-interleave", cl::init(0), cl::Hidden,
115 cl::desc("Sets the vectorization interleave count. "
116 "Zero is autoselect."));
119 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
120 cl::desc("Enable if-conversion during vectorization."));
122 /// We don't vectorize loops with a known constant trip count below this number.
123 static cl::opt<unsigned>
124 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
126 cl::desc("Don't vectorize loops with a constant "
127 "trip count that is smaller than this "
130 /// This enables versioning on the strides of symbolically striding memory
131 /// accesses in code like the following.
132 /// for (i = 0; i < N; ++i)
133 /// A[i * Stride1] += B[i * Stride2] ...
135 /// Will be roughly translated to
136 /// if (Stride1 == 1 && Stride2 == 1) {
137 /// for (i = 0; i < N; i+=4)
141 static cl::opt<bool> EnableMemAccessVersioning(
142 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
143 cl::desc("Enable symblic stride memory access versioning"));
145 /// We don't unroll loops with a known constant trip count below this number.
146 static const unsigned TinyTripCountUnrollThreshold = 128;
148 /// When performing memory disambiguation checks at runtime do not make more
149 /// than this number of comparisons.
150 static const unsigned RuntimeMemoryCheckThreshold = 8;
152 /// Maximum simd width.
153 static const unsigned MaxVectorWidth = 64;
155 static cl::opt<unsigned> ForceTargetNumScalarRegs(
156 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
157 cl::desc("A flag that overrides the target's number of scalar registers."));
159 static cl::opt<unsigned> ForceTargetNumVectorRegs(
160 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
161 cl::desc("A flag that overrides the target's number of vector registers."));
163 /// Maximum vectorization interleave count.
164 static const unsigned MaxInterleaveFactor = 16;
166 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
167 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
168 cl::desc("A flag that overrides the target's max interleave factor for "
171 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
172 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
173 cl::desc("A flag that overrides the target's max interleave factor for "
174 "vectorized loops."));
176 static cl::opt<unsigned> ForceTargetInstructionCost(
177 "force-target-instruction-cost", cl::init(0), cl::Hidden,
178 cl::desc("A flag that overrides the target's expected cost for "
179 "an instruction to a single constant value. Mostly "
180 "useful for getting consistent testing."));
182 static cl::opt<unsigned> SmallLoopCost(
183 "small-loop-cost", cl::init(20), cl::Hidden,
184 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
186 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
187 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
188 cl::desc("Enable the use of the block frequency analysis to access PGO "
189 "heuristics minimizing code growth in cold regions and being more "
190 "aggressive in hot regions."));
192 // Runtime unroll loops for load/store throughput.
193 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
194 "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
195 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
197 /// The number of stores in a loop that are allowed to need predication.
198 static cl::opt<unsigned> NumberOfStoresToPredicate(
199 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
200 cl::desc("Max number of stores to be predicated behind an if."));
202 static cl::opt<bool> EnableIndVarRegisterHeur(
203 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
204 cl::desc("Count the induction variable only once when unrolling"));
206 static cl::opt<bool> EnableCondStoresVectorization(
207 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
208 cl::desc("Enable if predication of stores during vectorization."));
210 static cl::opt<unsigned> MaxNestedScalarReductionUF(
211 "max-nested-scalar-reduction-unroll", cl::init(2), cl::Hidden,
212 cl::desc("The maximum unroll factor to use when unrolling a scalar "
213 "reduction in a nested loop."));
217 // Forward declarations.
218 class LoopVectorizationLegality;
219 class LoopVectorizationCostModel;
220 class LoopVectorizeHints;
222 /// InnerLoopVectorizer vectorizes loops which contain only one basic
223 /// block to a specified vectorization factor (VF).
224 /// This class performs the widening of scalars into vectors, or multiple
225 /// scalars. This class also implements the following features:
226 /// * It inserts an epilogue loop for handling loops that don't have iteration
227 /// counts that are known to be a multiple of the vectorization factor.
228 /// * It handles the code generation for reduction variables.
229 /// * Scalarization (implementation using scalars) of un-vectorizable
231 /// InnerLoopVectorizer does not perform any vectorization-legality
232 /// checks, and relies on the caller to check for the different legality
233 /// aspects. The InnerLoopVectorizer relies on the
234 /// LoopVectorizationLegality class to provide information about the induction
235 /// and reduction variables that were found to a given vectorization factor.
236 class InnerLoopVectorizer {
238 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
239 DominatorTree *DT, const DataLayout *DL,
240 const TargetLibraryInfo *TLI, unsigned VecWidth,
241 unsigned UnrollFactor)
242 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
243 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
244 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
247 // Perform the actual loop widening (vectorization).
248 void vectorize(LoopVectorizationLegality *L) {
250 // Create a new empty loop. Unlink the old loop and connect the new one.
252 // Widen each instruction in the old loop to a new one in the new loop.
253 // Use the Legality module to find the induction and reduction variables.
255 // Register the new loop and update the analysis passes.
259 virtual ~InnerLoopVectorizer() {}
262 /// A small list of PHINodes.
263 typedef SmallVector<PHINode*, 4> PhiVector;
264 /// When we unroll loops we have multiple vector values for each scalar.
265 /// This data structure holds the unrolled and vectorized values that
266 /// originated from one scalar instruction.
267 typedef SmallVector<Value*, 2> VectorParts;
269 // When we if-convert we need create edge masks. We have to cache values so
270 // that we don't end up with exponential recursion/IR.
271 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
272 VectorParts> EdgeMaskCache;
274 /// \brief Add code that checks at runtime if the accessed arrays overlap.
276 /// Returns a pair of instructions where the first element is the first
277 /// instruction generated in possibly a sequence of instructions and the
278 /// second value is the final comparator value or NULL if no check is needed.
279 std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
281 /// \brief Add checks for strides that where assumed to be 1.
283 /// Returns the last check instruction and the first check instruction in the
284 /// pair as (first, last).
285 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
287 /// Create an empty loop, based on the loop ranges of the old loop.
288 void createEmptyLoop();
289 /// Copy and widen the instructions from the old loop.
290 virtual void vectorizeLoop();
292 /// \brief The Loop exit block may have single value PHI nodes where the
293 /// incoming value is 'Undef'. While vectorizing we only handled real values
294 /// that were defined inside the loop. Here we fix the 'undef case'.
298 /// A helper function that computes the predicate of the block BB, assuming
299 /// that the header block of the loop is set to True. It returns the *entry*
300 /// mask for the block BB.
301 VectorParts createBlockInMask(BasicBlock *BB);
302 /// A helper function that computes the predicate of the edge between SRC
304 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
306 /// A helper function to vectorize a single BB within the innermost loop.
307 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
309 /// Vectorize a single PHINode in a block. This method handles the induction
310 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
311 /// arbitrary length vectors.
312 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
313 unsigned UF, unsigned VF, PhiVector *PV);
315 /// Insert the new loop to the loop hierarchy and pass manager
316 /// and update the analysis passes.
317 void updateAnalysis();
319 /// This instruction is un-vectorizable. Implement it as a sequence
320 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
321 /// scalarized instruction behind an if block predicated on the control
322 /// dependence of the instruction.
323 virtual void scalarizeInstruction(Instruction *Instr,
324 bool IfPredicateStore=false);
326 /// Vectorize Load and Store instructions,
327 virtual void vectorizeMemoryInstruction(Instruction *Instr);
329 /// Create a broadcast instruction. This method generates a broadcast
330 /// instruction (shuffle) for loop invariant values and for the induction
331 /// value. If this is the induction variable then we extend it to N, N+1, ...
332 /// this is needed because each iteration in the loop corresponds to a SIMD
334 virtual Value *getBroadcastInstrs(Value *V);
336 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
337 /// to each vector element of Val. The sequence starts at StartIndex.
338 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
340 /// When we go over instructions in the basic block we rely on previous
341 /// values within the current basic block or on loop invariant values.
342 /// When we widen (vectorize) values we place them in the map. If the values
343 /// are not within the map, they have to be loop invariant, so we simply
344 /// broadcast them into a vector.
345 VectorParts &getVectorValue(Value *V);
347 /// Generate a shuffle sequence that will reverse the vector Vec.
348 virtual Value *reverseVector(Value *Vec);
350 /// This is a helper class that holds the vectorizer state. It maps scalar
351 /// instructions to vector instructions. When the code is 'unrolled' then
352 /// then a single scalar value is mapped to multiple vector parts. The parts
353 /// are stored in the VectorPart type.
355 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
357 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
359 /// \return True if 'Key' is saved in the Value Map.
360 bool has(Value *Key) const { return MapStorage.count(Key); }
362 /// Initializes a new entry in the map. Sets all of the vector parts to the
363 /// save value in 'Val'.
364 /// \return A reference to a vector with splat values.
365 VectorParts &splat(Value *Key, Value *Val) {
366 VectorParts &Entry = MapStorage[Key];
367 Entry.assign(UF, Val);
371 ///\return A reference to the value that is stored at 'Key'.
372 VectorParts &get(Value *Key) {
373 VectorParts &Entry = MapStorage[Key];
376 assert(Entry.size() == UF);
381 /// The unroll factor. Each entry in the map stores this number of vector
385 /// Map storage. We use std::map and not DenseMap because insertions to a
386 /// dense map invalidates its iterators.
387 std::map<Value *, VectorParts> MapStorage;
390 /// The original loop.
392 /// Scev analysis to use.
401 const DataLayout *DL;
402 /// Target Library Info.
403 const TargetLibraryInfo *TLI;
405 /// The vectorization SIMD factor to use. Each vector will have this many
410 /// The vectorization unroll factor to use. Each scalar is vectorized to this
411 /// many different vector instructions.
414 /// The builder that we use
417 // --- Vectorization state ---
419 /// The vector-loop preheader.
420 BasicBlock *LoopVectorPreHeader;
421 /// The scalar-loop preheader.
422 BasicBlock *LoopScalarPreHeader;
423 /// Middle Block between the vector and the scalar.
424 BasicBlock *LoopMiddleBlock;
425 ///The ExitBlock of the scalar loop.
426 BasicBlock *LoopExitBlock;
427 ///The vector loop body.
428 SmallVector<BasicBlock *, 4> LoopVectorBody;
429 ///The scalar loop body.
430 BasicBlock *LoopScalarBody;
431 /// A list of all bypass blocks. The first block is the entry of the loop.
432 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
434 /// The new Induction variable which was added to the new block.
436 /// The induction variable of the old basic block.
437 PHINode *OldInduction;
438 /// Holds the extended (to the widest induction type) start index.
440 /// Maps scalars to widened vectors.
442 EdgeMaskCache MaskCache;
444 LoopVectorizationLegality *Legal;
447 class InnerLoopUnroller : public InnerLoopVectorizer {
449 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
450 DominatorTree *DT, const DataLayout *DL,
451 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
452 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
455 void scalarizeInstruction(Instruction *Instr,
456 bool IfPredicateStore = false) override;
457 void vectorizeMemoryInstruction(Instruction *Instr) override;
458 Value *getBroadcastInstrs(Value *V) override;
459 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
460 Value *reverseVector(Value *Vec) override;
463 /// \brief Look for a meaningful debug location on the instruction or it's
465 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
470 if (I->getDebugLoc() != Empty)
473 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
474 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
475 if (OpInst->getDebugLoc() != Empty)
482 /// \brief Set the debug location in the builder using the debug location in the
484 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
485 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
486 B.SetCurrentDebugLocation(Inst->getDebugLoc());
488 B.SetCurrentDebugLocation(DebugLoc());
492 /// \return string containing a file name and a line # for the given loop.
493 static std::string getDebugLocString(const Loop *L) {
496 raw_string_ostream OS(Result);
497 const DebugLoc LoopDbgLoc = L->getStartLoc();
498 if (!LoopDbgLoc.isUnknown())
499 LoopDbgLoc.print(L->getHeader()->getContext(), OS);
501 // Just print the module name.
502 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
509 /// \brief Propagate known metadata from one instruction to another.
510 static void propagateMetadata(Instruction *To, const Instruction *From) {
511 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
512 From->getAllMetadataOtherThanDebugLoc(Metadata);
514 for (auto M : Metadata) {
515 unsigned Kind = M.first;
517 // These are safe to transfer (this is safe for TBAA, even when we
518 // if-convert, because should that metadata have had a control dependency
519 // on the condition, and thus actually aliased with some other
520 // non-speculated memory access when the condition was false, this would be
521 // caught by the runtime overlap checks).
522 if (Kind != LLVMContext::MD_tbaa &&
523 Kind != LLVMContext::MD_alias_scope &&
524 Kind != LLVMContext::MD_noalias &&
525 Kind != LLVMContext::MD_fpmath)
528 To->setMetadata(Kind, M.second);
532 /// \brief Propagate known metadata from one instruction to a vector of others.
533 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
535 if (Instruction *I = dyn_cast<Instruction>(V))
536 propagateMetadata(I, From);
539 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
540 /// to what vectorization factor.
541 /// This class does not look at the profitability of vectorization, only the
542 /// legality. This class has two main kinds of checks:
543 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
544 /// will change the order of memory accesses in a way that will change the
545 /// correctness of the program.
546 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
547 /// checks for a number of different conditions, such as the availability of a
548 /// single induction variable, that all types are supported and vectorize-able,
549 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
550 /// This class is also used by InnerLoopVectorizer for identifying
551 /// induction variable and the different reduction variables.
552 class LoopVectorizationLegality {
554 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
555 DominatorTree *DT, TargetLibraryInfo *TLI,
556 AliasAnalysis *AA, Function *F,
557 const TargetTransformInfo *TTI)
558 : NumPredStores(0), TheLoop(L), SE(SE), DL(DL), TLI(TLI), TheFunction(F),
559 TTI(TTI), Induction(nullptr), WidestIndTy(nullptr),
560 LAA(F, L, SE, DL, TLI, AA, DT,
561 LoopAccessAnalysis::VectorizerParams(
562 MaxVectorWidth, VectorizationFactor, VectorizationInterleave,
563 RuntimeMemoryCheckThreshold)),
564 HasFunNoNaNAttr(false) {}
566 /// This enum represents the kinds of reductions that we support.
568 RK_NoReduction, ///< Not a reduction.
569 RK_IntegerAdd, ///< Sum of integers.
570 RK_IntegerMult, ///< Product of integers.
571 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
572 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
573 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
574 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
575 RK_FloatAdd, ///< Sum of floats.
576 RK_FloatMult, ///< Product of floats.
577 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
580 /// This enum represents the kinds of inductions that we support.
582 IK_NoInduction, ///< Not an induction variable.
583 IK_IntInduction, ///< Integer induction variable. Step = C.
584 IK_PtrInduction ///< Pointer induction var. Step = C / sizeof(elem).
587 // This enum represents the kind of minmax reduction.
588 enum MinMaxReductionKind {
598 /// This struct holds information about reduction variables.
599 struct ReductionDescriptor {
600 ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
601 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
603 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
604 MinMaxReductionKind MK)
605 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
607 // The starting value of the reduction.
608 // It does not have to be zero!
609 TrackingVH<Value> StartValue;
610 // The instruction who's value is used outside the loop.
611 Instruction *LoopExitInstr;
612 // The kind of the reduction.
614 // If this a min/max reduction the kind of reduction.
615 MinMaxReductionKind MinMaxKind;
618 /// This POD struct holds information about a potential reduction operation.
619 struct ReductionInstDesc {
620 ReductionInstDesc(bool IsRedux, Instruction *I) :
621 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
623 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
624 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
626 // Is this instruction a reduction candidate.
628 // The last instruction in a min/max pattern (select of the select(icmp())
629 // pattern), or the current reduction instruction otherwise.
630 Instruction *PatternLastInst;
631 // If this is a min/max pattern the comparison predicate.
632 MinMaxReductionKind MinMaxKind;
635 /// A struct for saving information about induction variables.
636 struct InductionInfo {
637 InductionInfo(Value *Start, InductionKind K, ConstantInt *Step)
638 : StartValue(Start), IK(K), StepValue(Step) {
639 assert(IK != IK_NoInduction && "Not an induction");
640 assert(StartValue && "StartValue is null");
641 assert(StepValue && !StepValue->isZero() && "StepValue is zero");
642 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
643 "StartValue is not a pointer for pointer induction");
644 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
645 "StartValue is not an integer for integer induction");
646 assert(StepValue->getType()->isIntegerTy() &&
647 "StepValue is not an integer");
650 : StartValue(nullptr), IK(IK_NoInduction), StepValue(nullptr) {}
652 /// Get the consecutive direction. Returns:
653 /// 0 - unknown or non-consecutive.
654 /// 1 - consecutive and increasing.
655 /// -1 - consecutive and decreasing.
656 int getConsecutiveDirection() const {
657 if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
658 return StepValue->getSExtValue();
662 /// Compute the transformed value of Index at offset StartValue using step
664 /// For integer induction, returns StartValue + Index * StepValue.
665 /// For pointer induction, returns StartValue[Index * StepValue].
666 /// FIXME: The newly created binary instructions should contain nsw/nuw
667 /// flags, which can be found from the original scalar operations.
668 Value *transform(IRBuilder<> &B, Value *Index) const {
670 case IK_IntInduction:
671 assert(Index->getType() == StartValue->getType() &&
672 "Index type does not match StartValue type");
673 if (StepValue->isMinusOne())
674 return B.CreateSub(StartValue, Index);
675 if (!StepValue->isOne())
676 Index = B.CreateMul(Index, StepValue);
677 return B.CreateAdd(StartValue, Index);
679 case IK_PtrInduction:
680 if (StepValue->isMinusOne())
681 Index = B.CreateNeg(Index);
682 else if (!StepValue->isOne())
683 Index = B.CreateMul(Index, StepValue);
684 return B.CreateGEP(StartValue, Index);
689 llvm_unreachable("invalid enum");
693 TrackingVH<Value> StartValue;
697 ConstantInt *StepValue;
700 /// ReductionList contains the reduction descriptors for all
701 /// of the reductions that were found in the loop.
702 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
704 /// InductionList saves induction variables and maps them to the
705 /// induction descriptor.
706 typedef MapVector<PHINode*, InductionInfo> InductionList;
708 /// Returns true if it is legal to vectorize this loop.
709 /// This does not mean that it is profitable to vectorize this
710 /// loop, only that it is legal to do so.
713 /// Returns the Induction variable.
714 PHINode *getInduction() { return Induction; }
716 /// Returns the reduction variables found in the loop.
717 ReductionList *getReductionVars() { return &Reductions; }
719 /// Returns the induction variables found in the loop.
720 InductionList *getInductionVars() { return &Inductions; }
722 /// Returns the widest induction type.
723 Type *getWidestInductionType() { return WidestIndTy; }
725 /// Returns True if V is an induction variable in this loop.
726 bool isInductionVariable(const Value *V);
728 /// Return true if the block BB needs to be predicated in order for the loop
729 /// to be vectorized.
730 bool blockNeedsPredication(BasicBlock *BB);
732 /// Check if this pointer is consecutive when vectorizing. This happens
733 /// when the last index of the GEP is the induction variable, or that the
734 /// pointer itself is an induction variable.
735 /// This check allows us to vectorize A[idx] into a wide load/store.
737 /// 0 - Stride is unknown or non-consecutive.
738 /// 1 - Address is consecutive.
739 /// -1 - Address is consecutive, and decreasing.
740 int isConsecutivePtr(Value *Ptr);
742 /// Returns true if the value V is uniform within the loop.
743 bool isUniform(Value *V);
745 /// Returns true if this instruction will remain scalar after vectorization.
746 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
748 /// Returns the information that we collected about runtime memory check.
749 LoopAccessAnalysis::RuntimePointerCheck *getRuntimePointerCheck() {
750 return LAA.getRuntimePointerCheck();
753 /// This function returns the identity element (or neutral element) for
755 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
757 unsigned getMaxSafeDepDistBytes() { return LAA.getMaxSafeDepDistBytes(); }
759 bool hasStride(Value *V) { return StrideSet.count(V); }
760 bool mustCheckStrides() { return !StrideSet.empty(); }
761 SmallPtrSet<Value *, 8>::iterator strides_begin() {
762 return StrideSet.begin();
764 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
766 /// Returns true if the target machine supports masked store operation
767 /// for the given \p DataType and kind of access to \p Ptr.
768 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
769 return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
771 /// Returns true if the target machine supports masked load operation
772 /// for the given \p DataType and kind of access to \p Ptr.
773 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
774 return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
776 /// Returns true if vector representation of the instruction \p I
778 bool isMaskRequired(const Instruction* I) {
779 return (MaskedOp.count(I) != 0);
781 unsigned getNumStores() const {
784 unsigned getNumLoads() const {
787 unsigned getNumPredStores() const {
788 return NumPredStores;
791 /// Check if a single basic block loop is vectorizable.
792 /// At this point we know that this is a loop with a constant trip count
793 /// and we only need to check individual instructions.
794 bool canVectorizeInstrs();
796 /// When we vectorize loops we may change the order in which
797 /// we read and write from memory. This method checks if it is
798 /// legal to vectorize the code, considering only memory constrains.
799 /// Returns true if the loop is vectorizable
800 bool canVectorizeMemory();
802 /// Return true if we can vectorize this loop using the IF-conversion
804 bool canVectorizeWithIfConvert();
806 /// Collect the variables that need to stay uniform after vectorization.
807 void collectLoopUniforms();
809 /// Return true if all of the instructions in the block can be speculatively
810 /// executed. \p SafePtrs is a list of addresses that are known to be legal
811 /// and we know that we can read from them without segfault.
812 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
814 /// Returns True, if 'Phi' is the kind of reduction variable for type
815 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
816 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
817 /// Returns a struct describing if the instruction 'I' can be a reduction
818 /// variable of type 'Kind'. If the reduction is a min/max pattern of
819 /// select(icmp()) this function advances the instruction pointer 'I' from the
820 /// compare instruction to the select instruction and stores this pointer in
821 /// 'PatternLastInst' member of the returned struct.
822 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
823 ReductionInstDesc &Desc);
824 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
825 /// pattern corresponding to a min(X, Y) or max(X, Y).
826 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
827 ReductionInstDesc &Prev);
828 /// Returns the induction kind of Phi and record the step. This function may
829 /// return NoInduction if the PHI is not an induction variable.
830 InductionKind isInductionVariable(PHINode *Phi, ConstantInt *&StepValue);
832 /// \brief Collect memory access with loop invariant strides.
834 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
836 void collectStridedAccess(Value *LoadOrStoreInst);
838 /// Report an analysis message to assist the user in diagnosing loops that are
840 void emitAnalysis(VectorizationReport &Message) {
841 VectorizationReport::emitAnalysis(Message, TheFunction, TheLoop);
846 unsigned NumPredStores;
848 /// The loop that we evaluate.
852 /// DataLayout analysis.
853 const DataLayout *DL;
854 /// Target Library Info.
855 TargetLibraryInfo *TLI;
857 Function *TheFunction;
858 /// Target Transform Info
859 const TargetTransformInfo *TTI;
861 // --- vectorization state --- //
863 /// Holds the integer induction variable. This is the counter of the
866 /// Holds the reduction variables.
867 ReductionList Reductions;
868 /// Holds all of the induction variables that we found in the loop.
869 /// Notice that inductions don't need to start at zero and that induction
870 /// variables can be pointers.
871 InductionList Inductions;
872 /// Holds the widest induction type encountered.
875 /// Allowed outside users. This holds the reduction
876 /// vars which can be accessed from outside the loop.
877 SmallPtrSet<Value*, 4> AllowedExit;
878 /// This set holds the variables which are known to be uniform after
880 SmallPtrSet<Instruction*, 4> Uniforms;
881 LoopAccessAnalysis LAA;
882 /// Can we assume the absence of NaNs.
883 bool HasFunNoNaNAttr;
885 ValueToValueMap Strides;
886 SmallPtrSet<Value *, 8> StrideSet;
888 /// While vectorizing these instructions we have to generate a
889 /// call to the appropriate masked intrinsic
890 SmallPtrSet<const Instruction*, 8> MaskedOp;
893 /// LoopVectorizationCostModel - estimates the expected speedups due to
895 /// In many cases vectorization is not profitable. This can happen because of
896 /// a number of reasons. In this class we mainly attempt to predict the
897 /// expected speedup/slowdowns due to the supported instruction set. We use the
898 /// TargetTransformInfo to query the different backends for the cost of
899 /// different operations.
900 class LoopVectorizationCostModel {
902 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
903 LoopVectorizationLegality *Legal,
904 const TargetTransformInfo &TTI,
905 const DataLayout *DL, const TargetLibraryInfo *TLI,
906 AssumptionCache *AC, const Function *F,
907 const LoopVectorizeHints *Hints)
908 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI),
909 TheFunction(F), Hints(Hints) {
910 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
913 /// Information about vectorization costs
914 struct VectorizationFactor {
915 unsigned Width; // Vector width with best cost
916 unsigned Cost; // Cost of the loop with that width
918 /// \return The most profitable vectorization factor and the cost of that VF.
919 /// This method checks every power of two up to VF. If UserVF is not ZERO
920 /// then this vectorization factor will be selected if vectorization is
922 VectorizationFactor selectVectorizationFactor(bool OptForSize);
924 /// \return The size (in bits) of the widest type in the code that
925 /// needs to be vectorized. We ignore values that remain scalar such as
926 /// 64 bit loop indices.
927 unsigned getWidestType();
929 /// \return The most profitable unroll factor.
930 /// If UserUF is non-zero then this method finds the best unroll-factor
931 /// based on register pressure and other parameters.
932 /// VF and LoopCost are the selected vectorization factor and the cost of the
934 unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost);
936 /// \brief A struct that represents some properties of the register usage
938 struct RegisterUsage {
939 /// Holds the number of loop invariant values that are used in the loop.
940 unsigned LoopInvariantRegs;
941 /// Holds the maximum number of concurrent live intervals in the loop.
942 unsigned MaxLocalUsers;
943 /// Holds the number of instructions in the loop.
944 unsigned NumInstructions;
947 /// \return information about the register usage of the loop.
948 RegisterUsage calculateRegisterUsage();
951 /// Returns the expected execution cost. The unit of the cost does
952 /// not matter because we use the 'cost' units to compare different
953 /// vector widths. The cost that is returned is *not* normalized by
954 /// the factor width.
955 unsigned expectedCost(unsigned VF);
957 /// Returns the execution time cost of an instruction for a given vector
958 /// width. Vector width of one means scalar.
959 unsigned getInstructionCost(Instruction *I, unsigned VF);
961 /// A helper function for converting Scalar types to vector types.
962 /// If the incoming type is void, we return void. If the VF is 1, we return
964 static Type* ToVectorTy(Type *Scalar, unsigned VF);
966 /// Returns whether the instruction is a load or store and will be a emitted
967 /// as a vector operation.
968 bool isConsecutiveLoadOrStore(Instruction *I);
970 /// Report an analysis message to assist the user in diagnosing loops that are
972 void emitAnalysis(VectorizationReport &Message) {
973 VectorizationReport::emitAnalysis(Message, TheFunction, TheLoop);
976 /// Values used only by @llvm.assume calls.
977 SmallPtrSet<const Value *, 32> EphValues;
979 /// The loop that we evaluate.
983 /// Loop Info analysis.
985 /// Vectorization legality.
986 LoopVectorizationLegality *Legal;
987 /// Vector target information.
988 const TargetTransformInfo &TTI;
989 /// Target data layout information.
990 const DataLayout *DL;
991 /// Target Library Info.
992 const TargetLibraryInfo *TLI;
993 const Function *TheFunction;
994 // Loop Vectorize Hint.
995 const LoopVectorizeHints *Hints;
998 /// Utility class for getting and setting loop vectorizer hints in the form
999 /// of loop metadata.
1000 /// This class keeps a number of loop annotations locally (as member variables)
1001 /// and can, upon request, write them back as metadata on the loop. It will
1002 /// initially scan the loop for existing metadata, and will update the local
1003 /// values based on information in the loop.
1004 /// We cannot write all values to metadata, as the mere presence of some info,
1005 /// for example 'force', means a decision has been made. So, we need to be
1006 /// careful NOT to add them if the user hasn't specifically asked so.
1007 class LoopVectorizeHints {
1014 /// Hint - associates name and validation with the hint value.
1017 unsigned Value; // This may have to change for non-numeric values.
1020 Hint(const char * Name, unsigned Value, HintKind Kind)
1021 : Name(Name), Value(Value), Kind(Kind) { }
1023 bool validate(unsigned Val) {
1026 return isPowerOf2_32(Val) && Val <= MaxVectorWidth;
1028 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1036 /// Vectorization width.
1038 /// Vectorization interleave factor.
1040 /// Vectorization forced
1043 /// Return the loop metadata prefix.
1044 static StringRef Prefix() { return "llvm.loop."; }
1048 FK_Undefined = -1, ///< Not selected.
1049 FK_Disabled = 0, ///< Forcing disabled.
1050 FK_Enabled = 1, ///< Forcing enabled.
1053 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1054 : Width("vectorize.width", VectorizationFactor, HK_WIDTH),
1055 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1056 Force("vectorize.enable", FK_Undefined, HK_FORCE),
1058 // Populate values with existing loop metadata.
1059 getHintsFromMetadata();
1061 // force-vector-interleave overrides DisableInterleaving.
1062 if (VectorizationInterleave.getNumOccurrences() > 0)
1063 Interleave.Value = VectorizationInterleave;
1065 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1066 << "LV: Interleaving disabled by the pass manager\n");
1069 /// Mark the loop L as already vectorized by setting the width to 1.
1070 void setAlreadyVectorized() {
1071 Width.Value = Interleave.Value = 1;
1072 Hint Hints[] = {Width, Interleave};
1073 writeHintsToMetadata(Hints);
1076 /// Dumps all the hint information.
1077 std::string emitRemark() const {
1078 VectorizationReport R;
1079 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1080 R << "vectorization is explicitly disabled";
1082 R << "use -Rpass-analysis=loop-vectorize for more info";
1083 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1084 R << " (Force=true";
1085 if (Width.Value != 0)
1086 R << ", Vector Width=" << Width.Value;
1087 if (Interleave.Value != 0)
1088 R << ", Interleave Count=" << Interleave.Value;
1096 unsigned getWidth() const { return Width.Value; }
1097 unsigned getInterleave() const { return Interleave.Value; }
1098 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1101 /// Find hints specified in the loop metadata and update local values.
1102 void getHintsFromMetadata() {
1103 MDNode *LoopID = TheLoop->getLoopID();
1107 // First operand should refer to the loop id itself.
1108 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1109 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1111 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1112 const MDString *S = nullptr;
1113 SmallVector<Metadata *, 4> Args;
1115 // The expected hint is either a MDString or a MDNode with the first
1116 // operand a MDString.
1117 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1118 if (!MD || MD->getNumOperands() == 0)
1120 S = dyn_cast<MDString>(MD->getOperand(0));
1121 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1122 Args.push_back(MD->getOperand(i));
1124 S = dyn_cast<MDString>(LoopID->getOperand(i));
1125 assert(Args.size() == 0 && "too many arguments for MDString");
1131 // Check if the hint starts with the loop metadata prefix.
1132 StringRef Name = S->getString();
1133 if (Args.size() == 1)
1134 setHint(Name, Args[0]);
1138 /// Checks string hint with one operand and set value if valid.
1139 void setHint(StringRef Name, Metadata *Arg) {
1140 if (!Name.startswith(Prefix()))
1142 Name = Name.substr(Prefix().size(), StringRef::npos);
1144 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1146 unsigned Val = C->getZExtValue();
1148 Hint *Hints[] = {&Width, &Interleave, &Force};
1149 for (auto H : Hints) {
1150 if (Name == H->Name) {
1151 if (H->validate(Val))
1154 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1160 /// Create a new hint from name / value pair.
1161 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1162 LLVMContext &Context = TheLoop->getHeader()->getContext();
1163 Metadata *MDs[] = {MDString::get(Context, Name),
1164 ConstantAsMetadata::get(
1165 ConstantInt::get(Type::getInt32Ty(Context), V))};
1166 return MDNode::get(Context, MDs);
1169 /// Matches metadata with hint name.
1170 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1171 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1175 for (auto H : HintTypes)
1176 if (Name->getString().endswith(H.Name))
1181 /// Sets current hints into loop metadata, keeping other values intact.
1182 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1183 if (HintTypes.size() == 0)
1186 // Reserve the first element to LoopID (see below).
1187 SmallVector<Metadata *, 4> MDs(1);
1188 // If the loop already has metadata, then ignore the existing operands.
1189 MDNode *LoopID = TheLoop->getLoopID();
1191 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1192 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1193 // If node in update list, ignore old value.
1194 if (!matchesHintMetadataName(Node, HintTypes))
1195 MDs.push_back(Node);
1199 // Now, add the missing hints.
1200 for (auto H : HintTypes)
1201 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1203 // Replace current metadata node with new one.
1204 LLVMContext &Context = TheLoop->getHeader()->getContext();
1205 MDNode *NewLoopID = MDNode::get(Context, MDs);
1206 // Set operand 0 to refer to the loop id itself.
1207 NewLoopID->replaceOperandWith(0, NewLoopID);
1209 TheLoop->setLoopID(NewLoopID);
1212 /// The loop these hints belong to.
1213 const Loop *TheLoop;
1216 static void emitMissedWarning(Function *F, Loop *L,
1217 const LoopVectorizeHints &LH) {
1218 emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1219 L->getStartLoc(), LH.emitRemark());
1221 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1222 if (LH.getWidth() != 1)
1223 emitLoopVectorizeWarning(
1224 F->getContext(), *F, L->getStartLoc(),
1225 "failed explicitly specified loop vectorization");
1226 else if (LH.getInterleave() != 1)
1227 emitLoopInterleaveWarning(
1228 F->getContext(), *F, L->getStartLoc(),
1229 "failed explicitly specified loop interleaving");
1233 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1235 return V.push_back(&L);
1237 for (Loop *InnerL : L)
1238 addInnerLoop(*InnerL, V);
1241 /// The LoopVectorize Pass.
1242 struct LoopVectorize : public FunctionPass {
1243 /// Pass identification, replacement for typeid
1246 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1248 DisableUnrolling(NoUnrolling),
1249 AlwaysVectorize(AlwaysVectorize) {
1250 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1253 ScalarEvolution *SE;
1254 const DataLayout *DL;
1256 TargetTransformInfo *TTI;
1258 BlockFrequencyInfo *BFI;
1259 TargetLibraryInfo *TLI;
1261 AssumptionCache *AC;
1262 bool DisableUnrolling;
1263 bool AlwaysVectorize;
1265 BlockFrequency ColdEntryFreq;
1267 bool runOnFunction(Function &F) override {
1268 SE = &getAnalysis<ScalarEvolution>();
1269 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1270 DL = DLP ? &DLP->getDataLayout() : nullptr;
1271 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1272 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1273 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1274 BFI = &getAnalysis<BlockFrequencyInfo>();
1275 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1276 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1277 AA = &getAnalysis<AliasAnalysis>();
1278 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1280 // Compute some weights outside of the loop over the loops. Compute this
1281 // using a BranchProbability to re-use its scaling math.
1282 const BranchProbability ColdProb(1, 5); // 20%
1283 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1285 // If the target claims to have no vector registers don't attempt
1287 if (!TTI->getNumberOfRegisters(true))
1291 DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1292 << ": Missing data layout\n");
1296 // Build up a worklist of inner-loops to vectorize. This is necessary as
1297 // the act of vectorizing or partially unrolling a loop creates new loops
1298 // and can invalidate iterators across the loops.
1299 SmallVector<Loop *, 8> Worklist;
1302 addInnerLoop(*L, Worklist);
1304 LoopsAnalyzed += Worklist.size();
1306 // Now walk the identified inner loops.
1307 bool Changed = false;
1308 while (!Worklist.empty())
1309 Changed |= processLoop(Worklist.pop_back_val());
1311 // Process each loop nest in the function.
1315 bool processLoop(Loop *L) {
1316 assert(L->empty() && "Only process inner loops.");
1319 const std::string DebugLocStr = getDebugLocString(L);
1322 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1323 << L->getHeader()->getParent()->getName() << "\" from "
1324 << DebugLocStr << "\n");
1326 LoopVectorizeHints Hints(L, DisableUnrolling);
1328 DEBUG(dbgs() << "LV: Loop hints:"
1330 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1332 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1334 : "?")) << " width=" << Hints.getWidth()
1335 << " unroll=" << Hints.getInterleave() << "\n");
1337 // Function containing loop
1338 Function *F = L->getHeader()->getParent();
1340 // Looking at the diagnostic output is the only way to determine if a loop
1341 // was vectorized (other than looking at the IR or machine code), so it
1342 // is important to generate an optimization remark for each loop. Most of
1343 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1344 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1345 // less verbose reporting vectorized loops and unvectorized loops that may
1346 // benefit from vectorization, respectively.
1348 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1349 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1350 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1351 L->getStartLoc(), Hints.emitRemark());
1355 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1356 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1357 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1358 L->getStartLoc(), Hints.emitRemark());
1362 if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
1363 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1364 emitOptimizationRemarkAnalysis(
1365 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1366 "loop not vectorized: vector width and interleave count are "
1367 "explicitly set to 1");
1371 // Check the loop for a trip count threshold:
1372 // do not vectorize loops with a tiny trip count.
1373 const unsigned TC = SE->getSmallConstantTripCount(L);
1374 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1375 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1376 << "This loop is not worth vectorizing.");
1377 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1378 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1380 DEBUG(dbgs() << "\n");
1381 emitOptimizationRemarkAnalysis(
1382 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1383 "vectorization is not beneficial and is not explicitly forced");
1388 // Check if it is legal to vectorize the loop.
1389 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI, AA, F, TTI);
1390 if (!LVL.canVectorize()) {
1391 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1392 emitMissedWarning(F, L, Hints);
1396 // Use the cost model.
1397 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI, AC, F,
1400 // Check the function attributes to find out if this function should be
1401 // optimized for size.
1402 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1403 F->hasFnAttribute(Attribute::OptimizeForSize);
1405 // Compute the weighted frequency of this loop being executed and see if it
1406 // is less than 20% of the function entry baseline frequency. Note that we
1407 // always have a canonical loop here because we think we *can* vectoriez.
1408 // FIXME: This is hidden behind a flag due to pervasive problems with
1409 // exactly what block frequency models.
1410 if (LoopVectorizeWithBlockFrequency) {
1411 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1412 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1413 LoopEntryFreq < ColdEntryFreq)
1417 // Check the function attributes to see if implicit floats are allowed.a
1418 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1419 // an integer loop and the vector instructions selected are purely integer
1420 // vector instructions?
1421 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1422 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1423 "attribute is used.\n");
1424 emitOptimizationRemarkAnalysis(
1425 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1426 "loop not vectorized due to NoImplicitFloat attribute");
1427 emitMissedWarning(F, L, Hints);
1431 // Select the optimal vectorization factor.
1432 const LoopVectorizationCostModel::VectorizationFactor VF =
1433 CM.selectVectorizationFactor(OptForSize);
1435 // Select the unroll factor.
1437 CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
1439 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1440 << DebugLocStr << '\n');
1441 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1443 if (VF.Width == 1) {
1444 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
1447 emitOptimizationRemarkAnalysis(
1448 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1449 "not beneficial to vectorize and user disabled interleaving");
1452 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1454 // Report the unrolling decision.
1455 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1456 Twine("unrolled with interleaving factor " +
1458 " (vectorization not beneficial)"));
1460 // We decided not to vectorize, but we may want to unroll.
1462 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1463 Unroller.vectorize(&LVL);
1465 // If we decided that it is *legal* to vectorize the loop then do it.
1466 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1470 // Report the vectorization decision.
1471 emitOptimizationRemark(
1472 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1473 Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1474 ", unrolling interleave factor: " + Twine(UF) + ")");
1477 // Mark the loop as already vectorized to avoid vectorizing again.
1478 Hints.setAlreadyVectorized();
1480 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1484 void getAnalysisUsage(AnalysisUsage &AU) const override {
1485 AU.addRequired<AssumptionCacheTracker>();
1486 AU.addRequiredID(LoopSimplifyID);
1487 AU.addRequiredID(LCSSAID);
1488 AU.addRequired<BlockFrequencyInfo>();
1489 AU.addRequired<DominatorTreeWrapperPass>();
1490 AU.addRequired<LoopInfoWrapperPass>();
1491 AU.addRequired<ScalarEvolution>();
1492 AU.addRequired<TargetTransformInfoWrapperPass>();
1493 AU.addRequired<AliasAnalysis>();
1494 AU.addPreserved<LoopInfoWrapperPass>();
1495 AU.addPreserved<DominatorTreeWrapperPass>();
1496 AU.addPreserved<AliasAnalysis>();
1501 } // end anonymous namespace
1503 //===----------------------------------------------------------------------===//
1504 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1505 // LoopVectorizationCostModel.
1506 //===----------------------------------------------------------------------===//
1508 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1509 // We need to place the broadcast of invariant variables outside the loop.
1510 Instruction *Instr = dyn_cast<Instruction>(V);
1512 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1513 Instr->getParent()) != LoopVectorBody.end());
1514 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1516 // Place the code for broadcasting invariant variables in the new preheader.
1517 IRBuilder<>::InsertPointGuard Guard(Builder);
1519 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1521 // Broadcast the scalar into all locations in the vector.
1522 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1527 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1529 assert(Val->getType()->isVectorTy() && "Must be a vector");
1530 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1531 "Elem must be an integer");
1532 assert(Step->getType() == Val->getType()->getScalarType() &&
1533 "Step has wrong type");
1534 // Create the types.
1535 Type *ITy = Val->getType()->getScalarType();
1536 VectorType *Ty = cast<VectorType>(Val->getType());
1537 int VLen = Ty->getNumElements();
1538 SmallVector<Constant*, 8> Indices;
1540 // Create a vector of consecutive numbers from zero to VF.
1541 for (int i = 0; i < VLen; ++i)
1542 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1544 // Add the consecutive indices to the vector value.
1545 Constant *Cv = ConstantVector::get(Indices);
1546 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1547 Step = Builder.CreateVectorSplat(VLen, Step);
1548 assert(Step->getType() == Val->getType() && "Invalid step vec");
1549 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1550 // which can be found from the original scalar operations.
1551 Step = Builder.CreateMul(Cv, Step);
1552 return Builder.CreateAdd(Val, Step, "induction");
1555 /// \brief Find the operand of the GEP that should be checked for consecutive
1556 /// stores. This ignores trailing indices that have no effect on the final
1558 static unsigned getGEPInductionOperand(const DataLayout *DL,
1559 const GetElementPtrInst *Gep) {
1560 unsigned LastOperand = Gep->getNumOperands() - 1;
1561 unsigned GEPAllocSize = DL->getTypeAllocSize(
1562 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1564 // Walk backwards and try to peel off zeros.
1565 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1566 // Find the type we're currently indexing into.
1567 gep_type_iterator GEPTI = gep_type_begin(Gep);
1568 std::advance(GEPTI, LastOperand - 1);
1570 // If it's a type with the same allocation size as the result of the GEP we
1571 // can peel off the zero index.
1572 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1580 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1581 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1582 // Make sure that the pointer does not point to structs.
1583 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1586 // If this value is a pointer induction variable we know it is consecutive.
1587 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1588 if (Phi && Inductions.count(Phi)) {
1589 InductionInfo II = Inductions[Phi];
1590 return II.getConsecutiveDirection();
1593 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1597 unsigned NumOperands = Gep->getNumOperands();
1598 Value *GpPtr = Gep->getPointerOperand();
1599 // If this GEP value is a consecutive pointer induction variable and all of
1600 // the indices are constant then we know it is consecutive. We can
1601 Phi = dyn_cast<PHINode>(GpPtr);
1602 if (Phi && Inductions.count(Phi)) {
1604 // Make sure that the pointer does not point to structs.
1605 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1606 if (GepPtrType->getElementType()->isAggregateType())
1609 // Make sure that all of the index operands are loop invariant.
1610 for (unsigned i = 1; i < NumOperands; ++i)
1611 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1614 InductionInfo II = Inductions[Phi];
1615 return II.getConsecutiveDirection();
1618 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1620 // Check that all of the gep indices are uniform except for our induction
1622 for (unsigned i = 0; i != NumOperands; ++i)
1623 if (i != InductionOperand &&
1624 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1627 // We can emit wide load/stores only if the last non-zero index is the
1628 // induction variable.
1629 const SCEV *Last = nullptr;
1630 if (!Strides.count(Gep))
1631 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1633 // Because of the multiplication by a stride we can have a s/zext cast.
1634 // We are going to replace this stride by 1 so the cast is safe to ignore.
1636 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1637 // %0 = trunc i64 %indvars.iv to i32
1638 // %mul = mul i32 %0, %Stride1
1639 // %idxprom = zext i32 %mul to i64 << Safe cast.
1640 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1642 Last = replaceSymbolicStrideSCEV(SE, Strides,
1643 Gep->getOperand(InductionOperand), Gep);
1644 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1646 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1650 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1651 const SCEV *Step = AR->getStepRecurrence(*SE);
1653 // The memory is consecutive because the last index is consecutive
1654 // and all other indices are loop invariant.
1657 if (Step->isAllOnesValue())
1664 bool LoopVectorizationLegality::isUniform(Value *V) {
1665 return LAA.isUniform(V);
1668 InnerLoopVectorizer::VectorParts&
1669 InnerLoopVectorizer::getVectorValue(Value *V) {
1670 assert(V != Induction && "The new induction variable should not be used.");
1671 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1673 // If we have a stride that is replaced by one, do it here.
1674 if (Legal->hasStride(V))
1675 V = ConstantInt::get(V->getType(), 1);
1677 // If we have this scalar in the map, return it.
1678 if (WidenMap.has(V))
1679 return WidenMap.get(V);
1681 // If this scalar is unknown, assume that it is a constant or that it is
1682 // loop invariant. Broadcast V and save the value for future uses.
1683 Value *B = getBroadcastInstrs(V);
1684 return WidenMap.splat(V, B);
1687 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1688 assert(Vec->getType()->isVectorTy() && "Invalid type");
1689 SmallVector<Constant*, 8> ShuffleMask;
1690 for (unsigned i = 0; i < VF; ++i)
1691 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1693 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1694 ConstantVector::get(ShuffleMask),
1698 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1699 // Attempt to issue a wide load.
1700 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1701 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1703 assert((LI || SI) && "Invalid Load/Store instruction");
1705 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1706 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1707 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1708 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1709 // An alignment of 0 means target abi alignment. We need to use the scalar's
1710 // target abi alignment in such a case.
1712 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1713 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1714 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1715 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1717 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
1718 !Legal->isMaskRequired(SI))
1719 return scalarizeInstruction(Instr, true);
1721 if (ScalarAllocatedSize != VectorElementSize)
1722 return scalarizeInstruction(Instr);
1724 // If the pointer is loop invariant or if it is non-consecutive,
1725 // scalarize the load.
1726 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1727 bool Reverse = ConsecutiveStride < 0;
1728 bool UniformLoad = LI && Legal->isUniform(Ptr);
1729 if (!ConsecutiveStride || UniformLoad)
1730 return scalarizeInstruction(Instr);
1732 Constant *Zero = Builder.getInt32(0);
1733 VectorParts &Entry = WidenMap.get(Instr);
1735 // Handle consecutive loads/stores.
1736 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1737 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1738 setDebugLocFromInst(Builder, Gep);
1739 Value *PtrOperand = Gep->getPointerOperand();
1740 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1741 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1743 // Create the new GEP with the new induction variable.
1744 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1745 Gep2->setOperand(0, FirstBasePtr);
1746 Gep2->setName("gep.indvar.base");
1747 Ptr = Builder.Insert(Gep2);
1749 setDebugLocFromInst(Builder, Gep);
1750 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1751 OrigLoop) && "Base ptr must be invariant");
1753 // The last index does not have to be the induction. It can be
1754 // consecutive and be a function of the index. For example A[I+1];
1755 unsigned NumOperands = Gep->getNumOperands();
1756 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1757 // Create the new GEP with the new induction variable.
1758 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1760 for (unsigned i = 0; i < NumOperands; ++i) {
1761 Value *GepOperand = Gep->getOperand(i);
1762 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1764 // Update last index or loop invariant instruction anchored in loop.
1765 if (i == InductionOperand ||
1766 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1767 assert((i == InductionOperand ||
1768 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1769 "Must be last index or loop invariant");
1771 VectorParts &GEPParts = getVectorValue(GepOperand);
1772 Value *Index = GEPParts[0];
1773 Index = Builder.CreateExtractElement(Index, Zero);
1774 Gep2->setOperand(i, Index);
1775 Gep2->setName("gep.indvar.idx");
1778 Ptr = Builder.Insert(Gep2);
1780 // Use the induction element ptr.
1781 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1782 setDebugLocFromInst(Builder, Ptr);
1783 VectorParts &PtrVal = getVectorValue(Ptr);
1784 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1787 VectorParts Mask = createBlockInMask(Instr->getParent());
1790 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1791 "We do not allow storing to uniform addresses");
1792 setDebugLocFromInst(Builder, SI);
1793 // We don't want to update the value in the map as it might be used in
1794 // another expression. So don't use a reference type for "StoredVal".
1795 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1797 for (unsigned Part = 0; Part < UF; ++Part) {
1798 // Calculate the pointer for the specific unroll-part.
1799 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1802 // If we store to reverse consecutive memory locations then we need
1803 // to reverse the order of elements in the stored value.
1804 StoredVal[Part] = reverseVector(StoredVal[Part]);
1805 // If the address is consecutive but reversed, then the
1806 // wide store needs to start at the last vector element.
1807 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1808 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1809 Mask[Part] = reverseVector(Mask[Part]);
1812 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1813 DataTy->getPointerTo(AddressSpace));
1816 if (Legal->isMaskRequired(SI))
1817 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
1820 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
1821 propagateMetadata(NewSI, SI);
1827 assert(LI && "Must have a load instruction");
1828 setDebugLocFromInst(Builder, LI);
1829 for (unsigned Part = 0; Part < UF; ++Part) {
1830 // Calculate the pointer for the specific unroll-part.
1831 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1834 // If the address is consecutive but reversed, then the
1835 // wide load needs to start at the last vector element.
1836 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1837 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1838 Mask[Part] = reverseVector(Mask[Part]);
1842 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1843 DataTy->getPointerTo(AddressSpace));
1844 if (Legal->isMaskRequired(LI))
1845 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
1846 UndefValue::get(DataTy),
1847 "wide.masked.load");
1849 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
1850 propagateMetadata(NewLI, LI);
1851 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
1855 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1856 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1857 // Holds vector parameters or scalars, in case of uniform vals.
1858 SmallVector<VectorParts, 4> Params;
1860 setDebugLocFromInst(Builder, Instr);
1862 // Find all of the vectorized parameters.
1863 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1864 Value *SrcOp = Instr->getOperand(op);
1866 // If we are accessing the old induction variable, use the new one.
1867 if (SrcOp == OldInduction) {
1868 Params.push_back(getVectorValue(SrcOp));
1872 // Try using previously calculated values.
1873 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1875 // If the src is an instruction that appeared earlier in the basic block
1876 // then it should already be vectorized.
1877 if (SrcInst && OrigLoop->contains(SrcInst)) {
1878 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1879 // The parameter is a vector value from earlier.
1880 Params.push_back(WidenMap.get(SrcInst));
1882 // The parameter is a scalar from outside the loop. Maybe even a constant.
1883 VectorParts Scalars;
1884 Scalars.append(UF, SrcOp);
1885 Params.push_back(Scalars);
1889 assert(Params.size() == Instr->getNumOperands() &&
1890 "Invalid number of operands");
1892 // Does this instruction return a value ?
1893 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1895 Value *UndefVec = IsVoidRetTy ? nullptr :
1896 UndefValue::get(VectorType::get(Instr->getType(), VF));
1897 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1898 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1900 Instruction *InsertPt = Builder.GetInsertPoint();
1901 BasicBlock *IfBlock = Builder.GetInsertBlock();
1902 BasicBlock *CondBlock = nullptr;
1905 Loop *VectorLp = nullptr;
1906 if (IfPredicateStore) {
1907 assert(Instr->getParent()->getSinglePredecessor() &&
1908 "Only support single predecessor blocks");
1909 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1910 Instr->getParent());
1911 VectorLp = LI->getLoopFor(IfBlock);
1912 assert(VectorLp && "Must have a loop for this block");
1915 // For each vector unroll 'part':
1916 for (unsigned Part = 0; Part < UF; ++Part) {
1917 // For each scalar that we create:
1918 for (unsigned Width = 0; Width < VF; ++Width) {
1921 Value *Cmp = nullptr;
1922 if (IfPredicateStore) {
1923 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1924 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1925 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1926 LoopVectorBody.push_back(CondBlock);
1927 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
1928 // Update Builder with newly created basic block.
1929 Builder.SetInsertPoint(InsertPt);
1932 Instruction *Cloned = Instr->clone();
1934 Cloned->setName(Instr->getName() + ".cloned");
1935 // Replace the operands of the cloned instructions with extracted scalars.
1936 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1937 Value *Op = Params[op][Part];
1938 // Param is a vector. Need to extract the right lane.
1939 if (Op->getType()->isVectorTy())
1940 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1941 Cloned->setOperand(op, Op);
1944 // Place the cloned scalar in the new loop.
1945 Builder.Insert(Cloned);
1947 // If the original scalar returns a value we need to place it in a vector
1948 // so that future users will be able to use it.
1950 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1951 Builder.getInt32(Width));
1953 if (IfPredicateStore) {
1954 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1955 LoopVectorBody.push_back(NewIfBlock);
1956 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
1957 Builder.SetInsertPoint(InsertPt);
1958 Instruction *OldBr = IfBlock->getTerminator();
1959 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1960 OldBr->eraseFromParent();
1961 IfBlock = NewIfBlock;
1967 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1971 if (Instruction *I = dyn_cast<Instruction>(V))
1972 return I->getParent() == Loc->getParent() ? I : nullptr;
1976 std::pair<Instruction *, Instruction *>
1977 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1978 Instruction *tnullptr = nullptr;
1979 if (!Legal->mustCheckStrides())
1980 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1982 IRBuilder<> ChkBuilder(Loc);
1985 Value *Check = nullptr;
1986 Instruction *FirstInst = nullptr;
1987 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1988 SE = Legal->strides_end();
1990 Value *Ptr = stripIntegerCast(*SI);
1991 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1993 // Store the first instruction we create.
1994 FirstInst = getFirstInst(FirstInst, C, Loc);
1996 Check = ChkBuilder.CreateOr(Check, C);
2001 // We have to do this trickery because the IRBuilder might fold the check to a
2002 // constant expression in which case there is no Instruction anchored in a
2004 LLVMContext &Ctx = Loc->getContext();
2005 Instruction *TheCheck =
2006 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2007 ChkBuilder.Insert(TheCheck, "stride.not.one");
2008 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2010 return std::make_pair(FirstInst, TheCheck);
2013 std::pair<Instruction *, Instruction *>
2014 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
2015 LoopAccessAnalysis::RuntimePointerCheck *PtrRtCheck =
2016 Legal->getRuntimePointerCheck();
2018 Instruction *tnullptr = nullptr;
2019 if (!PtrRtCheck->Need)
2020 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2022 unsigned NumPointers = PtrRtCheck->Pointers.size();
2023 SmallVector<TrackingVH<Value> , 2> Starts;
2024 SmallVector<TrackingVH<Value> , 2> Ends;
2026 LLVMContext &Ctx = Loc->getContext();
2027 SCEVExpander Exp(*SE, "induction");
2028 Instruction *FirstInst = nullptr;
2030 for (unsigned i = 0; i < NumPointers; ++i) {
2031 Value *Ptr = PtrRtCheck->Pointers[i];
2032 const SCEV *Sc = SE->getSCEV(Ptr);
2034 if (SE->isLoopInvariant(Sc, OrigLoop)) {
2035 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
2037 Starts.push_back(Ptr);
2038 Ends.push_back(Ptr);
2040 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
2041 unsigned AS = Ptr->getType()->getPointerAddressSpace();
2043 // Use this type for pointer arithmetic.
2044 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
2046 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
2047 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
2048 Starts.push_back(Start);
2049 Ends.push_back(End);
2053 IRBuilder<> ChkBuilder(Loc);
2054 // Our instructions might fold to a constant.
2055 Value *MemoryRuntimeCheck = nullptr;
2056 for (unsigned i = 0; i < NumPointers; ++i) {
2057 for (unsigned j = i+1; j < NumPointers; ++j) {
2058 // No need to check if two readonly pointers intersect.
2059 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
2062 // Only need to check pointers between two different dependency sets.
2063 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
2065 // Only need to check pointers in the same alias set.
2066 if (PtrRtCheck->AliasSetId[i] != PtrRtCheck->AliasSetId[j])
2069 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
2070 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
2072 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
2073 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
2074 "Trying to bounds check pointers with different address spaces");
2076 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
2077 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
2079 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
2080 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
2081 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
2082 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
2084 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
2085 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
2086 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
2087 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
2088 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
2089 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2090 if (MemoryRuntimeCheck) {
2091 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
2093 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2095 MemoryRuntimeCheck = IsConflict;
2099 // We have to do this trickery because the IRBuilder might fold the check to a
2100 // constant expression in which case there is no Instruction anchored in a
2102 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
2103 ConstantInt::getTrue(Ctx));
2104 ChkBuilder.Insert(Check, "memcheck.conflict");
2105 FirstInst = getFirstInst(FirstInst, Check, Loc);
2106 return std::make_pair(FirstInst, Check);
2109 void InnerLoopVectorizer::createEmptyLoop() {
2111 In this function we generate a new loop. The new loop will contain
2112 the vectorized instructions while the old loop will continue to run the
2115 [ ] <-- Back-edge taken count overflow check.
2118 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2121 || [ ] <-- vector pre header.
2125 || [ ]_| <-- vector loop.
2128 | >[ ] <--- middle-block.
2131 -|- >[ ] <--- new preheader.
2135 | [ ]_| <-- old scalar loop to handle remainder.
2138 >[ ] <-- exit block.
2142 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2143 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
2144 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2145 assert(BypassBlock && "Invalid loop structure");
2146 assert(ExitBlock && "Must have an exit block");
2148 // Some loops have a single integer induction variable, while other loops
2149 // don't. One example is c++ iterators that often have multiple pointer
2150 // induction variables. In the code below we also support a case where we
2151 // don't have a single induction variable.
2152 OldInduction = Legal->getInduction();
2153 Type *IdxTy = Legal->getWidestInductionType();
2155 // Find the loop boundaries.
2156 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2157 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2159 // The exit count might have the type of i64 while the phi is i32. This can
2160 // happen if we have an induction variable that is sign extended before the
2161 // compare. The only way that we get a backedge taken count is that the
2162 // induction variable was signed and as such will not overflow. In such a case
2163 // truncation is legal.
2164 if (ExitCount->getType()->getPrimitiveSizeInBits() >
2165 IdxTy->getPrimitiveSizeInBits())
2166 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2168 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2169 // Get the total trip count from the count by adding 1.
2170 ExitCount = SE->getAddExpr(BackedgeTakeCount,
2171 SE->getConstant(BackedgeTakeCount->getType(), 1));
2173 // Expand the trip count and place the new instructions in the preheader.
2174 // Notice that the pre-header does not change, only the loop body.
2175 SCEVExpander Exp(*SE, "induction");
2177 // We need to test whether the backedge-taken count is uint##_max. Adding one
2178 // to it will cause overflow and an incorrect loop trip count in the vector
2179 // body. In case of overflow we want to directly jump to the scalar remainder
2181 Value *BackedgeCount =
2182 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2183 BypassBlock->getTerminator());
2184 if (BackedgeCount->getType()->isPointerTy())
2185 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2186 "backedge.ptrcnt.to.int",
2187 BypassBlock->getTerminator());
2188 Instruction *CheckBCOverflow =
2189 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2190 Constant::getAllOnesValue(BackedgeCount->getType()),
2191 "backedge.overflow", BypassBlock->getTerminator());
2193 // The loop index does not have to start at Zero. Find the original start
2194 // value from the induction PHI node. If we don't have an induction variable
2195 // then we know that it starts at zero.
2196 Builder.SetInsertPoint(BypassBlock->getTerminator());
2197 Value *StartIdx = ExtendedIdx = OldInduction ?
2198 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2200 ConstantInt::get(IdxTy, 0);
2202 // We need an instruction to anchor the overflow check on. StartIdx needs to
2203 // be defined before the overflow check branch. Because the scalar preheader
2204 // is going to merge the start index and so the overflow branch block needs to
2205 // contain a definition of the start index.
2206 Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
2207 StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
2208 BypassBlock->getTerminator());
2210 // Count holds the overall loop count (N).
2211 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2212 BypassBlock->getTerminator());
2214 LoopBypassBlocks.push_back(BypassBlock);
2216 // Split the single block loop into the two loop structure described above.
2217 BasicBlock *VectorPH =
2218 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2219 BasicBlock *VecBody =
2220 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2221 BasicBlock *MiddleBlock =
2222 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2223 BasicBlock *ScalarPH =
2224 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2226 // Create and register the new vector loop.
2227 Loop* Lp = new Loop();
2228 Loop *ParentLoop = OrigLoop->getParentLoop();
2230 // Insert the new loop into the loop nest and register the new basic blocks
2231 // before calling any utilities such as SCEV that require valid LoopInfo.
2233 ParentLoop->addChildLoop(Lp);
2234 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2235 ParentLoop->addBasicBlockToLoop(VectorPH, *LI);
2236 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2238 LI->addTopLevelLoop(Lp);
2240 Lp->addBasicBlockToLoop(VecBody, *LI);
2242 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2244 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2246 // Generate the induction variable.
2247 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2248 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2249 // The loop step is equal to the vectorization factor (num of SIMD elements)
2250 // times the unroll factor (num of SIMD instructions).
2251 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2253 // This is the IR builder that we use to add all of the logic for bypassing
2254 // the new vector loop.
2255 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2256 setDebugLocFromInst(BypassBuilder,
2257 getDebugLocFromInstOrOperands(OldInduction));
2259 // We may need to extend the index in case there is a type mismatch.
2260 // We know that the count starts at zero and does not overflow.
2261 if (Count->getType() != IdxTy) {
2262 // The exit count can be of pointer type. Convert it to the correct
2264 if (ExitCount->getType()->isPointerTy())
2265 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2267 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2270 // Add the start index to the loop count to get the new end index.
2271 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2273 // Now we need to generate the expression for N - (N % VF), which is
2274 // the part that the vectorized body will execute.
2275 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2276 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2277 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2278 "end.idx.rnd.down");
2280 // Now, compare the new count to zero. If it is zero skip the vector loop and
2281 // jump to the scalar loop.
2283 BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2285 BasicBlock *LastBypassBlock = BypassBlock;
2287 // Generate code to check that the loops trip count that we computed by adding
2288 // one to the backedge-taken count will not overflow.
2290 auto PastOverflowCheck =
2291 std::next(BasicBlock::iterator(OverflowCheckAnchor));
2292 BasicBlock *CheckBlock =
2293 LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2295 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2296 LoopBypassBlocks.push_back(CheckBlock);
2297 Instruction *OldTerm = LastBypassBlock->getTerminator();
2298 BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2299 OldTerm->eraseFromParent();
2300 LastBypassBlock = CheckBlock;
2303 // Generate the code to check that the strides we assumed to be one are really
2304 // one. We want the new basic block to start at the first instruction in a
2305 // sequence of instructions that form a check.
2306 Instruction *StrideCheck;
2307 Instruction *FirstCheckInst;
2308 std::tie(FirstCheckInst, StrideCheck) =
2309 addStrideCheck(LastBypassBlock->getTerminator());
2311 // Create a new block containing the stride check.
2312 BasicBlock *CheckBlock =
2313 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2315 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2316 LoopBypassBlocks.push_back(CheckBlock);
2318 // Replace the branch into the memory check block with a conditional branch
2319 // for the "few elements case".
2320 Instruction *OldTerm = LastBypassBlock->getTerminator();
2321 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2322 OldTerm->eraseFromParent();
2325 LastBypassBlock = CheckBlock;
2328 // Generate the code that checks in runtime if arrays overlap. We put the
2329 // checks into a separate block to make the more common case of few elements
2331 Instruction *MemRuntimeCheck;
2332 std::tie(FirstCheckInst, MemRuntimeCheck) =
2333 addRuntimeCheck(LastBypassBlock->getTerminator());
2334 if (MemRuntimeCheck) {
2335 // Create a new block containing the memory check.
2336 BasicBlock *CheckBlock =
2337 LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
2339 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2340 LoopBypassBlocks.push_back(CheckBlock);
2342 // Replace the branch into the memory check block with a conditional branch
2343 // for the "few elements case".
2344 Instruction *OldTerm = LastBypassBlock->getTerminator();
2345 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2346 OldTerm->eraseFromParent();
2348 Cmp = MemRuntimeCheck;
2349 LastBypassBlock = CheckBlock;
2352 LastBypassBlock->getTerminator()->eraseFromParent();
2353 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2356 // We are going to resume the execution of the scalar loop.
2357 // Go over all of the induction variables that we found and fix the
2358 // PHIs that are left in the scalar version of the loop.
2359 // The starting values of PHI nodes depend on the counter of the last
2360 // iteration in the vectorized loop.
2361 // If we come from a bypass edge then we need to start from the original
2364 // This variable saves the new starting index for the scalar loop.
2365 PHINode *ResumeIndex = nullptr;
2366 LoopVectorizationLegality::InductionList::iterator I, E;
2367 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2368 // Set builder to point to last bypass block.
2369 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2370 for (I = List->begin(), E = List->end(); I != E; ++I) {
2371 PHINode *OrigPhi = I->first;
2372 LoopVectorizationLegality::InductionInfo II = I->second;
2374 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2375 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2376 MiddleBlock->getTerminator());
2377 // We might have extended the type of the induction variable but we need a
2378 // truncated version for the scalar loop.
2379 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2380 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2381 MiddleBlock->getTerminator()) : nullptr;
2383 // Create phi nodes to merge from the backedge-taken check block.
2384 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2385 ScalarPH->getTerminator());
2386 BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2388 PHINode *BCTruncResumeVal = nullptr;
2389 if (OrigPhi == OldInduction) {
2391 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2392 ScalarPH->getTerminator());
2393 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2396 Value *EndValue = nullptr;
2398 case LoopVectorizationLegality::IK_NoInduction:
2399 llvm_unreachable("Unknown induction");
2400 case LoopVectorizationLegality::IK_IntInduction: {
2401 // Handle the integer induction counter.
2402 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2404 // We have the canonical induction variable.
2405 if (OrigPhi == OldInduction) {
2406 // Create a truncated version of the resume value for the scalar loop,
2407 // we might have promoted the type to a larger width.
2409 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2410 // The new PHI merges the original incoming value, in case of a bypass,
2411 // or the value at the end of the vectorized loop.
2412 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2413 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2414 TruncResumeVal->addIncoming(EndValue, VecBody);
2416 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2418 // We know what the end value is.
2419 EndValue = IdxEndRoundDown;
2420 // We also know which PHI node holds it.
2421 ResumeIndex = ResumeVal;
2425 // Not the canonical induction variable - add the vector loop count to the
2427 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2428 II.StartValue->getType(),
2430 EndValue = II.transform(BypassBuilder, CRD);
2431 EndValue->setName("ind.end");
2434 case LoopVectorizationLegality::IK_PtrInduction: {
2435 EndValue = II.transform(BypassBuilder, CountRoundDown);
2436 EndValue->setName("ptr.ind.end");
2441 // The new PHI merges the original incoming value, in case of a bypass,
2442 // or the value at the end of the vectorized loop.
2443 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2444 if (OrigPhi == OldInduction)
2445 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2447 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2449 ResumeVal->addIncoming(EndValue, VecBody);
2451 // Fix the scalar body counter (PHI node).
2452 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2454 // The old induction's phi node in the scalar body needs the truncated
2456 if (OrigPhi == OldInduction) {
2457 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2458 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2460 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2461 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2465 // If we are generating a new induction variable then we also need to
2466 // generate the code that calculates the exit value. This value is not
2467 // simply the end of the counter because we may skip the vectorized body
2468 // in case of a runtime check.
2470 assert(!ResumeIndex && "Unexpected resume value found");
2471 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2472 MiddleBlock->getTerminator());
2473 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2474 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2475 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2478 // Make sure that we found the index where scalar loop needs to continue.
2479 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2480 "Invalid resume Index");
2482 // Add a check in the middle block to see if we have completed
2483 // all of the iterations in the first vector loop.
2484 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2485 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2486 ResumeIndex, "cmp.n",
2487 MiddleBlock->getTerminator());
2489 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2490 // Remove the old terminator.
2491 MiddleBlock->getTerminator()->eraseFromParent();
2493 // Create i+1 and fill the PHINode.
2494 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2495 Induction->addIncoming(StartIdx, VectorPH);
2496 Induction->addIncoming(NextIdx, VecBody);
2497 // Create the compare.
2498 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2499 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2501 // Now we have two terminators. Remove the old one from the block.
2502 VecBody->getTerminator()->eraseFromParent();
2504 // Get ready to start creating new instructions into the vectorized body.
2505 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2508 LoopVectorPreHeader = VectorPH;
2509 LoopScalarPreHeader = ScalarPH;
2510 LoopMiddleBlock = MiddleBlock;
2511 LoopExitBlock = ExitBlock;
2512 LoopVectorBody.push_back(VecBody);
2513 LoopScalarBody = OldBasicBlock;
2515 LoopVectorizeHints Hints(Lp, true);
2516 Hints.setAlreadyVectorized();
2519 /// This function returns the identity element (or neutral element) for
2520 /// the operation K.
2522 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2527 // Adding, Xoring, Oring zero to a number does not change it.
2528 return ConstantInt::get(Tp, 0);
2529 case RK_IntegerMult:
2530 // Multiplying a number by 1 does not change it.
2531 return ConstantInt::get(Tp, 1);
2533 // AND-ing a number with an all-1 value does not change it.
2534 return ConstantInt::get(Tp, -1, true);
2536 // Multiplying a number by 1 does not change it.
2537 return ConstantFP::get(Tp, 1.0L);
2539 // Adding zero to a number does not change it.
2540 return ConstantFP::get(Tp, 0.0L);
2542 llvm_unreachable("Unknown reduction kind");
2546 /// This function translates the reduction kind to an LLVM binary operator.
2548 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2550 case LoopVectorizationLegality::RK_IntegerAdd:
2551 return Instruction::Add;
2552 case LoopVectorizationLegality::RK_IntegerMult:
2553 return Instruction::Mul;
2554 case LoopVectorizationLegality::RK_IntegerOr:
2555 return Instruction::Or;
2556 case LoopVectorizationLegality::RK_IntegerAnd:
2557 return Instruction::And;
2558 case LoopVectorizationLegality::RK_IntegerXor:
2559 return Instruction::Xor;
2560 case LoopVectorizationLegality::RK_FloatMult:
2561 return Instruction::FMul;
2562 case LoopVectorizationLegality::RK_FloatAdd:
2563 return Instruction::FAdd;
2564 case LoopVectorizationLegality::RK_IntegerMinMax:
2565 return Instruction::ICmp;
2566 case LoopVectorizationLegality::RK_FloatMinMax:
2567 return Instruction::FCmp;
2569 llvm_unreachable("Unknown reduction operation");
2573 Value *createMinMaxOp(IRBuilder<> &Builder,
2574 LoopVectorizationLegality::MinMaxReductionKind RK,
2577 CmpInst::Predicate P = CmpInst::ICMP_NE;
2580 llvm_unreachable("Unknown min/max reduction kind");
2581 case LoopVectorizationLegality::MRK_UIntMin:
2582 P = CmpInst::ICMP_ULT;
2584 case LoopVectorizationLegality::MRK_UIntMax:
2585 P = CmpInst::ICMP_UGT;
2587 case LoopVectorizationLegality::MRK_SIntMin:
2588 P = CmpInst::ICMP_SLT;
2590 case LoopVectorizationLegality::MRK_SIntMax:
2591 P = CmpInst::ICMP_SGT;
2593 case LoopVectorizationLegality::MRK_FloatMin:
2594 P = CmpInst::FCMP_OLT;
2596 case LoopVectorizationLegality::MRK_FloatMax:
2597 P = CmpInst::FCMP_OGT;
2602 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2603 RK == LoopVectorizationLegality::MRK_FloatMax)
2604 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2606 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2608 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2613 struct CSEDenseMapInfo {
2614 static bool canHandle(Instruction *I) {
2615 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2616 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2618 static inline Instruction *getEmptyKey() {
2619 return DenseMapInfo<Instruction *>::getEmptyKey();
2621 static inline Instruction *getTombstoneKey() {
2622 return DenseMapInfo<Instruction *>::getTombstoneKey();
2624 static unsigned getHashValue(Instruction *I) {
2625 assert(canHandle(I) && "Unknown instruction!");
2626 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2627 I->value_op_end()));
2629 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2630 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2631 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2633 return LHS->isIdenticalTo(RHS);
2638 /// \brief Check whether this block is a predicated block.
2639 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2640 /// = ...; " blocks. We start with one vectorized basic block. For every
2641 /// conditional block we split this vectorized block. Therefore, every second
2642 /// block will be a predicated one.
2643 static bool isPredicatedBlock(unsigned BlockNum) {
2644 return BlockNum % 2;
2647 ///\brief Perform cse of induction variable instructions.
2648 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2649 // Perform simple cse.
2650 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2651 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2652 BasicBlock *BB = BBs[i];
2653 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2654 Instruction *In = I++;
2656 if (!CSEDenseMapInfo::canHandle(In))
2659 // Check if we can replace this instruction with any of the
2660 // visited instructions.
2661 if (Instruction *V = CSEMap.lookup(In)) {
2662 In->replaceAllUsesWith(V);
2663 In->eraseFromParent();
2666 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2667 // ...;" blocks for predicated stores. Every second block is a predicated
2669 if (isPredicatedBlock(i))
2677 /// \brief Adds a 'fast' flag to floating point operations.
2678 static Value *addFastMathFlag(Value *V) {
2679 if (isa<FPMathOperator>(V)){
2680 FastMathFlags Flags;
2681 Flags.setUnsafeAlgebra();
2682 cast<Instruction>(V)->setFastMathFlags(Flags);
2687 void InnerLoopVectorizer::vectorizeLoop() {
2688 //===------------------------------------------------===//
2690 // Notice: any optimization or new instruction that go
2691 // into the code below should be also be implemented in
2694 //===------------------------------------------------===//
2695 Constant *Zero = Builder.getInt32(0);
2697 // In order to support reduction variables we need to be able to vectorize
2698 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2699 // stages. First, we create a new vector PHI node with no incoming edges.
2700 // We use this value when we vectorize all of the instructions that use the
2701 // PHI. Next, after all of the instructions in the block are complete we
2702 // add the new incoming edges to the PHI. At this point all of the
2703 // instructions in the basic block are vectorized, so we can use them to
2704 // construct the PHI.
2705 PhiVector RdxPHIsToFix;
2707 // Scan the loop in a topological order to ensure that defs are vectorized
2709 LoopBlocksDFS DFS(OrigLoop);
2712 // Vectorize all of the blocks in the original loop.
2713 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2714 be = DFS.endRPO(); bb != be; ++bb)
2715 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2717 // At this point every instruction in the original loop is widened to
2718 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2719 // that we vectorized. The PHI nodes are currently empty because we did
2720 // not want to introduce cycles. Notice that the remaining PHI nodes
2721 // that we need to fix are reduction variables.
2723 // Create the 'reduced' values for each of the induction vars.
2724 // The reduced values are the vector values that we scalarize and combine
2725 // after the loop is finished.
2726 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2728 PHINode *RdxPhi = *it;
2729 assert(RdxPhi && "Unable to recover vectorized PHI");
2731 // Find the reduction variable descriptor.
2732 assert(Legal->getReductionVars()->count(RdxPhi) &&
2733 "Unable to find the reduction variable");
2734 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2735 (*Legal->getReductionVars())[RdxPhi];
2737 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2739 // We need to generate a reduction vector from the incoming scalar.
2740 // To do so, we need to generate the 'identity' vector and override
2741 // one of the elements with the incoming scalar reduction. We need
2742 // to do it in the vector-loop preheader.
2743 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2745 // This is the vector-clone of the value that leaves the loop.
2746 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2747 Type *VecTy = VectorExit[0]->getType();
2749 // Find the reduction identity variable. Zero for addition, or, xor,
2750 // one for multiplication, -1 for And.
2753 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2754 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2755 // MinMax reduction have the start value as their identify.
2757 VectorStart = Identity = RdxDesc.StartValue;
2759 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2764 // Handle other reduction kinds:
2766 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2767 VecTy->getScalarType());
2770 // This vector is the Identity vector where the first element is the
2771 // incoming scalar reduction.
2772 VectorStart = RdxDesc.StartValue;
2774 Identity = ConstantVector::getSplat(VF, Iden);
2776 // This vector is the Identity vector where the first element is the
2777 // incoming scalar reduction.
2778 VectorStart = Builder.CreateInsertElement(Identity,
2779 RdxDesc.StartValue, Zero);
2783 // Fix the vector-loop phi.
2785 // Reductions do not have to start at zero. They can start with
2786 // any loop invariant values.
2787 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2788 BasicBlock *Latch = OrigLoop->getLoopLatch();
2789 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2790 VectorParts &Val = getVectorValue(LoopVal);
2791 for (unsigned part = 0; part < UF; ++part) {
2792 // Make sure to add the reduction stat value only to the
2793 // first unroll part.
2794 Value *StartVal = (part == 0) ? VectorStart : Identity;
2795 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
2796 LoopVectorPreHeader);
2797 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2798 LoopVectorBody.back());
2801 // Before each round, move the insertion point right between
2802 // the PHIs and the values we are going to write.
2803 // This allows us to write both PHINodes and the extractelement
2805 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2807 VectorParts RdxParts;
2808 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2809 for (unsigned part = 0; part < UF; ++part) {
2810 // This PHINode contains the vectorized reduction variable, or
2811 // the initial value vector, if we bypass the vector loop.
2812 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2813 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2814 Value *StartVal = (part == 0) ? VectorStart : Identity;
2815 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2816 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2817 NewPhi->addIncoming(RdxExitVal[part],
2818 LoopVectorBody.back());
2819 RdxParts.push_back(NewPhi);
2822 // Reduce all of the unrolled parts into a single vector.
2823 Value *ReducedPartRdx = RdxParts[0];
2824 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2825 setDebugLocFromInst(Builder, ReducedPartRdx);
2826 for (unsigned part = 1; part < UF; ++part) {
2827 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2828 // Floating point operations had to be 'fast' to enable the reduction.
2829 ReducedPartRdx = addFastMathFlag(
2830 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2831 ReducedPartRdx, "bin.rdx"));
2833 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2834 ReducedPartRdx, RdxParts[part]);
2838 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2839 // and vector ops, reducing the set of values being computed by half each
2841 assert(isPowerOf2_32(VF) &&
2842 "Reduction emission only supported for pow2 vectors!");
2843 Value *TmpVec = ReducedPartRdx;
2844 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2845 for (unsigned i = VF; i != 1; i >>= 1) {
2846 // Move the upper half of the vector to the lower half.
2847 for (unsigned j = 0; j != i/2; ++j)
2848 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2850 // Fill the rest of the mask with undef.
2851 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2852 UndefValue::get(Builder.getInt32Ty()));
2855 Builder.CreateShuffleVector(TmpVec,
2856 UndefValue::get(TmpVec->getType()),
2857 ConstantVector::get(ShuffleMask),
2860 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2861 // Floating point operations had to be 'fast' to enable the reduction.
2862 TmpVec = addFastMathFlag(Builder.CreateBinOp(
2863 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2865 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2868 // The result is in the first element of the vector.
2869 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2870 Builder.getInt32(0));
2873 // Create a phi node that merges control-flow from the backedge-taken check
2874 // block and the middle block.
2875 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2876 LoopScalarPreHeader->getTerminator());
2877 BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
2878 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2880 // Now, we need to fix the users of the reduction variable
2881 // inside and outside of the scalar remainder loop.
2882 // We know that the loop is in LCSSA form. We need to update the
2883 // PHI nodes in the exit blocks.
2884 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2885 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2886 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2887 if (!LCSSAPhi) break;
2889 // All PHINodes need to have a single entry edge, or two if
2890 // we already fixed them.
2891 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2893 // We found our reduction value exit-PHI. Update it with the
2894 // incoming bypass edge.
2895 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2896 // Add an edge coming from the bypass.
2897 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2900 }// end of the LCSSA phi scan.
2902 // Fix the scalar loop reduction variable with the incoming reduction sum
2903 // from the vector body and from the backedge value.
2904 int IncomingEdgeBlockIdx =
2905 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2906 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2907 // Pick the other block.
2908 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2909 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
2910 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2911 }// end of for each redux variable.
2915 // Remove redundant induction instructions.
2916 cse(LoopVectorBody);
2919 void InnerLoopVectorizer::fixLCSSAPHIs() {
2920 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2921 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2922 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2923 if (!LCSSAPhi) break;
2924 if (LCSSAPhi->getNumIncomingValues() == 1)
2925 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2930 InnerLoopVectorizer::VectorParts
2931 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2932 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2935 // Look for cached value.
2936 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2937 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2938 if (ECEntryIt != MaskCache.end())
2939 return ECEntryIt->second;
2941 VectorParts SrcMask = createBlockInMask(Src);
2943 // The terminator has to be a branch inst!
2944 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2945 assert(BI && "Unexpected terminator found");
2947 if (BI->isConditional()) {
2948 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2950 if (BI->getSuccessor(0) != Dst)
2951 for (unsigned part = 0; part < UF; ++part)
2952 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2954 for (unsigned part = 0; part < UF; ++part)
2955 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2957 MaskCache[Edge] = EdgeMask;
2961 MaskCache[Edge] = SrcMask;
2965 InnerLoopVectorizer::VectorParts
2966 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2967 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2969 // Loop incoming mask is all-one.
2970 if (OrigLoop->getHeader() == BB) {
2971 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2972 return getVectorValue(C);
2975 // This is the block mask. We OR all incoming edges, and with zero.
2976 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2977 VectorParts BlockMask = getVectorValue(Zero);
2980 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2981 VectorParts EM = createEdgeMask(*it, BB);
2982 for (unsigned part = 0; part < UF; ++part)
2983 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2989 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2990 InnerLoopVectorizer::VectorParts &Entry,
2991 unsigned UF, unsigned VF, PhiVector *PV) {
2992 PHINode* P = cast<PHINode>(PN);
2993 // Handle reduction variables:
2994 if (Legal->getReductionVars()->count(P)) {
2995 for (unsigned part = 0; part < UF; ++part) {
2996 // This is phase one of vectorizing PHIs.
2997 Type *VecTy = (VF == 1) ? PN->getType() :
2998 VectorType::get(PN->getType(), VF);
2999 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
3000 LoopVectorBody.back()-> getFirstInsertionPt());
3006 setDebugLocFromInst(Builder, P);
3007 // Check for PHI nodes that are lowered to vector selects.
3008 if (P->getParent() != OrigLoop->getHeader()) {
3009 // We know that all PHIs in non-header blocks are converted into
3010 // selects, so we don't have to worry about the insertion order and we
3011 // can just use the builder.
3012 // At this point we generate the predication tree. There may be
3013 // duplications since this is a simple recursive scan, but future
3014 // optimizations will clean it up.
3016 unsigned NumIncoming = P->getNumIncomingValues();
3018 // Generate a sequence of selects of the form:
3019 // SELECT(Mask3, In3,
3020 // SELECT(Mask2, In2,
3022 for (unsigned In = 0; In < NumIncoming; In++) {
3023 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3025 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3027 for (unsigned part = 0; part < UF; ++part) {
3028 // We might have single edge PHIs (blocks) - use an identity
3029 // 'select' for the first PHI operand.
3031 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3034 // Select between the current value and the previous incoming edge
3035 // based on the incoming mask.
3036 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3037 Entry[part], "predphi");
3043 // This PHINode must be an induction variable.
3044 // Make sure that we know about it.
3045 assert(Legal->getInductionVars()->count(P) &&
3046 "Not an induction variable");
3048 LoopVectorizationLegality::InductionInfo II =
3049 Legal->getInductionVars()->lookup(P);
3051 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3052 // which can be found from the original scalar operations.
3054 case LoopVectorizationLegality::IK_NoInduction:
3055 llvm_unreachable("Unknown induction");
3056 case LoopVectorizationLegality::IK_IntInduction: {
3057 assert(P->getType() == II.StartValue->getType() && "Types must match");
3058 Type *PhiTy = P->getType();
3060 if (P == OldInduction) {
3061 // Handle the canonical induction variable. We might have had to
3063 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
3065 // Handle other induction variables that are now based on the
3067 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
3069 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
3070 Broadcasted = II.transform(Builder, NormalizedIdx);
3071 Broadcasted->setName("offset.idx");
3073 Broadcasted = getBroadcastInstrs(Broadcasted);
3074 // After broadcasting the induction variable we need to make the vector
3075 // consecutive by adding 0, 1, 2, etc.
3076 for (unsigned part = 0; part < UF; ++part)
3077 Entry[part] = getStepVector(Broadcasted, VF * part, II.StepValue);
3080 case LoopVectorizationLegality::IK_PtrInduction:
3081 // Handle the pointer induction variable case.
3082 assert(P->getType()->isPointerTy() && "Unexpected type.");
3083 // This is the normalized GEP that starts counting at zero.
3084 Value *NormalizedIdx =
3085 Builder.CreateSub(Induction, ExtendedIdx, "normalized.idx");
3086 // This is the vector of results. Notice that we don't generate
3087 // vector geps because scalar geps result in better code.
3088 for (unsigned part = 0; part < UF; ++part) {
3090 int EltIndex = part;
3091 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3092 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3093 Value *SclrGep = II.transform(Builder, GlobalIdx);
3094 SclrGep->setName("next.gep");
3095 Entry[part] = SclrGep;
3099 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3100 for (unsigned int i = 0; i < VF; ++i) {
3101 int EltIndex = i + part * VF;
3102 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3103 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3104 Value *SclrGep = II.transform(Builder, GlobalIdx);
3105 SclrGep->setName("next.gep");
3106 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3107 Builder.getInt32(i),
3110 Entry[part] = VecVal;
3116 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3117 // For each instruction in the old loop.
3118 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3119 VectorParts &Entry = WidenMap.get(it);
3120 switch (it->getOpcode()) {
3121 case Instruction::Br:
3122 // Nothing to do for PHIs and BR, since we already took care of the
3123 // loop control flow instructions.
3125 case Instruction::PHI: {
3126 // Vectorize PHINodes.
3127 widenPHIInstruction(it, Entry, UF, VF, PV);
3131 case Instruction::Add:
3132 case Instruction::FAdd:
3133 case Instruction::Sub:
3134 case Instruction::FSub:
3135 case Instruction::Mul:
3136 case Instruction::FMul:
3137 case Instruction::UDiv:
3138 case Instruction::SDiv:
3139 case Instruction::FDiv:
3140 case Instruction::URem:
3141 case Instruction::SRem:
3142 case Instruction::FRem:
3143 case Instruction::Shl:
3144 case Instruction::LShr:
3145 case Instruction::AShr:
3146 case Instruction::And:
3147 case Instruction::Or:
3148 case Instruction::Xor: {
3149 // Just widen binops.
3150 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3151 setDebugLocFromInst(Builder, BinOp);
3152 VectorParts &A = getVectorValue(it->getOperand(0));
3153 VectorParts &B = getVectorValue(it->getOperand(1));
3155 // Use this vector value for all users of the original instruction.
3156 for (unsigned Part = 0; Part < UF; ++Part) {
3157 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3159 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3160 VecOp->copyIRFlags(BinOp);
3165 propagateMetadata(Entry, it);
3168 case Instruction::Select: {
3170 // If the selector is loop invariant we can create a select
3171 // instruction with a scalar condition. Otherwise, use vector-select.
3172 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3174 setDebugLocFromInst(Builder, it);
3176 // The condition can be loop invariant but still defined inside the
3177 // loop. This means that we can't just use the original 'cond' value.
3178 // We have to take the 'vectorized' value and pick the first lane.
3179 // Instcombine will make this a no-op.
3180 VectorParts &Cond = getVectorValue(it->getOperand(0));
3181 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3182 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3184 Value *ScalarCond = (VF == 1) ? Cond[0] :
3185 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3187 for (unsigned Part = 0; Part < UF; ++Part) {
3188 Entry[Part] = Builder.CreateSelect(
3189 InvariantCond ? ScalarCond : Cond[Part],
3194 propagateMetadata(Entry, it);
3198 case Instruction::ICmp:
3199 case Instruction::FCmp: {
3200 // Widen compares. Generate vector compares.
3201 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3202 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3203 setDebugLocFromInst(Builder, it);
3204 VectorParts &A = getVectorValue(it->getOperand(0));
3205 VectorParts &B = getVectorValue(it->getOperand(1));
3206 for (unsigned Part = 0; Part < UF; ++Part) {
3209 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3211 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3215 propagateMetadata(Entry, it);
3219 case Instruction::Store:
3220 case Instruction::Load:
3221 vectorizeMemoryInstruction(it);
3223 case Instruction::ZExt:
3224 case Instruction::SExt:
3225 case Instruction::FPToUI:
3226 case Instruction::FPToSI:
3227 case Instruction::FPExt:
3228 case Instruction::PtrToInt:
3229 case Instruction::IntToPtr:
3230 case Instruction::SIToFP:
3231 case Instruction::UIToFP:
3232 case Instruction::Trunc:
3233 case Instruction::FPTrunc:
3234 case Instruction::BitCast: {
3235 CastInst *CI = dyn_cast<CastInst>(it);
3236 setDebugLocFromInst(Builder, it);
3237 /// Optimize the special case where the source is the induction
3238 /// variable. Notice that we can only optimize the 'trunc' case
3239 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3240 /// c. other casts depend on pointer size.
3241 if (CI->getOperand(0) == OldInduction &&
3242 it->getOpcode() == Instruction::Trunc) {
3243 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3245 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3246 LoopVectorizationLegality::InductionInfo II =
3247 Legal->getInductionVars()->lookup(OldInduction);
3249 ConstantInt::getSigned(CI->getType(), II.StepValue->getSExtValue());
3250 for (unsigned Part = 0; Part < UF; ++Part)
3251 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3252 propagateMetadata(Entry, it);
3255 /// Vectorize casts.
3256 Type *DestTy = (VF == 1) ? CI->getType() :
3257 VectorType::get(CI->getType(), VF);
3259 VectorParts &A = getVectorValue(it->getOperand(0));
3260 for (unsigned Part = 0; Part < UF; ++Part)
3261 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3262 propagateMetadata(Entry, it);
3266 case Instruction::Call: {
3267 // Ignore dbg intrinsics.
3268 if (isa<DbgInfoIntrinsic>(it))
3270 setDebugLocFromInst(Builder, it);
3272 Module *M = BB->getParent()->getParent();
3273 CallInst *CI = cast<CallInst>(it);
3274 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3275 assert(ID && "Not an intrinsic call!");
3277 case Intrinsic::assume:
3278 case Intrinsic::lifetime_end:
3279 case Intrinsic::lifetime_start:
3280 scalarizeInstruction(it);
3283 bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
3284 for (unsigned Part = 0; Part < UF; ++Part) {
3285 SmallVector<Value *, 4> Args;
3286 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3287 if (HasScalarOpd && i == 1) {
3288 Args.push_back(CI->getArgOperand(i));
3291 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3292 Args.push_back(Arg[Part]);
3294 Type *Tys[] = {CI->getType()};
3296 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3298 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3299 Entry[Part] = Builder.CreateCall(F, Args);
3302 propagateMetadata(Entry, it);
3309 // All other instructions are unsupported. Scalarize them.
3310 scalarizeInstruction(it);
3313 }// end of for_each instr.
3316 void InnerLoopVectorizer::updateAnalysis() {
3317 // Forget the original basic block.
3318 SE->forgetLoop(OrigLoop);
3320 // Update the dominator tree information.
3321 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3322 "Entry does not dominate exit.");
3324 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3325 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3326 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3328 // Due to if predication of stores we might create a sequence of "if(pred)
3329 // a[i] = ...; " blocks.
3330 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3332 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3333 else if (isPredicatedBlock(i)) {
3334 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3336 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3340 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3341 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3342 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3343 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3345 DEBUG(DT->verifyDomTree());
3348 /// \brief Check whether it is safe to if-convert this phi node.
3350 /// Phi nodes with constant expressions that can trap are not safe to if
3352 static bool canIfConvertPHINodes(BasicBlock *BB) {
3353 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3354 PHINode *Phi = dyn_cast<PHINode>(I);
3357 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3358 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3365 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3366 if (!EnableIfConversion) {
3367 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3371 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3373 // A list of pointers that we can safely read and write to.
3374 SmallPtrSet<Value *, 8> SafePointes;
3376 // Collect safe addresses.
3377 for (Loop::block_iterator BI = TheLoop->block_begin(),
3378 BE = TheLoop->block_end(); BI != BE; ++BI) {
3379 BasicBlock *BB = *BI;
3381 if (blockNeedsPredication(BB))
3384 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3385 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3386 SafePointes.insert(LI->getPointerOperand());
3387 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3388 SafePointes.insert(SI->getPointerOperand());
3392 // Collect the blocks that need predication.
3393 BasicBlock *Header = TheLoop->getHeader();
3394 for (Loop::block_iterator BI = TheLoop->block_begin(),
3395 BE = TheLoop->block_end(); BI != BE; ++BI) {
3396 BasicBlock *BB = *BI;
3398 // We don't support switch statements inside loops.
3399 if (!isa<BranchInst>(BB->getTerminator())) {
3400 emitAnalysis(VectorizationReport(BB->getTerminator())
3401 << "loop contains a switch statement");
3405 // We must be able to predicate all blocks that need to be predicated.
3406 if (blockNeedsPredication(BB)) {
3407 if (!blockCanBePredicated(BB, SafePointes)) {
3408 emitAnalysis(VectorizationReport(BB->getTerminator())
3409 << "control flow cannot be substituted for a select");
3412 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3413 emitAnalysis(VectorizationReport(BB->getTerminator())
3414 << "control flow cannot be substituted for a select");
3419 // We can if-convert this loop.
3423 bool LoopVectorizationLegality::canVectorize() {
3424 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3425 // be canonicalized.
3426 if (!TheLoop->getLoopPreheader()) {
3428 VectorizationReport() <<
3429 "loop control flow is not understood by vectorizer");
3433 // We can only vectorize innermost loops.
3434 if (!TheLoop->getSubLoopsVector().empty()) {
3435 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3439 // We must have a single backedge.
3440 if (TheLoop->getNumBackEdges() != 1) {
3442 VectorizationReport() <<
3443 "loop control flow is not understood by vectorizer");
3447 // We must have a single exiting block.
3448 if (!TheLoop->getExitingBlock()) {
3450 VectorizationReport() <<
3451 "loop control flow is not understood by vectorizer");
3455 // We only handle bottom-tested loops, i.e. loop in which the condition is
3456 // checked at the end of each iteration. With that we can assume that all
3457 // instructions in the loop are executed the same number of times.
3458 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3460 VectorizationReport() <<
3461 "loop control flow is not understood by vectorizer");
3465 // We need to have a loop header.
3466 DEBUG(dbgs() << "LV: Found a loop: " <<
3467 TheLoop->getHeader()->getName() << '\n');
3469 // Check if we can if-convert non-single-bb loops.
3470 unsigned NumBlocks = TheLoop->getNumBlocks();
3471 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3472 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3476 // ScalarEvolution needs to be able to find the exit count.
3477 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3478 if (ExitCount == SE->getCouldNotCompute()) {
3479 emitAnalysis(VectorizationReport() <<
3480 "could not determine number of loop iterations");
3481 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3485 // Check if we can vectorize the instructions and CFG in this loop.
3486 if (!canVectorizeInstrs()) {
3487 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3491 // Go over each instruction and look at memory deps.
3492 if (!canVectorizeMemory()) {
3493 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3497 // Collect all of the variables that remain uniform after vectorization.
3498 collectLoopUniforms();
3500 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3501 (LAA.getRuntimePointerCheck()->Need ? " (with a runtime bound check)" :
3505 // Okay! We can vectorize. At this point we don't have any other mem analysis
3506 // which may limit our maximum vectorization factor, so just return true with
3511 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3512 if (Ty->isPointerTy())
3513 return DL.getIntPtrType(Ty);
3515 // It is possible that char's or short's overflow when we ask for the loop's
3516 // trip count, work around this by changing the type size.
3517 if (Ty->getScalarSizeInBits() < 32)
3518 return Type::getInt32Ty(Ty->getContext());
3523 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3524 Ty0 = convertPointerToIntegerType(DL, Ty0);
3525 Ty1 = convertPointerToIntegerType(DL, Ty1);
3526 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3531 /// \brief Check that the instruction has outside loop users and is not an
3532 /// identified reduction variable.
3533 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3534 SmallPtrSetImpl<Value *> &Reductions) {
3535 // Reduction instructions are allowed to have exit users. All other
3536 // instructions must not have external users.
3537 if (!Reductions.count(Inst))
3538 //Check that all of the users of the loop are inside the BB.
3539 for (User *U : Inst->users()) {
3540 Instruction *UI = cast<Instruction>(U);
3541 // This user may be a reduction exit value.
3542 if (!TheLoop->contains(UI)) {
3543 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3550 bool LoopVectorizationLegality::canVectorizeInstrs() {
3551 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3552 BasicBlock *Header = TheLoop->getHeader();
3554 // Look for the attribute signaling the absence of NaNs.
3555 Function &F = *Header->getParent();
3556 if (F.hasFnAttribute("no-nans-fp-math"))
3557 HasFunNoNaNAttr = F.getAttributes().getAttribute(
3558 AttributeSet::FunctionIndex,
3559 "no-nans-fp-math").getValueAsString() == "true";
3561 // For each block in the loop.
3562 for (Loop::block_iterator bb = TheLoop->block_begin(),
3563 be = TheLoop->block_end(); bb != be; ++bb) {
3565 // Scan the instructions in the block and look for hazards.
3566 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3569 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3570 Type *PhiTy = Phi->getType();
3571 // Check that this PHI type is allowed.
3572 if (!PhiTy->isIntegerTy() &&
3573 !PhiTy->isFloatingPointTy() &&
3574 !PhiTy->isPointerTy()) {
3575 emitAnalysis(VectorizationReport(it)
3576 << "loop control flow is not understood by vectorizer");
3577 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3581 // If this PHINode is not in the header block, then we know that we
3582 // can convert it to select during if-conversion. No need to check if
3583 // the PHIs in this block are induction or reduction variables.
3584 if (*bb != Header) {
3585 // Check that this instruction has no outside users or is an
3586 // identified reduction value with an outside user.
3587 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3589 emitAnalysis(VectorizationReport(it) <<
3590 "value could not be identified as "
3591 "an induction or reduction variable");
3595 // We only allow if-converted PHIs with exactly two incoming values.
3596 if (Phi->getNumIncomingValues() != 2) {
3597 emitAnalysis(VectorizationReport(it)
3598 << "control flow not understood by vectorizer");
3599 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3603 // This is the value coming from the preheader.
3604 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3605 ConstantInt *StepValue = nullptr;
3606 // Check if this is an induction variable.
3607 InductionKind IK = isInductionVariable(Phi, StepValue);
3609 if (IK_NoInduction != IK) {
3610 // Get the widest type.
3612 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3614 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3616 // Int inductions are special because we only allow one IV.
3617 if (IK == IK_IntInduction && StepValue->isOne()) {
3618 // Use the phi node with the widest type as induction. Use the last
3619 // one if there are multiple (no good reason for doing this other
3620 // than it is expedient).
3621 if (!Induction || PhiTy == WidestIndTy)
3625 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3626 Inductions[Phi] = InductionInfo(StartValue, IK, StepValue);
3628 // Until we explicitly handle the case of an induction variable with
3629 // an outside loop user we have to give up vectorizing this loop.
3630 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3631 emitAnalysis(VectorizationReport(it) <<
3632 "use of induction value outside of the "
3633 "loop is not handled by vectorizer");
3640 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3641 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3644 if (AddReductionVar(Phi, RK_IntegerMult)) {
3645 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3648 if (AddReductionVar(Phi, RK_IntegerOr)) {
3649 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3652 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3653 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3656 if (AddReductionVar(Phi, RK_IntegerXor)) {
3657 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3660 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3661 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3664 if (AddReductionVar(Phi, RK_FloatMult)) {
3665 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3668 if (AddReductionVar(Phi, RK_FloatAdd)) {
3669 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3672 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3673 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3678 emitAnalysis(VectorizationReport(it) <<
3679 "value that could not be identified as "
3680 "reduction is used outside the loop");
3681 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3683 }// end of PHI handling
3685 // We still don't handle functions. However, we can ignore dbg intrinsic
3686 // calls and we do handle certain intrinsic and libm functions.
3687 CallInst *CI = dyn_cast<CallInst>(it);
3688 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3689 emitAnalysis(VectorizationReport(it) <<
3690 "call instruction cannot be vectorized");
3691 DEBUG(dbgs() << "LV: Found a call site.\n");
3695 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
3696 // second argument is the same (i.e. loop invariant)
3698 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
3699 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
3700 emitAnalysis(VectorizationReport(it)
3701 << "intrinsic instruction cannot be vectorized");
3702 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
3707 // Check that the instruction return type is vectorizable.
3708 // Also, we can't vectorize extractelement instructions.
3709 if ((!VectorType::isValidElementType(it->getType()) &&
3710 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3711 emitAnalysis(VectorizationReport(it)
3712 << "instruction return type cannot be vectorized");
3713 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3717 // Check that the stored type is vectorizable.
3718 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3719 Type *T = ST->getValueOperand()->getType();
3720 if (!VectorType::isValidElementType(T)) {
3721 emitAnalysis(VectorizationReport(ST) <<
3722 "store instruction cannot be vectorized");
3725 if (EnableMemAccessVersioning)
3726 collectStridedAccess(ST);
3729 if (EnableMemAccessVersioning)
3730 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3731 collectStridedAccess(LI);
3733 // Reduction instructions are allowed to have exit users.
3734 // All other instructions must not have external users.
3735 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3736 emitAnalysis(VectorizationReport(it) <<
3737 "value cannot be used outside the loop");
3746 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3747 if (Inductions.empty()) {
3748 emitAnalysis(VectorizationReport()
3749 << "loop induction variable could not be identified");
3757 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3758 /// return the induction operand of the gep pointer.
3759 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3760 const DataLayout *DL, Loop *Lp) {
3761 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3765 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3767 // Check that all of the gep indices are uniform except for our induction
3769 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3770 if (i != InductionOperand &&
3771 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3773 return GEP->getOperand(InductionOperand);
3776 ///\brief Look for a cast use of the passed value.
3777 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3778 Value *UniqueCast = nullptr;
3779 for (User *U : Ptr->users()) {
3780 CastInst *CI = dyn_cast<CastInst>(U);
3781 if (CI && CI->getType() == Ty) {
3791 ///\brief Get the stride of a pointer access in a loop.
3792 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3793 /// pointer to the Value, or null otherwise.
3794 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3795 const DataLayout *DL, Loop *Lp) {
3796 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3797 if (!PtrTy || PtrTy->isAggregateType())
3800 // Try to remove a gep instruction to make the pointer (actually index at this
3801 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3802 // pointer, otherwise, we are analyzing the index.
3803 Value *OrigPtr = Ptr;
3805 // The size of the pointer access.
3806 int64_t PtrAccessSize = 1;
3808 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3809 const SCEV *V = SE->getSCEV(Ptr);
3813 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3814 V = C->getOperand();
3816 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3820 V = S->getStepRecurrence(*SE);
3824 // Strip off the size of access multiplication if we are still analyzing the
3826 if (OrigPtr == Ptr) {
3827 DL->getTypeAllocSize(PtrTy->getElementType());
3828 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3829 if (M->getOperand(0)->getSCEVType() != scConstant)
3832 const APInt &APStepVal =
3833 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3835 // Huge step value - give up.
3836 if (APStepVal.getBitWidth() > 64)
3839 int64_t StepVal = APStepVal.getSExtValue();
3840 if (PtrAccessSize != StepVal)
3842 V = M->getOperand(1);
3847 Type *StripedOffRecurrenceCast = nullptr;
3848 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3849 StripedOffRecurrenceCast = C->getType();
3850 V = C->getOperand();
3853 // Look for the loop invariant symbolic value.
3854 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3858 Value *Stride = U->getValue();
3859 if (!Lp->isLoopInvariant(Stride))
3862 // If we have stripped off the recurrence cast we have to make sure that we
3863 // return the value that is used in this loop so that we can replace it later.
3864 if (StripedOffRecurrenceCast)
3865 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3870 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
3871 Value *Ptr = nullptr;
3872 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3873 Ptr = LI->getPointerOperand();
3874 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3875 Ptr = SI->getPointerOperand();
3879 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3883 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3884 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3885 Strides[Ptr] = Stride;
3886 StrideSet.insert(Stride);
3889 void LoopVectorizationLegality::collectLoopUniforms() {
3890 // We now know that the loop is vectorizable!
3891 // Collect variables that will remain uniform after vectorization.
3892 std::vector<Value*> Worklist;
3893 BasicBlock *Latch = TheLoop->getLoopLatch();
3895 // Start with the conditional branch and walk up the block.
3896 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3898 // Also add all consecutive pointer values; these values will be uniform
3899 // after vectorization (and subsequent cleanup) and, until revectorization is
3900 // supported, all dependencies must also be uniform.
3901 for (Loop::block_iterator B = TheLoop->block_begin(),
3902 BE = TheLoop->block_end(); B != BE; ++B)
3903 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3905 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3906 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3908 while (!Worklist.empty()) {
3909 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3910 Worklist.pop_back();
3912 // Look at instructions inside this loop.
3913 // Stop when reaching PHI nodes.
3914 // TODO: we need to follow values all over the loop, not only in this block.
3915 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3918 // This is a known uniform.
3921 // Insert all operands.
3922 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3926 bool LoopVectorizationLegality::canVectorizeMemory() {
3927 return LAA.canVectorizeMemory(Strides);
3930 static bool hasMultipleUsesOf(Instruction *I,
3931 SmallPtrSetImpl<Instruction *> &Insts) {
3932 unsigned NumUses = 0;
3933 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
3934 if (Insts.count(dyn_cast<Instruction>(*Use)))
3943 static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set) {
3944 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
3945 if (!Set.count(dyn_cast<Instruction>(*Use)))
3950 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
3951 ReductionKind Kind) {
3952 if (Phi->getNumIncomingValues() != 2)
3955 // Reduction variables are only found in the loop header block.
3956 if (Phi->getParent() != TheLoop->getHeader())
3959 // Obtain the reduction start value from the value that comes from the loop
3961 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
3963 // ExitInstruction is the single value which is used outside the loop.
3964 // We only allow for a single reduction value to be used outside the loop.
3965 // This includes users of the reduction, variables (which form a cycle
3966 // which ends in the phi node).
3967 Instruction *ExitInstruction = nullptr;
3968 // Indicates that we found a reduction operation in our scan.
3969 bool FoundReduxOp = false;
3971 // We start with the PHI node and scan for all of the users of this
3972 // instruction. All users must be instructions that can be used as reduction
3973 // variables (such as ADD). We must have a single out-of-block user. The cycle
3974 // must include the original PHI.
3975 bool FoundStartPHI = false;
3977 // To recognize min/max patterns formed by a icmp select sequence, we store
3978 // the number of instruction we saw from the recognized min/max pattern,
3979 // to make sure we only see exactly the two instructions.
3980 unsigned NumCmpSelectPatternInst = 0;
3981 ReductionInstDesc ReduxDesc(false, nullptr);
3983 SmallPtrSet<Instruction *, 8> VisitedInsts;
3984 SmallVector<Instruction *, 8> Worklist;
3985 Worklist.push_back(Phi);
3986 VisitedInsts.insert(Phi);
3988 // A value in the reduction can be used:
3989 // - By the reduction:
3990 // - Reduction operation:
3991 // - One use of reduction value (safe).
3992 // - Multiple use of reduction value (not safe).
3994 // - All uses of the PHI must be the reduction (safe).
3995 // - Otherwise, not safe.
3996 // - By one instruction outside of the loop (safe).
3997 // - By further instructions outside of the loop (not safe).
3998 // - By an instruction that is not part of the reduction (not safe).
4000 // * An instruction type other than PHI or the reduction operation.
4001 // * A PHI in the header other than the initial PHI.
4002 while (!Worklist.empty()) {
4003 Instruction *Cur = Worklist.back();
4004 Worklist.pop_back();
4007 // If the instruction has no users then this is a broken chain and can't be
4008 // a reduction variable.
4009 if (Cur->use_empty())
4012 bool IsAPhi = isa<PHINode>(Cur);
4014 // A header PHI use other than the original PHI.
4015 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
4018 // Reductions of instructions such as Div, and Sub is only possible if the
4019 // LHS is the reduction variable.
4020 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
4021 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
4022 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
4025 // Any reduction instruction must be of one of the allowed kinds.
4026 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
4027 if (!ReduxDesc.IsReduction)
4030 // A reduction operation must only have one use of the reduction value.
4031 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
4032 hasMultipleUsesOf(Cur, VisitedInsts))
4035 // All inputs to a PHI node must be a reduction value.
4036 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4039 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4040 isa<SelectInst>(Cur)))
4041 ++NumCmpSelectPatternInst;
4042 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4043 isa<SelectInst>(Cur)))
4044 ++NumCmpSelectPatternInst;
4046 // Check whether we found a reduction operator.
4047 FoundReduxOp |= !IsAPhi;
4049 // Process users of current instruction. Push non-PHI nodes after PHI nodes
4050 // onto the stack. This way we are going to have seen all inputs to PHI
4051 // nodes once we get to them.
4052 SmallVector<Instruction *, 8> NonPHIs;
4053 SmallVector<Instruction *, 8> PHIs;
4054 for (User *U : Cur->users()) {
4055 Instruction *UI = cast<Instruction>(U);
4057 // Check if we found the exit user.
4058 BasicBlock *Parent = UI->getParent();
4059 if (!TheLoop->contains(Parent)) {
4060 // Exit if you find multiple outside users or if the header phi node is
4061 // being used. In this case the user uses the value of the previous
4062 // iteration, in which case we would loose "VF-1" iterations of the
4063 // reduction operation if we vectorize.
4064 if (ExitInstruction != nullptr || Cur == Phi)
4067 // The instruction used by an outside user must be the last instruction
4068 // before we feed back to the reduction phi. Otherwise, we loose VF-1
4069 // operations on the value.
4070 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
4073 ExitInstruction = Cur;
4077 // Process instructions only once (termination). Each reduction cycle
4078 // value must only be used once, except by phi nodes and min/max
4079 // reductions which are represented as a cmp followed by a select.
4080 ReductionInstDesc IgnoredVal(false, nullptr);
4081 if (VisitedInsts.insert(UI).second) {
4082 if (isa<PHINode>(UI))
4085 NonPHIs.push_back(UI);
4086 } else if (!isa<PHINode>(UI) &&
4087 ((!isa<FCmpInst>(UI) &&
4088 !isa<ICmpInst>(UI) &&
4089 !isa<SelectInst>(UI)) ||
4090 !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
4093 // Remember that we completed the cycle.
4095 FoundStartPHI = true;
4097 Worklist.append(PHIs.begin(), PHIs.end());
4098 Worklist.append(NonPHIs.begin(), NonPHIs.end());
4101 // This means we have seen one but not the other instruction of the
4102 // pattern or more than just a select and cmp.
4103 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4104 NumCmpSelectPatternInst != 2)
4107 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4110 // We found a reduction var if we have reached the original phi node and we
4111 // only have a single instruction with out-of-loop users.
4113 // This instruction is allowed to have out-of-loop users.
4114 AllowedExit.insert(ExitInstruction);
4116 // Save the description of this reduction variable.
4117 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4118 ReduxDesc.MinMaxKind);
4119 Reductions[Phi] = RD;
4120 // We've ended the cycle. This is a reduction variable if we have an
4121 // outside user and it has a binary op.
4126 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4127 /// pattern corresponding to a min(X, Y) or max(X, Y).
4128 LoopVectorizationLegality::ReductionInstDesc
4129 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4130 ReductionInstDesc &Prev) {
4132 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4133 "Expect a select instruction");
4134 Instruction *Cmp = nullptr;
4135 SelectInst *Select = nullptr;
4137 // We must handle the select(cmp()) as a single instruction. Advance to the
4139 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4140 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
4141 return ReductionInstDesc(false, I);
4142 return ReductionInstDesc(Select, Prev.MinMaxKind);
4145 // Only handle single use cases for now.
4146 if (!(Select = dyn_cast<SelectInst>(I)))
4147 return ReductionInstDesc(false, I);
4148 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4149 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4150 return ReductionInstDesc(false, I);
4151 if (!Cmp->hasOneUse())
4152 return ReductionInstDesc(false, I);
4157 // Look for a min/max pattern.
4158 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4159 return ReductionInstDesc(Select, MRK_UIntMin);
4160 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4161 return ReductionInstDesc(Select, MRK_UIntMax);
4162 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4163 return ReductionInstDesc(Select, MRK_SIntMax);
4164 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4165 return ReductionInstDesc(Select, MRK_SIntMin);
4166 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4167 return ReductionInstDesc(Select, MRK_FloatMin);
4168 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4169 return ReductionInstDesc(Select, MRK_FloatMax);
4170 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4171 return ReductionInstDesc(Select, MRK_FloatMin);
4172 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4173 return ReductionInstDesc(Select, MRK_FloatMax);
4175 return ReductionInstDesc(false, I);
4178 LoopVectorizationLegality::ReductionInstDesc
4179 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4181 ReductionInstDesc &Prev) {
4182 bool FP = I->getType()->isFloatingPointTy();
4183 bool FastMath = FP && I->hasUnsafeAlgebra();
4184 switch (I->getOpcode()) {
4186 return ReductionInstDesc(false, I);
4187 case Instruction::PHI:
4188 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4189 Kind != RK_FloatMinMax))
4190 return ReductionInstDesc(false, I);
4191 return ReductionInstDesc(I, Prev.MinMaxKind);
4192 case Instruction::Sub:
4193 case Instruction::Add:
4194 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4195 case Instruction::Mul:
4196 return ReductionInstDesc(Kind == RK_IntegerMult, I);
4197 case Instruction::And:
4198 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4199 case Instruction::Or:
4200 return ReductionInstDesc(Kind == RK_IntegerOr, I);
4201 case Instruction::Xor:
4202 return ReductionInstDesc(Kind == RK_IntegerXor, I);
4203 case Instruction::FMul:
4204 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4205 case Instruction::FSub:
4206 case Instruction::FAdd:
4207 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4208 case Instruction::FCmp:
4209 case Instruction::ICmp:
4210 case Instruction::Select:
4211 if (Kind != RK_IntegerMinMax &&
4212 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4213 return ReductionInstDesc(false, I);
4214 return isMinMaxSelectCmpPattern(I, Prev);
4218 LoopVectorizationLegality::InductionKind
4219 LoopVectorizationLegality::isInductionVariable(PHINode *Phi,
4220 ConstantInt *&StepValue) {
4221 Type *PhiTy = Phi->getType();
4222 // We only handle integer and pointer inductions variables.
4223 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4224 return IK_NoInduction;
4226 // Check that the PHI is consecutive.
4227 const SCEV *PhiScev = SE->getSCEV(Phi);
4228 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4230 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4231 return IK_NoInduction;
4234 const SCEV *Step = AR->getStepRecurrence(*SE);
4235 // Calculate the pointer stride and check if it is consecutive.
4236 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4238 return IK_NoInduction;
4240 ConstantInt *CV = C->getValue();
4241 if (PhiTy->isIntegerTy()) {
4243 return IK_IntInduction;
4246 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4247 Type *PointerElementType = PhiTy->getPointerElementType();
4248 // The pointer stride cannot be determined if the pointer element type is not
4250 if (!PointerElementType->isSized())
4251 return IK_NoInduction;
4253 int64_t Size = static_cast<int64_t>(DL->getTypeAllocSize(PointerElementType));
4254 int64_t CVSize = CV->getSExtValue();
4256 return IK_NoInduction;
4257 StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
4258 return IK_PtrInduction;
4261 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4262 Value *In0 = const_cast<Value*>(V);
4263 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4267 return Inductions.count(PN);
4270 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4271 return LAA.blockNeedsPredication(BB);
4274 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4275 SmallPtrSetImpl<Value *> &SafePtrs) {
4277 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4278 // Check that we don't have a constant expression that can trap as operand.
4279 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4281 if (Constant *C = dyn_cast<Constant>(*OI))
4285 // We might be able to hoist the load.
4286 if (it->mayReadFromMemory()) {
4287 LoadInst *LI = dyn_cast<LoadInst>(it);
4290 if (!SafePtrs.count(LI->getPointerOperand())) {
4291 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4292 MaskedOp.insert(LI);
4299 // We don't predicate stores at the moment.
4300 if (it->mayWriteToMemory()) {
4301 StoreInst *SI = dyn_cast<StoreInst>(it);
4302 // We only support predication of stores in basic blocks with one
4307 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4308 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4310 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4311 !isSinglePredecessor) {
4312 // Build a masked store if it is legal for the target, otherwise scalarize
4314 bool isLegalMaskedOp =
4315 isLegalMaskedStore(SI->getValueOperand()->getType(),
4316 SI->getPointerOperand());
4317 if (isLegalMaskedOp) {
4319 MaskedOp.insert(SI);
4328 // The instructions below can trap.
4329 switch (it->getOpcode()) {
4331 case Instruction::UDiv:
4332 case Instruction::SDiv:
4333 case Instruction::URem:
4334 case Instruction::SRem:
4342 LoopVectorizationCostModel::VectorizationFactor
4343 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4344 // Width 1 means no vectorize
4345 VectorizationFactor Factor = { 1U, 0U };
4346 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4347 emitAnalysis(VectorizationReport() <<
4348 "runtime pointer checks needed. Enable vectorization of this "
4349 "loop with '#pragma clang loop vectorize(enable)' when "
4350 "compiling with -Os");
4351 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4355 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4356 emitAnalysis(VectorizationReport() <<
4357 "store that is conditionally executed prevents vectorization");
4358 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4362 // Find the trip count.
4363 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4364 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4366 unsigned WidestType = getWidestType();
4367 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4368 unsigned MaxSafeDepDist = -1U;
4369 if (Legal->getMaxSafeDepDistBytes() != -1U)
4370 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4371 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4372 WidestRegister : MaxSafeDepDist);
4373 unsigned MaxVectorSize = WidestRegister / WidestType;
4374 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4375 DEBUG(dbgs() << "LV: The Widest register is: "
4376 << WidestRegister << " bits.\n");
4378 if (MaxVectorSize == 0) {
4379 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4383 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4384 " into one vector!");
4386 unsigned VF = MaxVectorSize;
4388 // If we optimize the program for size, avoid creating the tail loop.
4390 // If we are unable to calculate the trip count then don't try to vectorize.
4393 (VectorizationReport() <<
4394 "unable to calculate the loop count due to complex control flow");
4395 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4399 // Find the maximum SIMD width that can fit within the trip count.
4400 VF = TC % MaxVectorSize;
4405 // If the trip count that we found modulo the vectorization factor is not
4406 // zero then we require a tail.
4408 emitAnalysis(VectorizationReport() <<
4409 "cannot optimize for size and vectorize at the "
4410 "same time. Enable vectorization of this loop "
4411 "with '#pragma clang loop vectorize(enable)' "
4412 "when compiling with -Os");
4413 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4418 int UserVF = Hints->getWidth();
4420 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4421 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4423 Factor.Width = UserVF;
4427 float Cost = expectedCost(1);
4429 const float ScalarCost = Cost;
4432 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4434 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4435 // Ignore scalar width, because the user explicitly wants vectorization.
4436 if (ForceVectorization && VF > 1) {
4438 Cost = expectedCost(Width) / (float)Width;
4441 for (unsigned i=2; i <= VF; i*=2) {
4442 // Notice that the vector loop needs to be executed less times, so
4443 // we need to divide the cost of the vector loops by the width of
4444 // the vector elements.
4445 float VectorCost = expectedCost(i) / (float)i;
4446 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4447 (int)VectorCost << ".\n");
4448 if (VectorCost < Cost) {
4454 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4455 << "LV: Vectorization seems to be not beneficial, "
4456 << "but was forced by a user.\n");
4457 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4458 Factor.Width = Width;
4459 Factor.Cost = Width * Cost;
4463 unsigned LoopVectorizationCostModel::getWidestType() {
4464 unsigned MaxWidth = 8;
4467 for (Loop::block_iterator bb = TheLoop->block_begin(),
4468 be = TheLoop->block_end(); bb != be; ++bb) {
4469 BasicBlock *BB = *bb;
4471 // For each instruction in the loop.
4472 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4473 Type *T = it->getType();
4475 // Ignore ephemeral values.
4476 if (EphValues.count(it))
4479 // Only examine Loads, Stores and PHINodes.
4480 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4483 // Examine PHI nodes that are reduction variables.
4484 if (PHINode *PN = dyn_cast<PHINode>(it))
4485 if (!Legal->getReductionVars()->count(PN))
4488 // Examine the stored values.
4489 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4490 T = ST->getValueOperand()->getType();
4492 // Ignore loaded pointer types and stored pointer types that are not
4493 // consecutive. However, we do want to take consecutive stores/loads of
4494 // pointer vectors into account.
4495 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4498 MaxWidth = std::max(MaxWidth,
4499 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
4507 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
4509 unsigned LoopCost) {
4511 // -- The unroll heuristics --
4512 // We unroll the loop in order to expose ILP and reduce the loop overhead.
4513 // There are many micro-architectural considerations that we can't predict
4514 // at this level. For example, frontend pressure (on decode or fetch) due to
4515 // code size, or the number and capabilities of the execution ports.
4517 // We use the following heuristics to select the unroll factor:
4518 // 1. If the code has reductions, then we unroll in order to break the cross
4519 // iteration dependency.
4520 // 2. If the loop is really small, then we unroll in order to reduce the loop
4522 // 3. We don't unroll if we think that we will spill registers to memory due
4523 // to the increased register pressure.
4525 // Use the user preference, unless 'auto' is selected.
4526 int UserUF = Hints->getInterleave();
4530 // When we optimize for size, we don't unroll.
4534 // We used the distance for the unroll factor.
4535 if (Legal->getMaxSafeDepDistBytes() != -1U)
4538 // Do not unroll loops with a relatively small trip count.
4539 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4540 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
4543 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4544 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4548 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4549 TargetNumRegisters = ForceTargetNumScalarRegs;
4551 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4552 TargetNumRegisters = ForceTargetNumVectorRegs;
4555 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4556 // We divide by these constants so assume that we have at least one
4557 // instruction that uses at least one register.
4558 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4559 R.NumInstructions = std::max(R.NumInstructions, 1U);
4561 // We calculate the unroll factor using the following formula.
4562 // Subtract the number of loop invariants from the number of available
4563 // registers. These registers are used by all of the unrolled instances.
4564 // Next, divide the remaining registers by the number of registers that is
4565 // required by the loop, in order to estimate how many parallel instances
4566 // fit without causing spills. All of this is rounded down if necessary to be
4567 // a power of two. We want power of two unroll factors to simplify any
4568 // addressing operations or alignment considerations.
4569 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4572 // Don't count the induction variable as unrolled.
4573 if (EnableIndVarRegisterHeur)
4574 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4575 std::max(1U, (R.MaxLocalUsers - 1)));
4577 // Clamp the unroll factor ranges to reasonable factors.
4578 unsigned MaxInterleaveSize = TTI.getMaxInterleaveFactor();
4580 // Check if the user has overridden the unroll max.
4582 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4583 MaxInterleaveSize = ForceTargetMaxScalarInterleaveFactor;
4585 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4586 MaxInterleaveSize = ForceTargetMaxVectorInterleaveFactor;
4589 // If we did not calculate the cost for VF (because the user selected the VF)
4590 // then we calculate the cost of VF here.
4592 LoopCost = expectedCost(VF);
4594 // Clamp the calculated UF to be between the 1 and the max unroll factor
4595 // that the target allows.
4596 if (UF > MaxInterleaveSize)
4597 UF = MaxInterleaveSize;
4601 // Unroll if we vectorized this loop and there is a reduction that could
4602 // benefit from unrolling.
4603 if (VF > 1 && Legal->getReductionVars()->size()) {
4604 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
4608 // Note that if we've already vectorized the loop we will have done the
4609 // runtime check and so unrolling won't require further checks.
4610 bool UnrollingRequiresRuntimePointerCheck =
4611 (VF == 1 && Legal->getRuntimePointerCheck()->Need);
4613 // We want to unroll small loops in order to reduce the loop overhead and
4614 // potentially expose ILP opportunities.
4615 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4616 if (!UnrollingRequiresRuntimePointerCheck &&
4617 LoopCost < SmallLoopCost) {
4618 // We assume that the cost overhead is 1 and we use the cost model
4619 // to estimate the cost of the loop and unroll until the cost of the
4620 // loop overhead is about 5% of the cost of the loop.
4621 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4623 // Unroll until store/load ports (estimated by max unroll factor) are
4625 unsigned NumStores = Legal->getNumStores();
4626 unsigned NumLoads = Legal->getNumLoads();
4627 unsigned StoresUF = UF / (NumStores ? NumStores : 1);
4628 unsigned LoadsUF = UF / (NumLoads ? NumLoads : 1);
4630 // If we have a scalar reduction (vector reductions are already dealt with
4631 // by this point), we can increase the critical path length if the loop
4632 // we're unrolling is inside another loop. Limit, by default to 2, so the
4633 // critical path only gets increased by one reduction operation.
4634 if (Legal->getReductionVars()->size() &&
4635 TheLoop->getLoopDepth() > 1) {
4636 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionUF);
4637 SmallUF = std::min(SmallUF, F);
4638 StoresUF = std::min(StoresUF, F);
4639 LoadsUF = std::min(LoadsUF, F);
4642 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
4643 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
4644 return std::max(StoresUF, LoadsUF);
4647 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
4651 DEBUG(dbgs() << "LV: Not Unrolling.\n");
4655 LoopVectorizationCostModel::RegisterUsage
4656 LoopVectorizationCostModel::calculateRegisterUsage() {
4657 // This function calculates the register usage by measuring the highest number
4658 // of values that are alive at a single location. Obviously, this is a very
4659 // rough estimation. We scan the loop in a topological order in order and
4660 // assign a number to each instruction. We use RPO to ensure that defs are
4661 // met before their users. We assume that each instruction that has in-loop
4662 // users starts an interval. We record every time that an in-loop value is
4663 // used, so we have a list of the first and last occurrences of each
4664 // instruction. Next, we transpose this data structure into a multi map that
4665 // holds the list of intervals that *end* at a specific location. This multi
4666 // map allows us to perform a linear search. We scan the instructions linearly
4667 // and record each time that a new interval starts, by placing it in a set.
4668 // If we find this value in the multi-map then we remove it from the set.
4669 // The max register usage is the maximum size of the set.
4670 // We also search for instructions that are defined outside the loop, but are
4671 // used inside the loop. We need this number separately from the max-interval
4672 // usage number because when we unroll, loop-invariant values do not take
4674 LoopBlocksDFS DFS(TheLoop);
4678 R.NumInstructions = 0;
4680 // Each 'key' in the map opens a new interval. The values
4681 // of the map are the index of the 'last seen' usage of the
4682 // instruction that is the key.
4683 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4684 // Maps instruction to its index.
4685 DenseMap<unsigned, Instruction*> IdxToInstr;
4686 // Marks the end of each interval.
4687 IntervalMap EndPoint;
4688 // Saves the list of instruction indices that are used in the loop.
4689 SmallSet<Instruction*, 8> Ends;
4690 // Saves the list of values that are used in the loop but are
4691 // defined outside the loop, such as arguments and constants.
4692 SmallPtrSet<Value*, 8> LoopInvariants;
4695 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4696 be = DFS.endRPO(); bb != be; ++bb) {
4697 R.NumInstructions += (*bb)->size();
4698 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4700 Instruction *I = it;
4701 IdxToInstr[Index++] = I;
4703 // Save the end location of each USE.
4704 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4705 Value *U = I->getOperand(i);
4706 Instruction *Instr = dyn_cast<Instruction>(U);
4708 // Ignore non-instruction values such as arguments, constants, etc.
4709 if (!Instr) continue;
4711 // If this instruction is outside the loop then record it and continue.
4712 if (!TheLoop->contains(Instr)) {
4713 LoopInvariants.insert(Instr);
4717 // Overwrite previous end points.
4718 EndPoint[Instr] = Index;
4724 // Saves the list of intervals that end with the index in 'key'.
4725 typedef SmallVector<Instruction*, 2> InstrList;
4726 DenseMap<unsigned, InstrList> TransposeEnds;
4728 // Transpose the EndPoints to a list of values that end at each index.
4729 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4731 TransposeEnds[it->second].push_back(it->first);
4733 SmallSet<Instruction*, 8> OpenIntervals;
4734 unsigned MaxUsage = 0;
4737 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4738 for (unsigned int i = 0; i < Index; ++i) {
4739 Instruction *I = IdxToInstr[i];
4740 // Ignore instructions that are never used within the loop.
4741 if (!Ends.count(I)) continue;
4743 // Ignore ephemeral values.
4744 if (EphValues.count(I))
4747 // Remove all of the instructions that end at this location.
4748 InstrList &List = TransposeEnds[i];
4749 for (unsigned int j=0, e = List.size(); j < e; ++j)
4750 OpenIntervals.erase(List[j]);
4752 // Count the number of live interals.
4753 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4755 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4756 OpenIntervals.size() << '\n');
4758 // Add the current instruction to the list of open intervals.
4759 OpenIntervals.insert(I);
4762 unsigned Invariant = LoopInvariants.size();
4763 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
4764 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
4765 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
4767 R.LoopInvariantRegs = Invariant;
4768 R.MaxLocalUsers = MaxUsage;
4772 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4776 for (Loop::block_iterator bb = TheLoop->block_begin(),
4777 be = TheLoop->block_end(); bb != be; ++bb) {
4778 unsigned BlockCost = 0;
4779 BasicBlock *BB = *bb;
4781 // For each instruction in the old loop.
4782 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4783 // Skip dbg intrinsics.
4784 if (isa<DbgInfoIntrinsic>(it))
4787 // Ignore ephemeral values.
4788 if (EphValues.count(it))
4791 unsigned C = getInstructionCost(it, VF);
4793 // Check if we should override the cost.
4794 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
4795 C = ForceTargetInstructionCost;
4798 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
4799 VF << " For instruction: " << *it << '\n');
4802 // We assume that if-converted blocks have a 50% chance of being executed.
4803 // When the code is scalar then some of the blocks are avoided due to CF.
4804 // When the code is vectorized we execute all code paths.
4805 if (VF == 1 && Legal->blockNeedsPredication(*bb))
4814 /// \brief Check whether the address computation for a non-consecutive memory
4815 /// access looks like an unlikely candidate for being merged into the indexing
4818 /// We look for a GEP which has one index that is an induction variable and all
4819 /// other indices are loop invariant. If the stride of this access is also
4820 /// within a small bound we decide that this address computation can likely be
4821 /// merged into the addressing mode.
4822 /// In all other cases, we identify the address computation as complex.
4823 static bool isLikelyComplexAddressComputation(Value *Ptr,
4824 LoopVectorizationLegality *Legal,
4825 ScalarEvolution *SE,
4826 const Loop *TheLoop) {
4827 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
4831 // We are looking for a gep with all loop invariant indices except for one
4832 // which should be an induction variable.
4833 unsigned NumOperands = Gep->getNumOperands();
4834 for (unsigned i = 1; i < NumOperands; ++i) {
4835 Value *Opd = Gep->getOperand(i);
4836 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
4837 !Legal->isInductionVariable(Opd))
4841 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
4842 // can likely be merged into the address computation.
4843 unsigned MaxMergeDistance = 64;
4845 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
4849 // Check the step is constant.
4850 const SCEV *Step = AddRec->getStepRecurrence(*SE);
4851 // Calculate the pointer stride and check if it is consecutive.
4852 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4856 const APInt &APStepVal = C->getValue()->getValue();
4858 // Huge step value - give up.
4859 if (APStepVal.getBitWidth() > 64)
4862 int64_t StepVal = APStepVal.getSExtValue();
4864 return StepVal > MaxMergeDistance;
4867 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
4868 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
4874 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
4875 // If we know that this instruction will remain uniform, check the cost of
4876 // the scalar version.
4877 if (Legal->isUniformAfterVectorization(I))
4880 Type *RetTy = I->getType();
4881 Type *VectorTy = ToVectorTy(RetTy, VF);
4883 // TODO: We need to estimate the cost of intrinsic calls.
4884 switch (I->getOpcode()) {
4885 case Instruction::GetElementPtr:
4886 // We mark this instruction as zero-cost because the cost of GEPs in
4887 // vectorized code depends on whether the corresponding memory instruction
4888 // is scalarized or not. Therefore, we handle GEPs with the memory
4889 // instruction cost.
4891 case Instruction::Br: {
4892 return TTI.getCFInstrCost(I->getOpcode());
4894 case Instruction::PHI:
4895 //TODO: IF-converted IFs become selects.
4897 case Instruction::Add:
4898 case Instruction::FAdd:
4899 case Instruction::Sub:
4900 case Instruction::FSub:
4901 case Instruction::Mul:
4902 case Instruction::FMul:
4903 case Instruction::UDiv:
4904 case Instruction::SDiv:
4905 case Instruction::FDiv:
4906 case Instruction::URem:
4907 case Instruction::SRem:
4908 case Instruction::FRem:
4909 case Instruction::Shl:
4910 case Instruction::LShr:
4911 case Instruction::AShr:
4912 case Instruction::And:
4913 case Instruction::Or:
4914 case Instruction::Xor: {
4915 // Since we will replace the stride by 1 the multiplication should go away.
4916 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
4918 // Certain instructions can be cheaper to vectorize if they have a constant
4919 // second vector operand. One example of this are shifts on x86.
4920 TargetTransformInfo::OperandValueKind Op1VK =
4921 TargetTransformInfo::OK_AnyValue;
4922 TargetTransformInfo::OperandValueKind Op2VK =
4923 TargetTransformInfo::OK_AnyValue;
4924 TargetTransformInfo::OperandValueProperties Op1VP =
4925 TargetTransformInfo::OP_None;
4926 TargetTransformInfo::OperandValueProperties Op2VP =
4927 TargetTransformInfo::OP_None;
4928 Value *Op2 = I->getOperand(1);
4930 // Check for a splat of a constant or for a non uniform vector of constants.
4931 if (isa<ConstantInt>(Op2)) {
4932 ConstantInt *CInt = cast<ConstantInt>(Op2);
4933 if (CInt && CInt->getValue().isPowerOf2())
4934 Op2VP = TargetTransformInfo::OP_PowerOf2;
4935 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4936 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
4937 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
4938 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
4940 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
4941 if (CInt && CInt->getValue().isPowerOf2())
4942 Op2VP = TargetTransformInfo::OP_PowerOf2;
4943 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4947 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
4950 case Instruction::Select: {
4951 SelectInst *SI = cast<SelectInst>(I);
4952 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
4953 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
4954 Type *CondTy = SI->getCondition()->getType();
4956 CondTy = VectorType::get(CondTy, VF);
4958 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
4960 case Instruction::ICmp:
4961 case Instruction::FCmp: {
4962 Type *ValTy = I->getOperand(0)->getType();
4963 VectorTy = ToVectorTy(ValTy, VF);
4964 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
4966 case Instruction::Store:
4967 case Instruction::Load: {
4968 StoreInst *SI = dyn_cast<StoreInst>(I);
4969 LoadInst *LI = dyn_cast<LoadInst>(I);
4970 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
4972 VectorTy = ToVectorTy(ValTy, VF);
4974 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
4975 unsigned AS = SI ? SI->getPointerAddressSpace() :
4976 LI->getPointerAddressSpace();
4977 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
4978 // We add the cost of address computation here instead of with the gep
4979 // instruction because only here we know whether the operation is
4982 return TTI.getAddressComputationCost(VectorTy) +
4983 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4985 // Scalarized loads/stores.
4986 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
4987 bool Reverse = ConsecutiveStride < 0;
4988 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
4989 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
4990 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
4991 bool IsComplexComputation =
4992 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
4994 // The cost of extracting from the value vector and pointer vector.
4995 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
4996 for (unsigned i = 0; i < VF; ++i) {
4997 // The cost of extracting the pointer operand.
4998 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
4999 // In case of STORE, the cost of ExtractElement from the vector.
5000 // In case of LOAD, the cost of InsertElement into the returned
5002 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5003 Instruction::InsertElement,
5007 // The cost of the scalar loads/stores.
5008 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5009 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5014 // Wide load/stores.
5015 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5016 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5019 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5023 case Instruction::ZExt:
5024 case Instruction::SExt:
5025 case Instruction::FPToUI:
5026 case Instruction::FPToSI:
5027 case Instruction::FPExt:
5028 case Instruction::PtrToInt:
5029 case Instruction::IntToPtr:
5030 case Instruction::SIToFP:
5031 case Instruction::UIToFP:
5032 case Instruction::Trunc:
5033 case Instruction::FPTrunc:
5034 case Instruction::BitCast: {
5035 // We optimize the truncation of induction variable.
5036 // The cost of these is the same as the scalar operation.
5037 if (I->getOpcode() == Instruction::Trunc &&
5038 Legal->isInductionVariable(I->getOperand(0)))
5039 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5040 I->getOperand(0)->getType());
5042 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5043 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5045 case Instruction::Call: {
5046 CallInst *CI = cast<CallInst>(I);
5047 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5048 assert(ID && "Not an intrinsic call!");
5049 Type *RetTy = ToVectorTy(CI->getType(), VF);
5050 SmallVector<Type*, 4> Tys;
5051 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5052 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5053 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5056 // We are scalarizing the instruction. Return the cost of the scalar
5057 // instruction, plus the cost of insert and extract into vector
5058 // elements, times the vector width.
5061 if (!RetTy->isVoidTy() && VF != 1) {
5062 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5064 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5067 // The cost of inserting the results plus extracting each one of the
5069 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5072 // The cost of executing VF copies of the scalar instruction. This opcode
5073 // is unknown. Assume that it is the same as 'mul'.
5074 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5080 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
5081 if (Scalar->isVoidTy() || VF == 1)
5083 return VectorType::get(Scalar, VF);
5086 char LoopVectorize::ID = 0;
5087 static const char lv_name[] = "Loop Vectorization";
5088 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5089 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5090 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
5091 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5092 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5093 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5094 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5095 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5096 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5097 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5098 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5101 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5102 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5106 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5107 // Check for a store.
5108 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5109 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5111 // Check for a load.
5112 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5113 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5119 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5120 bool IfPredicateStore) {
5121 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5122 // Holds vector parameters or scalars, in case of uniform vals.
5123 SmallVector<VectorParts, 4> Params;
5125 setDebugLocFromInst(Builder, Instr);
5127 // Find all of the vectorized parameters.
5128 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5129 Value *SrcOp = Instr->getOperand(op);
5131 // If we are accessing the old induction variable, use the new one.
5132 if (SrcOp == OldInduction) {
5133 Params.push_back(getVectorValue(SrcOp));
5137 // Try using previously calculated values.
5138 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5140 // If the src is an instruction that appeared earlier in the basic block
5141 // then it should already be vectorized.
5142 if (SrcInst && OrigLoop->contains(SrcInst)) {
5143 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5144 // The parameter is a vector value from earlier.
5145 Params.push_back(WidenMap.get(SrcInst));
5147 // The parameter is a scalar from outside the loop. Maybe even a constant.
5148 VectorParts Scalars;
5149 Scalars.append(UF, SrcOp);
5150 Params.push_back(Scalars);
5154 assert(Params.size() == Instr->getNumOperands() &&
5155 "Invalid number of operands");
5157 // Does this instruction return a value ?
5158 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5160 Value *UndefVec = IsVoidRetTy ? nullptr :
5161 UndefValue::get(Instr->getType());
5162 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5163 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5165 Instruction *InsertPt = Builder.GetInsertPoint();
5166 BasicBlock *IfBlock = Builder.GetInsertBlock();
5167 BasicBlock *CondBlock = nullptr;
5170 Loop *VectorLp = nullptr;
5171 if (IfPredicateStore) {
5172 assert(Instr->getParent()->getSinglePredecessor() &&
5173 "Only support single predecessor blocks");
5174 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5175 Instr->getParent());
5176 VectorLp = LI->getLoopFor(IfBlock);
5177 assert(VectorLp && "Must have a loop for this block");
5180 // For each vector unroll 'part':
5181 for (unsigned Part = 0; Part < UF; ++Part) {
5182 // For each scalar that we create:
5184 // Start an "if (pred) a[i] = ..." block.
5185 Value *Cmp = nullptr;
5186 if (IfPredicateStore) {
5187 if (Cond[Part]->getType()->isVectorTy())
5189 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5190 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5191 ConstantInt::get(Cond[Part]->getType(), 1));
5192 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5193 LoopVectorBody.push_back(CondBlock);
5194 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
5195 // Update Builder with newly created basic block.
5196 Builder.SetInsertPoint(InsertPt);
5199 Instruction *Cloned = Instr->clone();
5201 Cloned->setName(Instr->getName() + ".cloned");
5202 // Replace the operands of the cloned instructions with extracted scalars.
5203 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5204 Value *Op = Params[op][Part];
5205 Cloned->setOperand(op, Op);
5208 // Place the cloned scalar in the new loop.
5209 Builder.Insert(Cloned);
5211 // If the original scalar returns a value we need to place it in a vector
5212 // so that future users will be able to use it.
5214 VecResults[Part] = Cloned;
5217 if (IfPredicateStore) {
5218 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5219 LoopVectorBody.push_back(NewIfBlock);
5220 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
5221 Builder.SetInsertPoint(InsertPt);
5222 Instruction *OldBr = IfBlock->getTerminator();
5223 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
5224 OldBr->eraseFromParent();
5225 IfBlock = NewIfBlock;
5230 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5231 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5232 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5234 return scalarizeInstruction(Instr, IfPredicateStore);
5237 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5241 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5245 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5246 // When unrolling and the VF is 1, we only need to add a simple scalar.
5247 Type *ITy = Val->getType();
5248 assert(!ITy->isVectorTy() && "Val must be a scalar");
5249 Constant *C = ConstantInt::get(ITy, StartIdx);
5250 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");