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, true>
110 VectorizationFactor("force-vector-width", cl::Hidden,
111 cl::desc("Sets the SIMD width. Zero is autoselect."),
112 cl::location(VectorizerParams::VectorizationFactor));
113 unsigned VectorizerParams::VectorizationFactor = 0;
115 static cl::opt<unsigned, true>
116 VectorizationInterleave("force-vector-interleave", cl::Hidden,
117 cl::desc("Sets the vectorization interleave count. "
118 "Zero is autoselect."),
120 VectorizerParams::VectorizationInterleave));
121 unsigned VectorizerParams::VectorizationInterleave = 0;
124 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
125 cl::desc("Enable if-conversion during vectorization."));
127 /// We don't vectorize loops with a known constant trip count below this number.
128 static cl::opt<unsigned>
129 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
131 cl::desc("Don't vectorize loops with a constant "
132 "trip count that is smaller than this "
135 /// This enables versioning on the strides of symbolically striding memory
136 /// accesses in code like the following.
137 /// for (i = 0; i < N; ++i)
138 /// A[i * Stride1] += B[i * Stride2] ...
140 /// Will be roughly translated to
141 /// if (Stride1 == 1 && Stride2 == 1) {
142 /// for (i = 0; i < N; i+=4)
146 static cl::opt<bool> EnableMemAccessVersioning(
147 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
148 cl::desc("Enable symblic stride memory access versioning"));
150 /// We don't unroll loops with a known constant trip count below this number.
151 static const unsigned TinyTripCountUnrollThreshold = 128;
153 /// When performing memory disambiguation checks at runtime do not make more
154 /// than this number of comparisons.
155 const unsigned VectorizerParams::RuntimeMemoryCheckThreshold = 8;
157 /// Maximum simd width.
158 const unsigned VectorizerParams::MaxVectorWidth = 64;
160 static cl::opt<unsigned> ForceTargetNumScalarRegs(
161 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
162 cl::desc("A flag that overrides the target's number of scalar registers."));
164 static cl::opt<unsigned> ForceTargetNumVectorRegs(
165 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
166 cl::desc("A flag that overrides the target's number of vector registers."));
168 /// Maximum vectorization interleave count.
169 static const unsigned MaxInterleaveFactor = 16;
171 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
172 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
173 cl::desc("A flag that overrides the target's max interleave factor for "
176 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
177 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
178 cl::desc("A flag that overrides the target's max interleave factor for "
179 "vectorized loops."));
181 static cl::opt<unsigned> ForceTargetInstructionCost(
182 "force-target-instruction-cost", cl::init(0), cl::Hidden,
183 cl::desc("A flag that overrides the target's expected cost for "
184 "an instruction to a single constant value. Mostly "
185 "useful for getting consistent testing."));
187 static cl::opt<unsigned> SmallLoopCost(
188 "small-loop-cost", cl::init(20), cl::Hidden,
189 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
191 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
192 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
193 cl::desc("Enable the use of the block frequency analysis to access PGO "
194 "heuristics minimizing code growth in cold regions and being more "
195 "aggressive in hot regions."));
197 // Runtime unroll loops for load/store throughput.
198 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
199 "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
200 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
202 /// The number of stores in a loop that are allowed to need predication.
203 static cl::opt<unsigned> NumberOfStoresToPredicate(
204 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
205 cl::desc("Max number of stores to be predicated behind an if."));
207 static cl::opt<bool> EnableIndVarRegisterHeur(
208 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
209 cl::desc("Count the induction variable only once when unrolling"));
211 static cl::opt<bool> EnableCondStoresVectorization(
212 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
213 cl::desc("Enable if predication of stores during vectorization."));
215 static cl::opt<unsigned> MaxNestedScalarReductionUF(
216 "max-nested-scalar-reduction-unroll", cl::init(2), cl::Hidden,
217 cl::desc("The maximum unroll factor to use when unrolling a scalar "
218 "reduction in a nested loop."));
222 // Forward declarations.
223 class LoopVectorizationLegality;
224 class LoopVectorizationCostModel;
225 class LoopVectorizeHints;
227 /// InnerLoopVectorizer vectorizes loops which contain only one basic
228 /// block to a specified vectorization factor (VF).
229 /// This class performs the widening of scalars into vectors, or multiple
230 /// scalars. This class also implements the following features:
231 /// * It inserts an epilogue loop for handling loops that don't have iteration
232 /// counts that are known to be a multiple of the vectorization factor.
233 /// * It handles the code generation for reduction variables.
234 /// * Scalarization (implementation using scalars) of un-vectorizable
236 /// InnerLoopVectorizer does not perform any vectorization-legality
237 /// checks, and relies on the caller to check for the different legality
238 /// aspects. The InnerLoopVectorizer relies on the
239 /// LoopVectorizationLegality class to provide information about the induction
240 /// and reduction variables that were found to a given vectorization factor.
241 class InnerLoopVectorizer {
243 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
244 DominatorTree *DT, const DataLayout *DL,
245 const TargetLibraryInfo *TLI, unsigned VecWidth,
246 unsigned UnrollFactor)
247 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
248 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
249 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
252 // Perform the actual loop widening (vectorization).
253 void vectorize(LoopVectorizationLegality *L) {
255 // Create a new empty loop. Unlink the old loop and connect the new one.
257 // Widen each instruction in the old loop to a new one in the new loop.
258 // Use the Legality module to find the induction and reduction variables.
260 // Register the new loop and update the analysis passes.
264 virtual ~InnerLoopVectorizer() {}
267 /// A small list of PHINodes.
268 typedef SmallVector<PHINode*, 4> PhiVector;
269 /// When we unroll loops we have multiple vector values for each scalar.
270 /// This data structure holds the unrolled and vectorized values that
271 /// originated from one scalar instruction.
272 typedef SmallVector<Value*, 2> VectorParts;
274 // When we if-convert we need create edge masks. We have to cache values so
275 // that we don't end up with exponential recursion/IR.
276 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
277 VectorParts> EdgeMaskCache;
279 /// \brief Add checks for strides that where assumed to be 1.
281 /// Returns the last check instruction and the first check instruction in the
282 /// pair as (first, last).
283 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
285 /// Create an empty loop, based on the loop ranges of the old loop.
286 void createEmptyLoop();
287 /// Copy and widen the instructions from the old loop.
288 virtual void vectorizeLoop();
290 /// \brief The Loop exit block may have single value PHI nodes where the
291 /// incoming value is 'Undef'. While vectorizing we only handled real values
292 /// that were defined inside the loop. Here we fix the 'undef case'.
296 /// A helper function that computes the predicate of the block BB, assuming
297 /// that the header block of the loop is set to True. It returns the *entry*
298 /// mask for the block BB.
299 VectorParts createBlockInMask(BasicBlock *BB);
300 /// A helper function that computes the predicate of the edge between SRC
302 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
304 /// A helper function to vectorize a single BB within the innermost loop.
305 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
307 /// Vectorize a single PHINode in a block. This method handles the induction
308 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
309 /// arbitrary length vectors.
310 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
311 unsigned UF, unsigned VF, PhiVector *PV);
313 /// Insert the new loop to the loop hierarchy and pass manager
314 /// and update the analysis passes.
315 void updateAnalysis();
317 /// This instruction is un-vectorizable. Implement it as a sequence
318 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
319 /// scalarized instruction behind an if block predicated on the control
320 /// dependence of the instruction.
321 virtual void scalarizeInstruction(Instruction *Instr,
322 bool IfPredicateStore=false);
324 /// Vectorize Load and Store instructions,
325 virtual void vectorizeMemoryInstruction(Instruction *Instr);
327 /// Create a broadcast instruction. This method generates a broadcast
328 /// instruction (shuffle) for loop invariant values and for the induction
329 /// value. If this is the induction variable then we extend it to N, N+1, ...
330 /// this is needed because each iteration in the loop corresponds to a SIMD
332 virtual Value *getBroadcastInstrs(Value *V);
334 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
335 /// to each vector element of Val. The sequence starts at StartIndex.
336 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
338 /// When we go over instructions in the basic block we rely on previous
339 /// values within the current basic block or on loop invariant values.
340 /// When we widen (vectorize) values we place them in the map. If the values
341 /// are not within the map, they have to be loop invariant, so we simply
342 /// broadcast them into a vector.
343 VectorParts &getVectorValue(Value *V);
345 /// Generate a shuffle sequence that will reverse the vector Vec.
346 virtual Value *reverseVector(Value *Vec);
348 /// This is a helper class that holds the vectorizer state. It maps scalar
349 /// instructions to vector instructions. When the code is 'unrolled' then
350 /// then a single scalar value is mapped to multiple vector parts. The parts
351 /// are stored in the VectorPart type.
353 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
355 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
357 /// \return True if 'Key' is saved in the Value Map.
358 bool has(Value *Key) const { return MapStorage.count(Key); }
360 /// Initializes a new entry in the map. Sets all of the vector parts to the
361 /// save value in 'Val'.
362 /// \return A reference to a vector with splat values.
363 VectorParts &splat(Value *Key, Value *Val) {
364 VectorParts &Entry = MapStorage[Key];
365 Entry.assign(UF, Val);
369 ///\return A reference to the value that is stored at 'Key'.
370 VectorParts &get(Value *Key) {
371 VectorParts &Entry = MapStorage[Key];
374 assert(Entry.size() == UF);
379 /// The unroll factor. Each entry in the map stores this number of vector
383 /// Map storage. We use std::map and not DenseMap because insertions to a
384 /// dense map invalidates its iterators.
385 std::map<Value *, VectorParts> MapStorage;
388 /// The original loop.
390 /// Scev analysis to use.
399 const DataLayout *DL;
400 /// Target Library Info.
401 const TargetLibraryInfo *TLI;
403 /// The vectorization SIMD factor to use. Each vector will have this many
408 /// The vectorization unroll factor to use. Each scalar is vectorized to this
409 /// many different vector instructions.
412 /// The builder that we use
415 // --- Vectorization state ---
417 /// The vector-loop preheader.
418 BasicBlock *LoopVectorPreHeader;
419 /// The scalar-loop preheader.
420 BasicBlock *LoopScalarPreHeader;
421 /// Middle Block between the vector and the scalar.
422 BasicBlock *LoopMiddleBlock;
423 ///The ExitBlock of the scalar loop.
424 BasicBlock *LoopExitBlock;
425 ///The vector loop body.
426 SmallVector<BasicBlock *, 4> LoopVectorBody;
427 ///The scalar loop body.
428 BasicBlock *LoopScalarBody;
429 /// A list of all bypass blocks. The first block is the entry of the loop.
430 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
432 /// The new Induction variable which was added to the new block.
434 /// The induction variable of the old basic block.
435 PHINode *OldInduction;
436 /// Holds the extended (to the widest induction type) start index.
438 /// Maps scalars to widened vectors.
440 EdgeMaskCache MaskCache;
442 LoopVectorizationLegality *Legal;
445 class InnerLoopUnroller : public InnerLoopVectorizer {
447 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
448 DominatorTree *DT, const DataLayout *DL,
449 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
450 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
453 void scalarizeInstruction(Instruction *Instr,
454 bool IfPredicateStore = false) override;
455 void vectorizeMemoryInstruction(Instruction *Instr) override;
456 Value *getBroadcastInstrs(Value *V) override;
457 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
458 Value *reverseVector(Value *Vec) override;
461 /// \brief Look for a meaningful debug location on the instruction or it's
463 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
468 if (I->getDebugLoc() != Empty)
471 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
472 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
473 if (OpInst->getDebugLoc() != Empty)
480 /// \brief Set the debug location in the builder using the debug location in the
482 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
483 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
484 B.SetCurrentDebugLocation(Inst->getDebugLoc());
486 B.SetCurrentDebugLocation(DebugLoc());
490 /// \return string containing a file name and a line # for the given loop.
491 static std::string getDebugLocString(const Loop *L) {
494 raw_string_ostream OS(Result);
495 const DebugLoc LoopDbgLoc = L->getStartLoc();
496 if (!LoopDbgLoc.isUnknown())
497 LoopDbgLoc.print(L->getHeader()->getContext(), OS);
499 // Just print the module name.
500 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
507 /// \brief Propagate known metadata from one instruction to another.
508 static void propagateMetadata(Instruction *To, const Instruction *From) {
509 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
510 From->getAllMetadataOtherThanDebugLoc(Metadata);
512 for (auto M : Metadata) {
513 unsigned Kind = M.first;
515 // These are safe to transfer (this is safe for TBAA, even when we
516 // if-convert, because should that metadata have had a control dependency
517 // on the condition, and thus actually aliased with some other
518 // non-speculated memory access when the condition was false, this would be
519 // caught by the runtime overlap checks).
520 if (Kind != LLVMContext::MD_tbaa &&
521 Kind != LLVMContext::MD_alias_scope &&
522 Kind != LLVMContext::MD_noalias &&
523 Kind != LLVMContext::MD_fpmath)
526 To->setMetadata(Kind, M.second);
530 /// \brief Propagate known metadata from one instruction to a vector of others.
531 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
533 if (Instruction *I = dyn_cast<Instruction>(V))
534 propagateMetadata(I, From);
537 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
538 /// to what vectorization factor.
539 /// This class does not look at the profitability of vectorization, only the
540 /// legality. This class has two main kinds of checks:
541 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
542 /// will change the order of memory accesses in a way that will change the
543 /// correctness of the program.
544 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
545 /// checks for a number of different conditions, such as the availability of a
546 /// single induction variable, that all types are supported and vectorize-able,
547 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
548 /// This class is also used by InnerLoopVectorizer for identifying
549 /// induction variable and the different reduction variables.
550 class LoopVectorizationLegality {
552 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
553 DominatorTree *DT, TargetLibraryInfo *TLI,
554 AliasAnalysis *AA, Function *F,
555 const TargetTransformInfo *TTI)
556 : NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
557 TLI(TLI), TheFunction(F), TTI(TTI), Induction(nullptr),
558 WidestIndTy(nullptr),
559 LAI(L, SE, DL, TLI, AA, DT),
560 HasFunNoNaNAttr(false) {}
562 /// This enum represents the kinds of reductions that we support.
564 RK_NoReduction, ///< Not a reduction.
565 RK_IntegerAdd, ///< Sum of integers.
566 RK_IntegerMult, ///< Product of integers.
567 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
568 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
569 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
570 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
571 RK_FloatAdd, ///< Sum of floats.
572 RK_FloatMult, ///< Product of floats.
573 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
576 /// This enum represents the kinds of inductions that we support.
578 IK_NoInduction, ///< Not an induction variable.
579 IK_IntInduction, ///< Integer induction variable. Step = C.
580 IK_PtrInduction ///< Pointer induction var. Step = C / sizeof(elem).
583 // This enum represents the kind of minmax reduction.
584 enum MinMaxReductionKind {
594 /// This struct holds information about reduction variables.
595 struct ReductionDescriptor {
596 ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
597 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
599 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
600 MinMaxReductionKind MK)
601 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
603 // The starting value of the reduction.
604 // It does not have to be zero!
605 TrackingVH<Value> StartValue;
606 // The instruction who's value is used outside the loop.
607 Instruction *LoopExitInstr;
608 // The kind of the reduction.
610 // If this a min/max reduction the kind of reduction.
611 MinMaxReductionKind MinMaxKind;
614 /// This POD struct holds information about a potential reduction operation.
615 struct ReductionInstDesc {
616 ReductionInstDesc(bool IsRedux, Instruction *I) :
617 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
619 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
620 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
622 // Is this instruction a reduction candidate.
624 // The last instruction in a min/max pattern (select of the select(icmp())
625 // pattern), or the current reduction instruction otherwise.
626 Instruction *PatternLastInst;
627 // If this is a min/max pattern the comparison predicate.
628 MinMaxReductionKind MinMaxKind;
631 /// A struct for saving information about induction variables.
632 struct InductionInfo {
633 InductionInfo(Value *Start, InductionKind K, ConstantInt *Step)
634 : StartValue(Start), IK(K), StepValue(Step) {
635 assert(IK != IK_NoInduction && "Not an induction");
636 assert(StartValue && "StartValue is null");
637 assert(StepValue && !StepValue->isZero() && "StepValue is zero");
638 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
639 "StartValue is not a pointer for pointer induction");
640 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
641 "StartValue is not an integer for integer induction");
642 assert(StepValue->getType()->isIntegerTy() &&
643 "StepValue is not an integer");
646 : StartValue(nullptr), IK(IK_NoInduction), StepValue(nullptr) {}
648 /// Get the consecutive direction. Returns:
649 /// 0 - unknown or non-consecutive.
650 /// 1 - consecutive and increasing.
651 /// -1 - consecutive and decreasing.
652 int getConsecutiveDirection() const {
653 if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
654 return StepValue->getSExtValue();
658 /// Compute the transformed value of Index at offset StartValue using step
660 /// For integer induction, returns StartValue + Index * StepValue.
661 /// For pointer induction, returns StartValue[Index * StepValue].
662 /// FIXME: The newly created binary instructions should contain nsw/nuw
663 /// flags, which can be found from the original scalar operations.
664 Value *transform(IRBuilder<> &B, Value *Index) const {
666 case IK_IntInduction:
667 assert(Index->getType() == StartValue->getType() &&
668 "Index type does not match StartValue type");
669 if (StepValue->isMinusOne())
670 return B.CreateSub(StartValue, Index);
671 if (!StepValue->isOne())
672 Index = B.CreateMul(Index, StepValue);
673 return B.CreateAdd(StartValue, Index);
675 case IK_PtrInduction:
676 if (StepValue->isMinusOne())
677 Index = B.CreateNeg(Index);
678 else if (!StepValue->isOne())
679 Index = B.CreateMul(Index, StepValue);
680 return B.CreateGEP(StartValue, Index);
685 llvm_unreachable("invalid enum");
689 TrackingVH<Value> StartValue;
693 ConstantInt *StepValue;
696 /// ReductionList contains the reduction descriptors for all
697 /// of the reductions that were found in the loop.
698 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
700 /// InductionList saves induction variables and maps them to the
701 /// induction descriptor.
702 typedef MapVector<PHINode*, InductionInfo> InductionList;
704 /// Returns true if it is legal to vectorize this loop.
705 /// This does not mean that it is profitable to vectorize this
706 /// loop, only that it is legal to do so.
709 /// Returns the Induction variable.
710 PHINode *getInduction() { return Induction; }
712 /// Returns the reduction variables found in the loop.
713 ReductionList *getReductionVars() { return &Reductions; }
715 /// Returns the induction variables found in the loop.
716 InductionList *getInductionVars() { return &Inductions; }
718 /// Returns the widest induction type.
719 Type *getWidestInductionType() { return WidestIndTy; }
721 /// Returns True if V is an induction variable in this loop.
722 bool isInductionVariable(const Value *V);
724 /// Return true if the block BB needs to be predicated in order for the loop
725 /// to be vectorized.
726 bool blockNeedsPredication(BasicBlock *BB);
728 /// Check if this pointer is consecutive when vectorizing. This happens
729 /// when the last index of the GEP is the induction variable, or that the
730 /// pointer itself is an induction variable.
731 /// This check allows us to vectorize A[idx] into a wide load/store.
733 /// 0 - Stride is unknown or non-consecutive.
734 /// 1 - Address is consecutive.
735 /// -1 - Address is consecutive, and decreasing.
736 int isConsecutivePtr(Value *Ptr);
738 /// Returns true if the value V is uniform within the loop.
739 bool isUniform(Value *V);
741 /// Returns true if this instruction will remain scalar after vectorization.
742 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
744 /// Returns the information that we collected about runtime memory check.
745 LoopAccessInfo::RuntimePointerCheck *getRuntimePointerCheck() {
746 return LAI.getRuntimePointerCheck();
749 LoopAccessInfo *getLAI() {
753 /// This function returns the identity element (or neutral element) for
755 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
757 unsigned getMaxSafeDepDistBytes() { return LAI.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 {
782 return LAI.getNumStores();
784 unsigned getNumLoads() const {
785 return LAI.getNumLoads();
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);
844 unsigned NumPredStores;
846 /// The loop that we evaluate.
850 /// DataLayout analysis.
851 const DataLayout *DL;
852 /// Target Library Info.
853 TargetLibraryInfo *TLI;
855 Function *TheFunction;
856 /// Target Transform Info
857 const TargetTransformInfo *TTI;
859 // --- vectorization state --- //
861 /// Holds the integer induction variable. This is the counter of the
864 /// Holds the reduction variables.
865 ReductionList Reductions;
866 /// Holds all of the induction variables that we found in the loop.
867 /// Notice that inductions don't need to start at zero and that induction
868 /// variables can be pointers.
869 InductionList Inductions;
870 /// Holds the widest induction type encountered.
873 /// Allowed outside users. This holds the reduction
874 /// vars which can be accessed from outside the loop.
875 SmallPtrSet<Value*, 4> AllowedExit;
876 /// This set holds the variables which are known to be uniform after
878 SmallPtrSet<Instruction*, 4> Uniforms;
880 /// Can we assume the absence of NaNs.
881 bool HasFunNoNaNAttr;
883 ValueToValueMap Strides;
884 SmallPtrSet<Value *, 8> StrideSet;
886 /// While vectorizing these instructions we have to generate a
887 /// call to the appropriate masked intrinsic
888 SmallPtrSet<const Instruction*, 8> MaskedOp;
891 /// LoopVectorizationCostModel - estimates the expected speedups due to
893 /// In many cases vectorization is not profitable. This can happen because of
894 /// a number of reasons. In this class we mainly attempt to predict the
895 /// expected speedup/slowdowns due to the supported instruction set. We use the
896 /// TargetTransformInfo to query the different backends for the cost of
897 /// different operations.
898 class LoopVectorizationCostModel {
900 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
901 LoopVectorizationLegality *Legal,
902 const TargetTransformInfo &TTI,
903 const DataLayout *DL, const TargetLibraryInfo *TLI,
904 AssumptionCache *AC, const Function *F,
905 const LoopVectorizeHints *Hints)
906 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI),
907 TheFunction(F), Hints(Hints) {
908 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
911 /// Information about vectorization costs
912 struct VectorizationFactor {
913 unsigned Width; // Vector width with best cost
914 unsigned Cost; // Cost of the loop with that width
916 /// \return The most profitable vectorization factor and the cost of that VF.
917 /// This method checks every power of two up to VF. If UserVF is not ZERO
918 /// then this vectorization factor will be selected if vectorization is
920 VectorizationFactor selectVectorizationFactor(bool OptForSize);
922 /// \return The size (in bits) of the widest type in the code that
923 /// needs to be vectorized. We ignore values that remain scalar such as
924 /// 64 bit loop indices.
925 unsigned getWidestType();
927 /// \return The most profitable unroll factor.
928 /// If UserUF is non-zero then this method finds the best unroll-factor
929 /// based on register pressure and other parameters.
930 /// VF and LoopCost are the selected vectorization factor and the cost of the
932 unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost);
934 /// \brief A struct that represents some properties of the register usage
936 struct RegisterUsage {
937 /// Holds the number of loop invariant values that are used in the loop.
938 unsigned LoopInvariantRegs;
939 /// Holds the maximum number of concurrent live intervals in the loop.
940 unsigned MaxLocalUsers;
941 /// Holds the number of instructions in the loop.
942 unsigned NumInstructions;
945 /// \return information about the register usage of the loop.
946 RegisterUsage calculateRegisterUsage();
949 /// Returns the expected execution cost. The unit of the cost does
950 /// not matter because we use the 'cost' units to compare different
951 /// vector widths. The cost that is returned is *not* normalized by
952 /// the factor width.
953 unsigned expectedCost(unsigned VF);
955 /// Returns the execution time cost of an instruction for a given vector
956 /// width. Vector width of one means scalar.
957 unsigned getInstructionCost(Instruction *I, unsigned VF);
959 /// A helper function for converting Scalar types to vector types.
960 /// If the incoming type is void, we return void. If the VF is 1, we return
962 static Type* ToVectorTy(Type *Scalar, unsigned VF);
964 /// Returns whether the instruction is a load or store and will be a emitted
965 /// as a vector operation.
966 bool isConsecutiveLoadOrStore(Instruction *I);
968 /// Report an analysis message to assist the user in diagnosing loops that are
970 void emitAnalysis(VectorizationReport &Message) {
971 VectorizationReport::emitAnalysis(Message, TheFunction, TheLoop);
974 /// Values used only by @llvm.assume calls.
975 SmallPtrSet<const Value *, 32> EphValues;
977 /// The loop that we evaluate.
981 /// Loop Info analysis.
983 /// Vectorization legality.
984 LoopVectorizationLegality *Legal;
985 /// Vector target information.
986 const TargetTransformInfo &TTI;
987 /// Target data layout information.
988 const DataLayout *DL;
989 /// Target Library Info.
990 const TargetLibraryInfo *TLI;
991 const Function *TheFunction;
992 // Loop Vectorize Hint.
993 const LoopVectorizeHints *Hints;
996 /// Utility class for getting and setting loop vectorizer hints in the form
997 /// of loop metadata.
998 /// This class keeps a number of loop annotations locally (as member variables)
999 /// and can, upon request, write them back as metadata on the loop. It will
1000 /// initially scan the loop for existing metadata, and will update the local
1001 /// values based on information in the loop.
1002 /// We cannot write all values to metadata, as the mere presence of some info,
1003 /// for example 'force', means a decision has been made. So, we need to be
1004 /// careful NOT to add them if the user hasn't specifically asked so.
1005 class LoopVectorizeHints {
1012 /// Hint - associates name and validation with the hint value.
1015 unsigned Value; // This may have to change for non-numeric values.
1018 Hint(const char * Name, unsigned Value, HintKind Kind)
1019 : Name(Name), Value(Value), Kind(Kind) { }
1021 bool validate(unsigned Val) {
1024 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
1026 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1034 /// Vectorization width.
1036 /// Vectorization interleave factor.
1038 /// Vectorization forced
1041 /// Return the loop metadata prefix.
1042 static StringRef Prefix() { return "llvm.loop."; }
1046 FK_Undefined = -1, ///< Not selected.
1047 FK_Disabled = 0, ///< Forcing disabled.
1048 FK_Enabled = 1, ///< Forcing enabled.
1051 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1052 : Width("vectorize.width", VectorizationFactor, HK_WIDTH),
1053 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1054 Force("vectorize.enable", FK_Undefined, HK_FORCE),
1056 // Populate values with existing loop metadata.
1057 getHintsFromMetadata();
1059 // force-vector-interleave overrides DisableInterleaving.
1060 if (VectorizationInterleave.getNumOccurrences() > 0)
1061 Interleave.Value = VectorizationInterleave;
1063 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1064 << "LV: Interleaving disabled by the pass manager\n");
1067 /// Mark the loop L as already vectorized by setting the width to 1.
1068 void setAlreadyVectorized() {
1069 Width.Value = Interleave.Value = 1;
1070 Hint Hints[] = {Width, Interleave};
1071 writeHintsToMetadata(Hints);
1074 /// Dumps all the hint information.
1075 std::string emitRemark() const {
1076 VectorizationReport R;
1077 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1078 R << "vectorization is explicitly disabled";
1080 R << "use -Rpass-analysis=loop-vectorize for more info";
1081 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1082 R << " (Force=true";
1083 if (Width.Value != 0)
1084 R << ", Vector Width=" << Width.Value;
1085 if (Interleave.Value != 0)
1086 R << ", Interleave Count=" << Interleave.Value;
1094 unsigned getWidth() const { return Width.Value; }
1095 unsigned getInterleave() const { return Interleave.Value; }
1096 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1099 /// Find hints specified in the loop metadata and update local values.
1100 void getHintsFromMetadata() {
1101 MDNode *LoopID = TheLoop->getLoopID();
1105 // First operand should refer to the loop id itself.
1106 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1107 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1109 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1110 const MDString *S = nullptr;
1111 SmallVector<Metadata *, 4> Args;
1113 // The expected hint is either a MDString or a MDNode with the first
1114 // operand a MDString.
1115 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1116 if (!MD || MD->getNumOperands() == 0)
1118 S = dyn_cast<MDString>(MD->getOperand(0));
1119 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1120 Args.push_back(MD->getOperand(i));
1122 S = dyn_cast<MDString>(LoopID->getOperand(i));
1123 assert(Args.size() == 0 && "too many arguments for MDString");
1129 // Check if the hint starts with the loop metadata prefix.
1130 StringRef Name = S->getString();
1131 if (Args.size() == 1)
1132 setHint(Name, Args[0]);
1136 /// Checks string hint with one operand and set value if valid.
1137 void setHint(StringRef Name, Metadata *Arg) {
1138 if (!Name.startswith(Prefix()))
1140 Name = Name.substr(Prefix().size(), StringRef::npos);
1142 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1144 unsigned Val = C->getZExtValue();
1146 Hint *Hints[] = {&Width, &Interleave, &Force};
1147 for (auto H : Hints) {
1148 if (Name == H->Name) {
1149 if (H->validate(Val))
1152 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1158 /// Create a new hint from name / value pair.
1159 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1160 LLVMContext &Context = TheLoop->getHeader()->getContext();
1161 Metadata *MDs[] = {MDString::get(Context, Name),
1162 ConstantAsMetadata::get(
1163 ConstantInt::get(Type::getInt32Ty(Context), V))};
1164 return MDNode::get(Context, MDs);
1167 /// Matches metadata with hint name.
1168 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1169 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1173 for (auto H : HintTypes)
1174 if (Name->getString().endswith(H.Name))
1179 /// Sets current hints into loop metadata, keeping other values intact.
1180 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1181 if (HintTypes.size() == 0)
1184 // Reserve the first element to LoopID (see below).
1185 SmallVector<Metadata *, 4> MDs(1);
1186 // If the loop already has metadata, then ignore the existing operands.
1187 MDNode *LoopID = TheLoop->getLoopID();
1189 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1190 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1191 // If node in update list, ignore old value.
1192 if (!matchesHintMetadataName(Node, HintTypes))
1193 MDs.push_back(Node);
1197 // Now, add the missing hints.
1198 for (auto H : HintTypes)
1199 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1201 // Replace current metadata node with new one.
1202 LLVMContext &Context = TheLoop->getHeader()->getContext();
1203 MDNode *NewLoopID = MDNode::get(Context, MDs);
1204 // Set operand 0 to refer to the loop id itself.
1205 NewLoopID->replaceOperandWith(0, NewLoopID);
1207 TheLoop->setLoopID(NewLoopID);
1210 /// The loop these hints belong to.
1211 const Loop *TheLoop;
1214 static void emitMissedWarning(Function *F, Loop *L,
1215 const LoopVectorizeHints &LH) {
1216 emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1217 L->getStartLoc(), LH.emitRemark());
1219 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1220 if (LH.getWidth() != 1)
1221 emitLoopVectorizeWarning(
1222 F->getContext(), *F, L->getStartLoc(),
1223 "failed explicitly specified loop vectorization");
1224 else if (LH.getInterleave() != 1)
1225 emitLoopInterleaveWarning(
1226 F->getContext(), *F, L->getStartLoc(),
1227 "failed explicitly specified loop interleaving");
1231 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1233 return V.push_back(&L);
1235 for (Loop *InnerL : L)
1236 addInnerLoop(*InnerL, V);
1239 /// The LoopVectorize Pass.
1240 struct LoopVectorize : public FunctionPass {
1241 /// Pass identification, replacement for typeid
1244 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1246 DisableUnrolling(NoUnrolling),
1247 AlwaysVectorize(AlwaysVectorize) {
1248 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1251 ScalarEvolution *SE;
1252 const DataLayout *DL;
1254 TargetTransformInfo *TTI;
1256 BlockFrequencyInfo *BFI;
1257 TargetLibraryInfo *TLI;
1259 AssumptionCache *AC;
1260 bool DisableUnrolling;
1261 bool AlwaysVectorize;
1263 BlockFrequency ColdEntryFreq;
1265 bool runOnFunction(Function &F) override {
1266 SE = &getAnalysis<ScalarEvolution>();
1267 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1268 DL = DLP ? &DLP->getDataLayout() : nullptr;
1269 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1270 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1271 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1272 BFI = &getAnalysis<BlockFrequencyInfo>();
1273 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1274 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1275 AA = &getAnalysis<AliasAnalysis>();
1276 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1278 // Compute some weights outside of the loop over the loops. Compute this
1279 // using a BranchProbability to re-use its scaling math.
1280 const BranchProbability ColdProb(1, 5); // 20%
1281 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1283 // If the target claims to have no vector registers don't attempt
1285 if (!TTI->getNumberOfRegisters(true))
1289 DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1290 << ": Missing data layout\n");
1294 // Build up a worklist of inner-loops to vectorize. This is necessary as
1295 // the act of vectorizing or partially unrolling a loop creates new loops
1296 // and can invalidate iterators across the loops.
1297 SmallVector<Loop *, 8> Worklist;
1300 addInnerLoop(*L, Worklist);
1302 LoopsAnalyzed += Worklist.size();
1304 // Now walk the identified inner loops.
1305 bool Changed = false;
1306 while (!Worklist.empty())
1307 Changed |= processLoop(Worklist.pop_back_val());
1309 // Process each loop nest in the function.
1313 bool processLoop(Loop *L) {
1314 assert(L->empty() && "Only process inner loops.");
1317 const std::string DebugLocStr = getDebugLocString(L);
1320 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1321 << L->getHeader()->getParent()->getName() << "\" from "
1322 << DebugLocStr << "\n");
1324 LoopVectorizeHints Hints(L, DisableUnrolling);
1326 DEBUG(dbgs() << "LV: Loop hints:"
1328 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1330 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1332 : "?")) << " width=" << Hints.getWidth()
1333 << " unroll=" << Hints.getInterleave() << "\n");
1335 // Function containing loop
1336 Function *F = L->getHeader()->getParent();
1338 // Looking at the diagnostic output is the only way to determine if a loop
1339 // was vectorized (other than looking at the IR or machine code), so it
1340 // is important to generate an optimization remark for each loop. Most of
1341 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1342 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1343 // less verbose reporting vectorized loops and unvectorized loops that may
1344 // benefit from vectorization, respectively.
1346 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1347 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1348 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1349 L->getStartLoc(), Hints.emitRemark());
1353 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1354 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1355 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1356 L->getStartLoc(), Hints.emitRemark());
1360 if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
1361 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1362 emitOptimizationRemarkAnalysis(
1363 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1364 "loop not vectorized: vector width and interleave count are "
1365 "explicitly set to 1");
1369 // Check the loop for a trip count threshold:
1370 // do not vectorize loops with a tiny trip count.
1371 const unsigned TC = SE->getSmallConstantTripCount(L);
1372 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1373 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1374 << "This loop is not worth vectorizing.");
1375 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1376 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1378 DEBUG(dbgs() << "\n");
1379 emitOptimizationRemarkAnalysis(
1380 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1381 "vectorization is not beneficial and is not explicitly forced");
1386 // Check if it is legal to vectorize the loop.
1387 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI, AA, F, TTI);
1388 if (!LVL.canVectorize()) {
1389 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1390 emitMissedWarning(F, L, Hints);
1394 // Use the cost model.
1395 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI, AC, F,
1398 // Check the function attributes to find out if this function should be
1399 // optimized for size.
1400 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1401 F->hasFnAttribute(Attribute::OptimizeForSize);
1403 // Compute the weighted frequency of this loop being executed and see if it
1404 // is less than 20% of the function entry baseline frequency. Note that we
1405 // always have a canonical loop here because we think we *can* vectoriez.
1406 // FIXME: This is hidden behind a flag due to pervasive problems with
1407 // exactly what block frequency models.
1408 if (LoopVectorizeWithBlockFrequency) {
1409 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1410 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1411 LoopEntryFreq < ColdEntryFreq)
1415 // Check the function attributes to see if implicit floats are allowed.a
1416 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1417 // an integer loop and the vector instructions selected are purely integer
1418 // vector instructions?
1419 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1420 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1421 "attribute is used.\n");
1422 emitOptimizationRemarkAnalysis(
1423 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1424 "loop not vectorized due to NoImplicitFloat attribute");
1425 emitMissedWarning(F, L, Hints);
1429 // Select the optimal vectorization factor.
1430 const LoopVectorizationCostModel::VectorizationFactor VF =
1431 CM.selectVectorizationFactor(OptForSize);
1433 // Select the unroll factor.
1435 CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
1437 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1438 << DebugLocStr << '\n');
1439 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1441 if (VF.Width == 1) {
1442 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
1445 emitOptimizationRemarkAnalysis(
1446 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1447 "not beneficial to vectorize and user disabled interleaving");
1450 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1452 // Report the unrolling decision.
1453 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1454 Twine("unrolled with interleaving factor " +
1456 " (vectorization not beneficial)"));
1458 // We decided not to vectorize, but we may want to unroll.
1460 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1461 Unroller.vectorize(&LVL);
1463 // If we decided that it is *legal* to vectorize the loop then do it.
1464 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1468 // Report the vectorization decision.
1469 emitOptimizationRemark(
1470 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1471 Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1472 ", unrolling interleave factor: " + Twine(UF) + ")");
1475 // Mark the loop as already vectorized to avoid vectorizing again.
1476 Hints.setAlreadyVectorized();
1478 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1482 void getAnalysisUsage(AnalysisUsage &AU) const override {
1483 AU.addRequired<AssumptionCacheTracker>();
1484 AU.addRequiredID(LoopSimplifyID);
1485 AU.addRequiredID(LCSSAID);
1486 AU.addRequired<BlockFrequencyInfo>();
1487 AU.addRequired<DominatorTreeWrapperPass>();
1488 AU.addRequired<LoopInfoWrapperPass>();
1489 AU.addRequired<ScalarEvolution>();
1490 AU.addRequired<TargetTransformInfoWrapperPass>();
1491 AU.addRequired<AliasAnalysis>();
1492 AU.addPreserved<LoopInfoWrapperPass>();
1493 AU.addPreserved<DominatorTreeWrapperPass>();
1494 AU.addPreserved<AliasAnalysis>();
1499 } // end anonymous namespace
1501 //===----------------------------------------------------------------------===//
1502 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1503 // LoopVectorizationCostModel.
1504 //===----------------------------------------------------------------------===//
1506 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1507 // We need to place the broadcast of invariant variables outside the loop.
1508 Instruction *Instr = dyn_cast<Instruction>(V);
1510 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1511 Instr->getParent()) != LoopVectorBody.end());
1512 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1514 // Place the code for broadcasting invariant variables in the new preheader.
1515 IRBuilder<>::InsertPointGuard Guard(Builder);
1517 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1519 // Broadcast the scalar into all locations in the vector.
1520 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1525 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1527 assert(Val->getType()->isVectorTy() && "Must be a vector");
1528 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1529 "Elem must be an integer");
1530 assert(Step->getType() == Val->getType()->getScalarType() &&
1531 "Step has wrong type");
1532 // Create the types.
1533 Type *ITy = Val->getType()->getScalarType();
1534 VectorType *Ty = cast<VectorType>(Val->getType());
1535 int VLen = Ty->getNumElements();
1536 SmallVector<Constant*, 8> Indices;
1538 // Create a vector of consecutive numbers from zero to VF.
1539 for (int i = 0; i < VLen; ++i)
1540 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1542 // Add the consecutive indices to the vector value.
1543 Constant *Cv = ConstantVector::get(Indices);
1544 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1545 Step = Builder.CreateVectorSplat(VLen, Step);
1546 assert(Step->getType() == Val->getType() && "Invalid step vec");
1547 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1548 // which can be found from the original scalar operations.
1549 Step = Builder.CreateMul(Cv, Step);
1550 return Builder.CreateAdd(Val, Step, "induction");
1553 /// \brief Find the operand of the GEP that should be checked for consecutive
1554 /// stores. This ignores trailing indices that have no effect on the final
1556 static unsigned getGEPInductionOperand(const DataLayout *DL,
1557 const GetElementPtrInst *Gep) {
1558 unsigned LastOperand = Gep->getNumOperands() - 1;
1559 unsigned GEPAllocSize = DL->getTypeAllocSize(
1560 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1562 // Walk backwards and try to peel off zeros.
1563 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1564 // Find the type we're currently indexing into.
1565 gep_type_iterator GEPTI = gep_type_begin(Gep);
1566 std::advance(GEPTI, LastOperand - 1);
1568 // If it's a type with the same allocation size as the result of the GEP we
1569 // can peel off the zero index.
1570 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1578 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1579 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1580 // Make sure that the pointer does not point to structs.
1581 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1584 // If this value is a pointer induction variable we know it is consecutive.
1585 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1586 if (Phi && Inductions.count(Phi)) {
1587 InductionInfo II = Inductions[Phi];
1588 return II.getConsecutiveDirection();
1591 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1595 unsigned NumOperands = Gep->getNumOperands();
1596 Value *GpPtr = Gep->getPointerOperand();
1597 // If this GEP value is a consecutive pointer induction variable and all of
1598 // the indices are constant then we know it is consecutive. We can
1599 Phi = dyn_cast<PHINode>(GpPtr);
1600 if (Phi && Inductions.count(Phi)) {
1602 // Make sure that the pointer does not point to structs.
1603 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1604 if (GepPtrType->getElementType()->isAggregateType())
1607 // Make sure that all of the index operands are loop invariant.
1608 for (unsigned i = 1; i < NumOperands; ++i)
1609 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1612 InductionInfo II = Inductions[Phi];
1613 return II.getConsecutiveDirection();
1616 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1618 // Check that all of the gep indices are uniform except for our induction
1620 for (unsigned i = 0; i != NumOperands; ++i)
1621 if (i != InductionOperand &&
1622 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1625 // We can emit wide load/stores only if the last non-zero index is the
1626 // induction variable.
1627 const SCEV *Last = nullptr;
1628 if (!Strides.count(Gep))
1629 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1631 // Because of the multiplication by a stride we can have a s/zext cast.
1632 // We are going to replace this stride by 1 so the cast is safe to ignore.
1634 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1635 // %0 = trunc i64 %indvars.iv to i32
1636 // %mul = mul i32 %0, %Stride1
1637 // %idxprom = zext i32 %mul to i64 << Safe cast.
1638 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1640 Last = replaceSymbolicStrideSCEV(SE, Strides,
1641 Gep->getOperand(InductionOperand), Gep);
1642 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1644 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1648 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1649 const SCEV *Step = AR->getStepRecurrence(*SE);
1651 // The memory is consecutive because the last index is consecutive
1652 // and all other indices are loop invariant.
1655 if (Step->isAllOnesValue())
1662 bool LoopVectorizationLegality::isUniform(Value *V) {
1663 return LAI.isUniform(V);
1666 InnerLoopVectorizer::VectorParts&
1667 InnerLoopVectorizer::getVectorValue(Value *V) {
1668 assert(V != Induction && "The new induction variable should not be used.");
1669 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1671 // If we have a stride that is replaced by one, do it here.
1672 if (Legal->hasStride(V))
1673 V = ConstantInt::get(V->getType(), 1);
1675 // If we have this scalar in the map, return it.
1676 if (WidenMap.has(V))
1677 return WidenMap.get(V);
1679 // If this scalar is unknown, assume that it is a constant or that it is
1680 // loop invariant. Broadcast V and save the value for future uses.
1681 Value *B = getBroadcastInstrs(V);
1682 return WidenMap.splat(V, B);
1685 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1686 assert(Vec->getType()->isVectorTy() && "Invalid type");
1687 SmallVector<Constant*, 8> ShuffleMask;
1688 for (unsigned i = 0; i < VF; ++i)
1689 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1691 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1692 ConstantVector::get(ShuffleMask),
1696 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1697 // Attempt to issue a wide load.
1698 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1699 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1701 assert((LI || SI) && "Invalid Load/Store instruction");
1703 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1704 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1705 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1706 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1707 // An alignment of 0 means target abi alignment. We need to use the scalar's
1708 // target abi alignment in such a case.
1710 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1711 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1712 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1713 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1715 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
1716 !Legal->isMaskRequired(SI))
1717 return scalarizeInstruction(Instr, true);
1719 if (ScalarAllocatedSize != VectorElementSize)
1720 return scalarizeInstruction(Instr);
1722 // If the pointer is loop invariant or if it is non-consecutive,
1723 // scalarize the load.
1724 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1725 bool Reverse = ConsecutiveStride < 0;
1726 bool UniformLoad = LI && Legal->isUniform(Ptr);
1727 if (!ConsecutiveStride || UniformLoad)
1728 return scalarizeInstruction(Instr);
1730 Constant *Zero = Builder.getInt32(0);
1731 VectorParts &Entry = WidenMap.get(Instr);
1733 // Handle consecutive loads/stores.
1734 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1735 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1736 setDebugLocFromInst(Builder, Gep);
1737 Value *PtrOperand = Gep->getPointerOperand();
1738 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1739 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1741 // Create the new GEP with the new induction variable.
1742 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1743 Gep2->setOperand(0, FirstBasePtr);
1744 Gep2->setName("gep.indvar.base");
1745 Ptr = Builder.Insert(Gep2);
1747 setDebugLocFromInst(Builder, Gep);
1748 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1749 OrigLoop) && "Base ptr must be invariant");
1751 // The last index does not have to be the induction. It can be
1752 // consecutive and be a function of the index. For example A[I+1];
1753 unsigned NumOperands = Gep->getNumOperands();
1754 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1755 // Create the new GEP with the new induction variable.
1756 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1758 for (unsigned i = 0; i < NumOperands; ++i) {
1759 Value *GepOperand = Gep->getOperand(i);
1760 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1762 // Update last index or loop invariant instruction anchored in loop.
1763 if (i == InductionOperand ||
1764 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1765 assert((i == InductionOperand ||
1766 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1767 "Must be last index or loop invariant");
1769 VectorParts &GEPParts = getVectorValue(GepOperand);
1770 Value *Index = GEPParts[0];
1771 Index = Builder.CreateExtractElement(Index, Zero);
1772 Gep2->setOperand(i, Index);
1773 Gep2->setName("gep.indvar.idx");
1776 Ptr = Builder.Insert(Gep2);
1778 // Use the induction element ptr.
1779 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1780 setDebugLocFromInst(Builder, Ptr);
1781 VectorParts &PtrVal = getVectorValue(Ptr);
1782 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1785 VectorParts Mask = createBlockInMask(Instr->getParent());
1788 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1789 "We do not allow storing to uniform addresses");
1790 setDebugLocFromInst(Builder, SI);
1791 // We don't want to update the value in the map as it might be used in
1792 // another expression. So don't use a reference type for "StoredVal".
1793 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1795 for (unsigned Part = 0; Part < UF; ++Part) {
1796 // Calculate the pointer for the specific unroll-part.
1797 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1800 // If we store to reverse consecutive memory locations then we need
1801 // to reverse the order of elements in the stored value.
1802 StoredVal[Part] = reverseVector(StoredVal[Part]);
1803 // If the address is consecutive but reversed, then the
1804 // wide store needs to start at the last vector element.
1805 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1806 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1807 Mask[Part] = reverseVector(Mask[Part]);
1810 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1811 DataTy->getPointerTo(AddressSpace));
1814 if (Legal->isMaskRequired(SI))
1815 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
1818 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
1819 propagateMetadata(NewSI, SI);
1825 assert(LI && "Must have a load instruction");
1826 setDebugLocFromInst(Builder, LI);
1827 for (unsigned Part = 0; Part < UF; ++Part) {
1828 // Calculate the pointer for the specific unroll-part.
1829 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1832 // If the address is consecutive but reversed, then the
1833 // wide load needs to start at the last vector element.
1834 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1835 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1836 Mask[Part] = reverseVector(Mask[Part]);
1840 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1841 DataTy->getPointerTo(AddressSpace));
1842 if (Legal->isMaskRequired(LI))
1843 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
1844 UndefValue::get(DataTy),
1845 "wide.masked.load");
1847 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
1848 propagateMetadata(NewLI, LI);
1849 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
1853 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1854 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1855 // Holds vector parameters or scalars, in case of uniform vals.
1856 SmallVector<VectorParts, 4> Params;
1858 setDebugLocFromInst(Builder, Instr);
1860 // Find all of the vectorized parameters.
1861 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1862 Value *SrcOp = Instr->getOperand(op);
1864 // If we are accessing the old induction variable, use the new one.
1865 if (SrcOp == OldInduction) {
1866 Params.push_back(getVectorValue(SrcOp));
1870 // Try using previously calculated values.
1871 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1873 // If the src is an instruction that appeared earlier in the basic block
1874 // then it should already be vectorized.
1875 if (SrcInst && OrigLoop->contains(SrcInst)) {
1876 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1877 // The parameter is a vector value from earlier.
1878 Params.push_back(WidenMap.get(SrcInst));
1880 // The parameter is a scalar from outside the loop. Maybe even a constant.
1881 VectorParts Scalars;
1882 Scalars.append(UF, SrcOp);
1883 Params.push_back(Scalars);
1887 assert(Params.size() == Instr->getNumOperands() &&
1888 "Invalid number of operands");
1890 // Does this instruction return a value ?
1891 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1893 Value *UndefVec = IsVoidRetTy ? nullptr :
1894 UndefValue::get(VectorType::get(Instr->getType(), VF));
1895 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1896 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1898 Instruction *InsertPt = Builder.GetInsertPoint();
1899 BasicBlock *IfBlock = Builder.GetInsertBlock();
1900 BasicBlock *CondBlock = nullptr;
1903 Loop *VectorLp = nullptr;
1904 if (IfPredicateStore) {
1905 assert(Instr->getParent()->getSinglePredecessor() &&
1906 "Only support single predecessor blocks");
1907 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1908 Instr->getParent());
1909 VectorLp = LI->getLoopFor(IfBlock);
1910 assert(VectorLp && "Must have a loop for this block");
1913 // For each vector unroll 'part':
1914 for (unsigned Part = 0; Part < UF; ++Part) {
1915 // For each scalar that we create:
1916 for (unsigned Width = 0; Width < VF; ++Width) {
1919 Value *Cmp = nullptr;
1920 if (IfPredicateStore) {
1921 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1922 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1923 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1924 LoopVectorBody.push_back(CondBlock);
1925 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
1926 // Update Builder with newly created basic block.
1927 Builder.SetInsertPoint(InsertPt);
1930 Instruction *Cloned = Instr->clone();
1932 Cloned->setName(Instr->getName() + ".cloned");
1933 // Replace the operands of the cloned instructions with extracted scalars.
1934 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1935 Value *Op = Params[op][Part];
1936 // Param is a vector. Need to extract the right lane.
1937 if (Op->getType()->isVectorTy())
1938 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1939 Cloned->setOperand(op, Op);
1942 // Place the cloned scalar in the new loop.
1943 Builder.Insert(Cloned);
1945 // If the original scalar returns a value we need to place it in a vector
1946 // so that future users will be able to use it.
1948 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1949 Builder.getInt32(Width));
1951 if (IfPredicateStore) {
1952 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1953 LoopVectorBody.push_back(NewIfBlock);
1954 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
1955 Builder.SetInsertPoint(InsertPt);
1956 Instruction *OldBr = IfBlock->getTerminator();
1957 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1958 OldBr->eraseFromParent();
1959 IfBlock = NewIfBlock;
1965 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1969 if (Instruction *I = dyn_cast<Instruction>(V))
1970 return I->getParent() == Loc->getParent() ? I : nullptr;
1974 std::pair<Instruction *, Instruction *>
1975 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1976 Instruction *tnullptr = nullptr;
1977 if (!Legal->mustCheckStrides())
1978 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1980 IRBuilder<> ChkBuilder(Loc);
1983 Value *Check = nullptr;
1984 Instruction *FirstInst = nullptr;
1985 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1986 SE = Legal->strides_end();
1988 Value *Ptr = stripIntegerCast(*SI);
1989 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1991 // Store the first instruction we create.
1992 FirstInst = getFirstInst(FirstInst, C, Loc);
1994 Check = ChkBuilder.CreateOr(Check, C);
1999 // We have to do this trickery because the IRBuilder might fold the check to a
2000 // constant expression in which case there is no Instruction anchored in a
2002 LLVMContext &Ctx = Loc->getContext();
2003 Instruction *TheCheck =
2004 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2005 ChkBuilder.Insert(TheCheck, "stride.not.one");
2006 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2008 return std::make_pair(FirstInst, TheCheck);
2011 void InnerLoopVectorizer::createEmptyLoop() {
2013 In this function we generate a new loop. The new loop will contain
2014 the vectorized instructions while the old loop will continue to run the
2017 [ ] <-- Back-edge taken count overflow check.
2020 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2023 || [ ] <-- vector pre header.
2027 || [ ]_| <-- vector loop.
2030 | >[ ] <--- middle-block.
2033 -|- >[ ] <--- new preheader.
2037 | [ ]_| <-- old scalar loop to handle remainder.
2040 >[ ] <-- exit block.
2044 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2045 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
2046 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2047 assert(BypassBlock && "Invalid loop structure");
2048 assert(ExitBlock && "Must have an exit block");
2050 // Some loops have a single integer induction variable, while other loops
2051 // don't. One example is c++ iterators that often have multiple pointer
2052 // induction variables. In the code below we also support a case where we
2053 // don't have a single induction variable.
2054 OldInduction = Legal->getInduction();
2055 Type *IdxTy = Legal->getWidestInductionType();
2057 // Find the loop boundaries.
2058 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2059 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2061 // The exit count might have the type of i64 while the phi is i32. This can
2062 // happen if we have an induction variable that is sign extended before the
2063 // compare. The only way that we get a backedge taken count is that the
2064 // induction variable was signed and as such will not overflow. In such a case
2065 // truncation is legal.
2066 if (ExitCount->getType()->getPrimitiveSizeInBits() >
2067 IdxTy->getPrimitiveSizeInBits())
2068 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2070 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2071 // Get the total trip count from the count by adding 1.
2072 ExitCount = SE->getAddExpr(BackedgeTakeCount,
2073 SE->getConstant(BackedgeTakeCount->getType(), 1));
2075 // Expand the trip count and place the new instructions in the preheader.
2076 // Notice that the pre-header does not change, only the loop body.
2077 SCEVExpander Exp(*SE, "induction");
2079 // We need to test whether the backedge-taken count is uint##_max. Adding one
2080 // to it will cause overflow and an incorrect loop trip count in the vector
2081 // body. In case of overflow we want to directly jump to the scalar remainder
2083 Value *BackedgeCount =
2084 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2085 BypassBlock->getTerminator());
2086 if (BackedgeCount->getType()->isPointerTy())
2087 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2088 "backedge.ptrcnt.to.int",
2089 BypassBlock->getTerminator());
2090 Instruction *CheckBCOverflow =
2091 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2092 Constant::getAllOnesValue(BackedgeCount->getType()),
2093 "backedge.overflow", BypassBlock->getTerminator());
2095 // The loop index does not have to start at Zero. Find the original start
2096 // value from the induction PHI node. If we don't have an induction variable
2097 // then we know that it starts at zero.
2098 Builder.SetInsertPoint(BypassBlock->getTerminator());
2099 Value *StartIdx = ExtendedIdx = OldInduction ?
2100 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2102 ConstantInt::get(IdxTy, 0);
2104 // We need an instruction to anchor the overflow check on. StartIdx needs to
2105 // be defined before the overflow check branch. Because the scalar preheader
2106 // is going to merge the start index and so the overflow branch block needs to
2107 // contain a definition of the start index.
2108 Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
2109 StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
2110 BypassBlock->getTerminator());
2112 // Count holds the overall loop count (N).
2113 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2114 BypassBlock->getTerminator());
2116 LoopBypassBlocks.push_back(BypassBlock);
2118 // Split the single block loop into the two loop structure described above.
2119 BasicBlock *VectorPH =
2120 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2121 BasicBlock *VecBody =
2122 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2123 BasicBlock *MiddleBlock =
2124 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2125 BasicBlock *ScalarPH =
2126 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2128 // Create and register the new vector loop.
2129 Loop* Lp = new Loop();
2130 Loop *ParentLoop = OrigLoop->getParentLoop();
2132 // Insert the new loop into the loop nest and register the new basic blocks
2133 // before calling any utilities such as SCEV that require valid LoopInfo.
2135 ParentLoop->addChildLoop(Lp);
2136 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2137 ParentLoop->addBasicBlockToLoop(VectorPH, *LI);
2138 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2140 LI->addTopLevelLoop(Lp);
2142 Lp->addBasicBlockToLoop(VecBody, *LI);
2144 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2146 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2148 // Generate the induction variable.
2149 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2150 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2151 // The loop step is equal to the vectorization factor (num of SIMD elements)
2152 // times the unroll factor (num of SIMD instructions).
2153 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2155 // This is the IR builder that we use to add all of the logic for bypassing
2156 // the new vector loop.
2157 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2158 setDebugLocFromInst(BypassBuilder,
2159 getDebugLocFromInstOrOperands(OldInduction));
2161 // We may need to extend the index in case there is a type mismatch.
2162 // We know that the count starts at zero and does not overflow.
2163 if (Count->getType() != IdxTy) {
2164 // The exit count can be of pointer type. Convert it to the correct
2166 if (ExitCount->getType()->isPointerTy())
2167 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2169 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2172 // Add the start index to the loop count to get the new end index.
2173 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2175 // Now we need to generate the expression for N - (N % VF), which is
2176 // the part that the vectorized body will execute.
2177 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2178 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2179 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2180 "end.idx.rnd.down");
2182 // Now, compare the new count to zero. If it is zero skip the vector loop and
2183 // jump to the scalar loop.
2185 BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2187 BasicBlock *LastBypassBlock = BypassBlock;
2189 // Generate code to check that the loops trip count that we computed by adding
2190 // one to the backedge-taken count will not overflow.
2192 auto PastOverflowCheck =
2193 std::next(BasicBlock::iterator(OverflowCheckAnchor));
2194 BasicBlock *CheckBlock =
2195 LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2197 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2198 LoopBypassBlocks.push_back(CheckBlock);
2199 Instruction *OldTerm = LastBypassBlock->getTerminator();
2200 BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2201 OldTerm->eraseFromParent();
2202 LastBypassBlock = CheckBlock;
2205 // Generate the code to check that the strides we assumed to be one are really
2206 // one. We want the new basic block to start at the first instruction in a
2207 // sequence of instructions that form a check.
2208 Instruction *StrideCheck;
2209 Instruction *FirstCheckInst;
2210 std::tie(FirstCheckInst, StrideCheck) =
2211 addStrideCheck(LastBypassBlock->getTerminator());
2213 // Create a new block containing the stride check.
2214 BasicBlock *CheckBlock =
2215 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2217 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2218 LoopBypassBlocks.push_back(CheckBlock);
2220 // Replace the branch into the memory check block with a conditional branch
2221 // for the "few elements case".
2222 Instruction *OldTerm = LastBypassBlock->getTerminator();
2223 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2224 OldTerm->eraseFromParent();
2227 LastBypassBlock = CheckBlock;
2230 // Generate the code that checks in runtime if arrays overlap. We put the
2231 // checks into a separate block to make the more common case of few elements
2233 Instruction *MemRuntimeCheck;
2234 std::tie(FirstCheckInst, MemRuntimeCheck) =
2235 Legal->getLAI()->addRuntimeCheck(LastBypassBlock->getTerminator());
2236 if (MemRuntimeCheck) {
2237 // Create a new block containing the memory check.
2238 BasicBlock *CheckBlock =
2239 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.memcheck");
2241 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2242 LoopBypassBlocks.push_back(CheckBlock);
2244 // Replace the branch into the memory check block with a conditional branch
2245 // for the "few elements case".
2246 Instruction *OldTerm = LastBypassBlock->getTerminator();
2247 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2248 OldTerm->eraseFromParent();
2250 Cmp = MemRuntimeCheck;
2251 LastBypassBlock = CheckBlock;
2254 LastBypassBlock->getTerminator()->eraseFromParent();
2255 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2258 // We are going to resume the execution of the scalar loop.
2259 // Go over all of the induction variables that we found and fix the
2260 // PHIs that are left in the scalar version of the loop.
2261 // The starting values of PHI nodes depend on the counter of the last
2262 // iteration in the vectorized loop.
2263 // If we come from a bypass edge then we need to start from the original
2266 // This variable saves the new starting index for the scalar loop.
2267 PHINode *ResumeIndex = nullptr;
2268 LoopVectorizationLegality::InductionList::iterator I, E;
2269 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2270 // Set builder to point to last bypass block.
2271 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2272 for (I = List->begin(), E = List->end(); I != E; ++I) {
2273 PHINode *OrigPhi = I->first;
2274 LoopVectorizationLegality::InductionInfo II = I->second;
2276 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2277 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2278 MiddleBlock->getTerminator());
2279 // We might have extended the type of the induction variable but we need a
2280 // truncated version for the scalar loop.
2281 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2282 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2283 MiddleBlock->getTerminator()) : nullptr;
2285 // Create phi nodes to merge from the backedge-taken check block.
2286 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2287 ScalarPH->getTerminator());
2288 BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2290 PHINode *BCTruncResumeVal = nullptr;
2291 if (OrigPhi == OldInduction) {
2293 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2294 ScalarPH->getTerminator());
2295 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2298 Value *EndValue = nullptr;
2300 case LoopVectorizationLegality::IK_NoInduction:
2301 llvm_unreachable("Unknown induction");
2302 case LoopVectorizationLegality::IK_IntInduction: {
2303 // Handle the integer induction counter.
2304 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2306 // We have the canonical induction variable.
2307 if (OrigPhi == OldInduction) {
2308 // Create a truncated version of the resume value for the scalar loop,
2309 // we might have promoted the type to a larger width.
2311 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2312 // The new PHI merges the original incoming value, in case of a bypass,
2313 // or the value at the end of the vectorized loop.
2314 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2315 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2316 TruncResumeVal->addIncoming(EndValue, VecBody);
2318 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2320 // We know what the end value is.
2321 EndValue = IdxEndRoundDown;
2322 // We also know which PHI node holds it.
2323 ResumeIndex = ResumeVal;
2327 // Not the canonical induction variable - add the vector loop count to the
2329 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2330 II.StartValue->getType(),
2332 EndValue = II.transform(BypassBuilder, CRD);
2333 EndValue->setName("ind.end");
2336 case LoopVectorizationLegality::IK_PtrInduction: {
2337 EndValue = II.transform(BypassBuilder, CountRoundDown);
2338 EndValue->setName("ptr.ind.end");
2343 // The new PHI merges the original incoming value, in case of a bypass,
2344 // or the value at the end of the vectorized loop.
2345 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2346 if (OrigPhi == OldInduction)
2347 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2349 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2351 ResumeVal->addIncoming(EndValue, VecBody);
2353 // Fix the scalar body counter (PHI node).
2354 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2356 // The old induction's phi node in the scalar body needs the truncated
2358 if (OrigPhi == OldInduction) {
2359 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2360 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2362 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2363 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2367 // If we are generating a new induction variable then we also need to
2368 // generate the code that calculates the exit value. This value is not
2369 // simply the end of the counter because we may skip the vectorized body
2370 // in case of a runtime check.
2372 assert(!ResumeIndex && "Unexpected resume value found");
2373 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2374 MiddleBlock->getTerminator());
2375 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2376 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2377 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2380 // Make sure that we found the index where scalar loop needs to continue.
2381 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2382 "Invalid resume Index");
2384 // Add a check in the middle block to see if we have completed
2385 // all of the iterations in the first vector loop.
2386 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2387 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2388 ResumeIndex, "cmp.n",
2389 MiddleBlock->getTerminator());
2391 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2392 // Remove the old terminator.
2393 MiddleBlock->getTerminator()->eraseFromParent();
2395 // Create i+1 and fill the PHINode.
2396 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2397 Induction->addIncoming(StartIdx, VectorPH);
2398 Induction->addIncoming(NextIdx, VecBody);
2399 // Create the compare.
2400 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2401 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2403 // Now we have two terminators. Remove the old one from the block.
2404 VecBody->getTerminator()->eraseFromParent();
2406 // Get ready to start creating new instructions into the vectorized body.
2407 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2410 LoopVectorPreHeader = VectorPH;
2411 LoopScalarPreHeader = ScalarPH;
2412 LoopMiddleBlock = MiddleBlock;
2413 LoopExitBlock = ExitBlock;
2414 LoopVectorBody.push_back(VecBody);
2415 LoopScalarBody = OldBasicBlock;
2417 LoopVectorizeHints Hints(Lp, true);
2418 Hints.setAlreadyVectorized();
2421 /// This function returns the identity element (or neutral element) for
2422 /// the operation K.
2424 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2429 // Adding, Xoring, Oring zero to a number does not change it.
2430 return ConstantInt::get(Tp, 0);
2431 case RK_IntegerMult:
2432 // Multiplying a number by 1 does not change it.
2433 return ConstantInt::get(Tp, 1);
2435 // AND-ing a number with an all-1 value does not change it.
2436 return ConstantInt::get(Tp, -1, true);
2438 // Multiplying a number by 1 does not change it.
2439 return ConstantFP::get(Tp, 1.0L);
2441 // Adding zero to a number does not change it.
2442 return ConstantFP::get(Tp, 0.0L);
2444 llvm_unreachable("Unknown reduction kind");
2448 /// This function translates the reduction kind to an LLVM binary operator.
2450 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2452 case LoopVectorizationLegality::RK_IntegerAdd:
2453 return Instruction::Add;
2454 case LoopVectorizationLegality::RK_IntegerMult:
2455 return Instruction::Mul;
2456 case LoopVectorizationLegality::RK_IntegerOr:
2457 return Instruction::Or;
2458 case LoopVectorizationLegality::RK_IntegerAnd:
2459 return Instruction::And;
2460 case LoopVectorizationLegality::RK_IntegerXor:
2461 return Instruction::Xor;
2462 case LoopVectorizationLegality::RK_FloatMult:
2463 return Instruction::FMul;
2464 case LoopVectorizationLegality::RK_FloatAdd:
2465 return Instruction::FAdd;
2466 case LoopVectorizationLegality::RK_IntegerMinMax:
2467 return Instruction::ICmp;
2468 case LoopVectorizationLegality::RK_FloatMinMax:
2469 return Instruction::FCmp;
2471 llvm_unreachable("Unknown reduction operation");
2475 Value *createMinMaxOp(IRBuilder<> &Builder,
2476 LoopVectorizationLegality::MinMaxReductionKind RK,
2479 CmpInst::Predicate P = CmpInst::ICMP_NE;
2482 llvm_unreachable("Unknown min/max reduction kind");
2483 case LoopVectorizationLegality::MRK_UIntMin:
2484 P = CmpInst::ICMP_ULT;
2486 case LoopVectorizationLegality::MRK_UIntMax:
2487 P = CmpInst::ICMP_UGT;
2489 case LoopVectorizationLegality::MRK_SIntMin:
2490 P = CmpInst::ICMP_SLT;
2492 case LoopVectorizationLegality::MRK_SIntMax:
2493 P = CmpInst::ICMP_SGT;
2495 case LoopVectorizationLegality::MRK_FloatMin:
2496 P = CmpInst::FCMP_OLT;
2498 case LoopVectorizationLegality::MRK_FloatMax:
2499 P = CmpInst::FCMP_OGT;
2504 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2505 RK == LoopVectorizationLegality::MRK_FloatMax)
2506 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2508 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2510 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2515 struct CSEDenseMapInfo {
2516 static bool canHandle(Instruction *I) {
2517 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2518 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2520 static inline Instruction *getEmptyKey() {
2521 return DenseMapInfo<Instruction *>::getEmptyKey();
2523 static inline Instruction *getTombstoneKey() {
2524 return DenseMapInfo<Instruction *>::getTombstoneKey();
2526 static unsigned getHashValue(Instruction *I) {
2527 assert(canHandle(I) && "Unknown instruction!");
2528 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2529 I->value_op_end()));
2531 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2532 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2533 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2535 return LHS->isIdenticalTo(RHS);
2540 /// \brief Check whether this block is a predicated block.
2541 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2542 /// = ...; " blocks. We start with one vectorized basic block. For every
2543 /// conditional block we split this vectorized block. Therefore, every second
2544 /// block will be a predicated one.
2545 static bool isPredicatedBlock(unsigned BlockNum) {
2546 return BlockNum % 2;
2549 ///\brief Perform cse of induction variable instructions.
2550 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2551 // Perform simple cse.
2552 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2553 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2554 BasicBlock *BB = BBs[i];
2555 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2556 Instruction *In = I++;
2558 if (!CSEDenseMapInfo::canHandle(In))
2561 // Check if we can replace this instruction with any of the
2562 // visited instructions.
2563 if (Instruction *V = CSEMap.lookup(In)) {
2564 In->replaceAllUsesWith(V);
2565 In->eraseFromParent();
2568 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2569 // ...;" blocks for predicated stores. Every second block is a predicated
2571 if (isPredicatedBlock(i))
2579 /// \brief Adds a 'fast' flag to floating point operations.
2580 static Value *addFastMathFlag(Value *V) {
2581 if (isa<FPMathOperator>(V)){
2582 FastMathFlags Flags;
2583 Flags.setUnsafeAlgebra();
2584 cast<Instruction>(V)->setFastMathFlags(Flags);
2589 void InnerLoopVectorizer::vectorizeLoop() {
2590 //===------------------------------------------------===//
2592 // Notice: any optimization or new instruction that go
2593 // into the code below should be also be implemented in
2596 //===------------------------------------------------===//
2597 Constant *Zero = Builder.getInt32(0);
2599 // In order to support reduction variables we need to be able to vectorize
2600 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2601 // stages. First, we create a new vector PHI node with no incoming edges.
2602 // We use this value when we vectorize all of the instructions that use the
2603 // PHI. Next, after all of the instructions in the block are complete we
2604 // add the new incoming edges to the PHI. At this point all of the
2605 // instructions in the basic block are vectorized, so we can use them to
2606 // construct the PHI.
2607 PhiVector RdxPHIsToFix;
2609 // Scan the loop in a topological order to ensure that defs are vectorized
2611 LoopBlocksDFS DFS(OrigLoop);
2614 // Vectorize all of the blocks in the original loop.
2615 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2616 be = DFS.endRPO(); bb != be; ++bb)
2617 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2619 // At this point every instruction in the original loop is widened to
2620 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2621 // that we vectorized. The PHI nodes are currently empty because we did
2622 // not want to introduce cycles. Notice that the remaining PHI nodes
2623 // that we need to fix are reduction variables.
2625 // Create the 'reduced' values for each of the induction vars.
2626 // The reduced values are the vector values that we scalarize and combine
2627 // after the loop is finished.
2628 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2630 PHINode *RdxPhi = *it;
2631 assert(RdxPhi && "Unable to recover vectorized PHI");
2633 // Find the reduction variable descriptor.
2634 assert(Legal->getReductionVars()->count(RdxPhi) &&
2635 "Unable to find the reduction variable");
2636 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2637 (*Legal->getReductionVars())[RdxPhi];
2639 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2641 // We need to generate a reduction vector from the incoming scalar.
2642 // To do so, we need to generate the 'identity' vector and override
2643 // one of the elements with the incoming scalar reduction. We need
2644 // to do it in the vector-loop preheader.
2645 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2647 // This is the vector-clone of the value that leaves the loop.
2648 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2649 Type *VecTy = VectorExit[0]->getType();
2651 // Find the reduction identity variable. Zero for addition, or, xor,
2652 // one for multiplication, -1 for And.
2655 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2656 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2657 // MinMax reduction have the start value as their identify.
2659 VectorStart = Identity = RdxDesc.StartValue;
2661 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2666 // Handle other reduction kinds:
2668 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2669 VecTy->getScalarType());
2672 // This vector is the Identity vector where the first element is the
2673 // incoming scalar reduction.
2674 VectorStart = RdxDesc.StartValue;
2676 Identity = ConstantVector::getSplat(VF, Iden);
2678 // This vector is the Identity vector where the first element is the
2679 // incoming scalar reduction.
2680 VectorStart = Builder.CreateInsertElement(Identity,
2681 RdxDesc.StartValue, Zero);
2685 // Fix the vector-loop phi.
2687 // Reductions do not have to start at zero. They can start with
2688 // any loop invariant values.
2689 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2690 BasicBlock *Latch = OrigLoop->getLoopLatch();
2691 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2692 VectorParts &Val = getVectorValue(LoopVal);
2693 for (unsigned part = 0; part < UF; ++part) {
2694 // Make sure to add the reduction stat value only to the
2695 // first unroll part.
2696 Value *StartVal = (part == 0) ? VectorStart : Identity;
2697 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
2698 LoopVectorPreHeader);
2699 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2700 LoopVectorBody.back());
2703 // Before each round, move the insertion point right between
2704 // the PHIs and the values we are going to write.
2705 // This allows us to write both PHINodes and the extractelement
2707 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2709 VectorParts RdxParts;
2710 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2711 for (unsigned part = 0; part < UF; ++part) {
2712 // This PHINode contains the vectorized reduction variable, or
2713 // the initial value vector, if we bypass the vector loop.
2714 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2715 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2716 Value *StartVal = (part == 0) ? VectorStart : Identity;
2717 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2718 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2719 NewPhi->addIncoming(RdxExitVal[part],
2720 LoopVectorBody.back());
2721 RdxParts.push_back(NewPhi);
2724 // Reduce all of the unrolled parts into a single vector.
2725 Value *ReducedPartRdx = RdxParts[0];
2726 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2727 setDebugLocFromInst(Builder, ReducedPartRdx);
2728 for (unsigned part = 1; part < UF; ++part) {
2729 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2730 // Floating point operations had to be 'fast' to enable the reduction.
2731 ReducedPartRdx = addFastMathFlag(
2732 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2733 ReducedPartRdx, "bin.rdx"));
2735 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2736 ReducedPartRdx, RdxParts[part]);
2740 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2741 // and vector ops, reducing the set of values being computed by half each
2743 assert(isPowerOf2_32(VF) &&
2744 "Reduction emission only supported for pow2 vectors!");
2745 Value *TmpVec = ReducedPartRdx;
2746 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2747 for (unsigned i = VF; i != 1; i >>= 1) {
2748 // Move the upper half of the vector to the lower half.
2749 for (unsigned j = 0; j != i/2; ++j)
2750 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2752 // Fill the rest of the mask with undef.
2753 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2754 UndefValue::get(Builder.getInt32Ty()));
2757 Builder.CreateShuffleVector(TmpVec,
2758 UndefValue::get(TmpVec->getType()),
2759 ConstantVector::get(ShuffleMask),
2762 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2763 // Floating point operations had to be 'fast' to enable the reduction.
2764 TmpVec = addFastMathFlag(Builder.CreateBinOp(
2765 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2767 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2770 // The result is in the first element of the vector.
2771 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2772 Builder.getInt32(0));
2775 // Create a phi node that merges control-flow from the backedge-taken check
2776 // block and the middle block.
2777 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2778 LoopScalarPreHeader->getTerminator());
2779 BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
2780 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2782 // Now, we need to fix the users of the reduction variable
2783 // inside and outside of the scalar remainder loop.
2784 // We know that the loop is in LCSSA form. We need to update the
2785 // PHI nodes in the exit blocks.
2786 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2787 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2788 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2789 if (!LCSSAPhi) break;
2791 // All PHINodes need to have a single entry edge, or two if
2792 // we already fixed them.
2793 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2795 // We found our reduction value exit-PHI. Update it with the
2796 // incoming bypass edge.
2797 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2798 // Add an edge coming from the bypass.
2799 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2802 }// end of the LCSSA phi scan.
2804 // Fix the scalar loop reduction variable with the incoming reduction sum
2805 // from the vector body and from the backedge value.
2806 int IncomingEdgeBlockIdx =
2807 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2808 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2809 // Pick the other block.
2810 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2811 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
2812 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2813 }// end of for each redux variable.
2817 // Remove redundant induction instructions.
2818 cse(LoopVectorBody);
2821 void InnerLoopVectorizer::fixLCSSAPHIs() {
2822 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2823 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2824 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2825 if (!LCSSAPhi) break;
2826 if (LCSSAPhi->getNumIncomingValues() == 1)
2827 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2832 InnerLoopVectorizer::VectorParts
2833 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2834 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2837 // Look for cached value.
2838 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2839 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2840 if (ECEntryIt != MaskCache.end())
2841 return ECEntryIt->second;
2843 VectorParts SrcMask = createBlockInMask(Src);
2845 // The terminator has to be a branch inst!
2846 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2847 assert(BI && "Unexpected terminator found");
2849 if (BI->isConditional()) {
2850 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2852 if (BI->getSuccessor(0) != Dst)
2853 for (unsigned part = 0; part < UF; ++part)
2854 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2856 for (unsigned part = 0; part < UF; ++part)
2857 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2859 MaskCache[Edge] = EdgeMask;
2863 MaskCache[Edge] = SrcMask;
2867 InnerLoopVectorizer::VectorParts
2868 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2869 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2871 // Loop incoming mask is all-one.
2872 if (OrigLoop->getHeader() == BB) {
2873 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2874 return getVectorValue(C);
2877 // This is the block mask. We OR all incoming edges, and with zero.
2878 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2879 VectorParts BlockMask = getVectorValue(Zero);
2882 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2883 VectorParts EM = createEdgeMask(*it, BB);
2884 for (unsigned part = 0; part < UF; ++part)
2885 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2891 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2892 InnerLoopVectorizer::VectorParts &Entry,
2893 unsigned UF, unsigned VF, PhiVector *PV) {
2894 PHINode* P = cast<PHINode>(PN);
2895 // Handle reduction variables:
2896 if (Legal->getReductionVars()->count(P)) {
2897 for (unsigned part = 0; part < UF; ++part) {
2898 // This is phase one of vectorizing PHIs.
2899 Type *VecTy = (VF == 1) ? PN->getType() :
2900 VectorType::get(PN->getType(), VF);
2901 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2902 LoopVectorBody.back()-> getFirstInsertionPt());
2908 setDebugLocFromInst(Builder, P);
2909 // Check for PHI nodes that are lowered to vector selects.
2910 if (P->getParent() != OrigLoop->getHeader()) {
2911 // We know that all PHIs in non-header blocks are converted into
2912 // selects, so we don't have to worry about the insertion order and we
2913 // can just use the builder.
2914 // At this point we generate the predication tree. There may be
2915 // duplications since this is a simple recursive scan, but future
2916 // optimizations will clean it up.
2918 unsigned NumIncoming = P->getNumIncomingValues();
2920 // Generate a sequence of selects of the form:
2921 // SELECT(Mask3, In3,
2922 // SELECT(Mask2, In2,
2924 for (unsigned In = 0; In < NumIncoming; In++) {
2925 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2927 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2929 for (unsigned part = 0; part < UF; ++part) {
2930 // We might have single edge PHIs (blocks) - use an identity
2931 // 'select' for the first PHI operand.
2933 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2936 // Select between the current value and the previous incoming edge
2937 // based on the incoming mask.
2938 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2939 Entry[part], "predphi");
2945 // This PHINode must be an induction variable.
2946 // Make sure that we know about it.
2947 assert(Legal->getInductionVars()->count(P) &&
2948 "Not an induction variable");
2950 LoopVectorizationLegality::InductionInfo II =
2951 Legal->getInductionVars()->lookup(P);
2953 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2954 // which can be found from the original scalar operations.
2956 case LoopVectorizationLegality::IK_NoInduction:
2957 llvm_unreachable("Unknown induction");
2958 case LoopVectorizationLegality::IK_IntInduction: {
2959 assert(P->getType() == II.StartValue->getType() && "Types must match");
2960 Type *PhiTy = P->getType();
2962 if (P == OldInduction) {
2963 // Handle the canonical induction variable. We might have had to
2965 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2967 // Handle other induction variables that are now based on the
2969 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2971 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2972 Broadcasted = II.transform(Builder, NormalizedIdx);
2973 Broadcasted->setName("offset.idx");
2975 Broadcasted = getBroadcastInstrs(Broadcasted);
2976 // After broadcasting the induction variable we need to make the vector
2977 // consecutive by adding 0, 1, 2, etc.
2978 for (unsigned part = 0; part < UF; ++part)
2979 Entry[part] = getStepVector(Broadcasted, VF * part, II.StepValue);
2982 case LoopVectorizationLegality::IK_PtrInduction:
2983 // Handle the pointer induction variable case.
2984 assert(P->getType()->isPointerTy() && "Unexpected type.");
2985 // This is the normalized GEP that starts counting at zero.
2986 Value *NormalizedIdx =
2987 Builder.CreateSub(Induction, ExtendedIdx, "normalized.idx");
2988 // This is the vector of results. Notice that we don't generate
2989 // vector geps because scalar geps result in better code.
2990 for (unsigned part = 0; part < UF; ++part) {
2992 int EltIndex = part;
2993 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2994 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
2995 Value *SclrGep = II.transform(Builder, GlobalIdx);
2996 SclrGep->setName("next.gep");
2997 Entry[part] = SclrGep;
3001 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3002 for (unsigned int i = 0; i < VF; ++i) {
3003 int EltIndex = i + part * VF;
3004 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3005 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3006 Value *SclrGep = II.transform(Builder, GlobalIdx);
3007 SclrGep->setName("next.gep");
3008 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3009 Builder.getInt32(i),
3012 Entry[part] = VecVal;
3018 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3019 // For each instruction in the old loop.
3020 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3021 VectorParts &Entry = WidenMap.get(it);
3022 switch (it->getOpcode()) {
3023 case Instruction::Br:
3024 // Nothing to do for PHIs and BR, since we already took care of the
3025 // loop control flow instructions.
3027 case Instruction::PHI: {
3028 // Vectorize PHINodes.
3029 widenPHIInstruction(it, Entry, UF, VF, PV);
3033 case Instruction::Add:
3034 case Instruction::FAdd:
3035 case Instruction::Sub:
3036 case Instruction::FSub:
3037 case Instruction::Mul:
3038 case Instruction::FMul:
3039 case Instruction::UDiv:
3040 case Instruction::SDiv:
3041 case Instruction::FDiv:
3042 case Instruction::URem:
3043 case Instruction::SRem:
3044 case Instruction::FRem:
3045 case Instruction::Shl:
3046 case Instruction::LShr:
3047 case Instruction::AShr:
3048 case Instruction::And:
3049 case Instruction::Or:
3050 case Instruction::Xor: {
3051 // Just widen binops.
3052 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3053 setDebugLocFromInst(Builder, BinOp);
3054 VectorParts &A = getVectorValue(it->getOperand(0));
3055 VectorParts &B = getVectorValue(it->getOperand(1));
3057 // Use this vector value for all users of the original instruction.
3058 for (unsigned Part = 0; Part < UF; ++Part) {
3059 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3061 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3062 VecOp->copyIRFlags(BinOp);
3067 propagateMetadata(Entry, it);
3070 case Instruction::Select: {
3072 // If the selector is loop invariant we can create a select
3073 // instruction with a scalar condition. Otherwise, use vector-select.
3074 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3076 setDebugLocFromInst(Builder, it);
3078 // The condition can be loop invariant but still defined inside the
3079 // loop. This means that we can't just use the original 'cond' value.
3080 // We have to take the 'vectorized' value and pick the first lane.
3081 // Instcombine will make this a no-op.
3082 VectorParts &Cond = getVectorValue(it->getOperand(0));
3083 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3084 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3086 Value *ScalarCond = (VF == 1) ? Cond[0] :
3087 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3089 for (unsigned Part = 0; Part < UF; ++Part) {
3090 Entry[Part] = Builder.CreateSelect(
3091 InvariantCond ? ScalarCond : Cond[Part],
3096 propagateMetadata(Entry, it);
3100 case Instruction::ICmp:
3101 case Instruction::FCmp: {
3102 // Widen compares. Generate vector compares.
3103 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3104 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3105 setDebugLocFromInst(Builder, it);
3106 VectorParts &A = getVectorValue(it->getOperand(0));
3107 VectorParts &B = getVectorValue(it->getOperand(1));
3108 for (unsigned Part = 0; Part < UF; ++Part) {
3111 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3113 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3117 propagateMetadata(Entry, it);
3121 case Instruction::Store:
3122 case Instruction::Load:
3123 vectorizeMemoryInstruction(it);
3125 case Instruction::ZExt:
3126 case Instruction::SExt:
3127 case Instruction::FPToUI:
3128 case Instruction::FPToSI:
3129 case Instruction::FPExt:
3130 case Instruction::PtrToInt:
3131 case Instruction::IntToPtr:
3132 case Instruction::SIToFP:
3133 case Instruction::UIToFP:
3134 case Instruction::Trunc:
3135 case Instruction::FPTrunc:
3136 case Instruction::BitCast: {
3137 CastInst *CI = dyn_cast<CastInst>(it);
3138 setDebugLocFromInst(Builder, it);
3139 /// Optimize the special case where the source is the induction
3140 /// variable. Notice that we can only optimize the 'trunc' case
3141 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3142 /// c. other casts depend on pointer size.
3143 if (CI->getOperand(0) == OldInduction &&
3144 it->getOpcode() == Instruction::Trunc) {
3145 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3147 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3148 LoopVectorizationLegality::InductionInfo II =
3149 Legal->getInductionVars()->lookup(OldInduction);
3151 ConstantInt::getSigned(CI->getType(), II.StepValue->getSExtValue());
3152 for (unsigned Part = 0; Part < UF; ++Part)
3153 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3154 propagateMetadata(Entry, it);
3157 /// Vectorize casts.
3158 Type *DestTy = (VF == 1) ? CI->getType() :
3159 VectorType::get(CI->getType(), VF);
3161 VectorParts &A = getVectorValue(it->getOperand(0));
3162 for (unsigned Part = 0; Part < UF; ++Part)
3163 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3164 propagateMetadata(Entry, it);
3168 case Instruction::Call: {
3169 // Ignore dbg intrinsics.
3170 if (isa<DbgInfoIntrinsic>(it))
3172 setDebugLocFromInst(Builder, it);
3174 Module *M = BB->getParent()->getParent();
3175 CallInst *CI = cast<CallInst>(it);
3176 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3177 assert(ID && "Not an intrinsic call!");
3179 case Intrinsic::assume:
3180 case Intrinsic::lifetime_end:
3181 case Intrinsic::lifetime_start:
3182 scalarizeInstruction(it);
3185 bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
3186 for (unsigned Part = 0; Part < UF; ++Part) {
3187 SmallVector<Value *, 4> Args;
3188 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3189 if (HasScalarOpd && i == 1) {
3190 Args.push_back(CI->getArgOperand(i));
3193 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3194 Args.push_back(Arg[Part]);
3196 Type *Tys[] = {CI->getType()};
3198 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3200 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3201 Entry[Part] = Builder.CreateCall(F, Args);
3204 propagateMetadata(Entry, it);
3211 // All other instructions are unsupported. Scalarize them.
3212 scalarizeInstruction(it);
3215 }// end of for_each instr.
3218 void InnerLoopVectorizer::updateAnalysis() {
3219 // Forget the original basic block.
3220 SE->forgetLoop(OrigLoop);
3222 // Update the dominator tree information.
3223 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3224 "Entry does not dominate exit.");
3226 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3227 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3228 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3230 // Due to if predication of stores we might create a sequence of "if(pred)
3231 // a[i] = ...; " blocks.
3232 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3234 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3235 else if (isPredicatedBlock(i)) {
3236 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3238 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3242 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3243 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3244 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3245 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3247 DEBUG(DT->verifyDomTree());
3250 /// \brief Check whether it is safe to if-convert this phi node.
3252 /// Phi nodes with constant expressions that can trap are not safe to if
3254 static bool canIfConvertPHINodes(BasicBlock *BB) {
3255 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3256 PHINode *Phi = dyn_cast<PHINode>(I);
3259 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3260 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3267 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3268 if (!EnableIfConversion) {
3269 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3273 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3275 // A list of pointers that we can safely read and write to.
3276 SmallPtrSet<Value *, 8> SafePointes;
3278 // Collect safe addresses.
3279 for (Loop::block_iterator BI = TheLoop->block_begin(),
3280 BE = TheLoop->block_end(); BI != BE; ++BI) {
3281 BasicBlock *BB = *BI;
3283 if (blockNeedsPredication(BB))
3286 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3287 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3288 SafePointes.insert(LI->getPointerOperand());
3289 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3290 SafePointes.insert(SI->getPointerOperand());
3294 // Collect the blocks that need predication.
3295 BasicBlock *Header = TheLoop->getHeader();
3296 for (Loop::block_iterator BI = TheLoop->block_begin(),
3297 BE = TheLoop->block_end(); BI != BE; ++BI) {
3298 BasicBlock *BB = *BI;
3300 // We don't support switch statements inside loops.
3301 if (!isa<BranchInst>(BB->getTerminator())) {
3302 emitAnalysis(VectorizationReport(BB->getTerminator())
3303 << "loop contains a switch statement");
3307 // We must be able to predicate all blocks that need to be predicated.
3308 if (blockNeedsPredication(BB)) {
3309 if (!blockCanBePredicated(BB, SafePointes)) {
3310 emitAnalysis(VectorizationReport(BB->getTerminator())
3311 << "control flow cannot be substituted for a select");
3314 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3315 emitAnalysis(VectorizationReport(BB->getTerminator())
3316 << "control flow cannot be substituted for a select");
3321 // We can if-convert this loop.
3325 bool LoopVectorizationLegality::canVectorize() {
3326 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3327 // be canonicalized.
3328 if (!TheLoop->getLoopPreheader()) {
3330 VectorizationReport() <<
3331 "loop control flow is not understood by vectorizer");
3335 // We can only vectorize innermost loops.
3336 if (!TheLoop->getSubLoopsVector().empty()) {
3337 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3341 // We must have a single backedge.
3342 if (TheLoop->getNumBackEdges() != 1) {
3344 VectorizationReport() <<
3345 "loop control flow is not understood by vectorizer");
3349 // We must have a single exiting block.
3350 if (!TheLoop->getExitingBlock()) {
3352 VectorizationReport() <<
3353 "loop control flow is not understood by vectorizer");
3357 // We only handle bottom-tested loops, i.e. loop in which the condition is
3358 // checked at the end of each iteration. With that we can assume that all
3359 // instructions in the loop are executed the same number of times.
3360 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3362 VectorizationReport() <<
3363 "loop control flow is not understood by vectorizer");
3367 // We need to have a loop header.
3368 DEBUG(dbgs() << "LV: Found a loop: " <<
3369 TheLoop->getHeader()->getName() << '\n');
3371 // Check if we can if-convert non-single-bb loops.
3372 unsigned NumBlocks = TheLoop->getNumBlocks();
3373 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3374 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3378 // ScalarEvolution needs to be able to find the exit count.
3379 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3380 if (ExitCount == SE->getCouldNotCompute()) {
3381 emitAnalysis(VectorizationReport() <<
3382 "could not determine number of loop iterations");
3383 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3387 // Check if we can vectorize the instructions and CFG in this loop.
3388 if (!canVectorizeInstrs()) {
3389 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3393 // Go over each instruction and look at memory deps.
3394 if (!canVectorizeMemory()) {
3395 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3399 // Collect all of the variables that remain uniform after vectorization.
3400 collectLoopUniforms();
3402 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3403 (LAI.getRuntimePointerCheck()->Need ? " (with a runtime bound check)" :
3407 // Okay! We can vectorize. At this point we don't have any other mem analysis
3408 // which may limit our maximum vectorization factor, so just return true with
3413 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3414 if (Ty->isPointerTy())
3415 return DL.getIntPtrType(Ty);
3417 // It is possible that char's or short's overflow when we ask for the loop's
3418 // trip count, work around this by changing the type size.
3419 if (Ty->getScalarSizeInBits() < 32)
3420 return Type::getInt32Ty(Ty->getContext());
3425 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3426 Ty0 = convertPointerToIntegerType(DL, Ty0);
3427 Ty1 = convertPointerToIntegerType(DL, Ty1);
3428 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3433 /// \brief Check that the instruction has outside loop users and is not an
3434 /// identified reduction variable.
3435 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3436 SmallPtrSetImpl<Value *> &Reductions) {
3437 // Reduction instructions are allowed to have exit users. All other
3438 // instructions must not have external users.
3439 if (!Reductions.count(Inst))
3440 //Check that all of the users of the loop are inside the BB.
3441 for (User *U : Inst->users()) {
3442 Instruction *UI = cast<Instruction>(U);
3443 // This user may be a reduction exit value.
3444 if (!TheLoop->contains(UI)) {
3445 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3452 bool LoopVectorizationLegality::canVectorizeInstrs() {
3453 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3454 BasicBlock *Header = TheLoop->getHeader();
3456 // Look for the attribute signaling the absence of NaNs.
3457 Function &F = *Header->getParent();
3458 if (F.hasFnAttribute("no-nans-fp-math"))
3460 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
3462 // For each block in the loop.
3463 for (Loop::block_iterator bb = TheLoop->block_begin(),
3464 be = TheLoop->block_end(); bb != be; ++bb) {
3466 // Scan the instructions in the block and look for hazards.
3467 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3470 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3471 Type *PhiTy = Phi->getType();
3472 // Check that this PHI type is allowed.
3473 if (!PhiTy->isIntegerTy() &&
3474 !PhiTy->isFloatingPointTy() &&
3475 !PhiTy->isPointerTy()) {
3476 emitAnalysis(VectorizationReport(it)
3477 << "loop control flow is not understood by vectorizer");
3478 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3482 // If this PHINode is not in the header block, then we know that we
3483 // can convert it to select during if-conversion. No need to check if
3484 // the PHIs in this block are induction or reduction variables.
3485 if (*bb != Header) {
3486 // Check that this instruction has no outside users or is an
3487 // identified reduction value with an outside user.
3488 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3490 emitAnalysis(VectorizationReport(it) <<
3491 "value could not be identified as "
3492 "an induction or reduction variable");
3496 // We only allow if-converted PHIs with exactly two incoming values.
3497 if (Phi->getNumIncomingValues() != 2) {
3498 emitAnalysis(VectorizationReport(it)
3499 << "control flow not understood by vectorizer");
3500 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3504 // This is the value coming from the preheader.
3505 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3506 ConstantInt *StepValue = nullptr;
3507 // Check if this is an induction variable.
3508 InductionKind IK = isInductionVariable(Phi, StepValue);
3510 if (IK_NoInduction != IK) {
3511 // Get the widest type.
3513 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3515 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3517 // Int inductions are special because we only allow one IV.
3518 if (IK == IK_IntInduction && StepValue->isOne()) {
3519 // Use the phi node with the widest type as induction. Use the last
3520 // one if there are multiple (no good reason for doing this other
3521 // than it is expedient).
3522 if (!Induction || PhiTy == WidestIndTy)
3526 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3527 Inductions[Phi] = InductionInfo(StartValue, IK, StepValue);
3529 // Until we explicitly handle the case of an induction variable with
3530 // an outside loop user we have to give up vectorizing this loop.
3531 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3532 emitAnalysis(VectorizationReport(it) <<
3533 "use of induction value outside of the "
3534 "loop is not handled by vectorizer");
3541 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3542 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3545 if (AddReductionVar(Phi, RK_IntegerMult)) {
3546 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3549 if (AddReductionVar(Phi, RK_IntegerOr)) {
3550 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3553 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3554 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3557 if (AddReductionVar(Phi, RK_IntegerXor)) {
3558 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3561 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3562 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3565 if (AddReductionVar(Phi, RK_FloatMult)) {
3566 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3569 if (AddReductionVar(Phi, RK_FloatAdd)) {
3570 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3573 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3574 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3579 emitAnalysis(VectorizationReport(it) <<
3580 "value that could not be identified as "
3581 "reduction is used outside the loop");
3582 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3584 }// end of PHI handling
3586 // We still don't handle functions. However, we can ignore dbg intrinsic
3587 // calls and we do handle certain intrinsic and libm functions.
3588 CallInst *CI = dyn_cast<CallInst>(it);
3589 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3590 emitAnalysis(VectorizationReport(it) <<
3591 "call instruction cannot be vectorized");
3592 DEBUG(dbgs() << "LV: Found a call site.\n");
3596 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
3597 // second argument is the same (i.e. loop invariant)
3599 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
3600 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
3601 emitAnalysis(VectorizationReport(it)
3602 << "intrinsic instruction cannot be vectorized");
3603 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
3608 // Check that the instruction return type is vectorizable.
3609 // Also, we can't vectorize extractelement instructions.
3610 if ((!VectorType::isValidElementType(it->getType()) &&
3611 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3612 emitAnalysis(VectorizationReport(it)
3613 << "instruction return type cannot be vectorized");
3614 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3618 // Check that the stored type is vectorizable.
3619 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3620 Type *T = ST->getValueOperand()->getType();
3621 if (!VectorType::isValidElementType(T)) {
3622 emitAnalysis(VectorizationReport(ST) <<
3623 "store instruction cannot be vectorized");
3626 if (EnableMemAccessVersioning)
3627 collectStridedAccess(ST);
3630 if (EnableMemAccessVersioning)
3631 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3632 collectStridedAccess(LI);
3634 // Reduction instructions are allowed to have exit users.
3635 // All other instructions must not have external users.
3636 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3637 emitAnalysis(VectorizationReport(it) <<
3638 "value cannot be used outside the loop");
3647 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3648 if (Inductions.empty()) {
3649 emitAnalysis(VectorizationReport()
3650 << "loop induction variable could not be identified");
3658 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3659 /// return the induction operand of the gep pointer.
3660 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3661 const DataLayout *DL, Loop *Lp) {
3662 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3666 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3668 // Check that all of the gep indices are uniform except for our induction
3670 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3671 if (i != InductionOperand &&
3672 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3674 return GEP->getOperand(InductionOperand);
3677 ///\brief Look for a cast use of the passed value.
3678 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3679 Value *UniqueCast = nullptr;
3680 for (User *U : Ptr->users()) {
3681 CastInst *CI = dyn_cast<CastInst>(U);
3682 if (CI && CI->getType() == Ty) {
3692 ///\brief Get the stride of a pointer access in a loop.
3693 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3694 /// pointer to the Value, or null otherwise.
3695 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3696 const DataLayout *DL, Loop *Lp) {
3697 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3698 if (!PtrTy || PtrTy->isAggregateType())
3701 // Try to remove a gep instruction to make the pointer (actually index at this
3702 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3703 // pointer, otherwise, we are analyzing the index.
3704 Value *OrigPtr = Ptr;
3706 // The size of the pointer access.
3707 int64_t PtrAccessSize = 1;
3709 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3710 const SCEV *V = SE->getSCEV(Ptr);
3714 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3715 V = C->getOperand();
3717 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3721 V = S->getStepRecurrence(*SE);
3725 // Strip off the size of access multiplication if we are still analyzing the
3727 if (OrigPtr == Ptr) {
3728 DL->getTypeAllocSize(PtrTy->getElementType());
3729 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3730 if (M->getOperand(0)->getSCEVType() != scConstant)
3733 const APInt &APStepVal =
3734 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3736 // Huge step value - give up.
3737 if (APStepVal.getBitWidth() > 64)
3740 int64_t StepVal = APStepVal.getSExtValue();
3741 if (PtrAccessSize != StepVal)
3743 V = M->getOperand(1);
3748 Type *StripedOffRecurrenceCast = nullptr;
3749 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3750 StripedOffRecurrenceCast = C->getType();
3751 V = C->getOperand();
3754 // Look for the loop invariant symbolic value.
3755 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3759 Value *Stride = U->getValue();
3760 if (!Lp->isLoopInvariant(Stride))
3763 // If we have stripped off the recurrence cast we have to make sure that we
3764 // return the value that is used in this loop so that we can replace it later.
3765 if (StripedOffRecurrenceCast)
3766 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3771 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
3772 Value *Ptr = nullptr;
3773 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3774 Ptr = LI->getPointerOperand();
3775 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3776 Ptr = SI->getPointerOperand();
3780 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3784 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3785 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3786 Strides[Ptr] = Stride;
3787 StrideSet.insert(Stride);
3790 void LoopVectorizationLegality::collectLoopUniforms() {
3791 // We now know that the loop is vectorizable!
3792 // Collect variables that will remain uniform after vectorization.
3793 std::vector<Value*> Worklist;
3794 BasicBlock *Latch = TheLoop->getLoopLatch();
3796 // Start with the conditional branch and walk up the block.
3797 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3799 // Also add all consecutive pointer values; these values will be uniform
3800 // after vectorization (and subsequent cleanup) and, until revectorization is
3801 // supported, all dependencies must also be uniform.
3802 for (Loop::block_iterator B = TheLoop->block_begin(),
3803 BE = TheLoop->block_end(); B != BE; ++B)
3804 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3806 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3807 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3809 while (!Worklist.empty()) {
3810 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3811 Worklist.pop_back();
3813 // Look at instructions inside this loop.
3814 // Stop when reaching PHI nodes.
3815 // TODO: we need to follow values all over the loop, not only in this block.
3816 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3819 // This is a known uniform.
3822 // Insert all operands.
3823 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3827 bool LoopVectorizationLegality::canVectorizeMemory() {
3828 LAI.analyzeLoop(Strides);
3829 auto &OptionalReport = LAI.getReport();
3831 emitAnalysis(*OptionalReport);
3832 return LAI.canVectorizeMemory();
3835 static bool hasMultipleUsesOf(Instruction *I,
3836 SmallPtrSetImpl<Instruction *> &Insts) {
3837 unsigned NumUses = 0;
3838 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
3839 if (Insts.count(dyn_cast<Instruction>(*Use)))
3848 static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set) {
3849 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
3850 if (!Set.count(dyn_cast<Instruction>(*Use)))
3855 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
3856 ReductionKind Kind) {
3857 if (Phi->getNumIncomingValues() != 2)
3860 // Reduction variables are only found in the loop header block.
3861 if (Phi->getParent() != TheLoop->getHeader())
3864 // Obtain the reduction start value from the value that comes from the loop
3866 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
3868 // ExitInstruction is the single value which is used outside the loop.
3869 // We only allow for a single reduction value to be used outside the loop.
3870 // This includes users of the reduction, variables (which form a cycle
3871 // which ends in the phi node).
3872 Instruction *ExitInstruction = nullptr;
3873 // Indicates that we found a reduction operation in our scan.
3874 bool FoundReduxOp = false;
3876 // We start with the PHI node and scan for all of the users of this
3877 // instruction. All users must be instructions that can be used as reduction
3878 // variables (such as ADD). We must have a single out-of-block user. The cycle
3879 // must include the original PHI.
3880 bool FoundStartPHI = false;
3882 // To recognize min/max patterns formed by a icmp select sequence, we store
3883 // the number of instruction we saw from the recognized min/max pattern,
3884 // to make sure we only see exactly the two instructions.
3885 unsigned NumCmpSelectPatternInst = 0;
3886 ReductionInstDesc ReduxDesc(false, nullptr);
3888 SmallPtrSet<Instruction *, 8> VisitedInsts;
3889 SmallVector<Instruction *, 8> Worklist;
3890 Worklist.push_back(Phi);
3891 VisitedInsts.insert(Phi);
3893 // A value in the reduction can be used:
3894 // - By the reduction:
3895 // - Reduction operation:
3896 // - One use of reduction value (safe).
3897 // - Multiple use of reduction value (not safe).
3899 // - All uses of the PHI must be the reduction (safe).
3900 // - Otherwise, not safe.
3901 // - By one instruction outside of the loop (safe).
3902 // - By further instructions outside of the loop (not safe).
3903 // - By an instruction that is not part of the reduction (not safe).
3905 // * An instruction type other than PHI or the reduction operation.
3906 // * A PHI in the header other than the initial PHI.
3907 while (!Worklist.empty()) {
3908 Instruction *Cur = Worklist.back();
3909 Worklist.pop_back();
3912 // If the instruction has no users then this is a broken chain and can't be
3913 // a reduction variable.
3914 if (Cur->use_empty())
3917 bool IsAPhi = isa<PHINode>(Cur);
3919 // A header PHI use other than the original PHI.
3920 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
3923 // Reductions of instructions such as Div, and Sub is only possible if the
3924 // LHS is the reduction variable.
3925 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
3926 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
3927 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
3930 // Any reduction instruction must be of one of the allowed kinds.
3931 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
3932 if (!ReduxDesc.IsReduction)
3935 // A reduction operation must only have one use of the reduction value.
3936 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
3937 hasMultipleUsesOf(Cur, VisitedInsts))
3940 // All inputs to a PHI node must be a reduction value.
3941 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
3944 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
3945 isa<SelectInst>(Cur)))
3946 ++NumCmpSelectPatternInst;
3947 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
3948 isa<SelectInst>(Cur)))
3949 ++NumCmpSelectPatternInst;
3951 // Check whether we found a reduction operator.
3952 FoundReduxOp |= !IsAPhi;
3954 // Process users of current instruction. Push non-PHI nodes after PHI nodes
3955 // onto the stack. This way we are going to have seen all inputs to PHI
3956 // nodes once we get to them.
3957 SmallVector<Instruction *, 8> NonPHIs;
3958 SmallVector<Instruction *, 8> PHIs;
3959 for (User *U : Cur->users()) {
3960 Instruction *UI = cast<Instruction>(U);
3962 // Check if we found the exit user.
3963 BasicBlock *Parent = UI->getParent();
3964 if (!TheLoop->contains(Parent)) {
3965 // Exit if you find multiple outside users or if the header phi node is
3966 // being used. In this case the user uses the value of the previous
3967 // iteration, in which case we would loose "VF-1" iterations of the
3968 // reduction operation if we vectorize.
3969 if (ExitInstruction != nullptr || Cur == Phi)
3972 // The instruction used by an outside user must be the last instruction
3973 // before we feed back to the reduction phi. Otherwise, we loose VF-1
3974 // operations on the value.
3975 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
3978 ExitInstruction = Cur;
3982 // Process instructions only once (termination). Each reduction cycle
3983 // value must only be used once, except by phi nodes and min/max
3984 // reductions which are represented as a cmp followed by a select.
3985 ReductionInstDesc IgnoredVal(false, nullptr);
3986 if (VisitedInsts.insert(UI).second) {
3987 if (isa<PHINode>(UI))
3990 NonPHIs.push_back(UI);
3991 } else if (!isa<PHINode>(UI) &&
3992 ((!isa<FCmpInst>(UI) &&
3993 !isa<ICmpInst>(UI) &&
3994 !isa<SelectInst>(UI)) ||
3995 !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
3998 // Remember that we completed the cycle.
4000 FoundStartPHI = true;
4002 Worklist.append(PHIs.begin(), PHIs.end());
4003 Worklist.append(NonPHIs.begin(), NonPHIs.end());
4006 // This means we have seen one but not the other instruction of the
4007 // pattern or more than just a select and cmp.
4008 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4009 NumCmpSelectPatternInst != 2)
4012 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4015 // We found a reduction var if we have reached the original phi node and we
4016 // only have a single instruction with out-of-loop users.
4018 // This instruction is allowed to have out-of-loop users.
4019 AllowedExit.insert(ExitInstruction);
4021 // Save the description of this reduction variable.
4022 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4023 ReduxDesc.MinMaxKind);
4024 Reductions[Phi] = RD;
4025 // We've ended the cycle. This is a reduction variable if we have an
4026 // outside user and it has a binary op.
4031 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4032 /// pattern corresponding to a min(X, Y) or max(X, Y).
4033 LoopVectorizationLegality::ReductionInstDesc
4034 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4035 ReductionInstDesc &Prev) {
4037 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4038 "Expect a select instruction");
4039 Instruction *Cmp = nullptr;
4040 SelectInst *Select = nullptr;
4042 // We must handle the select(cmp()) as a single instruction. Advance to the
4044 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4045 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
4046 return ReductionInstDesc(false, I);
4047 return ReductionInstDesc(Select, Prev.MinMaxKind);
4050 // Only handle single use cases for now.
4051 if (!(Select = dyn_cast<SelectInst>(I)))
4052 return ReductionInstDesc(false, I);
4053 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4054 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4055 return ReductionInstDesc(false, I);
4056 if (!Cmp->hasOneUse())
4057 return ReductionInstDesc(false, I);
4062 // Look for a min/max pattern.
4063 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4064 return ReductionInstDesc(Select, MRK_UIntMin);
4065 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4066 return ReductionInstDesc(Select, MRK_UIntMax);
4067 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4068 return ReductionInstDesc(Select, MRK_SIntMax);
4069 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4070 return ReductionInstDesc(Select, MRK_SIntMin);
4071 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4072 return ReductionInstDesc(Select, MRK_FloatMin);
4073 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4074 return ReductionInstDesc(Select, MRK_FloatMax);
4075 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4076 return ReductionInstDesc(Select, MRK_FloatMin);
4077 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4078 return ReductionInstDesc(Select, MRK_FloatMax);
4080 return ReductionInstDesc(false, I);
4083 LoopVectorizationLegality::ReductionInstDesc
4084 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4086 ReductionInstDesc &Prev) {
4087 bool FP = I->getType()->isFloatingPointTy();
4088 bool FastMath = FP && I->hasUnsafeAlgebra();
4089 switch (I->getOpcode()) {
4091 return ReductionInstDesc(false, I);
4092 case Instruction::PHI:
4093 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4094 Kind != RK_FloatMinMax))
4095 return ReductionInstDesc(false, I);
4096 return ReductionInstDesc(I, Prev.MinMaxKind);
4097 case Instruction::Sub:
4098 case Instruction::Add:
4099 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4100 case Instruction::Mul:
4101 return ReductionInstDesc(Kind == RK_IntegerMult, I);
4102 case Instruction::And:
4103 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4104 case Instruction::Or:
4105 return ReductionInstDesc(Kind == RK_IntegerOr, I);
4106 case Instruction::Xor:
4107 return ReductionInstDesc(Kind == RK_IntegerXor, I);
4108 case Instruction::FMul:
4109 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4110 case Instruction::FSub:
4111 case Instruction::FAdd:
4112 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4113 case Instruction::FCmp:
4114 case Instruction::ICmp:
4115 case Instruction::Select:
4116 if (Kind != RK_IntegerMinMax &&
4117 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4118 return ReductionInstDesc(false, I);
4119 return isMinMaxSelectCmpPattern(I, Prev);
4123 LoopVectorizationLegality::InductionKind
4124 LoopVectorizationLegality::isInductionVariable(PHINode *Phi,
4125 ConstantInt *&StepValue) {
4126 Type *PhiTy = Phi->getType();
4127 // We only handle integer and pointer inductions variables.
4128 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4129 return IK_NoInduction;
4131 // Check that the PHI is consecutive.
4132 const SCEV *PhiScev = SE->getSCEV(Phi);
4133 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4135 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4136 return IK_NoInduction;
4139 const SCEV *Step = AR->getStepRecurrence(*SE);
4140 // Calculate the pointer stride and check if it is consecutive.
4141 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4143 return IK_NoInduction;
4145 ConstantInt *CV = C->getValue();
4146 if (PhiTy->isIntegerTy()) {
4148 return IK_IntInduction;
4151 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4152 Type *PointerElementType = PhiTy->getPointerElementType();
4153 // The pointer stride cannot be determined if the pointer element type is not
4155 if (!PointerElementType->isSized())
4156 return IK_NoInduction;
4158 int64_t Size = static_cast<int64_t>(DL->getTypeAllocSize(PointerElementType));
4159 int64_t CVSize = CV->getSExtValue();
4161 return IK_NoInduction;
4162 StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
4163 return IK_PtrInduction;
4166 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4167 Value *In0 = const_cast<Value*>(V);
4168 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4172 return Inductions.count(PN);
4175 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4176 return LAI.blockNeedsPredication(BB);
4179 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4180 SmallPtrSetImpl<Value *> &SafePtrs) {
4182 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4183 // Check that we don't have a constant expression that can trap as operand.
4184 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4186 if (Constant *C = dyn_cast<Constant>(*OI))
4190 // We might be able to hoist the load.
4191 if (it->mayReadFromMemory()) {
4192 LoadInst *LI = dyn_cast<LoadInst>(it);
4195 if (!SafePtrs.count(LI->getPointerOperand())) {
4196 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4197 MaskedOp.insert(LI);
4204 // We don't predicate stores at the moment.
4205 if (it->mayWriteToMemory()) {
4206 StoreInst *SI = dyn_cast<StoreInst>(it);
4207 // We only support predication of stores in basic blocks with one
4212 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4213 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4215 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4216 !isSinglePredecessor) {
4217 // Build a masked store if it is legal for the target, otherwise scalarize
4219 bool isLegalMaskedOp =
4220 isLegalMaskedStore(SI->getValueOperand()->getType(),
4221 SI->getPointerOperand());
4222 if (isLegalMaskedOp) {
4224 MaskedOp.insert(SI);
4233 // The instructions below can trap.
4234 switch (it->getOpcode()) {
4236 case Instruction::UDiv:
4237 case Instruction::SDiv:
4238 case Instruction::URem:
4239 case Instruction::SRem:
4247 LoopVectorizationCostModel::VectorizationFactor
4248 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4249 // Width 1 means no vectorize
4250 VectorizationFactor Factor = { 1U, 0U };
4251 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4252 emitAnalysis(VectorizationReport() <<
4253 "runtime pointer checks needed. Enable vectorization of this "
4254 "loop with '#pragma clang loop vectorize(enable)' when "
4255 "compiling with -Os");
4256 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4260 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4261 emitAnalysis(VectorizationReport() <<
4262 "store that is conditionally executed prevents vectorization");
4263 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4267 // Find the trip count.
4268 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4269 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4271 unsigned WidestType = getWidestType();
4272 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4273 unsigned MaxSafeDepDist = -1U;
4274 if (Legal->getMaxSafeDepDistBytes() != -1U)
4275 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4276 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4277 WidestRegister : MaxSafeDepDist);
4278 unsigned MaxVectorSize = WidestRegister / WidestType;
4279 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4280 DEBUG(dbgs() << "LV: The Widest register is: "
4281 << WidestRegister << " bits.\n");
4283 if (MaxVectorSize == 0) {
4284 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4288 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4289 " into one vector!");
4291 unsigned VF = MaxVectorSize;
4293 // If we optimize the program for size, avoid creating the tail loop.
4295 // If we are unable to calculate the trip count then don't try to vectorize.
4298 (VectorizationReport() <<
4299 "unable to calculate the loop count due to complex control flow");
4300 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4304 // Find the maximum SIMD width that can fit within the trip count.
4305 VF = TC % MaxVectorSize;
4310 // If the trip count that we found modulo the vectorization factor is not
4311 // zero then we require a tail.
4313 emitAnalysis(VectorizationReport() <<
4314 "cannot optimize for size and vectorize at the "
4315 "same time. Enable vectorization of this loop "
4316 "with '#pragma clang loop vectorize(enable)' "
4317 "when compiling with -Os");
4318 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4323 int UserVF = Hints->getWidth();
4325 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4326 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4328 Factor.Width = UserVF;
4332 float Cost = expectedCost(1);
4334 const float ScalarCost = Cost;
4337 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4339 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4340 // Ignore scalar width, because the user explicitly wants vectorization.
4341 if (ForceVectorization && VF > 1) {
4343 Cost = expectedCost(Width) / (float)Width;
4346 for (unsigned i=2; i <= VF; i*=2) {
4347 // Notice that the vector loop needs to be executed less times, so
4348 // we need to divide the cost of the vector loops by the width of
4349 // the vector elements.
4350 float VectorCost = expectedCost(i) / (float)i;
4351 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4352 (int)VectorCost << ".\n");
4353 if (VectorCost < Cost) {
4359 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4360 << "LV: Vectorization seems to be not beneficial, "
4361 << "but was forced by a user.\n");
4362 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4363 Factor.Width = Width;
4364 Factor.Cost = Width * Cost;
4368 unsigned LoopVectorizationCostModel::getWidestType() {
4369 unsigned MaxWidth = 8;
4372 for (Loop::block_iterator bb = TheLoop->block_begin(),
4373 be = TheLoop->block_end(); bb != be; ++bb) {
4374 BasicBlock *BB = *bb;
4376 // For each instruction in the loop.
4377 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4378 Type *T = it->getType();
4380 // Ignore ephemeral values.
4381 if (EphValues.count(it))
4384 // Only examine Loads, Stores and PHINodes.
4385 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4388 // Examine PHI nodes that are reduction variables.
4389 if (PHINode *PN = dyn_cast<PHINode>(it))
4390 if (!Legal->getReductionVars()->count(PN))
4393 // Examine the stored values.
4394 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4395 T = ST->getValueOperand()->getType();
4397 // Ignore loaded pointer types and stored pointer types that are not
4398 // consecutive. However, we do want to take consecutive stores/loads of
4399 // pointer vectors into account.
4400 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4403 MaxWidth = std::max(MaxWidth,
4404 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
4412 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
4414 unsigned LoopCost) {
4416 // -- The unroll heuristics --
4417 // We unroll the loop in order to expose ILP and reduce the loop overhead.
4418 // There are many micro-architectural considerations that we can't predict
4419 // at this level. For example, frontend pressure (on decode or fetch) due to
4420 // code size, or the number and capabilities of the execution ports.
4422 // We use the following heuristics to select the unroll factor:
4423 // 1. If the code has reductions, then we unroll in order to break the cross
4424 // iteration dependency.
4425 // 2. If the loop is really small, then we unroll in order to reduce the loop
4427 // 3. We don't unroll if we think that we will spill registers to memory due
4428 // to the increased register pressure.
4430 // Use the user preference, unless 'auto' is selected.
4431 int UserUF = Hints->getInterleave();
4435 // When we optimize for size, we don't unroll.
4439 // We used the distance for the unroll factor.
4440 if (Legal->getMaxSafeDepDistBytes() != -1U)
4443 // Do not unroll loops with a relatively small trip count.
4444 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4445 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
4448 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4449 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4453 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4454 TargetNumRegisters = ForceTargetNumScalarRegs;
4456 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4457 TargetNumRegisters = ForceTargetNumVectorRegs;
4460 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4461 // We divide by these constants so assume that we have at least one
4462 // instruction that uses at least one register.
4463 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4464 R.NumInstructions = std::max(R.NumInstructions, 1U);
4466 // We calculate the unroll factor using the following formula.
4467 // Subtract the number of loop invariants from the number of available
4468 // registers. These registers are used by all of the unrolled instances.
4469 // Next, divide the remaining registers by the number of registers that is
4470 // required by the loop, in order to estimate how many parallel instances
4471 // fit without causing spills. All of this is rounded down if necessary to be
4472 // a power of two. We want power of two unroll factors to simplify any
4473 // addressing operations or alignment considerations.
4474 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4477 // Don't count the induction variable as unrolled.
4478 if (EnableIndVarRegisterHeur)
4479 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4480 std::max(1U, (R.MaxLocalUsers - 1)));
4482 // Clamp the unroll factor ranges to reasonable factors.
4483 unsigned MaxInterleaveSize = TTI.getMaxInterleaveFactor();
4485 // Check if the user has overridden the unroll max.
4487 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4488 MaxInterleaveSize = ForceTargetMaxScalarInterleaveFactor;
4490 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4491 MaxInterleaveSize = ForceTargetMaxVectorInterleaveFactor;
4494 // If we did not calculate the cost for VF (because the user selected the VF)
4495 // then we calculate the cost of VF here.
4497 LoopCost = expectedCost(VF);
4499 // Clamp the calculated UF to be between the 1 and the max unroll factor
4500 // that the target allows.
4501 if (UF > MaxInterleaveSize)
4502 UF = MaxInterleaveSize;
4506 // Unroll if we vectorized this loop and there is a reduction that could
4507 // benefit from unrolling.
4508 if (VF > 1 && Legal->getReductionVars()->size()) {
4509 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
4513 // Note that if we've already vectorized the loop we will have done the
4514 // runtime check and so unrolling won't require further checks.
4515 bool UnrollingRequiresRuntimePointerCheck =
4516 (VF == 1 && Legal->getRuntimePointerCheck()->Need);
4518 // We want to unroll small loops in order to reduce the loop overhead and
4519 // potentially expose ILP opportunities.
4520 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4521 if (!UnrollingRequiresRuntimePointerCheck &&
4522 LoopCost < SmallLoopCost) {
4523 // We assume that the cost overhead is 1 and we use the cost model
4524 // to estimate the cost of the loop and unroll until the cost of the
4525 // loop overhead is about 5% of the cost of the loop.
4526 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4528 // Unroll until store/load ports (estimated by max unroll factor) are
4530 unsigned NumStores = Legal->getNumStores();
4531 unsigned NumLoads = Legal->getNumLoads();
4532 unsigned StoresUF = UF / (NumStores ? NumStores : 1);
4533 unsigned LoadsUF = UF / (NumLoads ? NumLoads : 1);
4535 // If we have a scalar reduction (vector reductions are already dealt with
4536 // by this point), we can increase the critical path length if the loop
4537 // we're unrolling is inside another loop. Limit, by default to 2, so the
4538 // critical path only gets increased by one reduction operation.
4539 if (Legal->getReductionVars()->size() &&
4540 TheLoop->getLoopDepth() > 1) {
4541 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionUF);
4542 SmallUF = std::min(SmallUF, F);
4543 StoresUF = std::min(StoresUF, F);
4544 LoadsUF = std::min(LoadsUF, F);
4547 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
4548 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
4549 return std::max(StoresUF, LoadsUF);
4552 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
4556 DEBUG(dbgs() << "LV: Not Unrolling.\n");
4560 LoopVectorizationCostModel::RegisterUsage
4561 LoopVectorizationCostModel::calculateRegisterUsage() {
4562 // This function calculates the register usage by measuring the highest number
4563 // of values that are alive at a single location. Obviously, this is a very
4564 // rough estimation. We scan the loop in a topological order in order and
4565 // assign a number to each instruction. We use RPO to ensure that defs are
4566 // met before their users. We assume that each instruction that has in-loop
4567 // users starts an interval. We record every time that an in-loop value is
4568 // used, so we have a list of the first and last occurrences of each
4569 // instruction. Next, we transpose this data structure into a multi map that
4570 // holds the list of intervals that *end* at a specific location. This multi
4571 // map allows us to perform a linear search. We scan the instructions linearly
4572 // and record each time that a new interval starts, by placing it in a set.
4573 // If we find this value in the multi-map then we remove it from the set.
4574 // The max register usage is the maximum size of the set.
4575 // We also search for instructions that are defined outside the loop, but are
4576 // used inside the loop. We need this number separately from the max-interval
4577 // usage number because when we unroll, loop-invariant values do not take
4579 LoopBlocksDFS DFS(TheLoop);
4583 R.NumInstructions = 0;
4585 // Each 'key' in the map opens a new interval. The values
4586 // of the map are the index of the 'last seen' usage of the
4587 // instruction that is the key.
4588 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4589 // Maps instruction to its index.
4590 DenseMap<unsigned, Instruction*> IdxToInstr;
4591 // Marks the end of each interval.
4592 IntervalMap EndPoint;
4593 // Saves the list of instruction indices that are used in the loop.
4594 SmallSet<Instruction*, 8> Ends;
4595 // Saves the list of values that are used in the loop but are
4596 // defined outside the loop, such as arguments and constants.
4597 SmallPtrSet<Value*, 8> LoopInvariants;
4600 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4601 be = DFS.endRPO(); bb != be; ++bb) {
4602 R.NumInstructions += (*bb)->size();
4603 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4605 Instruction *I = it;
4606 IdxToInstr[Index++] = I;
4608 // Save the end location of each USE.
4609 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4610 Value *U = I->getOperand(i);
4611 Instruction *Instr = dyn_cast<Instruction>(U);
4613 // Ignore non-instruction values such as arguments, constants, etc.
4614 if (!Instr) continue;
4616 // If this instruction is outside the loop then record it and continue.
4617 if (!TheLoop->contains(Instr)) {
4618 LoopInvariants.insert(Instr);
4622 // Overwrite previous end points.
4623 EndPoint[Instr] = Index;
4629 // Saves the list of intervals that end with the index in 'key'.
4630 typedef SmallVector<Instruction*, 2> InstrList;
4631 DenseMap<unsigned, InstrList> TransposeEnds;
4633 // Transpose the EndPoints to a list of values that end at each index.
4634 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4636 TransposeEnds[it->second].push_back(it->first);
4638 SmallSet<Instruction*, 8> OpenIntervals;
4639 unsigned MaxUsage = 0;
4642 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4643 for (unsigned int i = 0; i < Index; ++i) {
4644 Instruction *I = IdxToInstr[i];
4645 // Ignore instructions that are never used within the loop.
4646 if (!Ends.count(I)) continue;
4648 // Ignore ephemeral values.
4649 if (EphValues.count(I))
4652 // Remove all of the instructions that end at this location.
4653 InstrList &List = TransposeEnds[i];
4654 for (unsigned int j=0, e = List.size(); j < e; ++j)
4655 OpenIntervals.erase(List[j]);
4657 // Count the number of live interals.
4658 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4660 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4661 OpenIntervals.size() << '\n');
4663 // Add the current instruction to the list of open intervals.
4664 OpenIntervals.insert(I);
4667 unsigned Invariant = LoopInvariants.size();
4668 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
4669 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
4670 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
4672 R.LoopInvariantRegs = Invariant;
4673 R.MaxLocalUsers = MaxUsage;
4677 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4681 for (Loop::block_iterator bb = TheLoop->block_begin(),
4682 be = TheLoop->block_end(); bb != be; ++bb) {
4683 unsigned BlockCost = 0;
4684 BasicBlock *BB = *bb;
4686 // For each instruction in the old loop.
4687 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4688 // Skip dbg intrinsics.
4689 if (isa<DbgInfoIntrinsic>(it))
4692 // Ignore ephemeral values.
4693 if (EphValues.count(it))
4696 unsigned C = getInstructionCost(it, VF);
4698 // Check if we should override the cost.
4699 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
4700 C = ForceTargetInstructionCost;
4703 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
4704 VF << " For instruction: " << *it << '\n');
4707 // We assume that if-converted blocks have a 50% chance of being executed.
4708 // When the code is scalar then some of the blocks are avoided due to CF.
4709 // When the code is vectorized we execute all code paths.
4710 if (VF == 1 && Legal->blockNeedsPredication(*bb))
4719 /// \brief Check whether the address computation for a non-consecutive memory
4720 /// access looks like an unlikely candidate for being merged into the indexing
4723 /// We look for a GEP which has one index that is an induction variable and all
4724 /// other indices are loop invariant. If the stride of this access is also
4725 /// within a small bound we decide that this address computation can likely be
4726 /// merged into the addressing mode.
4727 /// In all other cases, we identify the address computation as complex.
4728 static bool isLikelyComplexAddressComputation(Value *Ptr,
4729 LoopVectorizationLegality *Legal,
4730 ScalarEvolution *SE,
4731 const Loop *TheLoop) {
4732 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
4736 // We are looking for a gep with all loop invariant indices except for one
4737 // which should be an induction variable.
4738 unsigned NumOperands = Gep->getNumOperands();
4739 for (unsigned i = 1; i < NumOperands; ++i) {
4740 Value *Opd = Gep->getOperand(i);
4741 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
4742 !Legal->isInductionVariable(Opd))
4746 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
4747 // can likely be merged into the address computation.
4748 unsigned MaxMergeDistance = 64;
4750 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
4754 // Check the step is constant.
4755 const SCEV *Step = AddRec->getStepRecurrence(*SE);
4756 // Calculate the pointer stride and check if it is consecutive.
4757 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4761 const APInt &APStepVal = C->getValue()->getValue();
4763 // Huge step value - give up.
4764 if (APStepVal.getBitWidth() > 64)
4767 int64_t StepVal = APStepVal.getSExtValue();
4769 return StepVal > MaxMergeDistance;
4772 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
4773 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
4779 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
4780 // If we know that this instruction will remain uniform, check the cost of
4781 // the scalar version.
4782 if (Legal->isUniformAfterVectorization(I))
4785 Type *RetTy = I->getType();
4786 Type *VectorTy = ToVectorTy(RetTy, VF);
4788 // TODO: We need to estimate the cost of intrinsic calls.
4789 switch (I->getOpcode()) {
4790 case Instruction::GetElementPtr:
4791 // We mark this instruction as zero-cost because the cost of GEPs in
4792 // vectorized code depends on whether the corresponding memory instruction
4793 // is scalarized or not. Therefore, we handle GEPs with the memory
4794 // instruction cost.
4796 case Instruction::Br: {
4797 return TTI.getCFInstrCost(I->getOpcode());
4799 case Instruction::PHI:
4800 //TODO: IF-converted IFs become selects.
4802 case Instruction::Add:
4803 case Instruction::FAdd:
4804 case Instruction::Sub:
4805 case Instruction::FSub:
4806 case Instruction::Mul:
4807 case Instruction::FMul:
4808 case Instruction::UDiv:
4809 case Instruction::SDiv:
4810 case Instruction::FDiv:
4811 case Instruction::URem:
4812 case Instruction::SRem:
4813 case Instruction::FRem:
4814 case Instruction::Shl:
4815 case Instruction::LShr:
4816 case Instruction::AShr:
4817 case Instruction::And:
4818 case Instruction::Or:
4819 case Instruction::Xor: {
4820 // Since we will replace the stride by 1 the multiplication should go away.
4821 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
4823 // Certain instructions can be cheaper to vectorize if they have a constant
4824 // second vector operand. One example of this are shifts on x86.
4825 TargetTransformInfo::OperandValueKind Op1VK =
4826 TargetTransformInfo::OK_AnyValue;
4827 TargetTransformInfo::OperandValueKind Op2VK =
4828 TargetTransformInfo::OK_AnyValue;
4829 TargetTransformInfo::OperandValueProperties Op1VP =
4830 TargetTransformInfo::OP_None;
4831 TargetTransformInfo::OperandValueProperties Op2VP =
4832 TargetTransformInfo::OP_None;
4833 Value *Op2 = I->getOperand(1);
4835 // Check for a splat of a constant or for a non uniform vector of constants.
4836 if (isa<ConstantInt>(Op2)) {
4837 ConstantInt *CInt = cast<ConstantInt>(Op2);
4838 if (CInt && CInt->getValue().isPowerOf2())
4839 Op2VP = TargetTransformInfo::OP_PowerOf2;
4840 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4841 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
4842 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
4843 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
4845 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
4846 if (CInt && CInt->getValue().isPowerOf2())
4847 Op2VP = TargetTransformInfo::OP_PowerOf2;
4848 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4852 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
4855 case Instruction::Select: {
4856 SelectInst *SI = cast<SelectInst>(I);
4857 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
4858 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
4859 Type *CondTy = SI->getCondition()->getType();
4861 CondTy = VectorType::get(CondTy, VF);
4863 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
4865 case Instruction::ICmp:
4866 case Instruction::FCmp: {
4867 Type *ValTy = I->getOperand(0)->getType();
4868 VectorTy = ToVectorTy(ValTy, VF);
4869 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
4871 case Instruction::Store:
4872 case Instruction::Load: {
4873 StoreInst *SI = dyn_cast<StoreInst>(I);
4874 LoadInst *LI = dyn_cast<LoadInst>(I);
4875 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
4877 VectorTy = ToVectorTy(ValTy, VF);
4879 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
4880 unsigned AS = SI ? SI->getPointerAddressSpace() :
4881 LI->getPointerAddressSpace();
4882 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
4883 // We add the cost of address computation here instead of with the gep
4884 // instruction because only here we know whether the operation is
4887 return TTI.getAddressComputationCost(VectorTy) +
4888 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4890 // Scalarized loads/stores.
4891 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
4892 bool Reverse = ConsecutiveStride < 0;
4893 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
4894 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
4895 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
4896 bool IsComplexComputation =
4897 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
4899 // The cost of extracting from the value vector and pointer vector.
4900 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
4901 for (unsigned i = 0; i < VF; ++i) {
4902 // The cost of extracting the pointer operand.
4903 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
4904 // In case of STORE, the cost of ExtractElement from the vector.
4905 // In case of LOAD, the cost of InsertElement into the returned
4907 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
4908 Instruction::InsertElement,
4912 // The cost of the scalar loads/stores.
4913 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
4914 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
4919 // Wide load/stores.
4920 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
4921 if (Legal->isMaskRequired(I))
4922 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
4925 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4928 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4932 case Instruction::ZExt:
4933 case Instruction::SExt:
4934 case Instruction::FPToUI:
4935 case Instruction::FPToSI:
4936 case Instruction::FPExt:
4937 case Instruction::PtrToInt:
4938 case Instruction::IntToPtr:
4939 case Instruction::SIToFP:
4940 case Instruction::UIToFP:
4941 case Instruction::Trunc:
4942 case Instruction::FPTrunc:
4943 case Instruction::BitCast: {
4944 // We optimize the truncation of induction variable.
4945 // The cost of these is the same as the scalar operation.
4946 if (I->getOpcode() == Instruction::Trunc &&
4947 Legal->isInductionVariable(I->getOperand(0)))
4948 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
4949 I->getOperand(0)->getType());
4951 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
4952 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
4954 case Instruction::Call: {
4955 CallInst *CI = cast<CallInst>(I);
4956 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
4957 assert(ID && "Not an intrinsic call!");
4958 Type *RetTy = ToVectorTy(CI->getType(), VF);
4959 SmallVector<Type*, 4> Tys;
4960 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
4961 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
4962 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
4965 // We are scalarizing the instruction. Return the cost of the scalar
4966 // instruction, plus the cost of insert and extract into vector
4967 // elements, times the vector width.
4970 if (!RetTy->isVoidTy() && VF != 1) {
4971 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
4973 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
4976 // The cost of inserting the results plus extracting each one of the
4978 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
4981 // The cost of executing VF copies of the scalar instruction. This opcode
4982 // is unknown. Assume that it is the same as 'mul'.
4983 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
4989 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
4990 if (Scalar->isVoidTy() || VF == 1)
4992 return VectorType::get(Scalar, VF);
4995 char LoopVectorize::ID = 0;
4996 static const char lv_name[] = "Loop Vectorization";
4997 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
4998 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
4999 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
5000 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5001 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5002 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5003 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5004 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5005 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5006 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5007 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5010 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5011 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5015 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5016 // Check for a store.
5017 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5018 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5020 // Check for a load.
5021 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5022 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5028 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5029 bool IfPredicateStore) {
5030 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5031 // Holds vector parameters or scalars, in case of uniform vals.
5032 SmallVector<VectorParts, 4> Params;
5034 setDebugLocFromInst(Builder, Instr);
5036 // Find all of the vectorized parameters.
5037 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5038 Value *SrcOp = Instr->getOperand(op);
5040 // If we are accessing the old induction variable, use the new one.
5041 if (SrcOp == OldInduction) {
5042 Params.push_back(getVectorValue(SrcOp));
5046 // Try using previously calculated values.
5047 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5049 // If the src is an instruction that appeared earlier in the basic block
5050 // then it should already be vectorized.
5051 if (SrcInst && OrigLoop->contains(SrcInst)) {
5052 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5053 // The parameter is a vector value from earlier.
5054 Params.push_back(WidenMap.get(SrcInst));
5056 // The parameter is a scalar from outside the loop. Maybe even a constant.
5057 VectorParts Scalars;
5058 Scalars.append(UF, SrcOp);
5059 Params.push_back(Scalars);
5063 assert(Params.size() == Instr->getNumOperands() &&
5064 "Invalid number of operands");
5066 // Does this instruction return a value ?
5067 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5069 Value *UndefVec = IsVoidRetTy ? nullptr :
5070 UndefValue::get(Instr->getType());
5071 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5072 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5074 Instruction *InsertPt = Builder.GetInsertPoint();
5075 BasicBlock *IfBlock = Builder.GetInsertBlock();
5076 BasicBlock *CondBlock = nullptr;
5079 Loop *VectorLp = nullptr;
5080 if (IfPredicateStore) {
5081 assert(Instr->getParent()->getSinglePredecessor() &&
5082 "Only support single predecessor blocks");
5083 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5084 Instr->getParent());
5085 VectorLp = LI->getLoopFor(IfBlock);
5086 assert(VectorLp && "Must have a loop for this block");
5089 // For each vector unroll 'part':
5090 for (unsigned Part = 0; Part < UF; ++Part) {
5091 // For each scalar that we create:
5093 // Start an "if (pred) a[i] = ..." block.
5094 Value *Cmp = nullptr;
5095 if (IfPredicateStore) {
5096 if (Cond[Part]->getType()->isVectorTy())
5098 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5099 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5100 ConstantInt::get(Cond[Part]->getType(), 1));
5101 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5102 LoopVectorBody.push_back(CondBlock);
5103 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
5104 // Update Builder with newly created basic block.
5105 Builder.SetInsertPoint(InsertPt);
5108 Instruction *Cloned = Instr->clone();
5110 Cloned->setName(Instr->getName() + ".cloned");
5111 // Replace the operands of the cloned instructions with extracted scalars.
5112 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5113 Value *Op = Params[op][Part];
5114 Cloned->setOperand(op, Op);
5117 // Place the cloned scalar in the new loop.
5118 Builder.Insert(Cloned);
5120 // If the original scalar returns a value we need to place it in a vector
5121 // so that future users will be able to use it.
5123 VecResults[Part] = Cloned;
5126 if (IfPredicateStore) {
5127 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5128 LoopVectorBody.push_back(NewIfBlock);
5129 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
5130 Builder.SetInsertPoint(InsertPt);
5131 Instruction *OldBr = IfBlock->getTerminator();
5132 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
5133 OldBr->eraseFromParent();
5134 IfBlock = NewIfBlock;
5139 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5140 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5141 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5143 return scalarizeInstruction(Instr, IfPredicateStore);
5146 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5150 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5154 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5155 // When unrolling and the VF is 1, we only need to add a simple scalar.
5156 Type *ITy = Val->getType();
5157 assert(!ITy->isVectorTy() && "Val must be a scalar");
5158 Constant *C = ConstantInt::get(ITy, StartIdx);
5159 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");