1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR.
12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
13 // of instructions in order to estimate the profitability of vectorization.
15 // The loop vectorizer combines consecutive loop iterations into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A unit that checks for the legality
22 // of the vectorization.
23 // 3. InnerLoopVectorizer - A unit that performs the actual
24 // widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 // of vectorization. It decides on the optimal vector width, which
27 // can be one, if vectorization is not profitable.
29 //===----------------------------------------------------------------------===//
31 // The reduction-variable vectorization is based on the paper:
32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
37 // Other ideas/concepts are from:
38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
41 // Vectorizing Compilers.
43 //===----------------------------------------------------------------------===//
45 #include "llvm/Transforms/Vectorize.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/EquivalenceClasses.h"
48 #include "llvm/ADT/Hashing.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/ADT/StringExtras.h"
56 #include "llvm/Analysis/AliasAnalysis.h"
57 #include "llvm/Analysis/AliasSetTracker.h"
58 #include "llvm/Analysis/AssumptionCache.h"
59 #include "llvm/Analysis/BlockFrequencyInfo.h"
60 #include "llvm/Analysis/CodeMetrics.h"
61 #include "llvm/Analysis/LoopAccessAnalysis.h"
62 #include "llvm/Analysis/LoopInfo.h"
63 #include "llvm/Analysis/LoopIterator.h"
64 #include "llvm/Analysis/LoopPass.h"
65 #include "llvm/Analysis/ScalarEvolution.h"
66 #include "llvm/Analysis/ScalarEvolutionExpander.h"
67 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
68 #include "llvm/Analysis/TargetTransformInfo.h"
69 #include "llvm/Analysis/ValueTracking.h"
70 #include "llvm/IR/Constants.h"
71 #include "llvm/IR/DataLayout.h"
72 #include "llvm/IR/DebugInfo.h"
73 #include "llvm/IR/DerivedTypes.h"
74 #include "llvm/IR/DiagnosticInfo.h"
75 #include "llvm/IR/Dominators.h"
76 #include "llvm/IR/Function.h"
77 #include "llvm/IR/IRBuilder.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/LLVMContext.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/Value.h"
85 #include "llvm/IR/ValueHandle.h"
86 #include "llvm/IR/Verifier.h"
87 #include "llvm/Pass.h"
88 #include "llvm/Support/BranchProbability.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Transforms/Scalar.h"
93 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
94 #include "llvm/Transforms/Utils/Local.h"
95 #include "llvm/Transforms/Utils/VectorUtils.h"
100 using namespace llvm;
101 using namespace llvm::PatternMatch;
103 #define LV_NAME "loop-vectorize"
104 #define DEBUG_TYPE LV_NAME
106 STATISTIC(LoopsVectorized, "Number of loops vectorized");
107 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
109 static cl::opt<unsigned>
110 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
111 cl::desc("Sets the SIMD width. Zero is autoselect."));
113 static cl::opt<unsigned>
114 VectorizationInterleave("force-vector-interleave", cl::init(0), cl::Hidden,
115 cl::desc("Sets the vectorization interleave count. "
116 "Zero is autoselect."));
119 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
120 cl::desc("Enable if-conversion during vectorization."));
122 /// We don't vectorize loops with a known constant trip count below this number.
123 static cl::opt<unsigned>
124 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
126 cl::desc("Don't vectorize loops with a constant "
127 "trip count that is smaller than this "
130 /// This enables versioning on the strides of symbolically striding memory
131 /// accesses in code like the following.
132 /// for (i = 0; i < N; ++i)
133 /// A[i * Stride1] += B[i * Stride2] ...
135 /// Will be roughly translated to
136 /// if (Stride1 == 1 && Stride2 == 1) {
137 /// for (i = 0; i < N; i+=4)
141 static cl::opt<bool> EnableMemAccessVersioning(
142 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
143 cl::desc("Enable symblic stride memory access versioning"));
145 /// We don't unroll loops with a known constant trip count below this number.
146 static const unsigned TinyTripCountUnrollThreshold = 128;
148 /// When performing memory disambiguation checks at runtime do not make more
149 /// than this number of comparisons.
150 static const unsigned RuntimeMemoryCheckThreshold = 8;
152 /// Maximum simd width.
153 static const unsigned MaxVectorWidth = 64;
155 static cl::opt<unsigned> ForceTargetNumScalarRegs(
156 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
157 cl::desc("A flag that overrides the target's number of scalar registers."));
159 static cl::opt<unsigned> ForceTargetNumVectorRegs(
160 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
161 cl::desc("A flag that overrides the target's number of vector registers."));
163 /// Maximum vectorization interleave count.
164 static const unsigned MaxInterleaveFactor = 16;
166 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
167 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
168 cl::desc("A flag that overrides the target's max interleave factor for "
171 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
172 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
173 cl::desc("A flag that overrides the target's max interleave factor for "
174 "vectorized loops."));
176 static cl::opt<unsigned> ForceTargetInstructionCost(
177 "force-target-instruction-cost", cl::init(0), cl::Hidden,
178 cl::desc("A flag that overrides the target's expected cost for "
179 "an instruction to a single constant value. Mostly "
180 "useful for getting consistent testing."));
182 static cl::opt<unsigned> SmallLoopCost(
183 "small-loop-cost", cl::init(20), cl::Hidden,
184 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
186 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
187 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
188 cl::desc("Enable the use of the block frequency analysis to access PGO "
189 "heuristics minimizing code growth in cold regions and being more "
190 "aggressive in hot regions."));
192 // Runtime unroll loops for load/store throughput.
193 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
194 "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
195 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
197 /// The number of stores in a loop that are allowed to need predication.
198 static cl::opt<unsigned> NumberOfStoresToPredicate(
199 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
200 cl::desc("Max number of stores to be predicated behind an if."));
202 static cl::opt<bool> EnableIndVarRegisterHeur(
203 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
204 cl::desc("Count the induction variable only once when unrolling"));
206 static cl::opt<bool> EnableCondStoresVectorization(
207 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
208 cl::desc("Enable if predication of stores during vectorization."));
210 static cl::opt<unsigned> MaxNestedScalarReductionUF(
211 "max-nested-scalar-reduction-unroll", cl::init(2), cl::Hidden,
212 cl::desc("The maximum unroll factor to use when unrolling a scalar "
213 "reduction in a nested loop."));
217 // Forward declarations.
218 class LoopVectorizationLegality;
219 class LoopVectorizationCostModel;
220 class LoopVectorizeHints;
222 /// InnerLoopVectorizer vectorizes loops which contain only one basic
223 /// block to a specified vectorization factor (VF).
224 /// This class performs the widening of scalars into vectors, or multiple
225 /// scalars. This class also implements the following features:
226 /// * It inserts an epilogue loop for handling loops that don't have iteration
227 /// counts that are known to be a multiple of the vectorization factor.
228 /// * It handles the code generation for reduction variables.
229 /// * Scalarization (implementation using scalars) of un-vectorizable
231 /// InnerLoopVectorizer does not perform any vectorization-legality
232 /// checks, and relies on the caller to check for the different legality
233 /// aspects. The InnerLoopVectorizer relies on the
234 /// LoopVectorizationLegality class to provide information about the induction
235 /// and reduction variables that were found to a given vectorization factor.
236 class InnerLoopVectorizer {
238 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
239 DominatorTree *DT, const DataLayout *DL,
240 const TargetLibraryInfo *TLI, unsigned VecWidth,
241 unsigned UnrollFactor)
242 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
243 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
244 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
247 // Perform the actual loop widening (vectorization).
248 void vectorize(LoopVectorizationLegality *L) {
250 // Create a new empty loop. Unlink the old loop and connect the new one.
252 // Widen each instruction in the old loop to a new one in the new loop.
253 // Use the Legality module to find the induction and reduction variables.
255 // Register the new loop and update the analysis passes.
259 virtual ~InnerLoopVectorizer() {}
262 /// A small list of PHINodes.
263 typedef SmallVector<PHINode*, 4> PhiVector;
264 /// When we unroll loops we have multiple vector values for each scalar.
265 /// This data structure holds the unrolled and vectorized values that
266 /// originated from one scalar instruction.
267 typedef SmallVector<Value*, 2> VectorParts;
269 // When we if-convert we need create edge masks. We have to cache values so
270 // that we don't end up with exponential recursion/IR.
271 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
272 VectorParts> EdgeMaskCache;
274 /// \brief Add checks for strides that where assumed to be 1.
276 /// Returns the last check instruction and the first check instruction in the
277 /// pair as (first, last).
278 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
280 /// Create an empty loop, based on the loop ranges of the old loop.
281 void createEmptyLoop();
282 /// Copy and widen the instructions from the old loop.
283 virtual void vectorizeLoop();
285 /// \brief The Loop exit block may have single value PHI nodes where the
286 /// incoming value is 'Undef'. While vectorizing we only handled real values
287 /// that were defined inside the loop. Here we fix the 'undef case'.
291 /// A helper function that computes the predicate of the block BB, assuming
292 /// that the header block of the loop is set to True. It returns the *entry*
293 /// mask for the block BB.
294 VectorParts createBlockInMask(BasicBlock *BB);
295 /// A helper function that computes the predicate of the edge between SRC
297 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
299 /// A helper function to vectorize a single BB within the innermost loop.
300 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
302 /// Vectorize a single PHINode in a block. This method handles the induction
303 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
304 /// arbitrary length vectors.
305 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
306 unsigned UF, unsigned VF, PhiVector *PV);
308 /// Insert the new loop to the loop hierarchy and pass manager
309 /// and update the analysis passes.
310 void updateAnalysis();
312 /// This instruction is un-vectorizable. Implement it as a sequence
313 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
314 /// scalarized instruction behind an if block predicated on the control
315 /// dependence of the instruction.
316 virtual void scalarizeInstruction(Instruction *Instr,
317 bool IfPredicateStore=false);
319 /// Vectorize Load and Store instructions,
320 virtual void vectorizeMemoryInstruction(Instruction *Instr);
322 /// Create a broadcast instruction. This method generates a broadcast
323 /// instruction (shuffle) for loop invariant values and for the induction
324 /// value. If this is the induction variable then we extend it to N, N+1, ...
325 /// this is needed because each iteration in the loop corresponds to a SIMD
327 virtual Value *getBroadcastInstrs(Value *V);
329 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
330 /// to each vector element of Val. The sequence starts at StartIndex.
331 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
333 /// When we go over instructions in the basic block we rely on previous
334 /// values within the current basic block or on loop invariant values.
335 /// When we widen (vectorize) values we place them in the map. If the values
336 /// are not within the map, they have to be loop invariant, so we simply
337 /// broadcast them into a vector.
338 VectorParts &getVectorValue(Value *V);
340 /// Generate a shuffle sequence that will reverse the vector Vec.
341 virtual Value *reverseVector(Value *Vec);
343 /// This is a helper class that holds the vectorizer state. It maps scalar
344 /// instructions to vector instructions. When the code is 'unrolled' then
345 /// then a single scalar value is mapped to multiple vector parts. The parts
346 /// are stored in the VectorPart type.
348 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
350 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
352 /// \return True if 'Key' is saved in the Value Map.
353 bool has(Value *Key) const { return MapStorage.count(Key); }
355 /// Initializes a new entry in the map. Sets all of the vector parts to the
356 /// save value in 'Val'.
357 /// \return A reference to a vector with splat values.
358 VectorParts &splat(Value *Key, Value *Val) {
359 VectorParts &Entry = MapStorage[Key];
360 Entry.assign(UF, Val);
364 ///\return A reference to the value that is stored at 'Key'.
365 VectorParts &get(Value *Key) {
366 VectorParts &Entry = MapStorage[Key];
369 assert(Entry.size() == UF);
374 /// The unroll factor. Each entry in the map stores this number of vector
378 /// Map storage. We use std::map and not DenseMap because insertions to a
379 /// dense map invalidates its iterators.
380 std::map<Value *, VectorParts> MapStorage;
383 /// The original loop.
385 /// Scev analysis to use.
394 const DataLayout *DL;
395 /// Target Library Info.
396 const TargetLibraryInfo *TLI;
398 /// The vectorization SIMD factor to use. Each vector will have this many
403 /// The vectorization unroll factor to use. Each scalar is vectorized to this
404 /// many different vector instructions.
407 /// The builder that we use
410 // --- Vectorization state ---
412 /// The vector-loop preheader.
413 BasicBlock *LoopVectorPreHeader;
414 /// The scalar-loop preheader.
415 BasicBlock *LoopScalarPreHeader;
416 /// Middle Block between the vector and the scalar.
417 BasicBlock *LoopMiddleBlock;
418 ///The ExitBlock of the scalar loop.
419 BasicBlock *LoopExitBlock;
420 ///The vector loop body.
421 SmallVector<BasicBlock *, 4> LoopVectorBody;
422 ///The scalar loop body.
423 BasicBlock *LoopScalarBody;
424 /// A list of all bypass blocks. The first block is the entry of the loop.
425 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
427 /// The new Induction variable which was added to the new block.
429 /// The induction variable of the old basic block.
430 PHINode *OldInduction;
431 /// Holds the extended (to the widest induction type) start index.
433 /// Maps scalars to widened vectors.
435 EdgeMaskCache MaskCache;
437 LoopVectorizationLegality *Legal;
440 class InnerLoopUnroller : public InnerLoopVectorizer {
442 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
443 DominatorTree *DT, const DataLayout *DL,
444 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
445 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
448 void scalarizeInstruction(Instruction *Instr,
449 bool IfPredicateStore = false) override;
450 void vectorizeMemoryInstruction(Instruction *Instr) override;
451 Value *getBroadcastInstrs(Value *V) override;
452 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
453 Value *reverseVector(Value *Vec) override;
456 /// \brief Look for a meaningful debug location on the instruction or it's
458 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
463 if (I->getDebugLoc() != Empty)
466 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
467 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
468 if (OpInst->getDebugLoc() != Empty)
475 /// \brief Set the debug location in the builder using the debug location in the
477 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
478 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
479 B.SetCurrentDebugLocation(Inst->getDebugLoc());
481 B.SetCurrentDebugLocation(DebugLoc());
485 /// \return string containing a file name and a line # for the given loop.
486 static std::string getDebugLocString(const Loop *L) {
489 raw_string_ostream OS(Result);
490 const DebugLoc LoopDbgLoc = L->getStartLoc();
491 if (!LoopDbgLoc.isUnknown())
492 LoopDbgLoc.print(L->getHeader()->getContext(), OS);
494 // Just print the module name.
495 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
502 /// \brief Propagate known metadata from one instruction to another.
503 static void propagateMetadata(Instruction *To, const Instruction *From) {
504 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
505 From->getAllMetadataOtherThanDebugLoc(Metadata);
507 for (auto M : Metadata) {
508 unsigned Kind = M.first;
510 // These are safe to transfer (this is safe for TBAA, even when we
511 // if-convert, because should that metadata have had a control dependency
512 // on the condition, and thus actually aliased with some other
513 // non-speculated memory access when the condition was false, this would be
514 // caught by the runtime overlap checks).
515 if (Kind != LLVMContext::MD_tbaa &&
516 Kind != LLVMContext::MD_alias_scope &&
517 Kind != LLVMContext::MD_noalias &&
518 Kind != LLVMContext::MD_fpmath)
521 To->setMetadata(Kind, M.second);
525 /// \brief Propagate known metadata from one instruction to a vector of others.
526 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
528 if (Instruction *I = dyn_cast<Instruction>(V))
529 propagateMetadata(I, From);
532 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
533 /// to what vectorization factor.
534 /// This class does not look at the profitability of vectorization, only the
535 /// legality. This class has two main kinds of checks:
536 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
537 /// will change the order of memory accesses in a way that will change the
538 /// correctness of the program.
539 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
540 /// checks for a number of different conditions, such as the availability of a
541 /// single induction variable, that all types are supported and vectorize-able,
542 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
543 /// This class is also used by InnerLoopVectorizer for identifying
544 /// induction variable and the different reduction variables.
545 class LoopVectorizationLegality {
547 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
548 DominatorTree *DT, TargetLibraryInfo *TLI,
549 AliasAnalysis *AA, Function *F,
550 const TargetTransformInfo *TTI)
551 : NumPredStores(0), TheLoop(L), SE(SE), DL(DL), TLI(TLI), TheFunction(F),
552 TTI(TTI), DT(DT), Induction(nullptr), WidestIndTy(nullptr),
553 LAI(F, L, SE, DL, TLI, AA, DT,
554 LoopAccessInfo::VectorizerParams(
555 MaxVectorWidth, VectorizationFactor, VectorizationInterleave,
556 RuntimeMemoryCheckThreshold)),
557 HasFunNoNaNAttr(false) {}
559 /// This enum represents the kinds of reductions that we support.
561 RK_NoReduction, ///< Not a reduction.
562 RK_IntegerAdd, ///< Sum of integers.
563 RK_IntegerMult, ///< Product of integers.
564 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
565 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
566 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
567 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
568 RK_FloatAdd, ///< Sum of floats.
569 RK_FloatMult, ///< Product of floats.
570 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
573 /// This enum represents the kinds of inductions that we support.
575 IK_NoInduction, ///< Not an induction variable.
576 IK_IntInduction, ///< Integer induction variable. Step = C.
577 IK_PtrInduction ///< Pointer induction var. Step = C / sizeof(elem).
580 // This enum represents the kind of minmax reduction.
581 enum MinMaxReductionKind {
591 /// This struct holds information about reduction variables.
592 struct ReductionDescriptor {
593 ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
594 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
596 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
597 MinMaxReductionKind MK)
598 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
600 // The starting value of the reduction.
601 // It does not have to be zero!
602 TrackingVH<Value> StartValue;
603 // The instruction who's value is used outside the loop.
604 Instruction *LoopExitInstr;
605 // The kind of the reduction.
607 // If this a min/max reduction the kind of reduction.
608 MinMaxReductionKind MinMaxKind;
611 /// This POD struct holds information about a potential reduction operation.
612 struct ReductionInstDesc {
613 ReductionInstDesc(bool IsRedux, Instruction *I) :
614 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
616 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
617 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
619 // Is this instruction a reduction candidate.
621 // The last instruction in a min/max pattern (select of the select(icmp())
622 // pattern), or the current reduction instruction otherwise.
623 Instruction *PatternLastInst;
624 // If this is a min/max pattern the comparison predicate.
625 MinMaxReductionKind MinMaxKind;
628 /// A struct for saving information about induction variables.
629 struct InductionInfo {
630 InductionInfo(Value *Start, InductionKind K, ConstantInt *Step)
631 : StartValue(Start), IK(K), StepValue(Step) {
632 assert(IK != IK_NoInduction && "Not an induction");
633 assert(StartValue && "StartValue is null");
634 assert(StepValue && !StepValue->isZero() && "StepValue is zero");
635 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
636 "StartValue is not a pointer for pointer induction");
637 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
638 "StartValue is not an integer for integer induction");
639 assert(StepValue->getType()->isIntegerTy() &&
640 "StepValue is not an integer");
643 : StartValue(nullptr), IK(IK_NoInduction), StepValue(nullptr) {}
645 /// Get the consecutive direction. Returns:
646 /// 0 - unknown or non-consecutive.
647 /// 1 - consecutive and increasing.
648 /// -1 - consecutive and decreasing.
649 int getConsecutiveDirection() const {
650 if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
651 return StepValue->getSExtValue();
655 /// Compute the transformed value of Index at offset StartValue using step
657 /// For integer induction, returns StartValue + Index * StepValue.
658 /// For pointer induction, returns StartValue[Index * StepValue].
659 /// FIXME: The newly created binary instructions should contain nsw/nuw
660 /// flags, which can be found from the original scalar operations.
661 Value *transform(IRBuilder<> &B, Value *Index) const {
663 case IK_IntInduction:
664 assert(Index->getType() == StartValue->getType() &&
665 "Index type does not match StartValue type");
666 if (StepValue->isMinusOne())
667 return B.CreateSub(StartValue, Index);
668 if (!StepValue->isOne())
669 Index = B.CreateMul(Index, StepValue);
670 return B.CreateAdd(StartValue, Index);
672 case IK_PtrInduction:
673 if (StepValue->isMinusOne())
674 Index = B.CreateNeg(Index);
675 else if (!StepValue->isOne())
676 Index = B.CreateMul(Index, StepValue);
677 return B.CreateGEP(StartValue, Index);
682 llvm_unreachable("invalid enum");
686 TrackingVH<Value> StartValue;
690 ConstantInt *StepValue;
693 /// ReductionList contains the reduction descriptors for all
694 /// of the reductions that were found in the loop.
695 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
697 /// InductionList saves induction variables and maps them to the
698 /// induction descriptor.
699 typedef MapVector<PHINode*, InductionInfo> InductionList;
701 /// Returns true if it is legal to vectorize this loop.
702 /// This does not mean that it is profitable to vectorize this
703 /// loop, only that it is legal to do so.
706 /// Returns the Induction variable.
707 PHINode *getInduction() { return Induction; }
709 /// Returns the reduction variables found in the loop.
710 ReductionList *getReductionVars() { return &Reductions; }
712 /// Returns the induction variables found in the loop.
713 InductionList *getInductionVars() { return &Inductions; }
715 /// Returns the widest induction type.
716 Type *getWidestInductionType() { return WidestIndTy; }
718 /// Returns True if V is an induction variable in this loop.
719 bool isInductionVariable(const Value *V);
721 /// Return true if the block BB needs to be predicated in order for the loop
722 /// to be vectorized.
723 bool blockNeedsPredication(BasicBlock *BB);
725 /// Check if this pointer is consecutive when vectorizing. This happens
726 /// when the last index of the GEP is the induction variable, or that the
727 /// pointer itself is an induction variable.
728 /// This check allows us to vectorize A[idx] into a wide load/store.
730 /// 0 - Stride is unknown or non-consecutive.
731 /// 1 - Address is consecutive.
732 /// -1 - Address is consecutive, and decreasing.
733 int isConsecutivePtr(Value *Ptr);
735 /// Returns true if the value V is uniform within the loop.
736 bool isUniform(Value *V);
738 /// Returns true if this instruction will remain scalar after vectorization.
739 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
741 /// Returns the information that we collected about runtime memory check.
742 LoopAccessInfo::RuntimePointerCheck *getRuntimePointerCheck() {
743 return LAI.getRuntimePointerCheck();
746 LoopAccessInfo *getLAI() { return &LAI; }
748 /// This function returns the identity element (or neutral element) for
750 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
752 unsigned getMaxSafeDepDistBytes() { return LAI.getMaxSafeDepDistBytes(); }
754 bool hasStride(Value *V) { return StrideSet.count(V); }
755 bool mustCheckStrides() { return !StrideSet.empty(); }
756 SmallPtrSet<Value *, 8>::iterator strides_begin() {
757 return StrideSet.begin();
759 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
761 /// Returns true if the target machine supports masked store operation
762 /// for the given \p DataType and kind of access to \p Ptr.
763 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
764 return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
766 /// Returns true if the target machine supports masked load operation
767 /// for the given \p DataType and kind of access to \p Ptr.
768 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
769 return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
771 /// Returns true if vector representation of the instruction \p I
773 bool isMaskRequired(const Instruction *I) { return (MaskedOp.count(I) != 0); }
774 unsigned getNumStores() const { return LAI.getNumStores(); }
775 unsigned getNumLoads() const { return LAI.getNumLoads(); }
776 unsigned getNumPredStores() const { return NumPredStores; }
779 /// Check if a single basic block loop is vectorizable.
780 /// At this point we know that this is a loop with a constant trip count
781 /// and we only need to check individual instructions.
782 bool canVectorizeInstrs();
784 /// When we vectorize loops we may change the order in which
785 /// we read and write from memory. This method checks if it is
786 /// legal to vectorize the code, considering only memory constrains.
787 /// Returns true if the loop is vectorizable
788 bool canVectorizeMemory();
790 /// Return true if we can vectorize this loop using the IF-conversion
792 bool canVectorizeWithIfConvert();
794 /// Collect the variables that need to stay uniform after vectorization.
795 void collectLoopUniforms();
797 /// Return true if all of the instructions in the block can be speculatively
798 /// executed. \p SafePtrs is a list of addresses that are known to be legal
799 /// and we know that we can read from them without segfault.
800 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
802 /// Returns True, if 'Phi' is the kind of reduction variable for type
803 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
804 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
805 /// Returns a struct describing if the instruction 'I' can be a reduction
806 /// variable of type 'Kind'. If the reduction is a min/max pattern of
807 /// select(icmp()) this function advances the instruction pointer 'I' from the
808 /// compare instruction to the select instruction and stores this pointer in
809 /// 'PatternLastInst' member of the returned struct.
810 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
811 ReductionInstDesc &Desc);
812 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
813 /// pattern corresponding to a min(X, Y) or max(X, Y).
814 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
815 ReductionInstDesc &Prev);
816 /// Returns the induction kind of Phi and record the step. This function may
817 /// return NoInduction if the PHI is not an induction variable.
818 InductionKind isInductionVariable(PHINode *Phi, ConstantInt *&StepValue);
820 /// \brief Collect memory access with loop invariant strides.
822 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
824 void collectStridedAccess(Value *LoadOrStoreInst);
826 /// Report an analysis message to assist the user in diagnosing loops that are
828 void emitAnalysis(VectorizationReport &Message) {
829 VectorizationReport::emitAnalysis(Message, TheFunction, TheLoop);
832 unsigned NumPredStores;
834 /// The loop that we evaluate.
838 /// DataLayout analysis.
839 const DataLayout *DL;
840 /// Target Library Info.
841 TargetLibraryInfo *TLI;
843 Function *TheFunction;
844 /// Target Transform Info
845 const TargetTransformInfo *TTI;
849 // --- vectorization state --- //
851 /// Holds the integer induction variable. This is the counter of the
854 /// Holds the reduction variables.
855 ReductionList Reductions;
856 /// Holds all of the induction variables that we found in the loop.
857 /// Notice that inductions don't need to start at zero and that induction
858 /// variables can be pointers.
859 InductionList Inductions;
860 /// Holds the widest induction type encountered.
863 /// Allowed outside users. This holds the reduction
864 /// vars which can be accessed from outside the loop.
865 SmallPtrSet<Value*, 4> AllowedExit;
866 /// This set holds the variables which are known to be uniform after
868 SmallPtrSet<Instruction *, 4> Uniforms;
870 /// Can we assume the absence of NaNs.
871 bool HasFunNoNaNAttr;
873 ValueToValueMap Strides;
874 SmallPtrSet<Value *, 8> StrideSet;
876 /// While vectorizing these instructions we have to generate a
877 /// call to the appropriate masked intrinsic
878 SmallPtrSet<const Instruction*, 8> MaskedOp;
881 /// LoopVectorizationCostModel - estimates the expected speedups due to
883 /// In many cases vectorization is not profitable. This can happen because of
884 /// a number of reasons. In this class we mainly attempt to predict the
885 /// expected speedup/slowdowns due to the supported instruction set. We use the
886 /// TargetTransformInfo to query the different backends for the cost of
887 /// different operations.
888 class LoopVectorizationCostModel {
890 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
891 LoopVectorizationLegality *Legal,
892 const TargetTransformInfo &TTI,
893 const DataLayout *DL, const TargetLibraryInfo *TLI,
894 AssumptionCache *AC, const Function *F,
895 const LoopVectorizeHints *Hints)
896 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI),
897 TheFunction(F), Hints(Hints) {
898 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
901 /// Information about vectorization costs
902 struct VectorizationFactor {
903 unsigned Width; // Vector width with best cost
904 unsigned Cost; // Cost of the loop with that width
906 /// \return The most profitable vectorization factor and the cost of that VF.
907 /// This method checks every power of two up to VF. If UserVF is not ZERO
908 /// then this vectorization factor will be selected if vectorization is
910 VectorizationFactor selectVectorizationFactor(bool OptForSize);
912 /// \return The size (in bits) of the widest type in the code that
913 /// needs to be vectorized. We ignore values that remain scalar such as
914 /// 64 bit loop indices.
915 unsigned getWidestType();
917 /// \return The most profitable unroll factor.
918 /// If UserUF is non-zero then this method finds the best unroll-factor
919 /// based on register pressure and other parameters.
920 /// VF and LoopCost are the selected vectorization factor and the cost of the
922 unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost);
924 /// \brief A struct that represents some properties of the register usage
926 struct RegisterUsage {
927 /// Holds the number of loop invariant values that are used in the loop.
928 unsigned LoopInvariantRegs;
929 /// Holds the maximum number of concurrent live intervals in the loop.
930 unsigned MaxLocalUsers;
931 /// Holds the number of instructions in the loop.
932 unsigned NumInstructions;
935 /// \return information about the register usage of the loop.
936 RegisterUsage calculateRegisterUsage();
939 /// Returns the expected execution cost. The unit of the cost does
940 /// not matter because we use the 'cost' units to compare different
941 /// vector widths. The cost that is returned is *not* normalized by
942 /// the factor width.
943 unsigned expectedCost(unsigned VF);
945 /// Returns the execution time cost of an instruction for a given vector
946 /// width. Vector width of one means scalar.
947 unsigned getInstructionCost(Instruction *I, unsigned VF);
949 /// A helper function for converting Scalar types to vector types.
950 /// If the incoming type is void, we return void. If the VF is 1, we return
952 static Type* ToVectorTy(Type *Scalar, unsigned VF);
954 /// Returns whether the instruction is a load or store and will be a emitted
955 /// as a vector operation.
956 bool isConsecutiveLoadOrStore(Instruction *I);
958 /// Report an analysis message to assist the user in diagnosing loops that are
960 void emitAnalysis(VectorizationReport &Message) {
961 VectorizationReport::emitAnalysis(Message, TheFunction, TheLoop);
964 /// Values used only by @llvm.assume calls.
965 SmallPtrSet<const Value *, 32> EphValues;
967 /// The loop that we evaluate.
971 /// Loop Info analysis.
973 /// Vectorization legality.
974 LoopVectorizationLegality *Legal;
975 /// Vector target information.
976 const TargetTransformInfo &TTI;
977 /// Target data layout information.
978 const DataLayout *DL;
979 /// Target Library Info.
980 const TargetLibraryInfo *TLI;
981 const Function *TheFunction;
982 // Loop Vectorize Hint.
983 const LoopVectorizeHints *Hints;
986 /// Utility class for getting and setting loop vectorizer hints in the form
987 /// of loop metadata.
988 /// This class keeps a number of loop annotations locally (as member variables)
989 /// and can, upon request, write them back as metadata on the loop. It will
990 /// initially scan the loop for existing metadata, and will update the local
991 /// values based on information in the loop.
992 /// We cannot write all values to metadata, as the mere presence of some info,
993 /// for example 'force', means a decision has been made. So, we need to be
994 /// careful NOT to add them if the user hasn't specifically asked so.
995 class LoopVectorizeHints {
1002 /// Hint - associates name and validation with the hint value.
1005 unsigned Value; // This may have to change for non-numeric values.
1008 Hint(const char * Name, unsigned Value, HintKind Kind)
1009 : Name(Name), Value(Value), Kind(Kind) { }
1011 bool validate(unsigned Val) {
1014 return isPowerOf2_32(Val) && Val <= MaxVectorWidth;
1016 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1024 /// Vectorization width.
1026 /// Vectorization interleave factor.
1028 /// Vectorization forced
1031 /// Return the loop metadata prefix.
1032 static StringRef Prefix() { return "llvm.loop."; }
1036 FK_Undefined = -1, ///< Not selected.
1037 FK_Disabled = 0, ///< Forcing disabled.
1038 FK_Enabled = 1, ///< Forcing enabled.
1041 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1042 : Width("vectorize.width", VectorizationFactor, HK_WIDTH),
1043 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1044 Force("vectorize.enable", FK_Undefined, HK_FORCE),
1046 // Populate values with existing loop metadata.
1047 getHintsFromMetadata();
1049 // force-vector-interleave overrides DisableInterleaving.
1050 if (VectorizationInterleave.getNumOccurrences() > 0)
1051 Interleave.Value = VectorizationInterleave;
1053 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1054 << "LV: Interleaving disabled by the pass manager\n");
1057 /// Mark the loop L as already vectorized by setting the width to 1.
1058 void setAlreadyVectorized() {
1059 Width.Value = Interleave.Value = 1;
1060 Hint Hints[] = {Width, Interleave};
1061 writeHintsToMetadata(Hints);
1064 /// Dumps all the hint information.
1065 std::string emitRemark() const {
1066 VectorizationReport R;
1067 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1068 R << "vectorization is explicitly disabled";
1070 R << "use -Rpass-analysis=loop-vectorize for more info";
1071 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1072 R << " (Force=true";
1073 if (Width.Value != 0)
1074 R << ", Vector Width=" << Width.Value;
1075 if (Interleave.Value != 0)
1076 R << ", Interleave Count=" << Interleave.Value;
1084 unsigned getWidth() const { return Width.Value; }
1085 unsigned getInterleave() const { return Interleave.Value; }
1086 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1089 /// Find hints specified in the loop metadata and update local values.
1090 void getHintsFromMetadata() {
1091 MDNode *LoopID = TheLoop->getLoopID();
1095 // First operand should refer to the loop id itself.
1096 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1097 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1099 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1100 const MDString *S = nullptr;
1101 SmallVector<Metadata *, 4> Args;
1103 // The expected hint is either a MDString or a MDNode with the first
1104 // operand a MDString.
1105 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1106 if (!MD || MD->getNumOperands() == 0)
1108 S = dyn_cast<MDString>(MD->getOperand(0));
1109 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1110 Args.push_back(MD->getOperand(i));
1112 S = dyn_cast<MDString>(LoopID->getOperand(i));
1113 assert(Args.size() == 0 && "too many arguments for MDString");
1119 // Check if the hint starts with the loop metadata prefix.
1120 StringRef Name = S->getString();
1121 if (Args.size() == 1)
1122 setHint(Name, Args[0]);
1126 /// Checks string hint with one operand and set value if valid.
1127 void setHint(StringRef Name, Metadata *Arg) {
1128 if (!Name.startswith(Prefix()))
1130 Name = Name.substr(Prefix().size(), StringRef::npos);
1132 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1134 unsigned Val = C->getZExtValue();
1136 Hint *Hints[] = {&Width, &Interleave, &Force};
1137 for (auto H : Hints) {
1138 if (Name == H->Name) {
1139 if (H->validate(Val))
1142 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1148 /// Create a new hint from name / value pair.
1149 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1150 LLVMContext &Context = TheLoop->getHeader()->getContext();
1151 Metadata *MDs[] = {MDString::get(Context, Name),
1152 ConstantAsMetadata::get(
1153 ConstantInt::get(Type::getInt32Ty(Context), V))};
1154 return MDNode::get(Context, MDs);
1157 /// Matches metadata with hint name.
1158 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1159 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1163 for (auto H : HintTypes)
1164 if (Name->getString().endswith(H.Name))
1169 /// Sets current hints into loop metadata, keeping other values intact.
1170 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1171 if (HintTypes.size() == 0)
1174 // Reserve the first element to LoopID (see below).
1175 SmallVector<Metadata *, 4> MDs(1);
1176 // If the loop already has metadata, then ignore the existing operands.
1177 MDNode *LoopID = TheLoop->getLoopID();
1179 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1180 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1181 // If node in update list, ignore old value.
1182 if (!matchesHintMetadataName(Node, HintTypes))
1183 MDs.push_back(Node);
1187 // Now, add the missing hints.
1188 for (auto H : HintTypes)
1189 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1191 // Replace current metadata node with new one.
1192 LLVMContext &Context = TheLoop->getHeader()->getContext();
1193 MDNode *NewLoopID = MDNode::get(Context, MDs);
1194 // Set operand 0 to refer to the loop id itself.
1195 NewLoopID->replaceOperandWith(0, NewLoopID);
1197 TheLoop->setLoopID(NewLoopID);
1200 /// The loop these hints belong to.
1201 const Loop *TheLoop;
1204 static void emitMissedWarning(Function *F, Loop *L,
1205 const LoopVectorizeHints &LH) {
1206 emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1207 L->getStartLoc(), LH.emitRemark());
1209 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1210 if (LH.getWidth() != 1)
1211 emitLoopVectorizeWarning(
1212 F->getContext(), *F, L->getStartLoc(),
1213 "failed explicitly specified loop vectorization");
1214 else if (LH.getInterleave() != 1)
1215 emitLoopInterleaveWarning(
1216 F->getContext(), *F, L->getStartLoc(),
1217 "failed explicitly specified loop interleaving");
1221 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1223 return V.push_back(&L);
1225 for (Loop *InnerL : L)
1226 addInnerLoop(*InnerL, V);
1229 /// The LoopVectorize Pass.
1230 struct LoopVectorize : public FunctionPass {
1231 /// Pass identification, replacement for typeid
1234 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1236 DisableUnrolling(NoUnrolling),
1237 AlwaysVectorize(AlwaysVectorize) {
1238 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1241 ScalarEvolution *SE;
1242 const DataLayout *DL;
1244 TargetTransformInfo *TTI;
1246 BlockFrequencyInfo *BFI;
1247 TargetLibraryInfo *TLI;
1249 AssumptionCache *AC;
1250 bool DisableUnrolling;
1251 bool AlwaysVectorize;
1253 BlockFrequency ColdEntryFreq;
1255 bool runOnFunction(Function &F) override {
1256 SE = &getAnalysis<ScalarEvolution>();
1257 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1258 DL = DLP ? &DLP->getDataLayout() : nullptr;
1259 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1260 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1261 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1262 BFI = &getAnalysis<BlockFrequencyInfo>();
1263 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1264 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1265 AA = &getAnalysis<AliasAnalysis>();
1266 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1268 // Compute some weights outside of the loop over the loops. Compute this
1269 // using a BranchProbability to re-use its scaling math.
1270 const BranchProbability ColdProb(1, 5); // 20%
1271 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1273 // If the target claims to have no vector registers don't attempt
1275 if (!TTI->getNumberOfRegisters(true))
1279 DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1280 << ": Missing data layout\n");
1284 // Build up a worklist of inner-loops to vectorize. This is necessary as
1285 // the act of vectorizing or partially unrolling a loop creates new loops
1286 // and can invalidate iterators across the loops.
1287 SmallVector<Loop *, 8> Worklist;
1290 addInnerLoop(*L, Worklist);
1292 LoopsAnalyzed += Worklist.size();
1294 // Now walk the identified inner loops.
1295 bool Changed = false;
1296 while (!Worklist.empty())
1297 Changed |= processLoop(Worklist.pop_back_val());
1299 // Process each loop nest in the function.
1303 bool processLoop(Loop *L) {
1304 assert(L->empty() && "Only process inner loops.");
1307 const std::string DebugLocStr = getDebugLocString(L);
1310 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1311 << L->getHeader()->getParent()->getName() << "\" from "
1312 << DebugLocStr << "\n");
1314 LoopVectorizeHints Hints(L, DisableUnrolling);
1316 DEBUG(dbgs() << "LV: Loop hints:"
1318 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1320 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1322 : "?")) << " width=" << Hints.getWidth()
1323 << " unroll=" << Hints.getInterleave() << "\n");
1325 // Function containing loop
1326 Function *F = L->getHeader()->getParent();
1328 // Looking at the diagnostic output is the only way to determine if a loop
1329 // was vectorized (other than looking at the IR or machine code), so it
1330 // is important to generate an optimization remark for each loop. Most of
1331 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1332 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1333 // less verbose reporting vectorized loops and unvectorized loops that may
1334 // benefit from vectorization, respectively.
1336 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1337 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1338 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1339 L->getStartLoc(), Hints.emitRemark());
1343 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1344 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1345 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1346 L->getStartLoc(), Hints.emitRemark());
1350 if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
1351 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1352 emitOptimizationRemarkAnalysis(
1353 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1354 "loop not vectorized: vector width and interleave count are "
1355 "explicitly set to 1");
1359 // Check the loop for a trip count threshold:
1360 // do not vectorize loops with a tiny trip count.
1361 const unsigned TC = SE->getSmallConstantTripCount(L);
1362 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1363 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1364 << "This loop is not worth vectorizing.");
1365 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1366 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1368 DEBUG(dbgs() << "\n");
1369 emitOptimizationRemarkAnalysis(
1370 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1371 "vectorization is not beneficial and is not explicitly forced");
1376 // Check if it is legal to vectorize the loop.
1377 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI, AA, F, TTI);
1378 if (!LVL.canVectorize()) {
1379 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1380 emitMissedWarning(F, L, Hints);
1384 // Use the cost model.
1385 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI, AC, F,
1388 // Check the function attributes to find out if this function should be
1389 // optimized for size.
1390 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1391 F->hasFnAttribute(Attribute::OptimizeForSize);
1393 // Compute the weighted frequency of this loop being executed and see if it
1394 // is less than 20% of the function entry baseline frequency. Note that we
1395 // always have a canonical loop here because we think we *can* vectoriez.
1396 // FIXME: This is hidden behind a flag due to pervasive problems with
1397 // exactly what block frequency models.
1398 if (LoopVectorizeWithBlockFrequency) {
1399 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1400 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1401 LoopEntryFreq < ColdEntryFreq)
1405 // Check the function attributes to see if implicit floats are allowed.a
1406 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1407 // an integer loop and the vector instructions selected are purely integer
1408 // vector instructions?
1409 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1410 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1411 "attribute is used.\n");
1412 emitOptimizationRemarkAnalysis(
1413 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1414 "loop not vectorized due to NoImplicitFloat attribute");
1415 emitMissedWarning(F, L, Hints);
1419 // Select the optimal vectorization factor.
1420 const LoopVectorizationCostModel::VectorizationFactor VF =
1421 CM.selectVectorizationFactor(OptForSize);
1423 // Select the unroll factor.
1425 CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
1427 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1428 << DebugLocStr << '\n');
1429 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1431 if (VF.Width == 1) {
1432 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
1435 emitOptimizationRemarkAnalysis(
1436 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1437 "not beneficial to vectorize and user disabled interleaving");
1440 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1442 // Report the unrolling decision.
1443 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1444 Twine("unrolled with interleaving factor " +
1446 " (vectorization not beneficial)"));
1448 // We decided not to vectorize, but we may want to unroll.
1450 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1451 Unroller.vectorize(&LVL);
1453 // If we decided that it is *legal* to vectorize the loop then do it.
1454 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1458 // Report the vectorization decision.
1459 emitOptimizationRemark(
1460 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1461 Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1462 ", unrolling interleave factor: " + Twine(UF) + ")");
1465 // Mark the loop as already vectorized to avoid vectorizing again.
1466 Hints.setAlreadyVectorized();
1468 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1472 void getAnalysisUsage(AnalysisUsage &AU) const override {
1473 AU.addRequired<AssumptionCacheTracker>();
1474 AU.addRequiredID(LoopSimplifyID);
1475 AU.addRequiredID(LCSSAID);
1476 AU.addRequired<BlockFrequencyInfo>();
1477 AU.addRequired<DominatorTreeWrapperPass>();
1478 AU.addRequired<LoopInfoWrapperPass>();
1479 AU.addRequired<ScalarEvolution>();
1480 AU.addRequired<TargetTransformInfoWrapperPass>();
1481 AU.addRequired<AliasAnalysis>();
1482 AU.addPreserved<LoopInfoWrapperPass>();
1483 AU.addPreserved<DominatorTreeWrapperPass>();
1484 AU.addPreserved<AliasAnalysis>();
1489 } // end anonymous namespace
1491 //===----------------------------------------------------------------------===//
1492 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1493 // LoopVectorizationCostModel.
1494 //===----------------------------------------------------------------------===//
1496 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1497 // We need to place the broadcast of invariant variables outside the loop.
1498 Instruction *Instr = dyn_cast<Instruction>(V);
1500 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1501 Instr->getParent()) != LoopVectorBody.end());
1502 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1504 // Place the code for broadcasting invariant variables in the new preheader.
1505 IRBuilder<>::InsertPointGuard Guard(Builder);
1507 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1509 // Broadcast the scalar into all locations in the vector.
1510 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1515 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1517 assert(Val->getType()->isVectorTy() && "Must be a vector");
1518 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1519 "Elem must be an integer");
1520 assert(Step->getType() == Val->getType()->getScalarType() &&
1521 "Step has wrong type");
1522 // Create the types.
1523 Type *ITy = Val->getType()->getScalarType();
1524 VectorType *Ty = cast<VectorType>(Val->getType());
1525 int VLen = Ty->getNumElements();
1526 SmallVector<Constant*, 8> Indices;
1528 // Create a vector of consecutive numbers from zero to VF.
1529 for (int i = 0; i < VLen; ++i)
1530 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1532 // Add the consecutive indices to the vector value.
1533 Constant *Cv = ConstantVector::get(Indices);
1534 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1535 Step = Builder.CreateVectorSplat(VLen, Step);
1536 assert(Step->getType() == Val->getType() && "Invalid step vec");
1537 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1538 // which can be found from the original scalar operations.
1539 Step = Builder.CreateMul(Cv, Step);
1540 return Builder.CreateAdd(Val, Step, "induction");
1543 /// \brief Find the operand of the GEP that should be checked for consecutive
1544 /// stores. This ignores trailing indices that have no effect on the final
1546 static unsigned getGEPInductionOperand(const DataLayout *DL,
1547 const GetElementPtrInst *Gep) {
1548 unsigned LastOperand = Gep->getNumOperands() - 1;
1549 unsigned GEPAllocSize = DL->getTypeAllocSize(
1550 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1552 // Walk backwards and try to peel off zeros.
1553 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1554 // Find the type we're currently indexing into.
1555 gep_type_iterator GEPTI = gep_type_begin(Gep);
1556 std::advance(GEPTI, LastOperand - 1);
1558 // If it's a type with the same allocation size as the result of the GEP we
1559 // can peel off the zero index.
1560 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1568 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1569 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1570 // Make sure that the pointer does not point to structs.
1571 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1574 // If this value is a pointer induction variable we know it is consecutive.
1575 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1576 if (Phi && Inductions.count(Phi)) {
1577 InductionInfo II = Inductions[Phi];
1578 return II.getConsecutiveDirection();
1581 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1585 unsigned NumOperands = Gep->getNumOperands();
1586 Value *GpPtr = Gep->getPointerOperand();
1587 // If this GEP value is a consecutive pointer induction variable and all of
1588 // the indices are constant then we know it is consecutive. We can
1589 Phi = dyn_cast<PHINode>(GpPtr);
1590 if (Phi && Inductions.count(Phi)) {
1592 // Make sure that the pointer does not point to structs.
1593 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1594 if (GepPtrType->getElementType()->isAggregateType())
1597 // Make sure that all of the index operands are loop invariant.
1598 for (unsigned i = 1; i < NumOperands; ++i)
1599 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1602 InductionInfo II = Inductions[Phi];
1603 return II.getConsecutiveDirection();
1606 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1608 // Check that all of the gep indices are uniform except for our induction
1610 for (unsigned i = 0; i != NumOperands; ++i)
1611 if (i != InductionOperand &&
1612 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1615 // We can emit wide load/stores only if the last non-zero index is the
1616 // induction variable.
1617 const SCEV *Last = nullptr;
1618 if (!Strides.count(Gep))
1619 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1621 // Because of the multiplication by a stride we can have a s/zext cast.
1622 // We are going to replace this stride by 1 so the cast is safe to ignore.
1624 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1625 // %0 = trunc i64 %indvars.iv to i32
1626 // %mul = mul i32 %0, %Stride1
1627 // %idxprom = zext i32 %mul to i64 << Safe cast.
1628 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1630 Last = replaceSymbolicStrideSCEV(SE, Strides,
1631 Gep->getOperand(InductionOperand), Gep);
1632 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1634 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1638 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1639 const SCEV *Step = AR->getStepRecurrence(*SE);
1641 // The memory is consecutive because the last index is consecutive
1642 // and all other indices are loop invariant.
1645 if (Step->isAllOnesValue())
1652 bool LoopVectorizationLegality::isUniform(Value *V) { return LAI.isUniform(V); }
1654 InnerLoopVectorizer::VectorParts&
1655 InnerLoopVectorizer::getVectorValue(Value *V) {
1656 assert(V != Induction && "The new induction variable should not be used.");
1657 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1659 // If we have a stride that is replaced by one, do it here.
1660 if (Legal->hasStride(V))
1661 V = ConstantInt::get(V->getType(), 1);
1663 // If we have this scalar in the map, return it.
1664 if (WidenMap.has(V))
1665 return WidenMap.get(V);
1667 // If this scalar is unknown, assume that it is a constant or that it is
1668 // loop invariant. Broadcast V and save the value for future uses.
1669 Value *B = getBroadcastInstrs(V);
1670 return WidenMap.splat(V, B);
1673 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1674 assert(Vec->getType()->isVectorTy() && "Invalid type");
1675 SmallVector<Constant*, 8> ShuffleMask;
1676 for (unsigned i = 0; i < VF; ++i)
1677 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1679 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1680 ConstantVector::get(ShuffleMask),
1684 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1685 // Attempt to issue a wide load.
1686 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1687 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1689 assert((LI || SI) && "Invalid Load/Store instruction");
1691 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1692 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1693 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1694 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1695 // An alignment of 0 means target abi alignment. We need to use the scalar's
1696 // target abi alignment in such a case.
1698 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1699 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1700 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1701 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1703 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
1704 !Legal->isMaskRequired(SI))
1705 return scalarizeInstruction(Instr, true);
1707 if (ScalarAllocatedSize != VectorElementSize)
1708 return scalarizeInstruction(Instr);
1710 // If the pointer is loop invariant or if it is non-consecutive,
1711 // scalarize the load.
1712 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1713 bool Reverse = ConsecutiveStride < 0;
1714 bool UniformLoad = LI && Legal->isUniform(Ptr);
1715 if (!ConsecutiveStride || UniformLoad)
1716 return scalarizeInstruction(Instr);
1718 Constant *Zero = Builder.getInt32(0);
1719 VectorParts &Entry = WidenMap.get(Instr);
1721 // Handle consecutive loads/stores.
1722 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1723 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1724 setDebugLocFromInst(Builder, Gep);
1725 Value *PtrOperand = Gep->getPointerOperand();
1726 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1727 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1729 // Create the new GEP with the new induction variable.
1730 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1731 Gep2->setOperand(0, FirstBasePtr);
1732 Gep2->setName("gep.indvar.base");
1733 Ptr = Builder.Insert(Gep2);
1735 setDebugLocFromInst(Builder, Gep);
1736 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1737 OrigLoop) && "Base ptr must be invariant");
1739 // The last index does not have to be the induction. It can be
1740 // consecutive and be a function of the index. For example A[I+1];
1741 unsigned NumOperands = Gep->getNumOperands();
1742 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1743 // Create the new GEP with the new induction variable.
1744 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1746 for (unsigned i = 0; i < NumOperands; ++i) {
1747 Value *GepOperand = Gep->getOperand(i);
1748 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1750 // Update last index or loop invariant instruction anchored in loop.
1751 if (i == InductionOperand ||
1752 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1753 assert((i == InductionOperand ||
1754 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1755 "Must be last index or loop invariant");
1757 VectorParts &GEPParts = getVectorValue(GepOperand);
1758 Value *Index = GEPParts[0];
1759 Index = Builder.CreateExtractElement(Index, Zero);
1760 Gep2->setOperand(i, Index);
1761 Gep2->setName("gep.indvar.idx");
1764 Ptr = Builder.Insert(Gep2);
1766 // Use the induction element ptr.
1767 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1768 setDebugLocFromInst(Builder, Ptr);
1769 VectorParts &PtrVal = getVectorValue(Ptr);
1770 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1773 VectorParts Mask = createBlockInMask(Instr->getParent());
1776 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1777 "We do not allow storing to uniform addresses");
1778 setDebugLocFromInst(Builder, SI);
1779 // We don't want to update the value in the map as it might be used in
1780 // another expression. So don't use a reference type for "StoredVal".
1781 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1783 for (unsigned Part = 0; Part < UF; ++Part) {
1784 // Calculate the pointer for the specific unroll-part.
1785 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1788 // If we store to reverse consecutive memory locations then we need
1789 // to reverse the order of elements in the stored value.
1790 StoredVal[Part] = reverseVector(StoredVal[Part]);
1791 // If the address is consecutive but reversed, then the
1792 // wide store needs to start at the last vector element.
1793 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1794 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1795 Mask[Part] = reverseVector(Mask[Part]);
1798 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1799 DataTy->getPointerTo(AddressSpace));
1802 if (Legal->isMaskRequired(SI))
1803 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
1806 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
1807 propagateMetadata(NewSI, SI);
1813 assert(LI && "Must have a load instruction");
1814 setDebugLocFromInst(Builder, LI);
1815 for (unsigned Part = 0; Part < UF; ++Part) {
1816 // Calculate the pointer for the specific unroll-part.
1817 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1820 // If the address is consecutive but reversed, then the
1821 // wide load needs to start at the last vector element.
1822 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1823 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1824 Mask[Part] = reverseVector(Mask[Part]);
1828 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1829 DataTy->getPointerTo(AddressSpace));
1830 if (Legal->isMaskRequired(LI))
1831 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
1832 UndefValue::get(DataTy),
1833 "wide.masked.load");
1835 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
1836 propagateMetadata(NewLI, LI);
1837 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
1841 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1842 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1843 // Holds vector parameters or scalars, in case of uniform vals.
1844 SmallVector<VectorParts, 4> Params;
1846 setDebugLocFromInst(Builder, Instr);
1848 // Find all of the vectorized parameters.
1849 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1850 Value *SrcOp = Instr->getOperand(op);
1852 // If we are accessing the old induction variable, use the new one.
1853 if (SrcOp == OldInduction) {
1854 Params.push_back(getVectorValue(SrcOp));
1858 // Try using previously calculated values.
1859 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1861 // If the src is an instruction that appeared earlier in the basic block
1862 // then it should already be vectorized.
1863 if (SrcInst && OrigLoop->contains(SrcInst)) {
1864 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1865 // The parameter is a vector value from earlier.
1866 Params.push_back(WidenMap.get(SrcInst));
1868 // The parameter is a scalar from outside the loop. Maybe even a constant.
1869 VectorParts Scalars;
1870 Scalars.append(UF, SrcOp);
1871 Params.push_back(Scalars);
1875 assert(Params.size() == Instr->getNumOperands() &&
1876 "Invalid number of operands");
1878 // Does this instruction return a value ?
1879 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1881 Value *UndefVec = IsVoidRetTy ? nullptr :
1882 UndefValue::get(VectorType::get(Instr->getType(), VF));
1883 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1884 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1886 Instruction *InsertPt = Builder.GetInsertPoint();
1887 BasicBlock *IfBlock = Builder.GetInsertBlock();
1888 BasicBlock *CondBlock = nullptr;
1891 Loop *VectorLp = nullptr;
1892 if (IfPredicateStore) {
1893 assert(Instr->getParent()->getSinglePredecessor() &&
1894 "Only support single predecessor blocks");
1895 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1896 Instr->getParent());
1897 VectorLp = LI->getLoopFor(IfBlock);
1898 assert(VectorLp && "Must have a loop for this block");
1901 // For each vector unroll 'part':
1902 for (unsigned Part = 0; Part < UF; ++Part) {
1903 // For each scalar that we create:
1904 for (unsigned Width = 0; Width < VF; ++Width) {
1907 Value *Cmp = nullptr;
1908 if (IfPredicateStore) {
1909 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1910 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1911 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1912 LoopVectorBody.push_back(CondBlock);
1913 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
1914 // Update Builder with newly created basic block.
1915 Builder.SetInsertPoint(InsertPt);
1918 Instruction *Cloned = Instr->clone();
1920 Cloned->setName(Instr->getName() + ".cloned");
1921 // Replace the operands of the cloned instructions with extracted scalars.
1922 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1923 Value *Op = Params[op][Part];
1924 // Param is a vector. Need to extract the right lane.
1925 if (Op->getType()->isVectorTy())
1926 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1927 Cloned->setOperand(op, Op);
1930 // Place the cloned scalar in the new loop.
1931 Builder.Insert(Cloned);
1933 // If the original scalar returns a value we need to place it in a vector
1934 // so that future users will be able to use it.
1936 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1937 Builder.getInt32(Width));
1939 if (IfPredicateStore) {
1940 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1941 LoopVectorBody.push_back(NewIfBlock);
1942 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
1943 Builder.SetInsertPoint(InsertPt);
1944 Instruction *OldBr = IfBlock->getTerminator();
1945 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1946 OldBr->eraseFromParent();
1947 IfBlock = NewIfBlock;
1953 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1957 if (Instruction *I = dyn_cast<Instruction>(V))
1958 return I->getParent() == Loc->getParent() ? I : nullptr;
1962 std::pair<Instruction *, Instruction *>
1963 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1964 Instruction *tnullptr = nullptr;
1965 if (!Legal->mustCheckStrides())
1966 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1968 IRBuilder<> ChkBuilder(Loc);
1971 Value *Check = nullptr;
1972 Instruction *FirstInst = nullptr;
1973 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1974 SE = Legal->strides_end();
1976 Value *Ptr = stripIntegerCast(*SI);
1977 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1979 // Store the first instruction we create.
1980 FirstInst = getFirstInst(FirstInst, C, Loc);
1982 Check = ChkBuilder.CreateOr(Check, C);
1987 // We have to do this trickery because the IRBuilder might fold the check to a
1988 // constant expression in which case there is no Instruction anchored in a
1990 LLVMContext &Ctx = Loc->getContext();
1991 Instruction *TheCheck =
1992 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
1993 ChkBuilder.Insert(TheCheck, "stride.not.one");
1994 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
1996 return std::make_pair(FirstInst, TheCheck);
1999 void InnerLoopVectorizer::createEmptyLoop() {
2001 In this function we generate a new loop. The new loop will contain
2002 the vectorized instructions while the old loop will continue to run the
2005 [ ] <-- Back-edge taken count overflow check.
2008 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2011 || [ ] <-- vector pre header.
2015 || [ ]_| <-- vector loop.
2018 | >[ ] <--- middle-block.
2021 -|- >[ ] <--- new preheader.
2025 | [ ]_| <-- old scalar loop to handle remainder.
2028 >[ ] <-- exit block.
2032 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2033 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
2034 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2035 assert(BypassBlock && "Invalid loop structure");
2036 assert(ExitBlock && "Must have an exit block");
2038 // Some loops have a single integer induction variable, while other loops
2039 // don't. One example is c++ iterators that often have multiple pointer
2040 // induction variables. In the code below we also support a case where we
2041 // don't have a single induction variable.
2042 OldInduction = Legal->getInduction();
2043 Type *IdxTy = Legal->getWidestInductionType();
2045 // Find the loop boundaries.
2046 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2047 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2049 // The exit count might have the type of i64 while the phi is i32. This can
2050 // happen if we have an induction variable that is sign extended before the
2051 // compare. The only way that we get a backedge taken count is that the
2052 // induction variable was signed and as such will not overflow. In such a case
2053 // truncation is legal.
2054 if (ExitCount->getType()->getPrimitiveSizeInBits() >
2055 IdxTy->getPrimitiveSizeInBits())
2056 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2058 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2059 // Get the total trip count from the count by adding 1.
2060 ExitCount = SE->getAddExpr(BackedgeTakeCount,
2061 SE->getConstant(BackedgeTakeCount->getType(), 1));
2063 // Expand the trip count and place the new instructions in the preheader.
2064 // Notice that the pre-header does not change, only the loop body.
2065 SCEVExpander Exp(*SE, "induction");
2067 // We need to test whether the backedge-taken count is uint##_max. Adding one
2068 // to it will cause overflow and an incorrect loop trip count in the vector
2069 // body. In case of overflow we want to directly jump to the scalar remainder
2071 Value *BackedgeCount =
2072 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2073 BypassBlock->getTerminator());
2074 if (BackedgeCount->getType()->isPointerTy())
2075 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2076 "backedge.ptrcnt.to.int",
2077 BypassBlock->getTerminator());
2078 Instruction *CheckBCOverflow =
2079 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2080 Constant::getAllOnesValue(BackedgeCount->getType()),
2081 "backedge.overflow", BypassBlock->getTerminator());
2083 // The loop index does not have to start at Zero. Find the original start
2084 // value from the induction PHI node. If we don't have an induction variable
2085 // then we know that it starts at zero.
2086 Builder.SetInsertPoint(BypassBlock->getTerminator());
2087 Value *StartIdx = ExtendedIdx = OldInduction ?
2088 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2090 ConstantInt::get(IdxTy, 0);
2092 // We need an instruction to anchor the overflow check on. StartIdx needs to
2093 // be defined before the overflow check branch. Because the scalar preheader
2094 // is going to merge the start index and so the overflow branch block needs to
2095 // contain a definition of the start index.
2096 Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
2097 StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
2098 BypassBlock->getTerminator());
2100 // Count holds the overall loop count (N).
2101 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2102 BypassBlock->getTerminator());
2104 LoopBypassBlocks.push_back(BypassBlock);
2106 // Split the single block loop into the two loop structure described above.
2107 BasicBlock *VectorPH =
2108 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2109 BasicBlock *VecBody =
2110 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2111 BasicBlock *MiddleBlock =
2112 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2113 BasicBlock *ScalarPH =
2114 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2116 // Create and register the new vector loop.
2117 Loop* Lp = new Loop();
2118 Loop *ParentLoop = OrigLoop->getParentLoop();
2120 // Insert the new loop into the loop nest and register the new basic blocks
2121 // before calling any utilities such as SCEV that require valid LoopInfo.
2123 ParentLoop->addChildLoop(Lp);
2124 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2125 ParentLoop->addBasicBlockToLoop(VectorPH, *LI);
2126 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2128 LI->addTopLevelLoop(Lp);
2130 Lp->addBasicBlockToLoop(VecBody, *LI);
2132 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2134 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2136 // Generate the induction variable.
2137 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2138 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2139 // The loop step is equal to the vectorization factor (num of SIMD elements)
2140 // times the unroll factor (num of SIMD instructions).
2141 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2143 // This is the IR builder that we use to add all of the logic for bypassing
2144 // the new vector loop.
2145 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2146 setDebugLocFromInst(BypassBuilder,
2147 getDebugLocFromInstOrOperands(OldInduction));
2149 // We may need to extend the index in case there is a type mismatch.
2150 // We know that the count starts at zero and does not overflow.
2151 if (Count->getType() != IdxTy) {
2152 // The exit count can be of pointer type. Convert it to the correct
2154 if (ExitCount->getType()->isPointerTy())
2155 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2157 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2160 // Add the start index to the loop count to get the new end index.
2161 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2163 // Now we need to generate the expression for N - (N % VF), which is
2164 // the part that the vectorized body will execute.
2165 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2166 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2167 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2168 "end.idx.rnd.down");
2170 // Now, compare the new count to zero. If it is zero skip the vector loop and
2171 // jump to the scalar loop.
2173 BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2175 BasicBlock *LastBypassBlock = BypassBlock;
2177 // Generate code to check that the loops trip count that we computed by adding
2178 // one to the backedge-taken count will not overflow.
2180 auto PastOverflowCheck =
2181 std::next(BasicBlock::iterator(OverflowCheckAnchor));
2182 BasicBlock *CheckBlock =
2183 LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2185 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2186 LoopBypassBlocks.push_back(CheckBlock);
2187 Instruction *OldTerm = LastBypassBlock->getTerminator();
2188 BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2189 OldTerm->eraseFromParent();
2190 LastBypassBlock = CheckBlock;
2193 // Generate the code to check that the strides we assumed to be one are really
2194 // one. We want the new basic block to start at the first instruction in a
2195 // sequence of instructions that form a check.
2196 Instruction *StrideCheck;
2197 Instruction *FirstCheckInst;
2198 std::tie(FirstCheckInst, StrideCheck) =
2199 addStrideCheck(LastBypassBlock->getTerminator());
2201 // Create a new block containing the stride check.
2202 BasicBlock *CheckBlock =
2203 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2205 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2206 LoopBypassBlocks.push_back(CheckBlock);
2208 // Replace the branch into the memory check block with a conditional branch
2209 // for the "few elements case".
2210 Instruction *OldTerm = LastBypassBlock->getTerminator();
2211 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2212 OldTerm->eraseFromParent();
2215 LastBypassBlock = CheckBlock;
2218 // Generate the code that checks in runtime if arrays overlap. We put the
2219 // checks into a separate block to make the more common case of few elements
2221 Instruction *MemRuntimeCheck;
2222 std::tie(FirstCheckInst, MemRuntimeCheck) =
2223 Legal->getLAI()->addRuntimeCheck(LastBypassBlock->getTerminator());
2224 if (MemRuntimeCheck) {
2225 // Create a new block containing the memory check.
2226 BasicBlock *CheckBlock =
2227 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.memcheck");
2229 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2230 LoopBypassBlocks.push_back(CheckBlock);
2232 // Replace the branch into the memory check block with a conditional branch
2233 // for the "few elements case".
2234 Instruction *OldTerm = LastBypassBlock->getTerminator();
2235 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2236 OldTerm->eraseFromParent();
2238 Cmp = MemRuntimeCheck;
2239 LastBypassBlock = CheckBlock;
2242 LastBypassBlock->getTerminator()->eraseFromParent();
2243 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2246 // We are going to resume the execution of the scalar loop.
2247 // Go over all of the induction variables that we found and fix the
2248 // PHIs that are left in the scalar version of the loop.
2249 // The starting values of PHI nodes depend on the counter of the last
2250 // iteration in the vectorized loop.
2251 // If we come from a bypass edge then we need to start from the original
2254 // This variable saves the new starting index for the scalar loop.
2255 PHINode *ResumeIndex = nullptr;
2256 LoopVectorizationLegality::InductionList::iterator I, E;
2257 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2258 // Set builder to point to last bypass block.
2259 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2260 for (I = List->begin(), E = List->end(); I != E; ++I) {
2261 PHINode *OrigPhi = I->first;
2262 LoopVectorizationLegality::InductionInfo II = I->second;
2264 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2265 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2266 MiddleBlock->getTerminator());
2267 // We might have extended the type of the induction variable but we need a
2268 // truncated version for the scalar loop.
2269 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2270 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2271 MiddleBlock->getTerminator()) : nullptr;
2273 // Create phi nodes to merge from the backedge-taken check block.
2274 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2275 ScalarPH->getTerminator());
2276 BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2278 PHINode *BCTruncResumeVal = nullptr;
2279 if (OrigPhi == OldInduction) {
2281 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2282 ScalarPH->getTerminator());
2283 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2286 Value *EndValue = nullptr;
2288 case LoopVectorizationLegality::IK_NoInduction:
2289 llvm_unreachable("Unknown induction");
2290 case LoopVectorizationLegality::IK_IntInduction: {
2291 // Handle the integer induction counter.
2292 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2294 // We have the canonical induction variable.
2295 if (OrigPhi == OldInduction) {
2296 // Create a truncated version of the resume value for the scalar loop,
2297 // we might have promoted the type to a larger width.
2299 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2300 // The new PHI merges the original incoming value, in case of a bypass,
2301 // or the value at the end of the vectorized loop.
2302 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2303 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2304 TruncResumeVal->addIncoming(EndValue, VecBody);
2306 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2308 // We know what the end value is.
2309 EndValue = IdxEndRoundDown;
2310 // We also know which PHI node holds it.
2311 ResumeIndex = ResumeVal;
2315 // Not the canonical induction variable - add the vector loop count to the
2317 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2318 II.StartValue->getType(),
2320 EndValue = II.transform(BypassBuilder, CRD);
2321 EndValue->setName("ind.end");
2324 case LoopVectorizationLegality::IK_PtrInduction: {
2325 EndValue = II.transform(BypassBuilder, CountRoundDown);
2326 EndValue->setName("ptr.ind.end");
2331 // The new PHI merges the original incoming value, in case of a bypass,
2332 // or the value at the end of the vectorized loop.
2333 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2334 if (OrigPhi == OldInduction)
2335 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2337 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2339 ResumeVal->addIncoming(EndValue, VecBody);
2341 // Fix the scalar body counter (PHI node).
2342 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2344 // The old induction's phi node in the scalar body needs the truncated
2346 if (OrigPhi == OldInduction) {
2347 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2348 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2350 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2351 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2355 // If we are generating a new induction variable then we also need to
2356 // generate the code that calculates the exit value. This value is not
2357 // simply the end of the counter because we may skip the vectorized body
2358 // in case of a runtime check.
2360 assert(!ResumeIndex && "Unexpected resume value found");
2361 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2362 MiddleBlock->getTerminator());
2363 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2364 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2365 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2368 // Make sure that we found the index where scalar loop needs to continue.
2369 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2370 "Invalid resume Index");
2372 // Add a check in the middle block to see if we have completed
2373 // all of the iterations in the first vector loop.
2374 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2375 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2376 ResumeIndex, "cmp.n",
2377 MiddleBlock->getTerminator());
2379 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2380 // Remove the old terminator.
2381 MiddleBlock->getTerminator()->eraseFromParent();
2383 // Create i+1 and fill the PHINode.
2384 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2385 Induction->addIncoming(StartIdx, VectorPH);
2386 Induction->addIncoming(NextIdx, VecBody);
2387 // Create the compare.
2388 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2389 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2391 // Now we have two terminators. Remove the old one from the block.
2392 VecBody->getTerminator()->eraseFromParent();
2394 // Get ready to start creating new instructions into the vectorized body.
2395 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2398 LoopVectorPreHeader = VectorPH;
2399 LoopScalarPreHeader = ScalarPH;
2400 LoopMiddleBlock = MiddleBlock;
2401 LoopExitBlock = ExitBlock;
2402 LoopVectorBody.push_back(VecBody);
2403 LoopScalarBody = OldBasicBlock;
2405 LoopVectorizeHints Hints(Lp, true);
2406 Hints.setAlreadyVectorized();
2409 /// This function returns the identity element (or neutral element) for
2410 /// the operation K.
2412 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2417 // Adding, Xoring, Oring zero to a number does not change it.
2418 return ConstantInt::get(Tp, 0);
2419 case RK_IntegerMult:
2420 // Multiplying a number by 1 does not change it.
2421 return ConstantInt::get(Tp, 1);
2423 // AND-ing a number with an all-1 value does not change it.
2424 return ConstantInt::get(Tp, -1, true);
2426 // Multiplying a number by 1 does not change it.
2427 return ConstantFP::get(Tp, 1.0L);
2429 // Adding zero to a number does not change it.
2430 return ConstantFP::get(Tp, 0.0L);
2432 llvm_unreachable("Unknown reduction kind");
2436 /// This function translates the reduction kind to an LLVM binary operator.
2438 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2440 case LoopVectorizationLegality::RK_IntegerAdd:
2441 return Instruction::Add;
2442 case LoopVectorizationLegality::RK_IntegerMult:
2443 return Instruction::Mul;
2444 case LoopVectorizationLegality::RK_IntegerOr:
2445 return Instruction::Or;
2446 case LoopVectorizationLegality::RK_IntegerAnd:
2447 return Instruction::And;
2448 case LoopVectorizationLegality::RK_IntegerXor:
2449 return Instruction::Xor;
2450 case LoopVectorizationLegality::RK_FloatMult:
2451 return Instruction::FMul;
2452 case LoopVectorizationLegality::RK_FloatAdd:
2453 return Instruction::FAdd;
2454 case LoopVectorizationLegality::RK_IntegerMinMax:
2455 return Instruction::ICmp;
2456 case LoopVectorizationLegality::RK_FloatMinMax:
2457 return Instruction::FCmp;
2459 llvm_unreachable("Unknown reduction operation");
2463 Value *createMinMaxOp(IRBuilder<> &Builder,
2464 LoopVectorizationLegality::MinMaxReductionKind RK,
2467 CmpInst::Predicate P = CmpInst::ICMP_NE;
2470 llvm_unreachable("Unknown min/max reduction kind");
2471 case LoopVectorizationLegality::MRK_UIntMin:
2472 P = CmpInst::ICMP_ULT;
2474 case LoopVectorizationLegality::MRK_UIntMax:
2475 P = CmpInst::ICMP_UGT;
2477 case LoopVectorizationLegality::MRK_SIntMin:
2478 P = CmpInst::ICMP_SLT;
2480 case LoopVectorizationLegality::MRK_SIntMax:
2481 P = CmpInst::ICMP_SGT;
2483 case LoopVectorizationLegality::MRK_FloatMin:
2484 P = CmpInst::FCMP_OLT;
2486 case LoopVectorizationLegality::MRK_FloatMax:
2487 P = CmpInst::FCMP_OGT;
2492 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2493 RK == LoopVectorizationLegality::MRK_FloatMax)
2494 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2496 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2498 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2503 struct CSEDenseMapInfo {
2504 static bool canHandle(Instruction *I) {
2505 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2506 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2508 static inline Instruction *getEmptyKey() {
2509 return DenseMapInfo<Instruction *>::getEmptyKey();
2511 static inline Instruction *getTombstoneKey() {
2512 return DenseMapInfo<Instruction *>::getTombstoneKey();
2514 static unsigned getHashValue(Instruction *I) {
2515 assert(canHandle(I) && "Unknown instruction!");
2516 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2517 I->value_op_end()));
2519 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2520 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2521 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2523 return LHS->isIdenticalTo(RHS);
2528 /// \brief Check whether this block is a predicated block.
2529 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2530 /// = ...; " blocks. We start with one vectorized basic block. For every
2531 /// conditional block we split this vectorized block. Therefore, every second
2532 /// block will be a predicated one.
2533 static bool isPredicatedBlock(unsigned BlockNum) {
2534 return BlockNum % 2;
2537 ///\brief Perform cse of induction variable instructions.
2538 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2539 // Perform simple cse.
2540 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2541 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2542 BasicBlock *BB = BBs[i];
2543 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2544 Instruction *In = I++;
2546 if (!CSEDenseMapInfo::canHandle(In))
2549 // Check if we can replace this instruction with any of the
2550 // visited instructions.
2551 if (Instruction *V = CSEMap.lookup(In)) {
2552 In->replaceAllUsesWith(V);
2553 In->eraseFromParent();
2556 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2557 // ...;" blocks for predicated stores. Every second block is a predicated
2559 if (isPredicatedBlock(i))
2567 /// \brief Adds a 'fast' flag to floating point operations.
2568 static Value *addFastMathFlag(Value *V) {
2569 if (isa<FPMathOperator>(V)){
2570 FastMathFlags Flags;
2571 Flags.setUnsafeAlgebra();
2572 cast<Instruction>(V)->setFastMathFlags(Flags);
2577 void InnerLoopVectorizer::vectorizeLoop() {
2578 //===------------------------------------------------===//
2580 // Notice: any optimization or new instruction that go
2581 // into the code below should be also be implemented in
2584 //===------------------------------------------------===//
2585 Constant *Zero = Builder.getInt32(0);
2587 // In order to support reduction variables we need to be able to vectorize
2588 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2589 // stages. First, we create a new vector PHI node with no incoming edges.
2590 // We use this value when we vectorize all of the instructions that use the
2591 // PHI. Next, after all of the instructions in the block are complete we
2592 // add the new incoming edges to the PHI. At this point all of the
2593 // instructions in the basic block are vectorized, so we can use them to
2594 // construct the PHI.
2595 PhiVector RdxPHIsToFix;
2597 // Scan the loop in a topological order to ensure that defs are vectorized
2599 LoopBlocksDFS DFS(OrigLoop);
2602 // Vectorize all of the blocks in the original loop.
2603 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2604 be = DFS.endRPO(); bb != be; ++bb)
2605 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2607 // At this point every instruction in the original loop is widened to
2608 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2609 // that we vectorized. The PHI nodes are currently empty because we did
2610 // not want to introduce cycles. Notice that the remaining PHI nodes
2611 // that we need to fix are reduction variables.
2613 // Create the 'reduced' values for each of the induction vars.
2614 // The reduced values are the vector values that we scalarize and combine
2615 // after the loop is finished.
2616 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2618 PHINode *RdxPhi = *it;
2619 assert(RdxPhi && "Unable to recover vectorized PHI");
2621 // Find the reduction variable descriptor.
2622 assert(Legal->getReductionVars()->count(RdxPhi) &&
2623 "Unable to find the reduction variable");
2624 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2625 (*Legal->getReductionVars())[RdxPhi];
2627 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2629 // We need to generate a reduction vector from the incoming scalar.
2630 // To do so, we need to generate the 'identity' vector and override
2631 // one of the elements with the incoming scalar reduction. We need
2632 // to do it in the vector-loop preheader.
2633 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2635 // This is the vector-clone of the value that leaves the loop.
2636 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2637 Type *VecTy = VectorExit[0]->getType();
2639 // Find the reduction identity variable. Zero for addition, or, xor,
2640 // one for multiplication, -1 for And.
2643 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2644 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2645 // MinMax reduction have the start value as their identify.
2647 VectorStart = Identity = RdxDesc.StartValue;
2649 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2654 // Handle other reduction kinds:
2656 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2657 VecTy->getScalarType());
2660 // This vector is the Identity vector where the first element is the
2661 // incoming scalar reduction.
2662 VectorStart = RdxDesc.StartValue;
2664 Identity = ConstantVector::getSplat(VF, Iden);
2666 // This vector is the Identity vector where the first element is the
2667 // incoming scalar reduction.
2668 VectorStart = Builder.CreateInsertElement(Identity,
2669 RdxDesc.StartValue, Zero);
2673 // Fix the vector-loop phi.
2675 // Reductions do not have to start at zero. They can start with
2676 // any loop invariant values.
2677 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2678 BasicBlock *Latch = OrigLoop->getLoopLatch();
2679 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2680 VectorParts &Val = getVectorValue(LoopVal);
2681 for (unsigned part = 0; part < UF; ++part) {
2682 // Make sure to add the reduction stat value only to the
2683 // first unroll part.
2684 Value *StartVal = (part == 0) ? VectorStart : Identity;
2685 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
2686 LoopVectorPreHeader);
2687 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2688 LoopVectorBody.back());
2691 // Before each round, move the insertion point right between
2692 // the PHIs and the values we are going to write.
2693 // This allows us to write both PHINodes and the extractelement
2695 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2697 VectorParts RdxParts;
2698 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2699 for (unsigned part = 0; part < UF; ++part) {
2700 // This PHINode contains the vectorized reduction variable, or
2701 // the initial value vector, if we bypass the vector loop.
2702 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2703 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2704 Value *StartVal = (part == 0) ? VectorStart : Identity;
2705 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2706 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2707 NewPhi->addIncoming(RdxExitVal[part],
2708 LoopVectorBody.back());
2709 RdxParts.push_back(NewPhi);
2712 // Reduce all of the unrolled parts into a single vector.
2713 Value *ReducedPartRdx = RdxParts[0];
2714 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2715 setDebugLocFromInst(Builder, ReducedPartRdx);
2716 for (unsigned part = 1; part < UF; ++part) {
2717 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2718 // Floating point operations had to be 'fast' to enable the reduction.
2719 ReducedPartRdx = addFastMathFlag(
2720 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2721 ReducedPartRdx, "bin.rdx"));
2723 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2724 ReducedPartRdx, RdxParts[part]);
2728 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2729 // and vector ops, reducing the set of values being computed by half each
2731 assert(isPowerOf2_32(VF) &&
2732 "Reduction emission only supported for pow2 vectors!");
2733 Value *TmpVec = ReducedPartRdx;
2734 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2735 for (unsigned i = VF; i != 1; i >>= 1) {
2736 // Move the upper half of the vector to the lower half.
2737 for (unsigned j = 0; j != i/2; ++j)
2738 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2740 // Fill the rest of the mask with undef.
2741 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2742 UndefValue::get(Builder.getInt32Ty()));
2745 Builder.CreateShuffleVector(TmpVec,
2746 UndefValue::get(TmpVec->getType()),
2747 ConstantVector::get(ShuffleMask),
2750 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2751 // Floating point operations had to be 'fast' to enable the reduction.
2752 TmpVec = addFastMathFlag(Builder.CreateBinOp(
2753 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2755 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2758 // The result is in the first element of the vector.
2759 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2760 Builder.getInt32(0));
2763 // Create a phi node that merges control-flow from the backedge-taken check
2764 // block and the middle block.
2765 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2766 LoopScalarPreHeader->getTerminator());
2767 BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
2768 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2770 // Now, we need to fix the users of the reduction variable
2771 // inside and outside of the scalar remainder loop.
2772 // We know that the loop is in LCSSA form. We need to update the
2773 // PHI nodes in the exit blocks.
2774 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2775 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2776 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2777 if (!LCSSAPhi) break;
2779 // All PHINodes need to have a single entry edge, or two if
2780 // we already fixed them.
2781 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2783 // We found our reduction value exit-PHI. Update it with the
2784 // incoming bypass edge.
2785 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2786 // Add an edge coming from the bypass.
2787 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2790 }// end of the LCSSA phi scan.
2792 // Fix the scalar loop reduction variable with the incoming reduction sum
2793 // from the vector body and from the backedge value.
2794 int IncomingEdgeBlockIdx =
2795 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2796 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2797 // Pick the other block.
2798 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2799 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
2800 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2801 }// end of for each redux variable.
2805 // Remove redundant induction instructions.
2806 cse(LoopVectorBody);
2809 void InnerLoopVectorizer::fixLCSSAPHIs() {
2810 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2811 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2812 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2813 if (!LCSSAPhi) break;
2814 if (LCSSAPhi->getNumIncomingValues() == 1)
2815 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2820 InnerLoopVectorizer::VectorParts
2821 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2822 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2825 // Look for cached value.
2826 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2827 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2828 if (ECEntryIt != MaskCache.end())
2829 return ECEntryIt->second;
2831 VectorParts SrcMask = createBlockInMask(Src);
2833 // The terminator has to be a branch inst!
2834 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2835 assert(BI && "Unexpected terminator found");
2837 if (BI->isConditional()) {
2838 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2840 if (BI->getSuccessor(0) != Dst)
2841 for (unsigned part = 0; part < UF; ++part)
2842 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2844 for (unsigned part = 0; part < UF; ++part)
2845 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2847 MaskCache[Edge] = EdgeMask;
2851 MaskCache[Edge] = SrcMask;
2855 InnerLoopVectorizer::VectorParts
2856 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2857 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2859 // Loop incoming mask is all-one.
2860 if (OrigLoop->getHeader() == BB) {
2861 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2862 return getVectorValue(C);
2865 // This is the block mask. We OR all incoming edges, and with zero.
2866 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2867 VectorParts BlockMask = getVectorValue(Zero);
2870 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2871 VectorParts EM = createEdgeMask(*it, BB);
2872 for (unsigned part = 0; part < UF; ++part)
2873 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2879 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2880 InnerLoopVectorizer::VectorParts &Entry,
2881 unsigned UF, unsigned VF, PhiVector *PV) {
2882 PHINode* P = cast<PHINode>(PN);
2883 // Handle reduction variables:
2884 if (Legal->getReductionVars()->count(P)) {
2885 for (unsigned part = 0; part < UF; ++part) {
2886 // This is phase one of vectorizing PHIs.
2887 Type *VecTy = (VF == 1) ? PN->getType() :
2888 VectorType::get(PN->getType(), VF);
2889 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2890 LoopVectorBody.back()-> getFirstInsertionPt());
2896 setDebugLocFromInst(Builder, P);
2897 // Check for PHI nodes that are lowered to vector selects.
2898 if (P->getParent() != OrigLoop->getHeader()) {
2899 // We know that all PHIs in non-header blocks are converted into
2900 // selects, so we don't have to worry about the insertion order and we
2901 // can just use the builder.
2902 // At this point we generate the predication tree. There may be
2903 // duplications since this is a simple recursive scan, but future
2904 // optimizations will clean it up.
2906 unsigned NumIncoming = P->getNumIncomingValues();
2908 // Generate a sequence of selects of the form:
2909 // SELECT(Mask3, In3,
2910 // SELECT(Mask2, In2,
2912 for (unsigned In = 0; In < NumIncoming; In++) {
2913 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2915 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2917 for (unsigned part = 0; part < UF; ++part) {
2918 // We might have single edge PHIs (blocks) - use an identity
2919 // 'select' for the first PHI operand.
2921 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2924 // Select between the current value and the previous incoming edge
2925 // based on the incoming mask.
2926 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2927 Entry[part], "predphi");
2933 // This PHINode must be an induction variable.
2934 // Make sure that we know about it.
2935 assert(Legal->getInductionVars()->count(P) &&
2936 "Not an induction variable");
2938 LoopVectorizationLegality::InductionInfo II =
2939 Legal->getInductionVars()->lookup(P);
2941 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2942 // which can be found from the original scalar operations.
2944 case LoopVectorizationLegality::IK_NoInduction:
2945 llvm_unreachable("Unknown induction");
2946 case LoopVectorizationLegality::IK_IntInduction: {
2947 assert(P->getType() == II.StartValue->getType() && "Types must match");
2948 Type *PhiTy = P->getType();
2950 if (P == OldInduction) {
2951 // Handle the canonical induction variable. We might have had to
2953 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2955 // Handle other induction variables that are now based on the
2957 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2959 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2960 Broadcasted = II.transform(Builder, NormalizedIdx);
2961 Broadcasted->setName("offset.idx");
2963 Broadcasted = getBroadcastInstrs(Broadcasted);
2964 // After broadcasting the induction variable we need to make the vector
2965 // consecutive by adding 0, 1, 2, etc.
2966 for (unsigned part = 0; part < UF; ++part)
2967 Entry[part] = getStepVector(Broadcasted, VF * part, II.StepValue);
2970 case LoopVectorizationLegality::IK_PtrInduction:
2971 // Handle the pointer induction variable case.
2972 assert(P->getType()->isPointerTy() && "Unexpected type.");
2973 // This is the normalized GEP that starts counting at zero.
2974 Value *NormalizedIdx =
2975 Builder.CreateSub(Induction, ExtendedIdx, "normalized.idx");
2976 // This is the vector of results. Notice that we don't generate
2977 // vector geps because scalar geps result in better code.
2978 for (unsigned part = 0; part < UF; ++part) {
2980 int EltIndex = part;
2981 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2982 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
2983 Value *SclrGep = II.transform(Builder, GlobalIdx);
2984 SclrGep->setName("next.gep");
2985 Entry[part] = SclrGep;
2989 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2990 for (unsigned int i = 0; i < VF; ++i) {
2991 int EltIndex = i + part * VF;
2992 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2993 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
2994 Value *SclrGep = II.transform(Builder, GlobalIdx);
2995 SclrGep->setName("next.gep");
2996 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2997 Builder.getInt32(i),
3000 Entry[part] = VecVal;
3006 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3007 // For each instruction in the old loop.
3008 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3009 VectorParts &Entry = WidenMap.get(it);
3010 switch (it->getOpcode()) {
3011 case Instruction::Br:
3012 // Nothing to do for PHIs and BR, since we already took care of the
3013 // loop control flow instructions.
3015 case Instruction::PHI: {
3016 // Vectorize PHINodes.
3017 widenPHIInstruction(it, Entry, UF, VF, PV);
3021 case Instruction::Add:
3022 case Instruction::FAdd:
3023 case Instruction::Sub:
3024 case Instruction::FSub:
3025 case Instruction::Mul:
3026 case Instruction::FMul:
3027 case Instruction::UDiv:
3028 case Instruction::SDiv:
3029 case Instruction::FDiv:
3030 case Instruction::URem:
3031 case Instruction::SRem:
3032 case Instruction::FRem:
3033 case Instruction::Shl:
3034 case Instruction::LShr:
3035 case Instruction::AShr:
3036 case Instruction::And:
3037 case Instruction::Or:
3038 case Instruction::Xor: {
3039 // Just widen binops.
3040 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3041 setDebugLocFromInst(Builder, BinOp);
3042 VectorParts &A = getVectorValue(it->getOperand(0));
3043 VectorParts &B = getVectorValue(it->getOperand(1));
3045 // Use this vector value for all users of the original instruction.
3046 for (unsigned Part = 0; Part < UF; ++Part) {
3047 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3049 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3050 VecOp->copyIRFlags(BinOp);
3055 propagateMetadata(Entry, it);
3058 case Instruction::Select: {
3060 // If the selector is loop invariant we can create a select
3061 // instruction with a scalar condition. Otherwise, use vector-select.
3062 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3064 setDebugLocFromInst(Builder, it);
3066 // The condition can be loop invariant but still defined inside the
3067 // loop. This means that we can't just use the original 'cond' value.
3068 // We have to take the 'vectorized' value and pick the first lane.
3069 // Instcombine will make this a no-op.
3070 VectorParts &Cond = getVectorValue(it->getOperand(0));
3071 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3072 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3074 Value *ScalarCond = (VF == 1) ? Cond[0] :
3075 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3077 for (unsigned Part = 0; Part < UF; ++Part) {
3078 Entry[Part] = Builder.CreateSelect(
3079 InvariantCond ? ScalarCond : Cond[Part],
3084 propagateMetadata(Entry, it);
3088 case Instruction::ICmp:
3089 case Instruction::FCmp: {
3090 // Widen compares. Generate vector compares.
3091 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3092 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3093 setDebugLocFromInst(Builder, it);
3094 VectorParts &A = getVectorValue(it->getOperand(0));
3095 VectorParts &B = getVectorValue(it->getOperand(1));
3096 for (unsigned Part = 0; Part < UF; ++Part) {
3099 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3101 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3105 propagateMetadata(Entry, it);
3109 case Instruction::Store:
3110 case Instruction::Load:
3111 vectorizeMemoryInstruction(it);
3113 case Instruction::ZExt:
3114 case Instruction::SExt:
3115 case Instruction::FPToUI:
3116 case Instruction::FPToSI:
3117 case Instruction::FPExt:
3118 case Instruction::PtrToInt:
3119 case Instruction::IntToPtr:
3120 case Instruction::SIToFP:
3121 case Instruction::UIToFP:
3122 case Instruction::Trunc:
3123 case Instruction::FPTrunc:
3124 case Instruction::BitCast: {
3125 CastInst *CI = dyn_cast<CastInst>(it);
3126 setDebugLocFromInst(Builder, it);
3127 /// Optimize the special case where the source is the induction
3128 /// variable. Notice that we can only optimize the 'trunc' case
3129 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3130 /// c. other casts depend on pointer size.
3131 if (CI->getOperand(0) == OldInduction &&
3132 it->getOpcode() == Instruction::Trunc) {
3133 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3135 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3136 LoopVectorizationLegality::InductionInfo II =
3137 Legal->getInductionVars()->lookup(OldInduction);
3139 ConstantInt::getSigned(CI->getType(), II.StepValue->getSExtValue());
3140 for (unsigned Part = 0; Part < UF; ++Part)
3141 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3142 propagateMetadata(Entry, it);
3145 /// Vectorize casts.
3146 Type *DestTy = (VF == 1) ? CI->getType() :
3147 VectorType::get(CI->getType(), VF);
3149 VectorParts &A = getVectorValue(it->getOperand(0));
3150 for (unsigned Part = 0; Part < UF; ++Part)
3151 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3152 propagateMetadata(Entry, it);
3156 case Instruction::Call: {
3157 // Ignore dbg intrinsics.
3158 if (isa<DbgInfoIntrinsic>(it))
3160 setDebugLocFromInst(Builder, it);
3162 Module *M = BB->getParent()->getParent();
3163 CallInst *CI = cast<CallInst>(it);
3164 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3165 assert(ID && "Not an intrinsic call!");
3167 case Intrinsic::assume:
3168 case Intrinsic::lifetime_end:
3169 case Intrinsic::lifetime_start:
3170 scalarizeInstruction(it);
3173 bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
3174 for (unsigned Part = 0; Part < UF; ++Part) {
3175 SmallVector<Value *, 4> Args;
3176 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3177 if (HasScalarOpd && i == 1) {
3178 Args.push_back(CI->getArgOperand(i));
3181 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3182 Args.push_back(Arg[Part]);
3184 Type *Tys[] = {CI->getType()};
3186 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3188 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3189 Entry[Part] = Builder.CreateCall(F, Args);
3192 propagateMetadata(Entry, it);
3199 // All other instructions are unsupported. Scalarize them.
3200 scalarizeInstruction(it);
3203 }// end of for_each instr.
3206 void InnerLoopVectorizer::updateAnalysis() {
3207 // Forget the original basic block.
3208 SE->forgetLoop(OrigLoop);
3210 // Update the dominator tree information.
3211 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3212 "Entry does not dominate exit.");
3214 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3215 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3216 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3218 // Due to if predication of stores we might create a sequence of "if(pred)
3219 // a[i] = ...; " blocks.
3220 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3222 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3223 else if (isPredicatedBlock(i)) {
3224 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3226 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3230 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3231 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3232 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3233 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3235 DEBUG(DT->verifyDomTree());
3238 /// \brief Check whether it is safe to if-convert this phi node.
3240 /// Phi nodes with constant expressions that can trap are not safe to if
3242 static bool canIfConvertPHINodes(BasicBlock *BB) {
3243 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3244 PHINode *Phi = dyn_cast<PHINode>(I);
3247 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3248 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3255 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3256 if (!EnableIfConversion) {
3257 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3261 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3263 // A list of pointers that we can safely read and write to.
3264 SmallPtrSet<Value *, 8> SafePointes;
3266 // Collect safe addresses.
3267 for (Loop::block_iterator BI = TheLoop->block_begin(),
3268 BE = TheLoop->block_end(); BI != BE; ++BI) {
3269 BasicBlock *BB = *BI;
3271 if (blockNeedsPredication(BB))
3274 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3275 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3276 SafePointes.insert(LI->getPointerOperand());
3277 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3278 SafePointes.insert(SI->getPointerOperand());
3282 // Collect the blocks that need predication.
3283 BasicBlock *Header = TheLoop->getHeader();
3284 for (Loop::block_iterator BI = TheLoop->block_begin(),
3285 BE = TheLoop->block_end(); BI != BE; ++BI) {
3286 BasicBlock *BB = *BI;
3288 // We don't support switch statements inside loops.
3289 if (!isa<BranchInst>(BB->getTerminator())) {
3290 emitAnalysis(VectorizationReport(BB->getTerminator())
3291 << "loop contains a switch statement");
3295 // We must be able to predicate all blocks that need to be predicated.
3296 if (blockNeedsPredication(BB)) {
3297 if (!blockCanBePredicated(BB, SafePointes)) {
3298 emitAnalysis(VectorizationReport(BB->getTerminator())
3299 << "control flow cannot be substituted for a select");
3302 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3303 emitAnalysis(VectorizationReport(BB->getTerminator())
3304 << "control flow cannot be substituted for a select");
3309 // We can if-convert this loop.
3313 bool LoopVectorizationLegality::canVectorize() {
3314 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3315 // be canonicalized.
3316 if (!TheLoop->getLoopPreheader()) {
3318 VectorizationReport() <<
3319 "loop control flow is not understood by vectorizer");
3323 // We can only vectorize innermost loops.
3324 if (!TheLoop->getSubLoopsVector().empty()) {
3325 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3329 // We must have a single backedge.
3330 if (TheLoop->getNumBackEdges() != 1) {
3332 VectorizationReport() <<
3333 "loop control flow is not understood by vectorizer");
3337 // We must have a single exiting block.
3338 if (!TheLoop->getExitingBlock()) {
3340 VectorizationReport() <<
3341 "loop control flow is not understood by vectorizer");
3345 // We only handle bottom-tested loops, i.e. loop in which the condition is
3346 // checked at the end of each iteration. With that we can assume that all
3347 // instructions in the loop are executed the same number of times.
3348 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3350 VectorizationReport() <<
3351 "loop control flow is not understood by vectorizer");
3355 // We need to have a loop header.
3356 DEBUG(dbgs() << "LV: Found a loop: " <<
3357 TheLoop->getHeader()->getName() << '\n');
3359 // Check if we can if-convert non-single-bb loops.
3360 unsigned NumBlocks = TheLoop->getNumBlocks();
3361 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3362 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3366 // ScalarEvolution needs to be able to find the exit count.
3367 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3368 if (ExitCount == SE->getCouldNotCompute()) {
3369 emitAnalysis(VectorizationReport() <<
3370 "could not determine number of loop iterations");
3371 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3375 // Check if we can vectorize the instructions and CFG in this loop.
3376 if (!canVectorizeInstrs()) {
3377 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3381 // Go over each instruction and look at memory deps.
3382 if (!canVectorizeMemory()) {
3383 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3387 // Collect all of the variables that remain uniform after vectorization.
3388 collectLoopUniforms();
3390 DEBUG(dbgs() << "LV: We can vectorize this loop"
3391 << (LAI.getRuntimePointerCheck()->Need
3392 ? " (with a runtime bound check)"
3395 // Okay! We can vectorize. At this point we don't have any other mem analysis
3396 // which may limit our maximum vectorization factor, so just return true with
3401 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3402 if (Ty->isPointerTy())
3403 return DL.getIntPtrType(Ty);
3405 // It is possible that char's or short's overflow when we ask for the loop's
3406 // trip count, work around this by changing the type size.
3407 if (Ty->getScalarSizeInBits() < 32)
3408 return Type::getInt32Ty(Ty->getContext());
3413 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3414 Ty0 = convertPointerToIntegerType(DL, Ty0);
3415 Ty1 = convertPointerToIntegerType(DL, Ty1);
3416 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3421 /// \brief Check that the instruction has outside loop users and is not an
3422 /// identified reduction variable.
3423 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3424 SmallPtrSetImpl<Value *> &Reductions) {
3425 // Reduction instructions are allowed to have exit users. All other
3426 // instructions must not have external users.
3427 if (!Reductions.count(Inst))
3428 //Check that all of the users of the loop are inside the BB.
3429 for (User *U : Inst->users()) {
3430 Instruction *UI = cast<Instruction>(U);
3431 // This user may be a reduction exit value.
3432 if (!TheLoop->contains(UI)) {
3433 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3440 bool LoopVectorizationLegality::canVectorizeInstrs() {
3441 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3442 BasicBlock *Header = TheLoop->getHeader();
3444 // Look for the attribute signaling the absence of NaNs.
3445 Function &F = *Header->getParent();
3446 if (F.hasFnAttribute("no-nans-fp-math"))
3448 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
3450 // For each block in the loop.
3451 for (Loop::block_iterator bb = TheLoop->block_begin(),
3452 be = TheLoop->block_end(); bb != be; ++bb) {
3454 // Scan the instructions in the block and look for hazards.
3455 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3458 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3459 Type *PhiTy = Phi->getType();
3460 // Check that this PHI type is allowed.
3461 if (!PhiTy->isIntegerTy() &&
3462 !PhiTy->isFloatingPointTy() &&
3463 !PhiTy->isPointerTy()) {
3464 emitAnalysis(VectorizationReport(it)
3465 << "loop control flow is not understood by vectorizer");
3466 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3470 // If this PHINode is not in the header block, then we know that we
3471 // can convert it to select during if-conversion. No need to check if
3472 // the PHIs in this block are induction or reduction variables.
3473 if (*bb != Header) {
3474 // Check that this instruction has no outside users or is an
3475 // identified reduction value with an outside user.
3476 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3478 emitAnalysis(VectorizationReport(it) <<
3479 "value could not be identified as "
3480 "an induction or reduction variable");
3484 // We only allow if-converted PHIs with exactly two incoming values.
3485 if (Phi->getNumIncomingValues() != 2) {
3486 emitAnalysis(VectorizationReport(it)
3487 << "control flow not understood by vectorizer");
3488 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3492 // This is the value coming from the preheader.
3493 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3494 ConstantInt *StepValue = nullptr;
3495 // Check if this is an induction variable.
3496 InductionKind IK = isInductionVariable(Phi, StepValue);
3498 if (IK_NoInduction != IK) {
3499 // Get the widest type.
3501 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3503 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3505 // Int inductions are special because we only allow one IV.
3506 if (IK == IK_IntInduction && StepValue->isOne()) {
3507 // Use the phi node with the widest type as induction. Use the last
3508 // one if there are multiple (no good reason for doing this other
3509 // than it is expedient).
3510 if (!Induction || PhiTy == WidestIndTy)
3514 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3515 Inductions[Phi] = InductionInfo(StartValue, IK, StepValue);
3517 // Until we explicitly handle the case of an induction variable with
3518 // an outside loop user we have to give up vectorizing this loop.
3519 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3520 emitAnalysis(VectorizationReport(it) <<
3521 "use of induction value outside of the "
3522 "loop is not handled by vectorizer");
3529 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3530 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3533 if (AddReductionVar(Phi, RK_IntegerMult)) {
3534 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3537 if (AddReductionVar(Phi, RK_IntegerOr)) {
3538 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3541 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3542 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3545 if (AddReductionVar(Phi, RK_IntegerXor)) {
3546 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3549 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3550 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3553 if (AddReductionVar(Phi, RK_FloatMult)) {
3554 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3557 if (AddReductionVar(Phi, RK_FloatAdd)) {
3558 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3561 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3562 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3567 emitAnalysis(VectorizationReport(it) <<
3568 "value that could not be identified as "
3569 "reduction is used outside the loop");
3570 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3572 }// end of PHI handling
3574 // We still don't handle functions. However, we can ignore dbg intrinsic
3575 // calls and we do handle certain intrinsic and libm functions.
3576 CallInst *CI = dyn_cast<CallInst>(it);
3577 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3578 emitAnalysis(VectorizationReport(it) <<
3579 "call instruction cannot be vectorized");
3580 DEBUG(dbgs() << "LV: Found a call site.\n");
3584 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
3585 // second argument is the same (i.e. loop invariant)
3587 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
3588 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
3589 emitAnalysis(VectorizationReport(it)
3590 << "intrinsic instruction cannot be vectorized");
3591 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
3596 // Check that the instruction return type is vectorizable.
3597 // Also, we can't vectorize extractelement instructions.
3598 if ((!VectorType::isValidElementType(it->getType()) &&
3599 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3600 emitAnalysis(VectorizationReport(it)
3601 << "instruction return type cannot be vectorized");
3602 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3606 // Check that the stored type is vectorizable.
3607 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3608 Type *T = ST->getValueOperand()->getType();
3609 if (!VectorType::isValidElementType(T)) {
3610 emitAnalysis(VectorizationReport(ST) <<
3611 "store instruction cannot be vectorized");
3614 if (EnableMemAccessVersioning)
3615 collectStridedAccess(ST);
3618 if (EnableMemAccessVersioning)
3619 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3620 collectStridedAccess(LI);
3622 // Reduction instructions are allowed to have exit users.
3623 // All other instructions must not have external users.
3624 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3625 emitAnalysis(VectorizationReport(it) <<
3626 "value cannot be used outside the loop");
3635 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3636 if (Inductions.empty()) {
3637 emitAnalysis(VectorizationReport()
3638 << "loop induction variable could not be identified");
3646 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3647 /// return the induction operand of the gep pointer.
3648 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3649 const DataLayout *DL, Loop *Lp) {
3650 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3654 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3656 // Check that all of the gep indices are uniform except for our induction
3658 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3659 if (i != InductionOperand &&
3660 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3662 return GEP->getOperand(InductionOperand);
3665 ///\brief Look for a cast use of the passed value.
3666 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3667 Value *UniqueCast = nullptr;
3668 for (User *U : Ptr->users()) {
3669 CastInst *CI = dyn_cast<CastInst>(U);
3670 if (CI && CI->getType() == Ty) {
3680 ///\brief Get the stride of a pointer access in a loop.
3681 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3682 /// pointer to the Value, or null otherwise.
3683 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3684 const DataLayout *DL, Loop *Lp) {
3685 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3686 if (!PtrTy || PtrTy->isAggregateType())
3689 // Try to remove a gep instruction to make the pointer (actually index at this
3690 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3691 // pointer, otherwise, we are analyzing the index.
3692 Value *OrigPtr = Ptr;
3694 // The size of the pointer access.
3695 int64_t PtrAccessSize = 1;
3697 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3698 const SCEV *V = SE->getSCEV(Ptr);
3702 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3703 V = C->getOperand();
3705 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3709 V = S->getStepRecurrence(*SE);
3713 // Strip off the size of access multiplication if we are still analyzing the
3715 if (OrigPtr == Ptr) {
3716 DL->getTypeAllocSize(PtrTy->getElementType());
3717 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3718 if (M->getOperand(0)->getSCEVType() != scConstant)
3721 const APInt &APStepVal =
3722 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3724 // Huge step value - give up.
3725 if (APStepVal.getBitWidth() > 64)
3728 int64_t StepVal = APStepVal.getSExtValue();
3729 if (PtrAccessSize != StepVal)
3731 V = M->getOperand(1);
3736 Type *StripedOffRecurrenceCast = nullptr;
3737 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3738 StripedOffRecurrenceCast = C->getType();
3739 V = C->getOperand();
3742 // Look for the loop invariant symbolic value.
3743 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3747 Value *Stride = U->getValue();
3748 if (!Lp->isLoopInvariant(Stride))
3751 // If we have stripped off the recurrence cast we have to make sure that we
3752 // return the value that is used in this loop so that we can replace it later.
3753 if (StripedOffRecurrenceCast)
3754 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3759 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
3760 Value *Ptr = nullptr;
3761 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3762 Ptr = LI->getPointerOperand();
3763 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3764 Ptr = SI->getPointerOperand();
3768 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3772 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3773 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3774 Strides[Ptr] = Stride;
3775 StrideSet.insert(Stride);
3778 void LoopVectorizationLegality::collectLoopUniforms() {
3779 // We now know that the loop is vectorizable!
3780 // Collect variables that will remain uniform after vectorization.
3781 std::vector<Value*> Worklist;
3782 BasicBlock *Latch = TheLoop->getLoopLatch();
3784 // Start with the conditional branch and walk up the block.
3785 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3787 // Also add all consecutive pointer values; these values will be uniform
3788 // after vectorization (and subsequent cleanup) and, until revectorization is
3789 // supported, all dependencies must also be uniform.
3790 for (Loop::block_iterator B = TheLoop->block_begin(),
3791 BE = TheLoop->block_end(); B != BE; ++B)
3792 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3794 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3795 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3797 while (!Worklist.empty()) {
3798 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3799 Worklist.pop_back();
3801 // Look at instructions inside this loop.
3802 // Stop when reaching PHI nodes.
3803 // TODO: we need to follow values all over the loop, not only in this block.
3804 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3807 // This is a known uniform.
3810 // Insert all operands.
3811 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3815 bool LoopVectorizationLegality::canVectorizeMemory() {
3816 return LAI.canVectorizeMemory(Strides);
3819 static bool hasMultipleUsesOf(Instruction *I,
3820 SmallPtrSetImpl<Instruction *> &Insts) {
3821 unsigned NumUses = 0;
3822 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
3823 if (Insts.count(dyn_cast<Instruction>(*Use)))
3832 static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set) {
3833 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
3834 if (!Set.count(dyn_cast<Instruction>(*Use)))
3839 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
3840 ReductionKind Kind) {
3841 if (Phi->getNumIncomingValues() != 2)
3844 // Reduction variables are only found in the loop header block.
3845 if (Phi->getParent() != TheLoop->getHeader())
3848 // Obtain the reduction start value from the value that comes from the loop
3850 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
3852 // ExitInstruction is the single value which is used outside the loop.
3853 // We only allow for a single reduction value to be used outside the loop.
3854 // This includes users of the reduction, variables (which form a cycle
3855 // which ends in the phi node).
3856 Instruction *ExitInstruction = nullptr;
3857 // Indicates that we found a reduction operation in our scan.
3858 bool FoundReduxOp = false;
3860 // We start with the PHI node and scan for all of the users of this
3861 // instruction. All users must be instructions that can be used as reduction
3862 // variables (such as ADD). We must have a single out-of-block user. The cycle
3863 // must include the original PHI.
3864 bool FoundStartPHI = false;
3866 // To recognize min/max patterns formed by a icmp select sequence, we store
3867 // the number of instruction we saw from the recognized min/max pattern,
3868 // to make sure we only see exactly the two instructions.
3869 unsigned NumCmpSelectPatternInst = 0;
3870 ReductionInstDesc ReduxDesc(false, nullptr);
3872 SmallPtrSet<Instruction *, 8> VisitedInsts;
3873 SmallVector<Instruction *, 8> Worklist;
3874 Worklist.push_back(Phi);
3875 VisitedInsts.insert(Phi);
3877 // A value in the reduction can be used:
3878 // - By the reduction:
3879 // - Reduction operation:
3880 // - One use of reduction value (safe).
3881 // - Multiple use of reduction value (not safe).
3883 // - All uses of the PHI must be the reduction (safe).
3884 // - Otherwise, not safe.
3885 // - By one instruction outside of the loop (safe).
3886 // - By further instructions outside of the loop (not safe).
3887 // - By an instruction that is not part of the reduction (not safe).
3889 // * An instruction type other than PHI or the reduction operation.
3890 // * A PHI in the header other than the initial PHI.
3891 while (!Worklist.empty()) {
3892 Instruction *Cur = Worklist.back();
3893 Worklist.pop_back();
3896 // If the instruction has no users then this is a broken chain and can't be
3897 // a reduction variable.
3898 if (Cur->use_empty())
3901 bool IsAPhi = isa<PHINode>(Cur);
3903 // A header PHI use other than the original PHI.
3904 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
3907 // Reductions of instructions such as Div, and Sub is only possible if the
3908 // LHS is the reduction variable.
3909 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
3910 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
3911 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
3914 // Any reduction instruction must be of one of the allowed kinds.
3915 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
3916 if (!ReduxDesc.IsReduction)
3919 // A reduction operation must only have one use of the reduction value.
3920 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
3921 hasMultipleUsesOf(Cur, VisitedInsts))
3924 // All inputs to a PHI node must be a reduction value.
3925 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
3928 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
3929 isa<SelectInst>(Cur)))
3930 ++NumCmpSelectPatternInst;
3931 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
3932 isa<SelectInst>(Cur)))
3933 ++NumCmpSelectPatternInst;
3935 // Check whether we found a reduction operator.
3936 FoundReduxOp |= !IsAPhi;
3938 // Process users of current instruction. Push non-PHI nodes after PHI nodes
3939 // onto the stack. This way we are going to have seen all inputs to PHI
3940 // nodes once we get to them.
3941 SmallVector<Instruction *, 8> NonPHIs;
3942 SmallVector<Instruction *, 8> PHIs;
3943 for (User *U : Cur->users()) {
3944 Instruction *UI = cast<Instruction>(U);
3946 // Check if we found the exit user.
3947 BasicBlock *Parent = UI->getParent();
3948 if (!TheLoop->contains(Parent)) {
3949 // Exit if you find multiple outside users or if the header phi node is
3950 // being used. In this case the user uses the value of the previous
3951 // iteration, in which case we would loose "VF-1" iterations of the
3952 // reduction operation if we vectorize.
3953 if (ExitInstruction != nullptr || Cur == Phi)
3956 // The instruction used by an outside user must be the last instruction
3957 // before we feed back to the reduction phi. Otherwise, we loose VF-1
3958 // operations on the value.
3959 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
3962 ExitInstruction = Cur;
3966 // Process instructions only once (termination). Each reduction cycle
3967 // value must only be used once, except by phi nodes and min/max
3968 // reductions which are represented as a cmp followed by a select.
3969 ReductionInstDesc IgnoredVal(false, nullptr);
3970 if (VisitedInsts.insert(UI).second) {
3971 if (isa<PHINode>(UI))
3974 NonPHIs.push_back(UI);
3975 } else if (!isa<PHINode>(UI) &&
3976 ((!isa<FCmpInst>(UI) &&
3977 !isa<ICmpInst>(UI) &&
3978 !isa<SelectInst>(UI)) ||
3979 !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
3982 // Remember that we completed the cycle.
3984 FoundStartPHI = true;
3986 Worklist.append(PHIs.begin(), PHIs.end());
3987 Worklist.append(NonPHIs.begin(), NonPHIs.end());
3990 // This means we have seen one but not the other instruction of the
3991 // pattern or more than just a select and cmp.
3992 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
3993 NumCmpSelectPatternInst != 2)
3996 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
3999 // We found a reduction var if we have reached the original phi node and we
4000 // only have a single instruction with out-of-loop users.
4002 // This instruction is allowed to have out-of-loop users.
4003 AllowedExit.insert(ExitInstruction);
4005 // Save the description of this reduction variable.
4006 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4007 ReduxDesc.MinMaxKind);
4008 Reductions[Phi] = RD;
4009 // We've ended the cycle. This is a reduction variable if we have an
4010 // outside user and it has a binary op.
4015 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4016 /// pattern corresponding to a min(X, Y) or max(X, Y).
4017 LoopVectorizationLegality::ReductionInstDesc
4018 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4019 ReductionInstDesc &Prev) {
4021 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4022 "Expect a select instruction");
4023 Instruction *Cmp = nullptr;
4024 SelectInst *Select = nullptr;
4026 // We must handle the select(cmp()) as a single instruction. Advance to the
4028 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4029 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
4030 return ReductionInstDesc(false, I);
4031 return ReductionInstDesc(Select, Prev.MinMaxKind);
4034 // Only handle single use cases for now.
4035 if (!(Select = dyn_cast<SelectInst>(I)))
4036 return ReductionInstDesc(false, I);
4037 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4038 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4039 return ReductionInstDesc(false, I);
4040 if (!Cmp->hasOneUse())
4041 return ReductionInstDesc(false, I);
4046 // Look for a min/max pattern.
4047 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4048 return ReductionInstDesc(Select, MRK_UIntMin);
4049 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4050 return ReductionInstDesc(Select, MRK_UIntMax);
4051 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4052 return ReductionInstDesc(Select, MRK_SIntMax);
4053 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4054 return ReductionInstDesc(Select, MRK_SIntMin);
4055 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4056 return ReductionInstDesc(Select, MRK_FloatMin);
4057 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4058 return ReductionInstDesc(Select, MRK_FloatMax);
4059 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4060 return ReductionInstDesc(Select, MRK_FloatMin);
4061 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4062 return ReductionInstDesc(Select, MRK_FloatMax);
4064 return ReductionInstDesc(false, I);
4067 LoopVectorizationLegality::ReductionInstDesc
4068 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4070 ReductionInstDesc &Prev) {
4071 bool FP = I->getType()->isFloatingPointTy();
4072 bool FastMath = FP && I->hasUnsafeAlgebra();
4073 switch (I->getOpcode()) {
4075 return ReductionInstDesc(false, I);
4076 case Instruction::PHI:
4077 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4078 Kind != RK_FloatMinMax))
4079 return ReductionInstDesc(false, I);
4080 return ReductionInstDesc(I, Prev.MinMaxKind);
4081 case Instruction::Sub:
4082 case Instruction::Add:
4083 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4084 case Instruction::Mul:
4085 return ReductionInstDesc(Kind == RK_IntegerMult, I);
4086 case Instruction::And:
4087 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4088 case Instruction::Or:
4089 return ReductionInstDesc(Kind == RK_IntegerOr, I);
4090 case Instruction::Xor:
4091 return ReductionInstDesc(Kind == RK_IntegerXor, I);
4092 case Instruction::FMul:
4093 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4094 case Instruction::FSub:
4095 case Instruction::FAdd:
4096 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4097 case Instruction::FCmp:
4098 case Instruction::ICmp:
4099 case Instruction::Select:
4100 if (Kind != RK_IntegerMinMax &&
4101 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4102 return ReductionInstDesc(false, I);
4103 return isMinMaxSelectCmpPattern(I, Prev);
4107 LoopVectorizationLegality::InductionKind
4108 LoopVectorizationLegality::isInductionVariable(PHINode *Phi,
4109 ConstantInt *&StepValue) {
4110 Type *PhiTy = Phi->getType();
4111 // We only handle integer and pointer inductions variables.
4112 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4113 return IK_NoInduction;
4115 // Check that the PHI is consecutive.
4116 const SCEV *PhiScev = SE->getSCEV(Phi);
4117 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4119 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4120 return IK_NoInduction;
4123 const SCEV *Step = AR->getStepRecurrence(*SE);
4124 // Calculate the pointer stride and check if it is consecutive.
4125 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4127 return IK_NoInduction;
4129 ConstantInt *CV = C->getValue();
4130 if (PhiTy->isIntegerTy()) {
4132 return IK_IntInduction;
4135 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4136 Type *PointerElementType = PhiTy->getPointerElementType();
4137 // The pointer stride cannot be determined if the pointer element type is not
4139 if (!PointerElementType->isSized())
4140 return IK_NoInduction;
4142 int64_t Size = static_cast<int64_t>(DL->getTypeAllocSize(PointerElementType));
4143 int64_t CVSize = CV->getSExtValue();
4145 return IK_NoInduction;
4146 StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
4147 return IK_PtrInduction;
4150 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4151 Value *In0 = const_cast<Value*>(V);
4152 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4156 return Inductions.count(PN);
4159 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4160 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4163 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4164 SmallPtrSetImpl<Value *> &SafePtrs) {
4166 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4167 // Check that we don't have a constant expression that can trap as operand.
4168 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4170 if (Constant *C = dyn_cast<Constant>(*OI))
4174 // We might be able to hoist the load.
4175 if (it->mayReadFromMemory()) {
4176 LoadInst *LI = dyn_cast<LoadInst>(it);
4179 if (!SafePtrs.count(LI->getPointerOperand())) {
4180 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4181 MaskedOp.insert(LI);
4188 // We don't predicate stores at the moment.
4189 if (it->mayWriteToMemory()) {
4190 StoreInst *SI = dyn_cast<StoreInst>(it);
4191 // We only support predication of stores in basic blocks with one
4196 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4197 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4199 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4200 !isSinglePredecessor) {
4201 // Build a masked store if it is legal for the target, otherwise scalarize
4203 bool isLegalMaskedOp =
4204 isLegalMaskedStore(SI->getValueOperand()->getType(),
4205 SI->getPointerOperand());
4206 if (isLegalMaskedOp) {
4208 MaskedOp.insert(SI);
4217 // The instructions below can trap.
4218 switch (it->getOpcode()) {
4220 case Instruction::UDiv:
4221 case Instruction::SDiv:
4222 case Instruction::URem:
4223 case Instruction::SRem:
4231 LoopVectorizationCostModel::VectorizationFactor
4232 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4233 // Width 1 means no vectorize
4234 VectorizationFactor Factor = { 1U, 0U };
4235 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4236 emitAnalysis(VectorizationReport() <<
4237 "runtime pointer checks needed. Enable vectorization of this "
4238 "loop with '#pragma clang loop vectorize(enable)' when "
4239 "compiling with -Os");
4240 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4244 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4245 emitAnalysis(VectorizationReport() <<
4246 "store that is conditionally executed prevents vectorization");
4247 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4251 // Find the trip count.
4252 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4253 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4255 unsigned WidestType = getWidestType();
4256 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4257 unsigned MaxSafeDepDist = -1U;
4258 if (Legal->getMaxSafeDepDistBytes() != -1U)
4259 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4260 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4261 WidestRegister : MaxSafeDepDist);
4262 unsigned MaxVectorSize = WidestRegister / WidestType;
4263 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4264 DEBUG(dbgs() << "LV: The Widest register is: "
4265 << WidestRegister << " bits.\n");
4267 if (MaxVectorSize == 0) {
4268 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4272 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4273 " into one vector!");
4275 unsigned VF = MaxVectorSize;
4277 // If we optimize the program for size, avoid creating the tail loop.
4279 // If we are unable to calculate the trip count then don't try to vectorize.
4282 (VectorizationReport() <<
4283 "unable to calculate the loop count due to complex control flow");
4284 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4288 // Find the maximum SIMD width that can fit within the trip count.
4289 VF = TC % MaxVectorSize;
4294 // If the trip count that we found modulo the vectorization factor is not
4295 // zero then we require a tail.
4297 emitAnalysis(VectorizationReport() <<
4298 "cannot optimize for size and vectorize at the "
4299 "same time. Enable vectorization of this loop "
4300 "with '#pragma clang loop vectorize(enable)' "
4301 "when compiling with -Os");
4302 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4307 int UserVF = Hints->getWidth();
4309 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4310 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4312 Factor.Width = UserVF;
4316 float Cost = expectedCost(1);
4318 const float ScalarCost = Cost;
4321 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4323 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4324 // Ignore scalar width, because the user explicitly wants vectorization.
4325 if (ForceVectorization && VF > 1) {
4327 Cost = expectedCost(Width) / (float)Width;
4330 for (unsigned i=2; i <= VF; i*=2) {
4331 // Notice that the vector loop needs to be executed less times, so
4332 // we need to divide the cost of the vector loops by the width of
4333 // the vector elements.
4334 float VectorCost = expectedCost(i) / (float)i;
4335 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4336 (int)VectorCost << ".\n");
4337 if (VectorCost < Cost) {
4343 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4344 << "LV: Vectorization seems to be not beneficial, "
4345 << "but was forced by a user.\n");
4346 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4347 Factor.Width = Width;
4348 Factor.Cost = Width * Cost;
4352 unsigned LoopVectorizationCostModel::getWidestType() {
4353 unsigned MaxWidth = 8;
4356 for (Loop::block_iterator bb = TheLoop->block_begin(),
4357 be = TheLoop->block_end(); bb != be; ++bb) {
4358 BasicBlock *BB = *bb;
4360 // For each instruction in the loop.
4361 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4362 Type *T = it->getType();
4364 // Ignore ephemeral values.
4365 if (EphValues.count(it))
4368 // Only examine Loads, Stores and PHINodes.
4369 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4372 // Examine PHI nodes that are reduction variables.
4373 if (PHINode *PN = dyn_cast<PHINode>(it))
4374 if (!Legal->getReductionVars()->count(PN))
4377 // Examine the stored values.
4378 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4379 T = ST->getValueOperand()->getType();
4381 // Ignore loaded pointer types and stored pointer types that are not
4382 // consecutive. However, we do want to take consecutive stores/loads of
4383 // pointer vectors into account.
4384 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4387 MaxWidth = std::max(MaxWidth,
4388 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
4396 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
4398 unsigned LoopCost) {
4400 // -- The unroll heuristics --
4401 // We unroll the loop in order to expose ILP and reduce the loop overhead.
4402 // There are many micro-architectural considerations that we can't predict
4403 // at this level. For example, frontend pressure (on decode or fetch) due to
4404 // code size, or the number and capabilities of the execution ports.
4406 // We use the following heuristics to select the unroll factor:
4407 // 1. If the code has reductions, then we unroll in order to break the cross
4408 // iteration dependency.
4409 // 2. If the loop is really small, then we unroll in order to reduce the loop
4411 // 3. We don't unroll if we think that we will spill registers to memory due
4412 // to the increased register pressure.
4414 // Use the user preference, unless 'auto' is selected.
4415 int UserUF = Hints->getInterleave();
4419 // When we optimize for size, we don't unroll.
4423 // We used the distance for the unroll factor.
4424 if (Legal->getMaxSafeDepDistBytes() != -1U)
4427 // Do not unroll loops with a relatively small trip count.
4428 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4429 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
4432 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4433 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4437 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4438 TargetNumRegisters = ForceTargetNumScalarRegs;
4440 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4441 TargetNumRegisters = ForceTargetNumVectorRegs;
4444 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4445 // We divide by these constants so assume that we have at least one
4446 // instruction that uses at least one register.
4447 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4448 R.NumInstructions = std::max(R.NumInstructions, 1U);
4450 // We calculate the unroll factor using the following formula.
4451 // Subtract the number of loop invariants from the number of available
4452 // registers. These registers are used by all of the unrolled instances.
4453 // Next, divide the remaining registers by the number of registers that is
4454 // required by the loop, in order to estimate how many parallel instances
4455 // fit without causing spills. All of this is rounded down if necessary to be
4456 // a power of two. We want power of two unroll factors to simplify any
4457 // addressing operations or alignment considerations.
4458 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4461 // Don't count the induction variable as unrolled.
4462 if (EnableIndVarRegisterHeur)
4463 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4464 std::max(1U, (R.MaxLocalUsers - 1)));
4466 // Clamp the unroll factor ranges to reasonable factors.
4467 unsigned MaxInterleaveSize = TTI.getMaxInterleaveFactor();
4469 // Check if the user has overridden the unroll max.
4471 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4472 MaxInterleaveSize = ForceTargetMaxScalarInterleaveFactor;
4474 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4475 MaxInterleaveSize = ForceTargetMaxVectorInterleaveFactor;
4478 // If we did not calculate the cost for VF (because the user selected the VF)
4479 // then we calculate the cost of VF here.
4481 LoopCost = expectedCost(VF);
4483 // Clamp the calculated UF to be between the 1 and the max unroll factor
4484 // that the target allows.
4485 if (UF > MaxInterleaveSize)
4486 UF = MaxInterleaveSize;
4490 // Unroll if we vectorized this loop and there is a reduction that could
4491 // benefit from unrolling.
4492 if (VF > 1 && Legal->getReductionVars()->size()) {
4493 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
4497 // Note that if we've already vectorized the loop we will have done the
4498 // runtime check and so unrolling won't require further checks.
4499 bool UnrollingRequiresRuntimePointerCheck =
4500 (VF == 1 && Legal->getRuntimePointerCheck()->Need);
4502 // We want to unroll small loops in order to reduce the loop overhead and
4503 // potentially expose ILP opportunities.
4504 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4505 if (!UnrollingRequiresRuntimePointerCheck &&
4506 LoopCost < SmallLoopCost) {
4507 // We assume that the cost overhead is 1 and we use the cost model
4508 // to estimate the cost of the loop and unroll until the cost of the
4509 // loop overhead is about 5% of the cost of the loop.
4510 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4512 // Unroll until store/load ports (estimated by max unroll factor) are
4514 unsigned NumStores = Legal->getNumStores();
4515 unsigned NumLoads = Legal->getNumLoads();
4516 unsigned StoresUF = UF / (NumStores ? NumStores : 1);
4517 unsigned LoadsUF = UF / (NumLoads ? NumLoads : 1);
4519 // If we have a scalar reduction (vector reductions are already dealt with
4520 // by this point), we can increase the critical path length if the loop
4521 // we're unrolling is inside another loop. Limit, by default to 2, so the
4522 // critical path only gets increased by one reduction operation.
4523 if (Legal->getReductionVars()->size() &&
4524 TheLoop->getLoopDepth() > 1) {
4525 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionUF);
4526 SmallUF = std::min(SmallUF, F);
4527 StoresUF = std::min(StoresUF, F);
4528 LoadsUF = std::min(LoadsUF, F);
4531 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
4532 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
4533 return std::max(StoresUF, LoadsUF);
4536 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
4540 DEBUG(dbgs() << "LV: Not Unrolling.\n");
4544 LoopVectorizationCostModel::RegisterUsage
4545 LoopVectorizationCostModel::calculateRegisterUsage() {
4546 // This function calculates the register usage by measuring the highest number
4547 // of values that are alive at a single location. Obviously, this is a very
4548 // rough estimation. We scan the loop in a topological order in order and
4549 // assign a number to each instruction. We use RPO to ensure that defs are
4550 // met before their users. We assume that each instruction that has in-loop
4551 // users starts an interval. We record every time that an in-loop value is
4552 // used, so we have a list of the first and last occurrences of each
4553 // instruction. Next, we transpose this data structure into a multi map that
4554 // holds the list of intervals that *end* at a specific location. This multi
4555 // map allows us to perform a linear search. We scan the instructions linearly
4556 // and record each time that a new interval starts, by placing it in a set.
4557 // If we find this value in the multi-map then we remove it from the set.
4558 // The max register usage is the maximum size of the set.
4559 // We also search for instructions that are defined outside the loop, but are
4560 // used inside the loop. We need this number separately from the max-interval
4561 // usage number because when we unroll, loop-invariant values do not take
4563 LoopBlocksDFS DFS(TheLoop);
4567 R.NumInstructions = 0;
4569 // Each 'key' in the map opens a new interval. The values
4570 // of the map are the index of the 'last seen' usage of the
4571 // instruction that is the key.
4572 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4573 // Maps instruction to its index.
4574 DenseMap<unsigned, Instruction*> IdxToInstr;
4575 // Marks the end of each interval.
4576 IntervalMap EndPoint;
4577 // Saves the list of instruction indices that are used in the loop.
4578 SmallSet<Instruction*, 8> Ends;
4579 // Saves the list of values that are used in the loop but are
4580 // defined outside the loop, such as arguments and constants.
4581 SmallPtrSet<Value*, 8> LoopInvariants;
4584 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4585 be = DFS.endRPO(); bb != be; ++bb) {
4586 R.NumInstructions += (*bb)->size();
4587 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4589 Instruction *I = it;
4590 IdxToInstr[Index++] = I;
4592 // Save the end location of each USE.
4593 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4594 Value *U = I->getOperand(i);
4595 Instruction *Instr = dyn_cast<Instruction>(U);
4597 // Ignore non-instruction values such as arguments, constants, etc.
4598 if (!Instr) continue;
4600 // If this instruction is outside the loop then record it and continue.
4601 if (!TheLoop->contains(Instr)) {
4602 LoopInvariants.insert(Instr);
4606 // Overwrite previous end points.
4607 EndPoint[Instr] = Index;
4613 // Saves the list of intervals that end with the index in 'key'.
4614 typedef SmallVector<Instruction*, 2> InstrList;
4615 DenseMap<unsigned, InstrList> TransposeEnds;
4617 // Transpose the EndPoints to a list of values that end at each index.
4618 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4620 TransposeEnds[it->second].push_back(it->first);
4622 SmallSet<Instruction*, 8> OpenIntervals;
4623 unsigned MaxUsage = 0;
4626 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4627 for (unsigned int i = 0; i < Index; ++i) {
4628 Instruction *I = IdxToInstr[i];
4629 // Ignore instructions that are never used within the loop.
4630 if (!Ends.count(I)) continue;
4632 // Ignore ephemeral values.
4633 if (EphValues.count(I))
4636 // Remove all of the instructions that end at this location.
4637 InstrList &List = TransposeEnds[i];
4638 for (unsigned int j=0, e = List.size(); j < e; ++j)
4639 OpenIntervals.erase(List[j]);
4641 // Count the number of live interals.
4642 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4644 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4645 OpenIntervals.size() << '\n');
4647 // Add the current instruction to the list of open intervals.
4648 OpenIntervals.insert(I);
4651 unsigned Invariant = LoopInvariants.size();
4652 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
4653 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
4654 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
4656 R.LoopInvariantRegs = Invariant;
4657 R.MaxLocalUsers = MaxUsage;
4661 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4665 for (Loop::block_iterator bb = TheLoop->block_begin(),
4666 be = TheLoop->block_end(); bb != be; ++bb) {
4667 unsigned BlockCost = 0;
4668 BasicBlock *BB = *bb;
4670 // For each instruction in the old loop.
4671 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4672 // Skip dbg intrinsics.
4673 if (isa<DbgInfoIntrinsic>(it))
4676 // Ignore ephemeral values.
4677 if (EphValues.count(it))
4680 unsigned C = getInstructionCost(it, VF);
4682 // Check if we should override the cost.
4683 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
4684 C = ForceTargetInstructionCost;
4687 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
4688 VF << " For instruction: " << *it << '\n');
4691 // We assume that if-converted blocks have a 50% chance of being executed.
4692 // When the code is scalar then some of the blocks are avoided due to CF.
4693 // When the code is vectorized we execute all code paths.
4694 if (VF == 1 && Legal->blockNeedsPredication(*bb))
4703 /// \brief Check whether the address computation for a non-consecutive memory
4704 /// access looks like an unlikely candidate for being merged into the indexing
4707 /// We look for a GEP which has one index that is an induction variable and all
4708 /// other indices are loop invariant. If the stride of this access is also
4709 /// within a small bound we decide that this address computation can likely be
4710 /// merged into the addressing mode.
4711 /// In all other cases, we identify the address computation as complex.
4712 static bool isLikelyComplexAddressComputation(Value *Ptr,
4713 LoopVectorizationLegality *Legal,
4714 ScalarEvolution *SE,
4715 const Loop *TheLoop) {
4716 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
4720 // We are looking for a gep with all loop invariant indices except for one
4721 // which should be an induction variable.
4722 unsigned NumOperands = Gep->getNumOperands();
4723 for (unsigned i = 1; i < NumOperands; ++i) {
4724 Value *Opd = Gep->getOperand(i);
4725 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
4726 !Legal->isInductionVariable(Opd))
4730 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
4731 // can likely be merged into the address computation.
4732 unsigned MaxMergeDistance = 64;
4734 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
4738 // Check the step is constant.
4739 const SCEV *Step = AddRec->getStepRecurrence(*SE);
4740 // Calculate the pointer stride and check if it is consecutive.
4741 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4745 const APInt &APStepVal = C->getValue()->getValue();
4747 // Huge step value - give up.
4748 if (APStepVal.getBitWidth() > 64)
4751 int64_t StepVal = APStepVal.getSExtValue();
4753 return StepVal > MaxMergeDistance;
4756 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
4757 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
4763 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
4764 // If we know that this instruction will remain uniform, check the cost of
4765 // the scalar version.
4766 if (Legal->isUniformAfterVectorization(I))
4769 Type *RetTy = I->getType();
4770 Type *VectorTy = ToVectorTy(RetTy, VF);
4772 // TODO: We need to estimate the cost of intrinsic calls.
4773 switch (I->getOpcode()) {
4774 case Instruction::GetElementPtr:
4775 // We mark this instruction as zero-cost because the cost of GEPs in
4776 // vectorized code depends on whether the corresponding memory instruction
4777 // is scalarized or not. Therefore, we handle GEPs with the memory
4778 // instruction cost.
4780 case Instruction::Br: {
4781 return TTI.getCFInstrCost(I->getOpcode());
4783 case Instruction::PHI:
4784 //TODO: IF-converted IFs become selects.
4786 case Instruction::Add:
4787 case Instruction::FAdd:
4788 case Instruction::Sub:
4789 case Instruction::FSub:
4790 case Instruction::Mul:
4791 case Instruction::FMul:
4792 case Instruction::UDiv:
4793 case Instruction::SDiv:
4794 case Instruction::FDiv:
4795 case Instruction::URem:
4796 case Instruction::SRem:
4797 case Instruction::FRem:
4798 case Instruction::Shl:
4799 case Instruction::LShr:
4800 case Instruction::AShr:
4801 case Instruction::And:
4802 case Instruction::Or:
4803 case Instruction::Xor: {
4804 // Since we will replace the stride by 1 the multiplication should go away.
4805 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
4807 // Certain instructions can be cheaper to vectorize if they have a constant
4808 // second vector operand. One example of this are shifts on x86.
4809 TargetTransformInfo::OperandValueKind Op1VK =
4810 TargetTransformInfo::OK_AnyValue;
4811 TargetTransformInfo::OperandValueKind Op2VK =
4812 TargetTransformInfo::OK_AnyValue;
4813 TargetTransformInfo::OperandValueProperties Op1VP =
4814 TargetTransformInfo::OP_None;
4815 TargetTransformInfo::OperandValueProperties Op2VP =
4816 TargetTransformInfo::OP_None;
4817 Value *Op2 = I->getOperand(1);
4819 // Check for a splat of a constant or for a non uniform vector of constants.
4820 if (isa<ConstantInt>(Op2)) {
4821 ConstantInt *CInt = cast<ConstantInt>(Op2);
4822 if (CInt && CInt->getValue().isPowerOf2())
4823 Op2VP = TargetTransformInfo::OP_PowerOf2;
4824 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4825 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
4826 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
4827 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
4829 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
4830 if (CInt && CInt->getValue().isPowerOf2())
4831 Op2VP = TargetTransformInfo::OP_PowerOf2;
4832 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4836 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
4839 case Instruction::Select: {
4840 SelectInst *SI = cast<SelectInst>(I);
4841 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
4842 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
4843 Type *CondTy = SI->getCondition()->getType();
4845 CondTy = VectorType::get(CondTy, VF);
4847 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
4849 case Instruction::ICmp:
4850 case Instruction::FCmp: {
4851 Type *ValTy = I->getOperand(0)->getType();
4852 VectorTy = ToVectorTy(ValTy, VF);
4853 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
4855 case Instruction::Store:
4856 case Instruction::Load: {
4857 StoreInst *SI = dyn_cast<StoreInst>(I);
4858 LoadInst *LI = dyn_cast<LoadInst>(I);
4859 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
4861 VectorTy = ToVectorTy(ValTy, VF);
4863 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
4864 unsigned AS = SI ? SI->getPointerAddressSpace() :
4865 LI->getPointerAddressSpace();
4866 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
4867 // We add the cost of address computation here instead of with the gep
4868 // instruction because only here we know whether the operation is
4871 return TTI.getAddressComputationCost(VectorTy) +
4872 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4874 // Scalarized loads/stores.
4875 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
4876 bool Reverse = ConsecutiveStride < 0;
4877 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
4878 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
4879 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
4880 bool IsComplexComputation =
4881 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
4883 // The cost of extracting from the value vector and pointer vector.
4884 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
4885 for (unsigned i = 0; i < VF; ++i) {
4886 // The cost of extracting the pointer operand.
4887 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
4888 // In case of STORE, the cost of ExtractElement from the vector.
4889 // In case of LOAD, the cost of InsertElement into the returned
4891 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
4892 Instruction::InsertElement,
4896 // The cost of the scalar loads/stores.
4897 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
4898 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
4903 // Wide load/stores.
4904 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
4905 if (Legal->isMaskRequired(I))
4906 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
4909 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4912 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4916 case Instruction::ZExt:
4917 case Instruction::SExt:
4918 case Instruction::FPToUI:
4919 case Instruction::FPToSI:
4920 case Instruction::FPExt:
4921 case Instruction::PtrToInt:
4922 case Instruction::IntToPtr:
4923 case Instruction::SIToFP:
4924 case Instruction::UIToFP:
4925 case Instruction::Trunc:
4926 case Instruction::FPTrunc:
4927 case Instruction::BitCast: {
4928 // We optimize the truncation of induction variable.
4929 // The cost of these is the same as the scalar operation.
4930 if (I->getOpcode() == Instruction::Trunc &&
4931 Legal->isInductionVariable(I->getOperand(0)))
4932 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
4933 I->getOperand(0)->getType());
4935 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
4936 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
4938 case Instruction::Call: {
4939 CallInst *CI = cast<CallInst>(I);
4940 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
4941 assert(ID && "Not an intrinsic call!");
4942 Type *RetTy = ToVectorTy(CI->getType(), VF);
4943 SmallVector<Type*, 4> Tys;
4944 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
4945 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
4946 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
4949 // We are scalarizing the instruction. Return the cost of the scalar
4950 // instruction, plus the cost of insert and extract into vector
4951 // elements, times the vector width.
4954 if (!RetTy->isVoidTy() && VF != 1) {
4955 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
4957 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
4960 // The cost of inserting the results plus extracting each one of the
4962 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
4965 // The cost of executing VF copies of the scalar instruction. This opcode
4966 // is unknown. Assume that it is the same as 'mul'.
4967 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
4973 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
4974 if (Scalar->isVoidTy() || VF == 1)
4976 return VectorType::get(Scalar, VF);
4979 char LoopVectorize::ID = 0;
4980 static const char lv_name[] = "Loop Vectorization";
4981 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
4982 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
4983 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4984 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4985 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
4986 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4987 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
4988 INITIALIZE_PASS_DEPENDENCY(LCSSA)
4989 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
4990 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
4991 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
4994 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
4995 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
4999 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5000 // Check for a store.
5001 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5002 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5004 // Check for a load.
5005 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5006 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5012 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5013 bool IfPredicateStore) {
5014 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5015 // Holds vector parameters or scalars, in case of uniform vals.
5016 SmallVector<VectorParts, 4> Params;
5018 setDebugLocFromInst(Builder, Instr);
5020 // Find all of the vectorized parameters.
5021 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5022 Value *SrcOp = Instr->getOperand(op);
5024 // If we are accessing the old induction variable, use the new one.
5025 if (SrcOp == OldInduction) {
5026 Params.push_back(getVectorValue(SrcOp));
5030 // Try using previously calculated values.
5031 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5033 // If the src is an instruction that appeared earlier in the basic block
5034 // then it should already be vectorized.
5035 if (SrcInst && OrigLoop->contains(SrcInst)) {
5036 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5037 // The parameter is a vector value from earlier.
5038 Params.push_back(WidenMap.get(SrcInst));
5040 // The parameter is a scalar from outside the loop. Maybe even a constant.
5041 VectorParts Scalars;
5042 Scalars.append(UF, SrcOp);
5043 Params.push_back(Scalars);
5047 assert(Params.size() == Instr->getNumOperands() &&
5048 "Invalid number of operands");
5050 // Does this instruction return a value ?
5051 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5053 Value *UndefVec = IsVoidRetTy ? nullptr :
5054 UndefValue::get(Instr->getType());
5055 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5056 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5058 Instruction *InsertPt = Builder.GetInsertPoint();
5059 BasicBlock *IfBlock = Builder.GetInsertBlock();
5060 BasicBlock *CondBlock = nullptr;
5063 Loop *VectorLp = nullptr;
5064 if (IfPredicateStore) {
5065 assert(Instr->getParent()->getSinglePredecessor() &&
5066 "Only support single predecessor blocks");
5067 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5068 Instr->getParent());
5069 VectorLp = LI->getLoopFor(IfBlock);
5070 assert(VectorLp && "Must have a loop for this block");
5073 // For each vector unroll 'part':
5074 for (unsigned Part = 0; Part < UF; ++Part) {
5075 // For each scalar that we create:
5077 // Start an "if (pred) a[i] = ..." block.
5078 Value *Cmp = nullptr;
5079 if (IfPredicateStore) {
5080 if (Cond[Part]->getType()->isVectorTy())
5082 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5083 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5084 ConstantInt::get(Cond[Part]->getType(), 1));
5085 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5086 LoopVectorBody.push_back(CondBlock);
5087 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
5088 // Update Builder with newly created basic block.
5089 Builder.SetInsertPoint(InsertPt);
5092 Instruction *Cloned = Instr->clone();
5094 Cloned->setName(Instr->getName() + ".cloned");
5095 // Replace the operands of the cloned instructions with extracted scalars.
5096 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5097 Value *Op = Params[op][Part];
5098 Cloned->setOperand(op, Op);
5101 // Place the cloned scalar in the new loop.
5102 Builder.Insert(Cloned);
5104 // If the original scalar returns a value we need to place it in a vector
5105 // so that future users will be able to use it.
5107 VecResults[Part] = Cloned;
5110 if (IfPredicateStore) {
5111 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5112 LoopVectorBody.push_back(NewIfBlock);
5113 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
5114 Builder.SetInsertPoint(InsertPt);
5115 Instruction *OldBr = IfBlock->getTerminator();
5116 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
5117 OldBr->eraseFromParent();
5118 IfBlock = NewIfBlock;
5123 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5124 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5125 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5127 return scalarizeInstruction(Instr, IfPredicateStore);
5130 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5134 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5138 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5139 // When unrolling and the VF is 1, we only need to add a simple scalar.
5140 Type *ITy = Val->getType();
5141 assert(!ITy->isVectorTy() && "Val must be a scalar");
5142 Constant *C = ConstantInt::get(ITy, StartIdx);
5143 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");