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/AssumptionTracker.h"
59 #include "llvm/Analysis/BlockFrequencyInfo.h"
60 #include "llvm/Analysis/CodeMetrics.h"
61 #include "llvm/Analysis/LoopInfo.h"
62 #include "llvm/Analysis/LoopIterator.h"
63 #include "llvm/Analysis/LoopPass.h"
64 #include "llvm/Analysis/ScalarEvolution.h"
65 #include "llvm/Analysis/ScalarEvolutionExpander.h"
66 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
67 #include "llvm/Analysis/TargetTransformInfo.h"
68 #include "llvm/Analysis/ValueTracking.h"
69 #include "llvm/IR/Constants.h"
70 #include "llvm/IR/DataLayout.h"
71 #include "llvm/IR/DebugInfo.h"
72 #include "llvm/IR/DerivedTypes.h"
73 #include "llvm/IR/DiagnosticInfo.h"
74 #include "llvm/IR/Dominators.h"
75 #include "llvm/IR/Function.h"
76 #include "llvm/IR/IRBuilder.h"
77 #include "llvm/IR/Instructions.h"
78 #include "llvm/IR/IntrinsicInst.h"
79 #include "llvm/IR/LLVMContext.h"
80 #include "llvm/IR/Module.h"
81 #include "llvm/IR/PatternMatch.h"
82 #include "llvm/IR/Type.h"
83 #include "llvm/IR/Value.h"
84 #include "llvm/IR/ValueHandle.h"
85 #include "llvm/IR/Verifier.h"
86 #include "llvm/Pass.h"
87 #include "llvm/Support/BranchProbability.h"
88 #include "llvm/Support/CommandLine.h"
89 #include "llvm/Support/Debug.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include "llvm/Transforms/Scalar.h"
92 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
93 #include "llvm/Transforms/Utils/Local.h"
94 #include "llvm/Transforms/Utils/VectorUtils.h"
100 using namespace llvm::PatternMatch;
102 #define LV_NAME "loop-vectorize"
103 #define DEBUG_TYPE LV_NAME
105 STATISTIC(LoopsVectorized, "Number of loops vectorized");
106 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
108 static cl::opt<unsigned>
109 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
110 cl::desc("Sets the SIMD width. Zero is autoselect."));
112 static cl::opt<unsigned>
113 VectorizationInterleave("force-vector-interleave", cl::init(0), cl::Hidden,
114 cl::desc("Sets the vectorization interleave count. "
115 "Zero is autoselect."));
118 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
119 cl::desc("Enable if-conversion during vectorization."));
121 /// We don't vectorize loops with a known constant trip count below this number.
122 static cl::opt<unsigned>
123 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
125 cl::desc("Don't vectorize loops with a constant "
126 "trip count that is smaller than this "
129 /// This enables versioning on the strides of symbolically striding memory
130 /// accesses in code like the following.
131 /// for (i = 0; i < N; ++i)
132 /// A[i * Stride1] += B[i * Stride2] ...
134 /// Will be roughly translated to
135 /// if (Stride1 == 1 && Stride2 == 1) {
136 /// for (i = 0; i < N; i+=4)
140 static cl::opt<bool> EnableMemAccessVersioning(
141 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
142 cl::desc("Enable symblic stride memory access versioning"));
144 /// We don't unroll loops with a known constant trip count below this number.
145 static const unsigned TinyTripCountUnrollThreshold = 128;
147 /// When performing memory disambiguation checks at runtime do not make more
148 /// than this number of comparisons.
149 static const unsigned RuntimeMemoryCheckThreshold = 8;
151 /// Maximum simd width.
152 static const unsigned MaxVectorWidth = 64;
154 static cl::opt<unsigned> ForceTargetNumScalarRegs(
155 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
156 cl::desc("A flag that overrides the target's number of scalar registers."));
158 static cl::opt<unsigned> ForceTargetNumVectorRegs(
159 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
160 cl::desc("A flag that overrides the target's number of vector registers."));
162 /// Maximum vectorization interleave count.
163 static const unsigned MaxInterleaveFactor = 16;
165 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
166 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
167 cl::desc("A flag that overrides the target's max interleave factor for "
170 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
171 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
172 cl::desc("A flag that overrides the target's max interleave factor for "
173 "vectorized loops."));
175 static cl::opt<unsigned> ForceTargetInstructionCost(
176 "force-target-instruction-cost", cl::init(0), cl::Hidden,
177 cl::desc("A flag that overrides the target's expected cost for "
178 "an instruction to a single constant value. Mostly "
179 "useful for getting consistent testing."));
181 static cl::opt<unsigned> SmallLoopCost(
182 "small-loop-cost", cl::init(20), cl::Hidden,
183 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
185 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
186 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
187 cl::desc("Enable the use of the block frequency analysis to access PGO "
188 "heuristics minimizing code growth in cold regions and being more "
189 "aggressive in hot regions."));
191 // Runtime unroll loops for load/store throughput.
192 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
193 "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
194 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
196 /// The number of stores in a loop that are allowed to need predication.
197 static cl::opt<unsigned> NumberOfStoresToPredicate(
198 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
199 cl::desc("Max number of stores to be predicated behind an if."));
201 static cl::opt<bool> EnableIndVarRegisterHeur(
202 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
203 cl::desc("Count the induction variable only once when unrolling"));
205 static cl::opt<bool> EnableCondStoresVectorization(
206 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
207 cl::desc("Enable if predication of stores during vectorization."));
209 static cl::opt<unsigned> MaxNestedScalarReductionUF(
210 "max-nested-scalar-reduction-unroll", cl::init(2), cl::Hidden,
211 cl::desc("The maximum unroll factor to use when unrolling a scalar "
212 "reduction in a nested loop."));
216 // Forward declarations.
217 class LoopVectorizationLegality;
218 class LoopVectorizationCostModel;
219 class LoopVectorizeHints;
221 /// Optimization analysis message produced during vectorization. Messages inform
222 /// the user why vectorization did not occur.
225 raw_string_ostream Out;
229 Report(Instruction *I = nullptr) : Out(Message), Instr(I) {
230 Out << "loop not vectorized: ";
233 template <typename A> Report &operator<<(const A &Value) {
238 Instruction *getInstr() { return Instr; }
240 std::string &str() { return Out.str(); }
241 operator Twine() { return Out.str(); }
244 /// InnerLoopVectorizer vectorizes loops which contain only one basic
245 /// block to a specified vectorization factor (VF).
246 /// This class performs the widening of scalars into vectors, or multiple
247 /// scalars. This class also implements the following features:
248 /// * It inserts an epilogue loop for handling loops that don't have iteration
249 /// counts that are known to be a multiple of the vectorization factor.
250 /// * It handles the code generation for reduction variables.
251 /// * Scalarization (implementation using scalars) of un-vectorizable
253 /// InnerLoopVectorizer does not perform any vectorization-legality
254 /// checks, and relies on the caller to check for the different legality
255 /// aspects. The InnerLoopVectorizer relies on the
256 /// LoopVectorizationLegality class to provide information about the induction
257 /// and reduction variables that were found to a given vectorization factor.
258 class InnerLoopVectorizer {
260 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
261 DominatorTree *DT, const DataLayout *DL,
262 const TargetLibraryInfo *TLI, unsigned VecWidth,
263 unsigned UnrollFactor)
264 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
265 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
266 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
269 // Perform the actual loop widening (vectorization).
270 void vectorize(LoopVectorizationLegality *L) {
272 // Create a new empty loop. Unlink the old loop and connect the new one.
274 // Widen each instruction in the old loop to a new one in the new loop.
275 // Use the Legality module to find the induction and reduction variables.
277 // Register the new loop and update the analysis passes.
281 virtual ~InnerLoopVectorizer() {}
284 /// A small list of PHINodes.
285 typedef SmallVector<PHINode*, 4> PhiVector;
286 /// When we unroll loops we have multiple vector values for each scalar.
287 /// This data structure holds the unrolled and vectorized values that
288 /// originated from one scalar instruction.
289 typedef SmallVector<Value*, 2> VectorParts;
291 // When we if-convert we need create edge masks. We have to cache values so
292 // that we don't end up with exponential recursion/IR.
293 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
294 VectorParts> EdgeMaskCache;
296 /// \brief Add code that checks at runtime if the accessed arrays overlap.
298 /// Returns a pair of instructions where the first element is the first
299 /// instruction generated in possibly a sequence of instructions and the
300 /// second value is the final comparator value or NULL if no check is needed.
301 std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
303 /// \brief Add checks for strides that where assumed to be 1.
305 /// Returns the last check instruction and the first check instruction in the
306 /// pair as (first, last).
307 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
309 /// Create an empty loop, based on the loop ranges of the old loop.
310 void createEmptyLoop();
311 /// Copy and widen the instructions from the old loop.
312 virtual void vectorizeLoop();
314 /// \brief The Loop exit block may have single value PHI nodes where the
315 /// incoming value is 'Undef'. While vectorizing we only handled real values
316 /// that were defined inside the loop. Here we fix the 'undef case'.
320 /// A helper function that computes the predicate of the block BB, assuming
321 /// that the header block of the loop is set to True. It returns the *entry*
322 /// mask for the block BB.
323 VectorParts createBlockInMask(BasicBlock *BB);
324 /// A helper function that computes the predicate of the edge between SRC
326 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
328 /// A helper function to vectorize a single BB within the innermost loop.
329 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
331 /// Vectorize a single PHINode in a block. This method handles the induction
332 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
333 /// arbitrary length vectors.
334 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
335 unsigned UF, unsigned VF, PhiVector *PV);
337 /// Insert the new loop to the loop hierarchy and pass manager
338 /// and update the analysis passes.
339 void updateAnalysis();
341 /// This instruction is un-vectorizable. Implement it as a sequence
342 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
343 /// scalarized instruction behind an if block predicated on the control
344 /// dependence of the instruction.
345 virtual void scalarizeInstruction(Instruction *Instr,
346 bool IfPredicateStore=false);
348 /// Vectorize Load and Store instructions,
349 virtual void vectorizeMemoryInstruction(Instruction *Instr);
351 /// Create a broadcast instruction. This method generates a broadcast
352 /// instruction (shuffle) for loop invariant values and for the induction
353 /// value. If this is the induction variable then we extend it to N, N+1, ...
354 /// this is needed because each iteration in the loop corresponds to a SIMD
356 virtual Value *getBroadcastInstrs(Value *V);
358 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
359 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
360 /// The sequence starts at StartIndex.
361 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
363 /// When we go over instructions in the basic block we rely on previous
364 /// values within the current basic block or on loop invariant values.
365 /// When we widen (vectorize) values we place them in the map. If the values
366 /// are not within the map, they have to be loop invariant, so we simply
367 /// broadcast them into a vector.
368 VectorParts &getVectorValue(Value *V);
370 /// Generate a shuffle sequence that will reverse the vector Vec.
371 virtual Value *reverseVector(Value *Vec);
373 /// This is a helper class that holds the vectorizer state. It maps scalar
374 /// instructions to vector instructions. When the code is 'unrolled' then
375 /// then a single scalar value is mapped to multiple vector parts. The parts
376 /// are stored in the VectorPart type.
378 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
380 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
382 /// \return True if 'Key' is saved in the Value Map.
383 bool has(Value *Key) const { return MapStorage.count(Key); }
385 /// Initializes a new entry in the map. Sets all of the vector parts to the
386 /// save value in 'Val'.
387 /// \return A reference to a vector with splat values.
388 VectorParts &splat(Value *Key, Value *Val) {
389 VectorParts &Entry = MapStorage[Key];
390 Entry.assign(UF, Val);
394 ///\return A reference to the value that is stored at 'Key'.
395 VectorParts &get(Value *Key) {
396 VectorParts &Entry = MapStorage[Key];
399 assert(Entry.size() == UF);
404 /// The unroll factor. Each entry in the map stores this number of vector
408 /// Map storage. We use std::map and not DenseMap because insertions to a
409 /// dense map invalidates its iterators.
410 std::map<Value *, VectorParts> MapStorage;
413 /// The original loop.
415 /// Scev analysis to use.
424 const DataLayout *DL;
425 /// Target Library Info.
426 const TargetLibraryInfo *TLI;
428 /// The vectorization SIMD factor to use. Each vector will have this many
433 /// The vectorization unroll factor to use. Each scalar is vectorized to this
434 /// many different vector instructions.
437 /// The builder that we use
440 // --- Vectorization state ---
442 /// The vector-loop preheader.
443 BasicBlock *LoopVectorPreHeader;
444 /// The scalar-loop preheader.
445 BasicBlock *LoopScalarPreHeader;
446 /// Middle Block between the vector and the scalar.
447 BasicBlock *LoopMiddleBlock;
448 ///The ExitBlock of the scalar loop.
449 BasicBlock *LoopExitBlock;
450 ///The vector loop body.
451 SmallVector<BasicBlock *, 4> LoopVectorBody;
452 ///The scalar loop body.
453 BasicBlock *LoopScalarBody;
454 /// A list of all bypass blocks. The first block is the entry of the loop.
455 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
457 /// The new Induction variable which was added to the new block.
459 /// The induction variable of the old basic block.
460 PHINode *OldInduction;
461 /// Holds the extended (to the widest induction type) start index.
463 /// Maps scalars to widened vectors.
465 EdgeMaskCache MaskCache;
467 LoopVectorizationLegality *Legal;
470 class InnerLoopUnroller : public InnerLoopVectorizer {
472 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
473 DominatorTree *DT, const DataLayout *DL,
474 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
475 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
478 void scalarizeInstruction(Instruction *Instr,
479 bool IfPredicateStore = false) override;
480 void vectorizeMemoryInstruction(Instruction *Instr) override;
481 Value *getBroadcastInstrs(Value *V) override;
482 Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate) override;
483 Value *reverseVector(Value *Vec) override;
486 /// \brief Look for a meaningful debug location on the instruction or it's
488 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
493 if (I->getDebugLoc() != Empty)
496 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
497 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
498 if (OpInst->getDebugLoc() != Empty)
505 /// \brief Set the debug location in the builder using the debug location in the
507 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
508 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
509 B.SetCurrentDebugLocation(Inst->getDebugLoc());
511 B.SetCurrentDebugLocation(DebugLoc());
515 /// \return string containing a file name and a line # for the given loop.
516 static std::string getDebugLocString(const Loop *L) {
519 raw_string_ostream OS(Result);
520 const DebugLoc LoopDbgLoc = L->getStartLoc();
521 if (!LoopDbgLoc.isUnknown())
522 LoopDbgLoc.print(L->getHeader()->getContext(), OS);
524 // Just print the module name.
525 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
532 /// \brief Propagate known metadata from one instruction to another.
533 static void propagateMetadata(Instruction *To, const Instruction *From) {
534 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
535 From->getAllMetadataOtherThanDebugLoc(Metadata);
537 for (auto M : Metadata) {
538 unsigned Kind = M.first;
540 // These are safe to transfer (this is safe for TBAA, even when we
541 // if-convert, because should that metadata have had a control dependency
542 // on the condition, and thus actually aliased with some other
543 // non-speculated memory access when the condition was false, this would be
544 // caught by the runtime overlap checks).
545 if (Kind != LLVMContext::MD_tbaa &&
546 Kind != LLVMContext::MD_alias_scope &&
547 Kind != LLVMContext::MD_noalias &&
548 Kind != LLVMContext::MD_fpmath)
551 To->setMetadata(Kind, M.second);
555 /// \brief Propagate known metadata from one instruction to a vector of others.
556 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
558 if (Instruction *I = dyn_cast<Instruction>(V))
559 propagateMetadata(I, From);
562 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
563 /// to what vectorization factor.
564 /// This class does not look at the profitability of vectorization, only the
565 /// legality. This class has two main kinds of checks:
566 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
567 /// will change the order of memory accesses in a way that will change the
568 /// correctness of the program.
569 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
570 /// checks for a number of different conditions, such as the availability of a
571 /// single induction variable, that all types are supported and vectorize-able,
572 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
573 /// This class is also used by InnerLoopVectorizer for identifying
574 /// induction variable and the different reduction variables.
575 class LoopVectorizationLegality {
579 unsigned NumPredStores;
581 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
582 DominatorTree *DT, TargetLibraryInfo *TLI,
583 AliasAnalysis *AA, Function *F)
584 : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
585 DT(DT), TLI(TLI), AA(AA), TheFunction(F), Induction(nullptr),
586 WidestIndTy(nullptr), HasFunNoNaNAttr(false), MaxSafeDepDistBytes(-1U) {
589 /// This enum represents the kinds of reductions that we support.
591 RK_NoReduction, ///< Not a reduction.
592 RK_IntegerAdd, ///< Sum of integers.
593 RK_IntegerMult, ///< Product of integers.
594 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
595 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
596 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
597 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
598 RK_FloatAdd, ///< Sum of floats.
599 RK_FloatMult, ///< Product of floats.
600 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
603 /// This enum represents the kinds of inductions that we support.
605 IK_NoInduction, ///< Not an induction variable.
606 IK_IntInduction, ///< Integer induction variable. Step = 1.
607 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
608 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
609 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
612 // This enum represents the kind of minmax reduction.
613 enum MinMaxReductionKind {
623 /// This struct holds information about reduction variables.
624 struct ReductionDescriptor {
625 ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
626 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
628 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
629 MinMaxReductionKind MK)
630 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
632 // The starting value of the reduction.
633 // It does not have to be zero!
634 TrackingVH<Value> StartValue;
635 // The instruction who's value is used outside the loop.
636 Instruction *LoopExitInstr;
637 // The kind of the reduction.
639 // If this a min/max reduction the kind of reduction.
640 MinMaxReductionKind MinMaxKind;
643 /// This POD struct holds information about a potential reduction operation.
644 struct ReductionInstDesc {
645 ReductionInstDesc(bool IsRedux, Instruction *I) :
646 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
648 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
649 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
651 // Is this instruction a reduction candidate.
653 // The last instruction in a min/max pattern (select of the select(icmp())
654 // pattern), or the current reduction instruction otherwise.
655 Instruction *PatternLastInst;
656 // If this is a min/max pattern the comparison predicate.
657 MinMaxReductionKind MinMaxKind;
660 /// This struct holds information about the memory runtime legality
661 /// check that a group of pointers do not overlap.
662 struct RuntimePointerCheck {
663 RuntimePointerCheck() : Need(false) {}
665 /// Reset the state of the pointer runtime information.
672 DependencySetId.clear();
676 /// Insert a pointer and calculate the start and end SCEVs.
677 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
678 unsigned DepSetId, unsigned ASId, ValueToValueMap &Strides);
680 /// This flag indicates if we need to add the runtime check.
682 /// Holds the pointers that we need to check.
683 SmallVector<TrackingVH<Value>, 2> Pointers;
684 /// Holds the pointer value at the beginning of the loop.
685 SmallVector<const SCEV*, 2> Starts;
686 /// Holds the pointer value at the end of the loop.
687 SmallVector<const SCEV*, 2> Ends;
688 /// Holds the information if this pointer is used for writing to memory.
689 SmallVector<bool, 2> IsWritePtr;
690 /// Holds the id of the set of pointers that could be dependent because of a
691 /// shared underlying object.
692 SmallVector<unsigned, 2> DependencySetId;
693 /// Holds the id of the disjoint alias set to which this pointer belongs.
694 SmallVector<unsigned, 2> AliasSetId;
697 /// A struct for saving information about induction variables.
698 struct InductionInfo {
699 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
700 InductionInfo() : StartValue(nullptr), IK(IK_NoInduction) {}
702 TrackingVH<Value> StartValue;
707 /// ReductionList contains the reduction descriptors for all
708 /// of the reductions that were found in the loop.
709 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
711 /// InductionList saves induction variables and maps them to the
712 /// induction descriptor.
713 typedef MapVector<PHINode*, InductionInfo> InductionList;
715 /// Returns true if it is legal to vectorize this loop.
716 /// This does not mean that it is profitable to vectorize this
717 /// loop, only that it is legal to do so.
720 /// Returns the Induction variable.
721 PHINode *getInduction() { return Induction; }
723 /// Returns the reduction variables found in the loop.
724 ReductionList *getReductionVars() { return &Reductions; }
726 /// Returns the induction variables found in the loop.
727 InductionList *getInductionVars() { return &Inductions; }
729 /// Returns the widest induction type.
730 Type *getWidestInductionType() { return WidestIndTy; }
732 /// Returns True if V is an induction variable in this loop.
733 bool isInductionVariable(const Value *V);
735 /// Return true if the block BB needs to be predicated in order for the loop
736 /// to be vectorized.
737 bool blockNeedsPredication(BasicBlock *BB);
739 /// Check if this pointer is consecutive when vectorizing. This happens
740 /// when the last index of the GEP is the induction variable, or that the
741 /// pointer itself is an induction variable.
742 /// This check allows us to vectorize A[idx] into a wide load/store.
744 /// 0 - Stride is unknown or non-consecutive.
745 /// 1 - Address is consecutive.
746 /// -1 - Address is consecutive, and decreasing.
747 int isConsecutivePtr(Value *Ptr);
749 /// Returns true if the value V is uniform within the loop.
750 bool isUniform(Value *V);
752 /// Returns true if this instruction will remain scalar after vectorization.
753 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
755 /// Returns the information that we collected about runtime memory check.
756 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
758 /// This function returns the identity element (or neutral element) for
760 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
762 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
764 bool hasStride(Value *V) { return StrideSet.count(V); }
765 bool mustCheckStrides() { return !StrideSet.empty(); }
766 SmallPtrSet<Value *, 8>::iterator strides_begin() {
767 return StrideSet.begin();
769 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
772 /// Check if a single basic block loop is vectorizable.
773 /// At this point we know that this is a loop with a constant trip count
774 /// and we only need to check individual instructions.
775 bool canVectorizeInstrs();
777 /// When we vectorize loops we may change the order in which
778 /// we read and write from memory. This method checks if it is
779 /// legal to vectorize the code, considering only memory constrains.
780 /// Returns true if the loop is vectorizable
781 bool canVectorizeMemory();
783 /// Return true if we can vectorize this loop using the IF-conversion
785 bool canVectorizeWithIfConvert();
787 /// Collect the variables that need to stay uniform after vectorization.
788 void collectLoopUniforms();
790 /// Return true if all of the instructions in the block can be speculatively
791 /// executed. \p SafePtrs is a list of addresses that are known to be legal
792 /// and we know that we can read from them without segfault.
793 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
795 /// Returns True, if 'Phi' is the kind of reduction variable for type
796 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
797 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
798 /// Returns a struct describing if the instruction 'I' can be a reduction
799 /// variable of type 'Kind'. If the reduction is a min/max pattern of
800 /// select(icmp()) this function advances the instruction pointer 'I' from the
801 /// compare instruction to the select instruction and stores this pointer in
802 /// 'PatternLastInst' member of the returned struct.
803 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
804 ReductionInstDesc &Desc);
805 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
806 /// pattern corresponding to a min(X, Y) or max(X, Y).
807 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
808 ReductionInstDesc &Prev);
809 /// Returns the induction kind of Phi. This function may return NoInduction
810 /// if the PHI is not an induction variable.
811 InductionKind isInductionVariable(PHINode *Phi);
813 /// \brief Collect memory access with loop invariant strides.
815 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
817 void collectStridedAcccess(Value *LoadOrStoreInst);
819 /// Report an analysis message to assist the user in diagnosing loops that are
821 void emitAnalysis(Report &Message) {
822 DebugLoc DL = TheLoop->getStartLoc();
823 if (Instruction *I = Message.getInstr())
824 DL = I->getDebugLoc();
825 emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
826 *TheFunction, DL, Message.str());
829 /// The loop that we evaluate.
833 /// DataLayout analysis.
834 const DataLayout *DL;
837 /// Target Library Info.
838 TargetLibraryInfo *TLI;
842 Function *TheFunction;
844 // --- vectorization state --- //
846 /// Holds the integer induction variable. This is the counter of the
849 /// Holds the reduction variables.
850 ReductionList Reductions;
851 /// Holds all of the induction variables that we found in the loop.
852 /// Notice that inductions don't need to start at zero and that induction
853 /// variables can be pointers.
854 InductionList Inductions;
855 /// Holds the widest induction type encountered.
858 /// Allowed outside users. This holds the reduction
859 /// vars which can be accessed from outside the loop.
860 SmallPtrSet<Value*, 4> AllowedExit;
861 /// This set holds the variables which are known to be uniform after
863 SmallPtrSet<Instruction*, 4> Uniforms;
864 /// We need to check that all of the pointers in this list are disjoint
866 RuntimePointerCheck PtrRtCheck;
867 /// Can we assume the absence of NaNs.
868 bool HasFunNoNaNAttr;
870 unsigned MaxSafeDepDistBytes;
872 ValueToValueMap Strides;
873 SmallPtrSet<Value *, 8> StrideSet;
876 /// LoopVectorizationCostModel - estimates the expected speedups due to
878 /// In many cases vectorization is not profitable. This can happen because of
879 /// a number of reasons. In this class we mainly attempt to predict the
880 /// expected speedup/slowdowns due to the supported instruction set. We use the
881 /// TargetTransformInfo to query the different backends for the cost of
882 /// different operations.
883 class LoopVectorizationCostModel {
885 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
886 LoopVectorizationLegality *Legal,
887 const TargetTransformInfo &TTI,
888 const DataLayout *DL, const TargetLibraryInfo *TLI,
889 AssumptionTracker *AT, const Function *F,
890 const LoopVectorizeHints *Hints)
891 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI),
892 TheFunction(F), Hints(Hints) {
893 CodeMetrics::collectEphemeralValues(L, AT, EphValues);
896 /// Information about vectorization costs
897 struct VectorizationFactor {
898 unsigned Width; // Vector width with best cost
899 unsigned Cost; // Cost of the loop with that width
901 /// \return The most profitable vectorization factor and the cost of that VF.
902 /// This method checks every power of two up to VF. If UserVF is not ZERO
903 /// then this vectorization factor will be selected if vectorization is
905 VectorizationFactor selectVectorizationFactor(bool OptForSize);
907 /// \return The size (in bits) of the widest type in the code that
908 /// needs to be vectorized. We ignore values that remain scalar such as
909 /// 64 bit loop indices.
910 unsigned getWidestType();
912 /// \return The most profitable unroll factor.
913 /// If UserUF is non-zero then this method finds the best unroll-factor
914 /// based on register pressure and other parameters.
915 /// VF and LoopCost are the selected vectorization factor and the cost of the
917 unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost);
919 /// \brief A struct that represents some properties of the register usage
921 struct RegisterUsage {
922 /// Holds the number of loop invariant values that are used in the loop.
923 unsigned LoopInvariantRegs;
924 /// Holds the maximum number of concurrent live intervals in the loop.
925 unsigned MaxLocalUsers;
926 /// Holds the number of instructions in the loop.
927 unsigned NumInstructions;
930 /// \return information about the register usage of the loop.
931 RegisterUsage calculateRegisterUsage();
934 /// Returns the expected execution cost. The unit of the cost does
935 /// not matter because we use the 'cost' units to compare different
936 /// vector widths. The cost that is returned is *not* normalized by
937 /// the factor width.
938 unsigned expectedCost(unsigned VF);
940 /// Returns the execution time cost of an instruction for a given vector
941 /// width. Vector width of one means scalar.
942 unsigned getInstructionCost(Instruction *I, unsigned VF);
944 /// A helper function for converting Scalar types to vector types.
945 /// If the incoming type is void, we return void. If the VF is 1, we return
947 static Type* ToVectorTy(Type *Scalar, unsigned VF);
949 /// Returns whether the instruction is a load or store and will be a emitted
950 /// as a vector operation.
951 bool isConsecutiveLoadOrStore(Instruction *I);
953 /// Report an analysis message to assist the user in diagnosing loops that are
955 void emitAnalysis(Report &Message) {
956 DebugLoc DL = TheLoop->getStartLoc();
957 if (Instruction *I = Message.getInstr())
958 DL = I->getDebugLoc();
959 emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
960 *TheFunction, DL, Message.str());
963 /// Values used only by @llvm.assume calls.
964 SmallPtrSet<const Value *, 32> EphValues;
966 /// The loop that we evaluate.
970 /// Loop Info analysis.
972 /// Vectorization legality.
973 LoopVectorizationLegality *Legal;
974 /// Vector target information.
975 const TargetTransformInfo &TTI;
976 /// Target data layout information.
977 const DataLayout *DL;
978 /// Target Library Info.
979 const TargetLibraryInfo *TLI;
980 const Function *TheFunction;
981 // Loop Vectorize Hint.
982 const LoopVectorizeHints *Hints;
985 /// Utility class for getting and setting loop vectorizer hints in the form
986 /// of loop metadata.
987 /// This class keeps a number of loop annotations locally (as member variables)
988 /// and can, upon request, write them back as metadata on the loop. It will
989 /// initially scan the loop for existing metadata, and will update the local
990 /// values based on information in the loop.
991 /// We cannot write all values to metadata, as the mere presence of some info,
992 /// for example 'force', means a decision has been made. So, we need to be
993 /// careful NOT to add them if the user hasn't specifically asked so.
994 class LoopVectorizeHints {
1001 /// Hint - associates name and validation with the hint value.
1004 unsigned Value; // This may have to change for non-numeric values.
1007 Hint(const char * Name, unsigned Value, HintKind Kind)
1008 : Name(Name), Value(Value), Kind(Kind) { }
1010 bool validate(unsigned Val) {
1013 return isPowerOf2_32(Val) && Val <= MaxVectorWidth;
1015 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1023 /// Vectorization width.
1025 /// Vectorization interleave factor.
1027 /// Vectorization forced
1030 /// Return the loop metadata prefix.
1031 static StringRef Prefix() { return "llvm.loop."; }
1035 FK_Undefined = -1, ///< Not selected.
1036 FK_Disabled = 0, ///< Forcing disabled.
1037 FK_Enabled = 1, ///< Forcing enabled.
1040 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1041 : Width("vectorize.width", VectorizationFactor, HK_WIDTH),
1042 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1043 Force("vectorize.enable", FK_Undefined, HK_FORCE),
1045 // Populate values with existing loop metadata.
1046 getHintsFromMetadata();
1048 // force-vector-interleave overrides DisableInterleaving.
1049 if (VectorizationInterleave.getNumOccurrences() > 0)
1050 Interleave.Value = VectorizationInterleave;
1052 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1053 << "LV: Interleaving disabled by the pass manager\n");
1056 /// Mark the loop L as already vectorized by setting the width to 1.
1057 void setAlreadyVectorized() {
1058 Width.Value = Interleave.Value = 1;
1059 Hint Hints[] = {Width, Interleave};
1060 writeHintsToMetadata(Hints);
1063 /// Dumps all the hint information.
1064 std::string emitRemark() const {
1066 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1067 R << "vectorization is explicitly disabled";
1069 R << "use -Rpass-analysis=loop-vectorize for more info";
1070 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1071 R << " (Force=true";
1072 if (Width.Value != 0)
1073 R << ", Vector Width=" << Width.Value;
1074 if (Interleave.Value != 0)
1075 R << ", Interleave Count=" << Interleave.Value;
1083 unsigned getWidth() const { return Width.Value; }
1084 unsigned getInterleave() const { return Interleave.Value; }
1085 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1088 /// Find hints specified in the loop metadata and update local values.
1089 void getHintsFromMetadata() {
1090 MDNode *LoopID = TheLoop->getLoopID();
1094 // First operand should refer to the loop id itself.
1095 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1096 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1098 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1099 const MDString *S = nullptr;
1100 SmallVector<Value*, 4> Args;
1102 // The expected hint is either a MDString or a MDNode with the first
1103 // operand a MDString.
1104 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1105 if (!MD || MD->getNumOperands() == 0)
1107 S = dyn_cast<MDString>(MD->getOperand(0));
1108 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1109 Args.push_back(MD->getOperand(i));
1111 S = dyn_cast<MDString>(LoopID->getOperand(i));
1112 assert(Args.size() == 0 && "too many arguments for MDString");
1118 // Check if the hint starts with the loop metadata prefix.
1119 StringRef Name = S->getString();
1120 if (Args.size() == 1)
1121 setHint(Name, Args[0]);
1125 /// Checks string hint with one operand and set value if valid.
1126 void setHint(StringRef Name, Value *Arg) {
1127 if (!Name.startswith(Prefix()))
1129 Name = Name.substr(Prefix().size(), StringRef::npos);
1131 const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
1133 unsigned Val = C->getZExtValue();
1135 Hint *Hints[] = {&Width, &Interleave, &Force};
1136 for (auto H : Hints) {
1137 if (Name == H->Name) {
1138 if (H->validate(Val))
1141 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1147 /// Create a new hint from name / value pair.
1148 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1149 LLVMContext &Context = TheLoop->getHeader()->getContext();
1150 Value *Vals[] = {MDString::get(Context, Name),
1151 ConstantInt::get(Type::getInt32Ty(Context), V)};
1152 return MDNode::get(Context, Vals);
1155 /// Matches metadata with hint name.
1156 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1157 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1161 for (auto H : HintTypes)
1162 if (Name->getString().endswith(H.Name))
1167 /// Sets current hints into loop metadata, keeping other values intact.
1168 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1169 if (HintTypes.size() == 0)
1172 // Reserve the first element to LoopID (see below).
1173 SmallVector<Value*, 4> Vals(1);
1174 // If the loop already has metadata, then ignore the existing operands.
1175 MDNode *LoopID = TheLoop->getLoopID();
1177 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1178 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1179 // If node in update list, ignore old value.
1180 if (!matchesHintMetadataName(Node, HintTypes))
1181 Vals.push_back(Node);
1185 // Now, add the missing hints.
1186 for (auto H : HintTypes)
1188 createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1190 // Replace current metadata node with new one.
1191 LLVMContext &Context = TheLoop->getHeader()->getContext();
1192 MDNode *NewLoopID = MDNode::get(Context, Vals);
1193 // Set operand 0 to refer to the loop id itself.
1194 NewLoopID->replaceOperandWith(0, NewLoopID);
1196 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 AssumptionTracker *AT;
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<LoopInfo>();
1260 TTI = &getAnalysis<TargetTransformInfo>();
1261 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1262 BFI = &getAnalysis<BlockFrequencyInfo>();
1263 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1264 AA = &getAnalysis<AliasAnalysis>();
1265 AT = &getAnalysis<AssumptionTracker>();
1267 // Compute some weights outside of the loop over the loops. Compute this
1268 // using a BranchProbability to re-use its scaling math.
1269 const BranchProbability ColdProb(1, 5); // 20%
1270 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1272 // If the target claims to have no vector registers don't attempt
1274 if (!TTI->getNumberOfRegisters(true))
1278 DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1279 << ": Missing data layout\n");
1283 // Build up a worklist of inner-loops to vectorize. This is necessary as
1284 // the act of vectorizing or partially unrolling a loop creates new loops
1285 // and can invalidate iterators across the loops.
1286 SmallVector<Loop *, 8> Worklist;
1289 addInnerLoop(*L, Worklist);
1291 LoopsAnalyzed += Worklist.size();
1293 // Now walk the identified inner loops.
1294 bool Changed = false;
1295 while (!Worklist.empty())
1296 Changed |= processLoop(Worklist.pop_back_val());
1298 // Process each loop nest in the function.
1302 bool processLoop(Loop *L) {
1303 assert(L->empty() && "Only process inner loops.");
1306 const std::string DebugLocStr = getDebugLocString(L);
1309 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1310 << L->getHeader()->getParent()->getName() << "\" from "
1311 << DebugLocStr << "\n");
1313 LoopVectorizeHints Hints(L, DisableUnrolling);
1315 DEBUG(dbgs() << "LV: Loop hints:"
1317 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1319 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1321 : "?")) << " width=" << Hints.getWidth()
1322 << " unroll=" << Hints.getInterleave() << "\n");
1324 // Function containing loop
1325 Function *F = L->getHeader()->getParent();
1327 // Looking at the diagnostic output is the only way to determine if a loop
1328 // was vectorized (other than looking at the IR or machine code), so it
1329 // is important to generate an optimization remark for each loop. Most of
1330 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1331 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1332 // less verbose reporting vectorized loops and unvectorized loops that may
1333 // benefit from vectorization, respectively.
1335 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1336 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1337 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1338 L->getStartLoc(), Hints.emitRemark());
1342 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1343 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1344 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1345 L->getStartLoc(), Hints.emitRemark());
1349 if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
1350 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1351 emitOptimizationRemarkAnalysis(
1352 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1353 "loop not vectorized: vector width and interleave count are "
1354 "explicitly set to 1");
1358 // Check the loop for a trip count threshold:
1359 // do not vectorize loops with a tiny trip count.
1360 const unsigned TC = SE->getSmallConstantTripCount(L);
1361 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1362 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1363 << "This loop is not worth vectorizing.");
1364 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1365 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1367 DEBUG(dbgs() << "\n");
1368 emitOptimizationRemarkAnalysis(
1369 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1370 "vectorization is not beneficial and is not explicitly forced");
1375 // Check if it is legal to vectorize the loop.
1376 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI, AA, F);
1377 if (!LVL.canVectorize()) {
1378 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1379 emitMissedWarning(F, L, Hints);
1383 // Use the cost model.
1384 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI, AT, F,
1387 // Check the function attributes to find out if this function should be
1388 // optimized for size.
1389 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1390 F->hasFnAttribute(Attribute::OptimizeForSize);
1392 // Compute the weighted frequency of this loop being executed and see if it
1393 // is less than 20% of the function entry baseline frequency. Note that we
1394 // always have a canonical loop here because we think we *can* vectoriez.
1395 // FIXME: This is hidden behind a flag due to pervasive problems with
1396 // exactly what block frequency models.
1397 if (LoopVectorizeWithBlockFrequency) {
1398 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1399 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1400 LoopEntryFreq < ColdEntryFreq)
1404 // Check the function attributes to see if implicit floats are allowed.a
1405 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1406 // an integer loop and the vector instructions selected are purely integer
1407 // vector instructions?
1408 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1409 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1410 "attribute is used.\n");
1411 emitOptimizationRemarkAnalysis(
1412 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1413 "loop not vectorized due to NoImplicitFloat attribute");
1414 emitMissedWarning(F, L, Hints);
1418 // Select the optimal vectorization factor.
1419 const LoopVectorizationCostModel::VectorizationFactor VF =
1420 CM.selectVectorizationFactor(OptForSize);
1422 // Select the unroll factor.
1424 CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
1426 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1427 << DebugLocStr << '\n');
1428 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1430 if (VF.Width == 1) {
1431 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
1434 emitOptimizationRemarkAnalysis(
1435 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1436 "not beneficial to vectorize and user disabled interleaving");
1439 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1441 // Report the unrolling decision.
1442 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1443 Twine("unrolled with interleaving factor " +
1445 " (vectorization not beneficial)"));
1447 // We decided not to vectorize, but we may want to unroll.
1449 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1450 Unroller.vectorize(&LVL);
1452 // If we decided that it is *legal* to vectorize the loop then do it.
1453 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1457 // Report the vectorization decision.
1458 emitOptimizationRemark(
1459 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1460 Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1461 ", unrolling interleave factor: " + Twine(UF) + ")");
1464 // Mark the loop as already vectorized to avoid vectorizing again.
1465 Hints.setAlreadyVectorized();
1467 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1471 void getAnalysisUsage(AnalysisUsage &AU) const override {
1472 AU.addRequired<AssumptionTracker>();
1473 AU.addRequiredID(LoopSimplifyID);
1474 AU.addRequiredID(LCSSAID);
1475 AU.addRequired<BlockFrequencyInfo>();
1476 AU.addRequired<DominatorTreeWrapperPass>();
1477 AU.addRequired<LoopInfo>();
1478 AU.addRequired<ScalarEvolution>();
1479 AU.addRequired<TargetTransformInfo>();
1480 AU.addRequired<AliasAnalysis>();
1481 AU.addPreserved<LoopInfo>();
1482 AU.addPreserved<DominatorTreeWrapperPass>();
1483 AU.addPreserved<AliasAnalysis>();
1488 } // end anonymous namespace
1490 //===----------------------------------------------------------------------===//
1491 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1492 // LoopVectorizationCostModel.
1493 //===----------------------------------------------------------------------===//
1495 static Value *stripIntegerCast(Value *V) {
1496 if (CastInst *CI = dyn_cast<CastInst>(V))
1497 if (CI->getOperand(0)->getType()->isIntegerTy())
1498 return CI->getOperand(0);
1502 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1504 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1506 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1507 ValueToValueMap &PtrToStride,
1508 Value *Ptr, Value *OrigPtr = nullptr) {
1510 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1512 // If there is an entry in the map return the SCEV of the pointer with the
1513 // symbolic stride replaced by one.
1514 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1515 if (SI != PtrToStride.end()) {
1516 Value *StrideVal = SI->second;
1519 StrideVal = stripIntegerCast(StrideVal);
1521 // Replace symbolic stride by one.
1522 Value *One = ConstantInt::get(StrideVal->getType(), 1);
1523 ValueToValueMap RewriteMap;
1524 RewriteMap[StrideVal] = One;
1527 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1528 DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1533 // Otherwise, just return the SCEV of the original pointer.
1534 return SE->getSCEV(Ptr);
1537 void LoopVectorizationLegality::RuntimePointerCheck::insert(
1538 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
1539 unsigned ASId, ValueToValueMap &Strides) {
1540 // Get the stride replaced scev.
1541 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1542 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1543 assert(AR && "Invalid addrec expression");
1544 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1545 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1546 Pointers.push_back(Ptr);
1547 Starts.push_back(AR->getStart());
1548 Ends.push_back(ScEnd);
1549 IsWritePtr.push_back(WritePtr);
1550 DependencySetId.push_back(DepSetId);
1551 AliasSetId.push_back(ASId);
1554 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1555 // We need to place the broadcast of invariant variables outside the loop.
1556 Instruction *Instr = dyn_cast<Instruction>(V);
1558 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1559 Instr->getParent()) != LoopVectorBody.end());
1560 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1562 // Place the code for broadcasting invariant variables in the new preheader.
1563 IRBuilder<>::InsertPointGuard Guard(Builder);
1565 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1567 // Broadcast the scalar into all locations in the vector.
1568 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1573 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1575 assert(Val->getType()->isVectorTy() && "Must be a vector");
1576 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1577 "Elem must be an integer");
1578 // Create the types.
1579 Type *ITy = Val->getType()->getScalarType();
1580 VectorType *Ty = cast<VectorType>(Val->getType());
1581 int VLen = Ty->getNumElements();
1582 SmallVector<Constant*, 8> Indices;
1584 // Create a vector of consecutive numbers from zero to VF.
1585 for (int i = 0; i < VLen; ++i) {
1586 int64_t Idx = Negate ? (-i) : i;
1587 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1590 // Add the consecutive indices to the vector value.
1591 Constant *Cv = ConstantVector::get(Indices);
1592 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1593 return Builder.CreateAdd(Val, Cv, "induction");
1596 /// \brief Find the operand of the GEP that should be checked for consecutive
1597 /// stores. This ignores trailing indices that have no effect on the final
1599 static unsigned getGEPInductionOperand(const DataLayout *DL,
1600 const GetElementPtrInst *Gep) {
1601 unsigned LastOperand = Gep->getNumOperands() - 1;
1602 unsigned GEPAllocSize = DL->getTypeAllocSize(
1603 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1605 // Walk backwards and try to peel off zeros.
1606 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1607 // Find the type we're currently indexing into.
1608 gep_type_iterator GEPTI = gep_type_begin(Gep);
1609 std::advance(GEPTI, LastOperand - 1);
1611 // If it's a type with the same allocation size as the result of the GEP we
1612 // can peel off the zero index.
1613 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1621 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1622 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1623 // Make sure that the pointer does not point to structs.
1624 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1627 // If this value is a pointer induction variable we know it is consecutive.
1628 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1629 if (Phi && Inductions.count(Phi)) {
1630 InductionInfo II = Inductions[Phi];
1631 if (IK_PtrInduction == II.IK)
1633 else if (IK_ReversePtrInduction == II.IK)
1637 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1641 unsigned NumOperands = Gep->getNumOperands();
1642 Value *GpPtr = Gep->getPointerOperand();
1643 // If this GEP value is a consecutive pointer induction variable and all of
1644 // the indices are constant then we know it is consecutive. We can
1645 Phi = dyn_cast<PHINode>(GpPtr);
1646 if (Phi && Inductions.count(Phi)) {
1648 // Make sure that the pointer does not point to structs.
1649 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1650 if (GepPtrType->getElementType()->isAggregateType())
1653 // Make sure that all of the index operands are loop invariant.
1654 for (unsigned i = 1; i < NumOperands; ++i)
1655 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1658 InductionInfo II = Inductions[Phi];
1659 if (IK_PtrInduction == II.IK)
1661 else if (IK_ReversePtrInduction == II.IK)
1665 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1667 // Check that all of the gep indices are uniform except for our induction
1669 for (unsigned i = 0; i != NumOperands; ++i)
1670 if (i != InductionOperand &&
1671 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1674 // We can emit wide load/stores only if the last non-zero index is the
1675 // induction variable.
1676 const SCEV *Last = nullptr;
1677 if (!Strides.count(Gep))
1678 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1680 // Because of the multiplication by a stride we can have a s/zext cast.
1681 // We are going to replace this stride by 1 so the cast is safe to ignore.
1683 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1684 // %0 = trunc i64 %indvars.iv to i32
1685 // %mul = mul i32 %0, %Stride1
1686 // %idxprom = zext i32 %mul to i64 << Safe cast.
1687 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1689 Last = replaceSymbolicStrideSCEV(SE, Strides,
1690 Gep->getOperand(InductionOperand), Gep);
1691 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1693 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1697 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1698 const SCEV *Step = AR->getStepRecurrence(*SE);
1700 // The memory is consecutive because the last index is consecutive
1701 // and all other indices are loop invariant.
1704 if (Step->isAllOnesValue())
1711 bool LoopVectorizationLegality::isUniform(Value *V) {
1712 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1715 InnerLoopVectorizer::VectorParts&
1716 InnerLoopVectorizer::getVectorValue(Value *V) {
1717 assert(V != Induction && "The new induction variable should not be used.");
1718 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1720 // If we have a stride that is replaced by one, do it here.
1721 if (Legal->hasStride(V))
1722 V = ConstantInt::get(V->getType(), 1);
1724 // If we have this scalar in the map, return it.
1725 if (WidenMap.has(V))
1726 return WidenMap.get(V);
1728 // If this scalar is unknown, assume that it is a constant or that it is
1729 // loop invariant. Broadcast V and save the value for future uses.
1730 Value *B = getBroadcastInstrs(V);
1731 return WidenMap.splat(V, B);
1734 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1735 assert(Vec->getType()->isVectorTy() && "Invalid type");
1736 SmallVector<Constant*, 8> ShuffleMask;
1737 for (unsigned i = 0; i < VF; ++i)
1738 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1740 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1741 ConstantVector::get(ShuffleMask),
1745 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1746 // Attempt to issue a wide load.
1747 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1748 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1750 assert((LI || SI) && "Invalid Load/Store instruction");
1752 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1753 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1754 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1755 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1756 // An alignment of 0 means target abi alignment. We need to use the scalar's
1757 // target abi alignment in such a case.
1759 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1760 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1761 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1762 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1764 if (SI && Legal->blockNeedsPredication(SI->getParent()))
1765 return scalarizeInstruction(Instr, true);
1767 if (ScalarAllocatedSize != VectorElementSize)
1768 return scalarizeInstruction(Instr);
1770 // If the pointer is loop invariant or if it is non-consecutive,
1771 // scalarize the load.
1772 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1773 bool Reverse = ConsecutiveStride < 0;
1774 bool UniformLoad = LI && Legal->isUniform(Ptr);
1775 if (!ConsecutiveStride || UniformLoad)
1776 return scalarizeInstruction(Instr);
1778 Constant *Zero = Builder.getInt32(0);
1779 VectorParts &Entry = WidenMap.get(Instr);
1781 // Handle consecutive loads/stores.
1782 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1783 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1784 setDebugLocFromInst(Builder, Gep);
1785 Value *PtrOperand = Gep->getPointerOperand();
1786 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1787 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1789 // Create the new GEP with the new induction variable.
1790 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1791 Gep2->setOperand(0, FirstBasePtr);
1792 Gep2->setName("gep.indvar.base");
1793 Ptr = Builder.Insert(Gep2);
1795 setDebugLocFromInst(Builder, Gep);
1796 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1797 OrigLoop) && "Base ptr must be invariant");
1799 // The last index does not have to be the induction. It can be
1800 // consecutive and be a function of the index. For example A[I+1];
1801 unsigned NumOperands = Gep->getNumOperands();
1802 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1803 // Create the new GEP with the new induction variable.
1804 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1806 for (unsigned i = 0; i < NumOperands; ++i) {
1807 Value *GepOperand = Gep->getOperand(i);
1808 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1810 // Update last index or loop invariant instruction anchored in loop.
1811 if (i == InductionOperand ||
1812 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1813 assert((i == InductionOperand ||
1814 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1815 "Must be last index or loop invariant");
1817 VectorParts &GEPParts = getVectorValue(GepOperand);
1818 Value *Index = GEPParts[0];
1819 Index = Builder.CreateExtractElement(Index, Zero);
1820 Gep2->setOperand(i, Index);
1821 Gep2->setName("gep.indvar.idx");
1824 Ptr = Builder.Insert(Gep2);
1826 // Use the induction element ptr.
1827 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1828 setDebugLocFromInst(Builder, Ptr);
1829 VectorParts &PtrVal = getVectorValue(Ptr);
1830 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1835 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1836 "We do not allow storing to uniform addresses");
1837 setDebugLocFromInst(Builder, SI);
1838 // We don't want to update the value in the map as it might be used in
1839 // another expression. So don't use a reference type for "StoredVal".
1840 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1842 for (unsigned Part = 0; Part < UF; ++Part) {
1843 // Calculate the pointer for the specific unroll-part.
1844 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1847 // If we store to reverse consecutive memory locations then we need
1848 // to reverse the order of elements in the stored value.
1849 StoredVal[Part] = reverseVector(StoredVal[Part]);
1850 // If the address is consecutive but reversed, then the
1851 // wide store needs to start at the last vector element.
1852 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1853 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1856 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1857 DataTy->getPointerTo(AddressSpace));
1859 Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
1860 propagateMetadata(NewSI, SI);
1866 assert(LI && "Must have a load instruction");
1867 setDebugLocFromInst(Builder, LI);
1868 for (unsigned Part = 0; Part < UF; ++Part) {
1869 // Calculate the pointer for the specific unroll-part.
1870 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1873 // If the address is consecutive but reversed, then the
1874 // wide store needs to start at the last vector element.
1875 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1876 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1879 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1880 DataTy->getPointerTo(AddressSpace));
1881 LoadInst *NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
1882 propagateMetadata(NewLI, LI);
1883 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
1887 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1888 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1889 // Holds vector parameters or scalars, in case of uniform vals.
1890 SmallVector<VectorParts, 4> Params;
1892 setDebugLocFromInst(Builder, Instr);
1894 // Find all of the vectorized parameters.
1895 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1896 Value *SrcOp = Instr->getOperand(op);
1898 // If we are accessing the old induction variable, use the new one.
1899 if (SrcOp == OldInduction) {
1900 Params.push_back(getVectorValue(SrcOp));
1904 // Try using previously calculated values.
1905 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1907 // If the src is an instruction that appeared earlier in the basic block
1908 // then it should already be vectorized.
1909 if (SrcInst && OrigLoop->contains(SrcInst)) {
1910 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1911 // The parameter is a vector value from earlier.
1912 Params.push_back(WidenMap.get(SrcInst));
1914 // The parameter is a scalar from outside the loop. Maybe even a constant.
1915 VectorParts Scalars;
1916 Scalars.append(UF, SrcOp);
1917 Params.push_back(Scalars);
1921 assert(Params.size() == Instr->getNumOperands() &&
1922 "Invalid number of operands");
1924 // Does this instruction return a value ?
1925 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1927 Value *UndefVec = IsVoidRetTy ? nullptr :
1928 UndefValue::get(VectorType::get(Instr->getType(), VF));
1929 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1930 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1932 Instruction *InsertPt = Builder.GetInsertPoint();
1933 BasicBlock *IfBlock = Builder.GetInsertBlock();
1934 BasicBlock *CondBlock = nullptr;
1937 Loop *VectorLp = nullptr;
1938 if (IfPredicateStore) {
1939 assert(Instr->getParent()->getSinglePredecessor() &&
1940 "Only support single predecessor blocks");
1941 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1942 Instr->getParent());
1943 VectorLp = LI->getLoopFor(IfBlock);
1944 assert(VectorLp && "Must have a loop for this block");
1947 // For each vector unroll 'part':
1948 for (unsigned Part = 0; Part < UF; ++Part) {
1949 // For each scalar that we create:
1950 for (unsigned Width = 0; Width < VF; ++Width) {
1953 Value *Cmp = nullptr;
1954 if (IfPredicateStore) {
1955 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1956 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1957 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1958 LoopVectorBody.push_back(CondBlock);
1959 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
1960 // Update Builder with newly created basic block.
1961 Builder.SetInsertPoint(InsertPt);
1964 Instruction *Cloned = Instr->clone();
1966 Cloned->setName(Instr->getName() + ".cloned");
1967 // Replace the operands of the cloned instructions with extracted scalars.
1968 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1969 Value *Op = Params[op][Part];
1970 // Param is a vector. Need to extract the right lane.
1971 if (Op->getType()->isVectorTy())
1972 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1973 Cloned->setOperand(op, Op);
1976 // Place the cloned scalar in the new loop.
1977 Builder.Insert(Cloned);
1979 // If the original scalar returns a value we need to place it in a vector
1980 // so that future users will be able to use it.
1982 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1983 Builder.getInt32(Width));
1985 if (IfPredicateStore) {
1986 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1987 LoopVectorBody.push_back(NewIfBlock);
1988 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
1989 Builder.SetInsertPoint(InsertPt);
1990 Instruction *OldBr = IfBlock->getTerminator();
1991 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1992 OldBr->eraseFromParent();
1993 IfBlock = NewIfBlock;
1999 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2003 if (Instruction *I = dyn_cast<Instruction>(V))
2004 return I->getParent() == Loc->getParent() ? I : nullptr;
2008 std::pair<Instruction *, Instruction *>
2009 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
2010 Instruction *tnullptr = nullptr;
2011 if (!Legal->mustCheckStrides())
2012 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2014 IRBuilder<> ChkBuilder(Loc);
2017 Value *Check = nullptr;
2018 Instruction *FirstInst = nullptr;
2019 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
2020 SE = Legal->strides_end();
2022 Value *Ptr = stripIntegerCast(*SI);
2023 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2025 // Store the first instruction we create.
2026 FirstInst = getFirstInst(FirstInst, C, Loc);
2028 Check = ChkBuilder.CreateOr(Check, C);
2033 // We have to do this trickery because the IRBuilder might fold the check to a
2034 // constant expression in which case there is no Instruction anchored in a
2036 LLVMContext &Ctx = Loc->getContext();
2037 Instruction *TheCheck =
2038 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2039 ChkBuilder.Insert(TheCheck, "stride.not.one");
2040 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2042 return std::make_pair(FirstInst, TheCheck);
2045 std::pair<Instruction *, Instruction *>
2046 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
2047 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
2048 Legal->getRuntimePointerCheck();
2050 Instruction *tnullptr = nullptr;
2051 if (!PtrRtCheck->Need)
2052 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2054 unsigned NumPointers = PtrRtCheck->Pointers.size();
2055 SmallVector<TrackingVH<Value> , 2> Starts;
2056 SmallVector<TrackingVH<Value> , 2> Ends;
2058 LLVMContext &Ctx = Loc->getContext();
2059 SCEVExpander Exp(*SE, "induction");
2060 Instruction *FirstInst = nullptr;
2062 for (unsigned i = 0; i < NumPointers; ++i) {
2063 Value *Ptr = PtrRtCheck->Pointers[i];
2064 const SCEV *Sc = SE->getSCEV(Ptr);
2066 if (SE->isLoopInvariant(Sc, OrigLoop)) {
2067 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
2069 Starts.push_back(Ptr);
2070 Ends.push_back(Ptr);
2072 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
2073 unsigned AS = Ptr->getType()->getPointerAddressSpace();
2075 // Use this type for pointer arithmetic.
2076 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
2078 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
2079 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
2080 Starts.push_back(Start);
2081 Ends.push_back(End);
2085 IRBuilder<> ChkBuilder(Loc);
2086 // Our instructions might fold to a constant.
2087 Value *MemoryRuntimeCheck = nullptr;
2088 for (unsigned i = 0; i < NumPointers; ++i) {
2089 for (unsigned j = i+1; j < NumPointers; ++j) {
2090 // No need to check if two readonly pointers intersect.
2091 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
2094 // Only need to check pointers between two different dependency sets.
2095 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
2097 // Only need to check pointers in the same alias set.
2098 if (PtrRtCheck->AliasSetId[i] != PtrRtCheck->AliasSetId[j])
2101 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
2102 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
2104 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
2105 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
2106 "Trying to bounds check pointers with different address spaces");
2108 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
2109 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
2111 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
2112 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
2113 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
2114 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
2116 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
2117 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
2118 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
2119 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
2120 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
2121 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2122 if (MemoryRuntimeCheck) {
2123 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
2125 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2127 MemoryRuntimeCheck = IsConflict;
2131 // We have to do this trickery because the IRBuilder might fold the check to a
2132 // constant expression in which case there is no Instruction anchored in a
2134 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
2135 ConstantInt::getTrue(Ctx));
2136 ChkBuilder.Insert(Check, "memcheck.conflict");
2137 FirstInst = getFirstInst(FirstInst, Check, Loc);
2138 return std::make_pair(FirstInst, Check);
2141 void InnerLoopVectorizer::createEmptyLoop() {
2143 In this function we generate a new loop. The new loop will contain
2144 the vectorized instructions while the old loop will continue to run the
2147 [ ] <-- Back-edge taken count overflow check.
2150 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2153 || [ ] <-- vector pre header.
2157 || [ ]_| <-- vector loop.
2160 | >[ ] <--- middle-block.
2163 -|- >[ ] <--- new preheader.
2167 | [ ]_| <-- old scalar loop to handle remainder.
2170 >[ ] <-- exit block.
2174 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2175 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
2176 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2177 assert(BypassBlock && "Invalid loop structure");
2178 assert(ExitBlock && "Must have an exit block");
2180 // Some loops have a single integer induction variable, while other loops
2181 // don't. One example is c++ iterators that often have multiple pointer
2182 // induction variables. In the code below we also support a case where we
2183 // don't have a single induction variable.
2184 OldInduction = Legal->getInduction();
2185 Type *IdxTy = Legal->getWidestInductionType();
2187 // Find the loop boundaries.
2188 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2189 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2191 // The exit count might have the type of i64 while the phi is i32. This can
2192 // happen if we have an induction variable that is sign extended before the
2193 // compare. The only way that we get a backedge taken count is that the
2194 // induction variable was signed and as such will not overflow. In such a case
2195 // truncation is legal.
2196 if (ExitCount->getType()->getPrimitiveSizeInBits() >
2197 IdxTy->getPrimitiveSizeInBits())
2198 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2200 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2201 // Get the total trip count from the count by adding 1.
2202 ExitCount = SE->getAddExpr(BackedgeTakeCount,
2203 SE->getConstant(BackedgeTakeCount->getType(), 1));
2205 // Expand the trip count and place the new instructions in the preheader.
2206 // Notice that the pre-header does not change, only the loop body.
2207 SCEVExpander Exp(*SE, "induction");
2209 // We need to test whether the backedge-taken count is uint##_max. Adding one
2210 // to it will cause overflow and an incorrect loop trip count in the vector
2211 // body. In case of overflow we want to directly jump to the scalar remainder
2213 Value *BackedgeCount =
2214 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2215 BypassBlock->getTerminator());
2216 if (BackedgeCount->getType()->isPointerTy())
2217 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2218 "backedge.ptrcnt.to.int",
2219 BypassBlock->getTerminator());
2220 Instruction *CheckBCOverflow =
2221 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2222 Constant::getAllOnesValue(BackedgeCount->getType()),
2223 "backedge.overflow", BypassBlock->getTerminator());
2225 // The loop index does not have to start at Zero. Find the original start
2226 // value from the induction PHI node. If we don't have an induction variable
2227 // then we know that it starts at zero.
2228 Builder.SetInsertPoint(BypassBlock->getTerminator());
2229 Value *StartIdx = ExtendedIdx = OldInduction ?
2230 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2232 ConstantInt::get(IdxTy, 0);
2234 // We need an instruction to anchor the overflow check on. StartIdx needs to
2235 // be defined before the overflow check branch. Because the scalar preheader
2236 // is going to merge the start index and so the overflow branch block needs to
2237 // contain a definition of the start index.
2238 Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
2239 StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
2240 BypassBlock->getTerminator());
2242 // Count holds the overall loop count (N).
2243 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2244 BypassBlock->getTerminator());
2246 LoopBypassBlocks.push_back(BypassBlock);
2248 // Split the single block loop into the two loop structure described above.
2249 BasicBlock *VectorPH =
2250 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2251 BasicBlock *VecBody =
2252 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2253 BasicBlock *MiddleBlock =
2254 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2255 BasicBlock *ScalarPH =
2256 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2258 // Create and register the new vector loop.
2259 Loop* Lp = new Loop();
2260 Loop *ParentLoop = OrigLoop->getParentLoop();
2262 // Insert the new loop into the loop nest and register the new basic blocks
2263 // before calling any utilities such as SCEV that require valid LoopInfo.
2265 ParentLoop->addChildLoop(Lp);
2266 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
2267 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
2268 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
2270 LI->addTopLevelLoop(Lp);
2272 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
2274 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2276 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2278 // Generate the induction variable.
2279 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2280 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2281 // The loop step is equal to the vectorization factor (num of SIMD elements)
2282 // times the unroll factor (num of SIMD instructions).
2283 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2285 // This is the IR builder that we use to add all of the logic for bypassing
2286 // the new vector loop.
2287 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2288 setDebugLocFromInst(BypassBuilder,
2289 getDebugLocFromInstOrOperands(OldInduction));
2291 // We may need to extend the index in case there is a type mismatch.
2292 // We know that the count starts at zero and does not overflow.
2293 if (Count->getType() != IdxTy) {
2294 // The exit count can be of pointer type. Convert it to the correct
2296 if (ExitCount->getType()->isPointerTy())
2297 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2299 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2302 // Add the start index to the loop count to get the new end index.
2303 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2305 // Now we need to generate the expression for N - (N % VF), which is
2306 // the part that the vectorized body will execute.
2307 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2308 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2309 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2310 "end.idx.rnd.down");
2312 // Now, compare the new count to zero. If it is zero skip the vector loop and
2313 // jump to the scalar loop.
2315 BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2317 BasicBlock *LastBypassBlock = BypassBlock;
2319 // Generate code to check that the loops trip count that we computed by adding
2320 // one to the backedge-taken count will not overflow.
2322 auto PastOverflowCheck =
2323 std::next(BasicBlock::iterator(OverflowCheckAnchor));
2324 BasicBlock *CheckBlock =
2325 LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2327 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2328 LoopBypassBlocks.push_back(CheckBlock);
2329 Instruction *OldTerm = LastBypassBlock->getTerminator();
2330 BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2331 OldTerm->eraseFromParent();
2332 LastBypassBlock = CheckBlock;
2335 // Generate the code to check that the strides we assumed to be one are really
2336 // one. We want the new basic block to start at the first instruction in a
2337 // sequence of instructions that form a check.
2338 Instruction *StrideCheck;
2339 Instruction *FirstCheckInst;
2340 std::tie(FirstCheckInst, StrideCheck) =
2341 addStrideCheck(LastBypassBlock->getTerminator());
2343 // Create a new block containing the stride check.
2344 BasicBlock *CheckBlock =
2345 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2347 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2348 LoopBypassBlocks.push_back(CheckBlock);
2350 // Replace the branch into the memory check block with a conditional branch
2351 // for the "few elements case".
2352 Instruction *OldTerm = LastBypassBlock->getTerminator();
2353 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2354 OldTerm->eraseFromParent();
2357 LastBypassBlock = CheckBlock;
2360 // Generate the code that checks in runtime if arrays overlap. We put the
2361 // checks into a separate block to make the more common case of few elements
2363 Instruction *MemRuntimeCheck;
2364 std::tie(FirstCheckInst, MemRuntimeCheck) =
2365 addRuntimeCheck(LastBypassBlock->getTerminator());
2366 if (MemRuntimeCheck) {
2367 // Create a new block containing the memory check.
2368 BasicBlock *CheckBlock =
2369 LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
2371 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
2372 LoopBypassBlocks.push_back(CheckBlock);
2374 // Replace the branch into the memory check block with a conditional branch
2375 // for the "few elements case".
2376 Instruction *OldTerm = LastBypassBlock->getTerminator();
2377 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2378 OldTerm->eraseFromParent();
2380 Cmp = MemRuntimeCheck;
2381 LastBypassBlock = CheckBlock;
2384 LastBypassBlock->getTerminator()->eraseFromParent();
2385 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2388 // We are going to resume the execution of the scalar loop.
2389 // Go over all of the induction variables that we found and fix the
2390 // PHIs that are left in the scalar version of the loop.
2391 // The starting values of PHI nodes depend on the counter of the last
2392 // iteration in the vectorized loop.
2393 // If we come from a bypass edge then we need to start from the original
2396 // This variable saves the new starting index for the scalar loop.
2397 PHINode *ResumeIndex = nullptr;
2398 LoopVectorizationLegality::InductionList::iterator I, E;
2399 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2400 // Set builder to point to last bypass block.
2401 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2402 for (I = List->begin(), E = List->end(); I != E; ++I) {
2403 PHINode *OrigPhi = I->first;
2404 LoopVectorizationLegality::InductionInfo II = I->second;
2406 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2407 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2408 MiddleBlock->getTerminator());
2409 // We might have extended the type of the induction variable but we need a
2410 // truncated version for the scalar loop.
2411 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2412 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2413 MiddleBlock->getTerminator()) : nullptr;
2415 // Create phi nodes to merge from the backedge-taken check block.
2416 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2417 ScalarPH->getTerminator());
2418 BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2420 PHINode *BCTruncResumeVal = nullptr;
2421 if (OrigPhi == OldInduction) {
2423 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2424 ScalarPH->getTerminator());
2425 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2428 Value *EndValue = nullptr;
2430 case LoopVectorizationLegality::IK_NoInduction:
2431 llvm_unreachable("Unknown induction");
2432 case LoopVectorizationLegality::IK_IntInduction: {
2433 // Handle the integer induction counter.
2434 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2436 // We have the canonical induction variable.
2437 if (OrigPhi == OldInduction) {
2438 // Create a truncated version of the resume value for the scalar loop,
2439 // we might have promoted the type to a larger width.
2441 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2442 // The new PHI merges the original incoming value, in case of a bypass,
2443 // or the value at the end of the vectorized loop.
2444 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2445 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2446 TruncResumeVal->addIncoming(EndValue, VecBody);
2448 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2450 // We know what the end value is.
2451 EndValue = IdxEndRoundDown;
2452 // We also know which PHI node holds it.
2453 ResumeIndex = ResumeVal;
2457 // Not the canonical induction variable - add the vector loop count to the
2459 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2460 II.StartValue->getType(),
2462 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
2465 case LoopVectorizationLegality::IK_ReverseIntInduction: {
2466 // Convert the CountRoundDown variable to the PHI size.
2467 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2468 II.StartValue->getType(),
2470 // Handle reverse integer induction counter.
2471 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
2474 case LoopVectorizationLegality::IK_PtrInduction: {
2475 // For pointer induction variables, calculate the offset using
2477 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2481 case LoopVectorizationLegality::IK_ReversePtrInduction: {
2482 // The value at the end of the loop for the reverse pointer is calculated
2483 // by creating a GEP with a negative index starting from the start value.
2484 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2485 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2487 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2493 // The new PHI merges the original incoming value, in case of a bypass,
2494 // or the value at the end of the vectorized loop.
2495 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2496 if (OrigPhi == OldInduction)
2497 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2499 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2501 ResumeVal->addIncoming(EndValue, VecBody);
2503 // Fix the scalar body counter (PHI node).
2504 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2506 // The old induction's phi node in the scalar body needs the truncated
2508 if (OrigPhi == OldInduction) {
2509 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2510 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2512 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2513 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2517 // If we are generating a new induction variable then we also need to
2518 // generate the code that calculates the exit value. This value is not
2519 // simply the end of the counter because we may skip the vectorized body
2520 // in case of a runtime check.
2522 assert(!ResumeIndex && "Unexpected resume value found");
2523 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2524 MiddleBlock->getTerminator());
2525 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2526 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2527 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2530 // Make sure that we found the index where scalar loop needs to continue.
2531 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2532 "Invalid resume Index");
2534 // Add a check in the middle block to see if we have completed
2535 // all of the iterations in the first vector loop.
2536 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2537 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2538 ResumeIndex, "cmp.n",
2539 MiddleBlock->getTerminator());
2541 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2542 // Remove the old terminator.
2543 MiddleBlock->getTerminator()->eraseFromParent();
2545 // Create i+1 and fill the PHINode.
2546 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2547 Induction->addIncoming(StartIdx, VectorPH);
2548 Induction->addIncoming(NextIdx, VecBody);
2549 // Create the compare.
2550 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2551 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2553 // Now we have two terminators. Remove the old one from the block.
2554 VecBody->getTerminator()->eraseFromParent();
2556 // Get ready to start creating new instructions into the vectorized body.
2557 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2560 LoopVectorPreHeader = VectorPH;
2561 LoopScalarPreHeader = ScalarPH;
2562 LoopMiddleBlock = MiddleBlock;
2563 LoopExitBlock = ExitBlock;
2564 LoopVectorBody.push_back(VecBody);
2565 LoopScalarBody = OldBasicBlock;
2567 LoopVectorizeHints Hints(Lp, true);
2568 Hints.setAlreadyVectorized();
2571 /// This function returns the identity element (or neutral element) for
2572 /// the operation K.
2574 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2579 // Adding, Xoring, Oring zero to a number does not change it.
2580 return ConstantInt::get(Tp, 0);
2581 case RK_IntegerMult:
2582 // Multiplying a number by 1 does not change it.
2583 return ConstantInt::get(Tp, 1);
2585 // AND-ing a number with an all-1 value does not change it.
2586 return ConstantInt::get(Tp, -1, true);
2588 // Multiplying a number by 1 does not change it.
2589 return ConstantFP::get(Tp, 1.0L);
2591 // Adding zero to a number does not change it.
2592 return ConstantFP::get(Tp, 0.0L);
2594 llvm_unreachable("Unknown reduction kind");
2598 /// This function translates the reduction kind to an LLVM binary operator.
2600 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2602 case LoopVectorizationLegality::RK_IntegerAdd:
2603 return Instruction::Add;
2604 case LoopVectorizationLegality::RK_IntegerMult:
2605 return Instruction::Mul;
2606 case LoopVectorizationLegality::RK_IntegerOr:
2607 return Instruction::Or;
2608 case LoopVectorizationLegality::RK_IntegerAnd:
2609 return Instruction::And;
2610 case LoopVectorizationLegality::RK_IntegerXor:
2611 return Instruction::Xor;
2612 case LoopVectorizationLegality::RK_FloatMult:
2613 return Instruction::FMul;
2614 case LoopVectorizationLegality::RK_FloatAdd:
2615 return Instruction::FAdd;
2616 case LoopVectorizationLegality::RK_IntegerMinMax:
2617 return Instruction::ICmp;
2618 case LoopVectorizationLegality::RK_FloatMinMax:
2619 return Instruction::FCmp;
2621 llvm_unreachable("Unknown reduction operation");
2625 Value *createMinMaxOp(IRBuilder<> &Builder,
2626 LoopVectorizationLegality::MinMaxReductionKind RK,
2629 CmpInst::Predicate P = CmpInst::ICMP_NE;
2632 llvm_unreachable("Unknown min/max reduction kind");
2633 case LoopVectorizationLegality::MRK_UIntMin:
2634 P = CmpInst::ICMP_ULT;
2636 case LoopVectorizationLegality::MRK_UIntMax:
2637 P = CmpInst::ICMP_UGT;
2639 case LoopVectorizationLegality::MRK_SIntMin:
2640 P = CmpInst::ICMP_SLT;
2642 case LoopVectorizationLegality::MRK_SIntMax:
2643 P = CmpInst::ICMP_SGT;
2645 case LoopVectorizationLegality::MRK_FloatMin:
2646 P = CmpInst::FCMP_OLT;
2648 case LoopVectorizationLegality::MRK_FloatMax:
2649 P = CmpInst::FCMP_OGT;
2654 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2655 RK == LoopVectorizationLegality::MRK_FloatMax)
2656 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2658 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2660 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2665 struct CSEDenseMapInfo {
2666 static bool canHandle(Instruction *I) {
2667 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2668 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2670 static inline Instruction *getEmptyKey() {
2671 return DenseMapInfo<Instruction *>::getEmptyKey();
2673 static inline Instruction *getTombstoneKey() {
2674 return DenseMapInfo<Instruction *>::getTombstoneKey();
2676 static unsigned getHashValue(Instruction *I) {
2677 assert(canHandle(I) && "Unknown instruction!");
2678 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2679 I->value_op_end()));
2681 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2682 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2683 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2685 return LHS->isIdenticalTo(RHS);
2690 /// \brief Check whether this block is a predicated block.
2691 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2692 /// = ...; " blocks. We start with one vectorized basic block. For every
2693 /// conditional block we split this vectorized block. Therefore, every second
2694 /// block will be a predicated one.
2695 static bool isPredicatedBlock(unsigned BlockNum) {
2696 return BlockNum % 2;
2699 ///\brief Perform cse of induction variable instructions.
2700 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2701 // Perform simple cse.
2702 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2703 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2704 BasicBlock *BB = BBs[i];
2705 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2706 Instruction *In = I++;
2708 if (!CSEDenseMapInfo::canHandle(In))
2711 // Check if we can replace this instruction with any of the
2712 // visited instructions.
2713 if (Instruction *V = CSEMap.lookup(In)) {
2714 In->replaceAllUsesWith(V);
2715 In->eraseFromParent();
2718 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2719 // ...;" blocks for predicated stores. Every second block is a predicated
2721 if (isPredicatedBlock(i))
2729 /// \brief Adds a 'fast' flag to floating point operations.
2730 static Value *addFastMathFlag(Value *V) {
2731 if (isa<FPMathOperator>(V)){
2732 FastMathFlags Flags;
2733 Flags.setUnsafeAlgebra();
2734 cast<Instruction>(V)->setFastMathFlags(Flags);
2739 void InnerLoopVectorizer::vectorizeLoop() {
2740 //===------------------------------------------------===//
2742 // Notice: any optimization or new instruction that go
2743 // into the code below should be also be implemented in
2746 //===------------------------------------------------===//
2747 Constant *Zero = Builder.getInt32(0);
2749 // In order to support reduction variables we need to be able to vectorize
2750 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2751 // stages. First, we create a new vector PHI node with no incoming edges.
2752 // We use this value when we vectorize all of the instructions that use the
2753 // PHI. Next, after all of the instructions in the block are complete we
2754 // add the new incoming edges to the PHI. At this point all of the
2755 // instructions in the basic block are vectorized, so we can use them to
2756 // construct the PHI.
2757 PhiVector RdxPHIsToFix;
2759 // Scan the loop in a topological order to ensure that defs are vectorized
2761 LoopBlocksDFS DFS(OrigLoop);
2764 // Vectorize all of the blocks in the original loop.
2765 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2766 be = DFS.endRPO(); bb != be; ++bb)
2767 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2769 // At this point every instruction in the original loop is widened to
2770 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2771 // that we vectorized. The PHI nodes are currently empty because we did
2772 // not want to introduce cycles. Notice that the remaining PHI nodes
2773 // that we need to fix are reduction variables.
2775 // Create the 'reduced' values for each of the induction vars.
2776 // The reduced values are the vector values that we scalarize and combine
2777 // after the loop is finished.
2778 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2780 PHINode *RdxPhi = *it;
2781 assert(RdxPhi && "Unable to recover vectorized PHI");
2783 // Find the reduction variable descriptor.
2784 assert(Legal->getReductionVars()->count(RdxPhi) &&
2785 "Unable to find the reduction variable");
2786 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2787 (*Legal->getReductionVars())[RdxPhi];
2789 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2791 // We need to generate a reduction vector from the incoming scalar.
2792 // To do so, we need to generate the 'identity' vector and override
2793 // one of the elements with the incoming scalar reduction. We need
2794 // to do it in the vector-loop preheader.
2795 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2797 // This is the vector-clone of the value that leaves the loop.
2798 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2799 Type *VecTy = VectorExit[0]->getType();
2801 // Find the reduction identity variable. Zero for addition, or, xor,
2802 // one for multiplication, -1 for And.
2805 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2806 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2807 // MinMax reduction have the start value as their identify.
2809 VectorStart = Identity = RdxDesc.StartValue;
2811 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2816 // Handle other reduction kinds:
2818 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2819 VecTy->getScalarType());
2822 // This vector is the Identity vector where the first element is the
2823 // incoming scalar reduction.
2824 VectorStart = RdxDesc.StartValue;
2826 Identity = ConstantVector::getSplat(VF, Iden);
2828 // This vector is the Identity vector where the first element is the
2829 // incoming scalar reduction.
2830 VectorStart = Builder.CreateInsertElement(Identity,
2831 RdxDesc.StartValue, Zero);
2835 // Fix the vector-loop phi.
2836 // We created the induction variable so we know that the
2837 // preheader is the first entry.
2838 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2840 // Reductions do not have to start at zero. They can start with
2841 // any loop invariant values.
2842 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2843 BasicBlock *Latch = OrigLoop->getLoopLatch();
2844 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2845 VectorParts &Val = getVectorValue(LoopVal);
2846 for (unsigned part = 0; part < UF; ++part) {
2847 // Make sure to add the reduction stat value only to the
2848 // first unroll part.
2849 Value *StartVal = (part == 0) ? VectorStart : Identity;
2850 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2851 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2852 LoopVectorBody.back());
2855 // Before each round, move the insertion point right between
2856 // the PHIs and the values we are going to write.
2857 // This allows us to write both PHINodes and the extractelement
2859 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2861 VectorParts RdxParts;
2862 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2863 for (unsigned part = 0; part < UF; ++part) {
2864 // This PHINode contains the vectorized reduction variable, or
2865 // the initial value vector, if we bypass the vector loop.
2866 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2867 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2868 Value *StartVal = (part == 0) ? VectorStart : Identity;
2869 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2870 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2871 NewPhi->addIncoming(RdxExitVal[part],
2872 LoopVectorBody.back());
2873 RdxParts.push_back(NewPhi);
2876 // Reduce all of the unrolled parts into a single vector.
2877 Value *ReducedPartRdx = RdxParts[0];
2878 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2879 setDebugLocFromInst(Builder, ReducedPartRdx);
2880 for (unsigned part = 1; part < UF; ++part) {
2881 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2882 // Floating point operations had to be 'fast' to enable the reduction.
2883 ReducedPartRdx = addFastMathFlag(
2884 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2885 ReducedPartRdx, "bin.rdx"));
2887 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2888 ReducedPartRdx, RdxParts[part]);
2892 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2893 // and vector ops, reducing the set of values being computed by half each
2895 assert(isPowerOf2_32(VF) &&
2896 "Reduction emission only supported for pow2 vectors!");
2897 Value *TmpVec = ReducedPartRdx;
2898 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2899 for (unsigned i = VF; i != 1; i >>= 1) {
2900 // Move the upper half of the vector to the lower half.
2901 for (unsigned j = 0; j != i/2; ++j)
2902 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2904 // Fill the rest of the mask with undef.
2905 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2906 UndefValue::get(Builder.getInt32Ty()));
2909 Builder.CreateShuffleVector(TmpVec,
2910 UndefValue::get(TmpVec->getType()),
2911 ConstantVector::get(ShuffleMask),
2914 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2915 // Floating point operations had to be 'fast' to enable the reduction.
2916 TmpVec = addFastMathFlag(Builder.CreateBinOp(
2917 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2919 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2922 // The result is in the first element of the vector.
2923 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2924 Builder.getInt32(0));
2927 // Create a phi node that merges control-flow from the backedge-taken check
2928 // block and the middle block.
2929 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2930 LoopScalarPreHeader->getTerminator());
2931 BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
2932 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2934 // Now, we need to fix the users of the reduction variable
2935 // inside and outside of the scalar remainder loop.
2936 // We know that the loop is in LCSSA form. We need to update the
2937 // PHI nodes in the exit blocks.
2938 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2939 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2940 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2941 if (!LCSSAPhi) break;
2943 // All PHINodes need to have a single entry edge, or two if
2944 // we already fixed them.
2945 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2947 // We found our reduction value exit-PHI. Update it with the
2948 // incoming bypass edge.
2949 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2950 // Add an edge coming from the bypass.
2951 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2954 }// end of the LCSSA phi scan.
2956 // Fix the scalar loop reduction variable with the incoming reduction sum
2957 // from the vector body and from the backedge value.
2958 int IncomingEdgeBlockIdx =
2959 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2960 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2961 // Pick the other block.
2962 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2963 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
2964 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2965 }// end of for each redux variable.
2969 // Remove redundant induction instructions.
2970 cse(LoopVectorBody);
2973 void InnerLoopVectorizer::fixLCSSAPHIs() {
2974 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2975 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2976 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2977 if (!LCSSAPhi) break;
2978 if (LCSSAPhi->getNumIncomingValues() == 1)
2979 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2984 InnerLoopVectorizer::VectorParts
2985 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2986 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2989 // Look for cached value.
2990 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2991 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2992 if (ECEntryIt != MaskCache.end())
2993 return ECEntryIt->second;
2995 VectorParts SrcMask = createBlockInMask(Src);
2997 // The terminator has to be a branch inst!
2998 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2999 assert(BI && "Unexpected terminator found");
3001 if (BI->isConditional()) {
3002 VectorParts EdgeMask = getVectorValue(BI->getCondition());
3004 if (BI->getSuccessor(0) != Dst)
3005 for (unsigned part = 0; part < UF; ++part)
3006 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3008 for (unsigned part = 0; part < UF; ++part)
3009 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3011 MaskCache[Edge] = EdgeMask;
3015 MaskCache[Edge] = SrcMask;
3019 InnerLoopVectorizer::VectorParts
3020 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3021 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3023 // Loop incoming mask is all-one.
3024 if (OrigLoop->getHeader() == BB) {
3025 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3026 return getVectorValue(C);
3029 // This is the block mask. We OR all incoming edges, and with zero.
3030 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3031 VectorParts BlockMask = getVectorValue(Zero);
3034 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3035 VectorParts EM = createEdgeMask(*it, BB);
3036 for (unsigned part = 0; part < UF; ++part)
3037 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3043 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3044 InnerLoopVectorizer::VectorParts &Entry,
3045 unsigned UF, unsigned VF, PhiVector *PV) {
3046 PHINode* P = cast<PHINode>(PN);
3047 // Handle reduction variables:
3048 if (Legal->getReductionVars()->count(P)) {
3049 for (unsigned part = 0; part < UF; ++part) {
3050 // This is phase one of vectorizing PHIs.
3051 Type *VecTy = (VF == 1) ? PN->getType() :
3052 VectorType::get(PN->getType(), VF);
3053 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
3054 LoopVectorBody.back()-> getFirstInsertionPt());
3060 setDebugLocFromInst(Builder, P);
3061 // Check for PHI nodes that are lowered to vector selects.
3062 if (P->getParent() != OrigLoop->getHeader()) {
3063 // We know that all PHIs in non-header blocks are converted into
3064 // selects, so we don't have to worry about the insertion order and we
3065 // can just use the builder.
3066 // At this point we generate the predication tree. There may be
3067 // duplications since this is a simple recursive scan, but future
3068 // optimizations will clean it up.
3070 unsigned NumIncoming = P->getNumIncomingValues();
3072 // Generate a sequence of selects of the form:
3073 // SELECT(Mask3, In3,
3074 // SELECT(Mask2, In2,
3076 for (unsigned In = 0; In < NumIncoming; In++) {
3077 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3079 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3081 for (unsigned part = 0; part < UF; ++part) {
3082 // We might have single edge PHIs (blocks) - use an identity
3083 // 'select' for the first PHI operand.
3085 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3088 // Select between the current value and the previous incoming edge
3089 // based on the incoming mask.
3090 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3091 Entry[part], "predphi");
3097 // This PHINode must be an induction variable.
3098 // Make sure that we know about it.
3099 assert(Legal->getInductionVars()->count(P) &&
3100 "Not an induction variable");
3102 LoopVectorizationLegality::InductionInfo II =
3103 Legal->getInductionVars()->lookup(P);
3106 case LoopVectorizationLegality::IK_NoInduction:
3107 llvm_unreachable("Unknown induction");
3108 case LoopVectorizationLegality::IK_IntInduction: {
3109 assert(P->getType() == II.StartValue->getType() && "Types must match");
3110 Type *PhiTy = P->getType();
3112 if (P == OldInduction) {
3113 // Handle the canonical induction variable. We might have had to
3115 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
3117 // Handle other induction variables that are now based on the
3119 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
3121 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
3122 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
3125 Broadcasted = getBroadcastInstrs(Broadcasted);
3126 // After broadcasting the induction variable we need to make the vector
3127 // consecutive by adding 0, 1, 2, etc.
3128 for (unsigned part = 0; part < UF; ++part)
3129 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
3132 case LoopVectorizationLegality::IK_ReverseIntInduction:
3133 case LoopVectorizationLegality::IK_PtrInduction:
3134 case LoopVectorizationLegality::IK_ReversePtrInduction:
3135 // Handle reverse integer and pointer inductions.
3136 Value *StartIdx = ExtendedIdx;
3137 // This is the normalized GEP that starts counting at zero.
3138 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
3141 // Handle the reverse integer induction variable case.
3142 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
3143 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
3144 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
3146 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
3149 // This is a new value so do not hoist it out.
3150 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
3151 // After broadcasting the induction variable we need to make the
3152 // vector consecutive by adding ... -3, -2, -1, 0.
3153 for (unsigned part = 0; part < UF; ++part)
3154 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
3159 // Handle the pointer induction variable case.
3160 assert(P->getType()->isPointerTy() && "Unexpected type.");
3162 // Is this a reverse induction ptr or a consecutive induction ptr.
3163 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
3166 // This is the vector of results. Notice that we don't generate
3167 // vector geps because scalar geps result in better code.
3168 for (unsigned part = 0; part < UF; ++part) {
3170 int EltIndex = (part) * (Reverse ? -1 : 1);
3171 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3174 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
3176 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
3178 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
3180 Entry[part] = SclrGep;
3184 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3185 for (unsigned int i = 0; i < VF; ++i) {
3186 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
3187 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3190 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
3192 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
3194 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
3196 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3197 Builder.getInt32(i),
3200 Entry[part] = VecVal;
3206 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3207 // For each instruction in the old loop.
3208 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3209 VectorParts &Entry = WidenMap.get(it);
3210 switch (it->getOpcode()) {
3211 case Instruction::Br:
3212 // Nothing to do for PHIs and BR, since we already took care of the
3213 // loop control flow instructions.
3215 case Instruction::PHI:{
3216 // Vectorize PHINodes.
3217 widenPHIInstruction(it, Entry, UF, VF, PV);
3221 case Instruction::Add:
3222 case Instruction::FAdd:
3223 case Instruction::Sub:
3224 case Instruction::FSub:
3225 case Instruction::Mul:
3226 case Instruction::FMul:
3227 case Instruction::UDiv:
3228 case Instruction::SDiv:
3229 case Instruction::FDiv:
3230 case Instruction::URem:
3231 case Instruction::SRem:
3232 case Instruction::FRem:
3233 case Instruction::Shl:
3234 case Instruction::LShr:
3235 case Instruction::AShr:
3236 case Instruction::And:
3237 case Instruction::Or:
3238 case Instruction::Xor: {
3239 // Just widen binops.
3240 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3241 setDebugLocFromInst(Builder, BinOp);
3242 VectorParts &A = getVectorValue(it->getOperand(0));
3243 VectorParts &B = getVectorValue(it->getOperand(1));
3245 // Use this vector value for all users of the original instruction.
3246 for (unsigned Part = 0; Part < UF; ++Part) {
3247 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3249 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3250 VecOp->copyIRFlags(BinOp);
3255 propagateMetadata(Entry, it);
3258 case Instruction::Select: {
3260 // If the selector is loop invariant we can create a select
3261 // instruction with a scalar condition. Otherwise, use vector-select.
3262 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3264 setDebugLocFromInst(Builder, it);
3266 // The condition can be loop invariant but still defined inside the
3267 // loop. This means that we can't just use the original 'cond' value.
3268 // We have to take the 'vectorized' value and pick the first lane.
3269 // Instcombine will make this a no-op.
3270 VectorParts &Cond = getVectorValue(it->getOperand(0));
3271 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3272 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3274 Value *ScalarCond = (VF == 1) ? Cond[0] :
3275 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3277 for (unsigned Part = 0; Part < UF; ++Part) {
3278 Entry[Part] = Builder.CreateSelect(
3279 InvariantCond ? ScalarCond : Cond[Part],
3284 propagateMetadata(Entry, it);
3288 case Instruction::ICmp:
3289 case Instruction::FCmp: {
3290 // Widen compares. Generate vector compares.
3291 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3292 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3293 setDebugLocFromInst(Builder, it);
3294 VectorParts &A = getVectorValue(it->getOperand(0));
3295 VectorParts &B = getVectorValue(it->getOperand(1));
3296 for (unsigned Part = 0; Part < UF; ++Part) {
3299 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3301 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3305 propagateMetadata(Entry, it);
3309 case Instruction::Store:
3310 case Instruction::Load:
3311 vectorizeMemoryInstruction(it);
3313 case Instruction::ZExt:
3314 case Instruction::SExt:
3315 case Instruction::FPToUI:
3316 case Instruction::FPToSI:
3317 case Instruction::FPExt:
3318 case Instruction::PtrToInt:
3319 case Instruction::IntToPtr:
3320 case Instruction::SIToFP:
3321 case Instruction::UIToFP:
3322 case Instruction::Trunc:
3323 case Instruction::FPTrunc:
3324 case Instruction::BitCast: {
3325 CastInst *CI = dyn_cast<CastInst>(it);
3326 setDebugLocFromInst(Builder, it);
3327 /// Optimize the special case where the source is the induction
3328 /// variable. Notice that we can only optimize the 'trunc' case
3329 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3330 /// c. other casts depend on pointer size.
3331 if (CI->getOperand(0) == OldInduction &&
3332 it->getOpcode() == Instruction::Trunc) {
3333 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3335 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3336 for (unsigned Part = 0; Part < UF; ++Part)
3337 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
3338 propagateMetadata(Entry, it);
3341 /// Vectorize casts.
3342 Type *DestTy = (VF == 1) ? CI->getType() :
3343 VectorType::get(CI->getType(), VF);
3345 VectorParts &A = getVectorValue(it->getOperand(0));
3346 for (unsigned Part = 0; Part < UF; ++Part)
3347 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3348 propagateMetadata(Entry, it);
3352 case Instruction::Call: {
3353 // Ignore dbg intrinsics.
3354 if (isa<DbgInfoIntrinsic>(it))
3356 setDebugLocFromInst(Builder, it);
3358 Module *M = BB->getParent()->getParent();
3359 CallInst *CI = cast<CallInst>(it);
3360 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3361 assert(ID && "Not an intrinsic call!");
3363 case Intrinsic::assume:
3364 case Intrinsic::lifetime_end:
3365 case Intrinsic::lifetime_start:
3366 scalarizeInstruction(it);
3369 bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
3370 for (unsigned Part = 0; Part < UF; ++Part) {
3371 SmallVector<Value *, 4> Args;
3372 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3373 if (HasScalarOpd && i == 1) {
3374 Args.push_back(CI->getArgOperand(i));
3377 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3378 Args.push_back(Arg[Part]);
3380 Type *Tys[] = {CI->getType()};
3382 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3384 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3385 Entry[Part] = Builder.CreateCall(F, Args);
3388 propagateMetadata(Entry, it);
3395 // All other instructions are unsupported. Scalarize them.
3396 scalarizeInstruction(it);
3399 }// end of for_each instr.
3402 void InnerLoopVectorizer::updateAnalysis() {
3403 // Forget the original basic block.
3404 SE->forgetLoop(OrigLoop);
3406 // Update the dominator tree information.
3407 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3408 "Entry does not dominate exit.");
3410 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3411 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3412 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3414 // Due to if predication of stores we might create a sequence of "if(pred)
3415 // a[i] = ...; " blocks.
3416 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3418 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3419 else if (isPredicatedBlock(i)) {
3420 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3422 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3426 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3427 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3428 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3429 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3431 DEBUG(DT->verifyDomTree());
3434 /// \brief Check whether it is safe to if-convert this phi node.
3436 /// Phi nodes with constant expressions that can trap are not safe to if
3438 static bool canIfConvertPHINodes(BasicBlock *BB) {
3439 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3440 PHINode *Phi = dyn_cast<PHINode>(I);
3443 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3444 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3451 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3452 if (!EnableIfConversion) {
3453 emitAnalysis(Report() << "if-conversion is disabled");
3457 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3459 // A list of pointers that we can safely read and write to.
3460 SmallPtrSet<Value *, 8> SafePointes;
3462 // Collect safe addresses.
3463 for (Loop::block_iterator BI = TheLoop->block_begin(),
3464 BE = TheLoop->block_end(); BI != BE; ++BI) {
3465 BasicBlock *BB = *BI;
3467 if (blockNeedsPredication(BB))
3470 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3471 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3472 SafePointes.insert(LI->getPointerOperand());
3473 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3474 SafePointes.insert(SI->getPointerOperand());
3478 // Collect the blocks that need predication.
3479 BasicBlock *Header = TheLoop->getHeader();
3480 for (Loop::block_iterator BI = TheLoop->block_begin(),
3481 BE = TheLoop->block_end(); BI != BE; ++BI) {
3482 BasicBlock *BB = *BI;
3484 // We don't support switch statements inside loops.
3485 if (!isa<BranchInst>(BB->getTerminator())) {
3486 emitAnalysis(Report(BB->getTerminator())
3487 << "loop contains a switch statement");
3491 // We must be able to predicate all blocks that need to be predicated.
3492 if (blockNeedsPredication(BB)) {
3493 if (!blockCanBePredicated(BB, SafePointes)) {
3494 emitAnalysis(Report(BB->getTerminator())
3495 << "control flow cannot be substituted for a select");
3498 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3499 emitAnalysis(Report(BB->getTerminator())
3500 << "control flow cannot be substituted for a select");
3505 // We can if-convert this loop.
3509 bool LoopVectorizationLegality::canVectorize() {
3510 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3511 // be canonicalized.
3512 if (!TheLoop->getLoopPreheader()) {
3514 Report() << "loop control flow is not understood by vectorizer");
3518 // We can only vectorize innermost loops.
3519 if (TheLoop->getSubLoopsVector().size()) {
3520 emitAnalysis(Report() << "loop is not the innermost loop");
3524 // We must have a single backedge.
3525 if (TheLoop->getNumBackEdges() != 1) {
3527 Report() << "loop control flow is not understood by vectorizer");
3531 // We must have a single exiting block.
3532 if (!TheLoop->getExitingBlock()) {
3534 Report() << "loop control flow is not understood by vectorizer");
3538 // We only handle bottom-tested loops, i.e. loop in which the condition is
3539 // checked at the end of each iteration. With that we can assume that all
3540 // instructions in the loop are executed the same number of times.
3541 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3543 Report() << "loop control flow is not understood by vectorizer");
3547 // We need to have a loop header.
3548 DEBUG(dbgs() << "LV: Found a loop: " <<
3549 TheLoop->getHeader()->getName() << '\n');
3551 // Check if we can if-convert non-single-bb loops.
3552 unsigned NumBlocks = TheLoop->getNumBlocks();
3553 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3554 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3558 // ScalarEvolution needs to be able to find the exit count.
3559 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3560 if (ExitCount == SE->getCouldNotCompute()) {
3561 emitAnalysis(Report() << "could not determine number of loop iterations");
3562 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3566 // Check if we can vectorize the instructions and CFG in this loop.
3567 if (!canVectorizeInstrs()) {
3568 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3572 // Go over each instruction and look at memory deps.
3573 if (!canVectorizeMemory()) {
3574 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3578 // Collect all of the variables that remain uniform after vectorization.
3579 collectLoopUniforms();
3581 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3582 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3585 // Okay! We can vectorize. At this point we don't have any other mem analysis
3586 // which may limit our maximum vectorization factor, so just return true with
3591 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3592 if (Ty->isPointerTy())
3593 return DL.getIntPtrType(Ty);
3595 // It is possible that char's or short's overflow when we ask for the loop's
3596 // trip count, work around this by changing the type size.
3597 if (Ty->getScalarSizeInBits() < 32)
3598 return Type::getInt32Ty(Ty->getContext());
3603 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3604 Ty0 = convertPointerToIntegerType(DL, Ty0);
3605 Ty1 = convertPointerToIntegerType(DL, Ty1);
3606 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3611 /// \brief Check that the instruction has outside loop users and is not an
3612 /// identified reduction variable.
3613 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3614 SmallPtrSetImpl<Value *> &Reductions) {
3615 // Reduction instructions are allowed to have exit users. All other
3616 // instructions must not have external users.
3617 if (!Reductions.count(Inst))
3618 //Check that all of the users of the loop are inside the BB.
3619 for (User *U : Inst->users()) {
3620 Instruction *UI = cast<Instruction>(U);
3621 // This user may be a reduction exit value.
3622 if (!TheLoop->contains(UI)) {
3623 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3630 bool LoopVectorizationLegality::canVectorizeInstrs() {
3631 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3632 BasicBlock *Header = TheLoop->getHeader();
3634 // Look for the attribute signaling the absence of NaNs.
3635 Function &F = *Header->getParent();
3636 if (F.hasFnAttribute("no-nans-fp-math"))
3637 HasFunNoNaNAttr = F.getAttributes().getAttribute(
3638 AttributeSet::FunctionIndex,
3639 "no-nans-fp-math").getValueAsString() == "true";
3641 // For each block in the loop.
3642 for (Loop::block_iterator bb = TheLoop->block_begin(),
3643 be = TheLoop->block_end(); bb != be; ++bb) {
3645 // Scan the instructions in the block and look for hazards.
3646 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3649 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3650 Type *PhiTy = Phi->getType();
3651 // Check that this PHI type is allowed.
3652 if (!PhiTy->isIntegerTy() &&
3653 !PhiTy->isFloatingPointTy() &&
3654 !PhiTy->isPointerTy()) {
3655 emitAnalysis(Report(it)
3656 << "loop control flow is not understood by vectorizer");
3657 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3661 // If this PHINode is not in the header block, then we know that we
3662 // can convert it to select during if-conversion. No need to check if
3663 // the PHIs in this block are induction or reduction variables.
3664 if (*bb != Header) {
3665 // Check that this instruction has no outside users or is an
3666 // identified reduction value with an outside user.
3667 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3669 emitAnalysis(Report(it) << "value could not be identified as "
3670 "an induction or reduction variable");
3674 // We only allow if-converted PHIs with more than two incoming values.
3675 if (Phi->getNumIncomingValues() != 2) {
3676 emitAnalysis(Report(it)
3677 << "control flow not understood by vectorizer");
3678 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3682 // This is the value coming from the preheader.
3683 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3684 // Check if this is an induction variable.
3685 InductionKind IK = isInductionVariable(Phi);
3687 if (IK_NoInduction != IK) {
3688 // Get the widest type.
3690 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3692 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3694 // Int inductions are special because we only allow one IV.
3695 if (IK == IK_IntInduction) {
3696 // Use the phi node with the widest type as induction. Use the last
3697 // one if there are multiple (no good reason for doing this other
3698 // than it is expedient).
3699 if (!Induction || PhiTy == WidestIndTy)
3703 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3704 Inductions[Phi] = InductionInfo(StartValue, IK);
3706 // Until we explicitly handle the case of an induction variable with
3707 // an outside loop user we have to give up vectorizing this loop.
3708 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3709 emitAnalysis(Report(it) << "use of induction value outside of the "
3710 "loop is not handled by vectorizer");
3717 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3718 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3721 if (AddReductionVar(Phi, RK_IntegerMult)) {
3722 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3725 if (AddReductionVar(Phi, RK_IntegerOr)) {
3726 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3729 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3730 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3733 if (AddReductionVar(Phi, RK_IntegerXor)) {
3734 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3737 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3738 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3741 if (AddReductionVar(Phi, RK_FloatMult)) {
3742 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3745 if (AddReductionVar(Phi, RK_FloatAdd)) {
3746 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3749 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3750 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3755 emitAnalysis(Report(it) << "value that could not be identified as "
3756 "reduction is used outside the loop");
3757 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3759 }// end of PHI handling
3761 // We still don't handle functions. However, we can ignore dbg intrinsic
3762 // calls and we do handle certain intrinsic and libm functions.
3763 CallInst *CI = dyn_cast<CallInst>(it);
3764 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3765 emitAnalysis(Report(it) << "call instruction cannot be vectorized");
3766 DEBUG(dbgs() << "LV: Found a call site.\n");
3770 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
3771 // second argument is the same (i.e. loop invariant)
3773 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
3774 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
3775 emitAnalysis(Report(it)
3776 << "intrinsic instruction cannot be vectorized");
3777 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
3782 // Check that the instruction return type is vectorizable.
3783 // Also, we can't vectorize extractelement instructions.
3784 if ((!VectorType::isValidElementType(it->getType()) &&
3785 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3786 emitAnalysis(Report(it)
3787 << "instruction return type cannot be vectorized");
3788 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3792 // Check that the stored type is vectorizable.
3793 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3794 Type *T = ST->getValueOperand()->getType();
3795 if (!VectorType::isValidElementType(T)) {
3796 emitAnalysis(Report(ST) << "store instruction cannot be vectorized");
3799 if (EnableMemAccessVersioning)
3800 collectStridedAcccess(ST);
3803 if (EnableMemAccessVersioning)
3804 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3805 collectStridedAcccess(LI);
3807 // Reduction instructions are allowed to have exit users.
3808 // All other instructions must not have external users.
3809 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3810 emitAnalysis(Report(it) << "value cannot be used outside the loop");
3819 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3820 if (Inductions.empty()) {
3821 emitAnalysis(Report()
3822 << "loop induction variable could not be identified");
3830 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3831 /// return the induction operand of the gep pointer.
3832 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3833 const DataLayout *DL, Loop *Lp) {
3834 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3838 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3840 // Check that all of the gep indices are uniform except for our induction
3842 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3843 if (i != InductionOperand &&
3844 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3846 return GEP->getOperand(InductionOperand);
3849 ///\brief Look for a cast use of the passed value.
3850 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3851 Value *UniqueCast = nullptr;
3852 for (User *U : Ptr->users()) {
3853 CastInst *CI = dyn_cast<CastInst>(U);
3854 if (CI && CI->getType() == Ty) {
3864 ///\brief Get the stride of a pointer access in a loop.
3865 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3866 /// pointer to the Value, or null otherwise.
3867 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3868 const DataLayout *DL, Loop *Lp) {
3869 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3870 if (!PtrTy || PtrTy->isAggregateType())
3873 // Try to remove a gep instruction to make the pointer (actually index at this
3874 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3875 // pointer, otherwise, we are analyzing the index.
3876 Value *OrigPtr = Ptr;
3878 // The size of the pointer access.
3879 int64_t PtrAccessSize = 1;
3881 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3882 const SCEV *V = SE->getSCEV(Ptr);
3886 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3887 V = C->getOperand();
3889 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3893 V = S->getStepRecurrence(*SE);
3897 // Strip off the size of access multiplication if we are still analyzing the
3899 if (OrigPtr == Ptr) {
3900 DL->getTypeAllocSize(PtrTy->getElementType());
3901 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3902 if (M->getOperand(0)->getSCEVType() != scConstant)
3905 const APInt &APStepVal =
3906 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3908 // Huge step value - give up.
3909 if (APStepVal.getBitWidth() > 64)
3912 int64_t StepVal = APStepVal.getSExtValue();
3913 if (PtrAccessSize != StepVal)
3915 V = M->getOperand(1);
3920 Type *StripedOffRecurrenceCast = nullptr;
3921 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3922 StripedOffRecurrenceCast = C->getType();
3923 V = C->getOperand();
3926 // Look for the loop invariant symbolic value.
3927 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3931 Value *Stride = U->getValue();
3932 if (!Lp->isLoopInvariant(Stride))
3935 // If we have stripped off the recurrence cast we have to make sure that we
3936 // return the value that is used in this loop so that we can replace it later.
3937 if (StripedOffRecurrenceCast)
3938 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3943 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
3944 Value *Ptr = nullptr;
3945 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3946 Ptr = LI->getPointerOperand();
3947 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3948 Ptr = SI->getPointerOperand();
3952 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3956 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3957 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3958 Strides[Ptr] = Stride;
3959 StrideSet.insert(Stride);
3962 void LoopVectorizationLegality::collectLoopUniforms() {
3963 // We now know that the loop is vectorizable!
3964 // Collect variables that will remain uniform after vectorization.
3965 std::vector<Value*> Worklist;
3966 BasicBlock *Latch = TheLoop->getLoopLatch();
3968 // Start with the conditional branch and walk up the block.
3969 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3971 // Also add all consecutive pointer values; these values will be uniform
3972 // after vectorization (and subsequent cleanup) and, until revectorization is
3973 // supported, all dependencies must also be uniform.
3974 for (Loop::block_iterator B = TheLoop->block_begin(),
3975 BE = TheLoop->block_end(); B != BE; ++B)
3976 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3978 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3979 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3981 while (Worklist.size()) {
3982 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3983 Worklist.pop_back();
3985 // Look at instructions inside this loop.
3986 // Stop when reaching PHI nodes.
3987 // TODO: we need to follow values all over the loop, not only in this block.
3988 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3991 // This is a known uniform.
3994 // Insert all operands.
3995 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4000 /// \brief Analyses memory accesses in a loop.
4002 /// Checks whether run time pointer checks are needed and builds sets for data
4003 /// dependence checking.
4004 class AccessAnalysis {
4006 /// \brief Read or write access location.
4007 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
4008 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
4010 /// \brief Set of potential dependent memory accesses.
4011 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
4013 AccessAnalysis(const DataLayout *Dl, AliasAnalysis *AA, DepCandidates &DA) :
4014 DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
4016 /// \brief Register a load and whether it is only read from.
4017 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
4018 Value *Ptr = const_cast<Value*>(Loc.Ptr);
4019 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
4020 Accesses.insert(MemAccessInfo(Ptr, false));
4022 ReadOnlyPtr.insert(Ptr);
4025 /// \brief Register a store.
4026 void addStore(AliasAnalysis::Location &Loc) {
4027 Value *Ptr = const_cast<Value*>(Loc.Ptr);
4028 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
4029 Accesses.insert(MemAccessInfo(Ptr, true));
4032 /// \brief Check whether we can check the pointers at runtime for
4033 /// non-intersection.
4034 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
4035 unsigned &NumComparisons, ScalarEvolution *SE,
4036 Loop *TheLoop, ValueToValueMap &Strides,
4037 bool ShouldCheckStride = false);
4039 /// \brief Goes over all memory accesses, checks whether a RT check is needed
4040 /// and builds sets of dependent accesses.
4041 void buildDependenceSets() {
4042 processMemAccesses();
4045 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
4047 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
4048 void resetDepChecks() { CheckDeps.clear(); }
4050 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
4053 typedef SetVector<MemAccessInfo> PtrAccessSet;
4055 /// \brief Go over all memory access and check whether runtime pointer checks
4056 /// are needed /// and build sets of dependency check candidates.
4057 void processMemAccesses();
4059 /// Set of all accesses.
4060 PtrAccessSet Accesses;
4062 /// Set of accesses that need a further dependence check.
4063 MemAccessInfoSet CheckDeps;
4065 /// Set of pointers that are read only.
4066 SmallPtrSet<Value*, 16> ReadOnlyPtr;
4068 const DataLayout *DL;
4070 /// An alias set tracker to partition the access set by underlying object and
4071 //intrinsic property (such as TBAA metadata).
4072 AliasSetTracker AST;
4074 /// Sets of potentially dependent accesses - members of one set share an
4075 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
4076 /// dependence check.
4077 DepCandidates &DepCands;
4079 bool IsRTCheckNeeded;
4082 } // end anonymous namespace
4084 /// \brief Check whether a pointer can participate in a runtime bounds check.
4085 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
4087 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
4088 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4092 return AR->isAffine();
4095 /// \brief Check the stride of the pointer and ensure that it does not wrap in
4096 /// the address space.
4097 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
4098 const Loop *Lp, ValueToValueMap &StridesMap);
4100 bool AccessAnalysis::canCheckPtrAtRT(
4101 LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
4102 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
4103 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
4104 // Find pointers with computable bounds. We are going to use this information
4105 // to place a runtime bound check.
4106 bool CanDoRT = true;
4108 bool IsDepCheckNeeded = isDependencyCheckNeeded();
4111 // We assign a consecutive id to access from different alias sets.
4112 // Accesses between different groups doesn't need to be checked.
4114 for (auto &AS : AST) {
4115 unsigned NumReadPtrChecks = 0;
4116 unsigned NumWritePtrChecks = 0;
4118 // We assign consecutive id to access from different dependence sets.
4119 // Accesses within the same set don't need a runtime check.
4120 unsigned RunningDepId = 1;
4121 DenseMap<Value *, unsigned> DepSetId;
4124 Value *Ptr = A.getValue();
4125 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
4126 MemAccessInfo Access(Ptr, IsWrite);
4129 ++NumWritePtrChecks;
4133 if (hasComputableBounds(SE, StridesMap, Ptr) &&
4134 // When we run after a failing dependency check we have to make sure we
4135 // don't have wrapping pointers.
4136 (!ShouldCheckStride ||
4137 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
4138 // The id of the dependence set.
4141 if (IsDepCheckNeeded) {
4142 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
4143 unsigned &LeaderId = DepSetId[Leader];
4145 LeaderId = RunningDepId++;
4148 // Each access has its own dependence set.
4149 DepId = RunningDepId++;
4151 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
4153 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
4159 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
4160 NumComparisons += 0; // Only one dependence set.
4162 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
4163 NumWritePtrChecks - 1));
4169 // If the pointers that we would use for the bounds comparison have different
4170 // address spaces, assume the values aren't directly comparable, so we can't
4171 // use them for the runtime check. We also have to assume they could
4172 // overlap. In the future there should be metadata for whether address spaces
4174 unsigned NumPointers = RtCheck.Pointers.size();
4175 for (unsigned i = 0; i < NumPointers; ++i) {
4176 for (unsigned j = i + 1; j < NumPointers; ++j) {
4177 // Only need to check pointers between two different dependency sets.
4178 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
4180 // Only need to check pointers in the same alias set.
4181 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
4184 Value *PtrI = RtCheck.Pointers[i];
4185 Value *PtrJ = RtCheck.Pointers[j];
4187 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
4188 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
4190 DEBUG(dbgs() << "LV: Runtime check would require comparison between"
4191 " different address spaces\n");
4200 void AccessAnalysis::processMemAccesses() {
4201 // We process the set twice: first we process read-write pointers, last we
4202 // process read-only pointers. This allows us to skip dependence tests for
4203 // read-only pointers.
4205 DEBUG(dbgs() << "LV: Processing memory accesses...\n");
4206 DEBUG(dbgs() << " AST: "; AST.dump());
4207 DEBUG(dbgs() << "LV: Accesses:\n");
4209 for (auto A : Accesses)
4210 dbgs() << "\t" << *A.getPointer() << " (" <<
4211 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
4212 "read-only" : "read")) << ")\n";
4215 // The AliasSetTracker has nicely partitioned our pointers by metadata
4216 // compatibility and potential for underlying-object overlap. As a result, we
4217 // only need to check for potential pointer dependencies within each alias
4219 for (auto &AS : AST) {
4220 // Note that both the alias-set tracker and the alias sets themselves used
4221 // linked lists internally and so the iteration order here is deterministic
4222 // (matching the original instruction order within each set).
4224 bool SetHasWrite = false;
4226 // Map of pointers to last access encountered.
4227 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
4228 UnderlyingObjToAccessMap ObjToLastAccess;
4230 // Set of access to check after all writes have been processed.
4231 PtrAccessSet DeferredAccesses;
4233 // Iterate over each alias set twice, once to process read/write pointers,
4234 // and then to process read-only pointers.
4235 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
4236 bool UseDeferred = SetIteration > 0;
4237 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
4240 Value *Ptr = A.getValue();
4241 bool IsWrite = S.count(MemAccessInfo(Ptr, true));
4243 // If we're using the deferred access set, then it contains only reads.
4244 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
4245 if (UseDeferred && !IsReadOnlyPtr)
4247 // Otherwise, the pointer must be in the PtrAccessSet, either as a read
4249 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
4250 S.count(MemAccessInfo(Ptr, false))) &&
4251 "Alias-set pointer not in the access set?");
4253 MemAccessInfo Access(Ptr, IsWrite);
4254 DepCands.insert(Access);
4256 // Memorize read-only pointers for later processing and skip them in the
4257 // first round (they need to be checked after we have seen all write
4258 // pointers). Note: we also mark pointer that are not consecutive as
4259 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need
4260 // the second check for "!IsWrite".
4261 if (!UseDeferred && IsReadOnlyPtr) {
4262 DeferredAccesses.insert(Access);
4266 // If this is a write - check other reads and writes for conflicts. If
4267 // this is a read only check other writes for conflicts (but only if
4268 // there is no other write to the ptr - this is an optimization to
4269 // catch "a[i] = a[i] + " without having to do a dependence check).
4270 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
4271 CheckDeps.insert(Access);
4272 IsRTCheckNeeded = true;
4278 // Create sets of pointers connected by a shared alias set and
4279 // underlying object.
4280 typedef SmallVector<Value *, 16> ValueVector;
4281 ValueVector TempObjects;
4282 GetUnderlyingObjects(Ptr, TempObjects, DL);
4283 for (Value *UnderlyingObj : TempObjects) {
4284 UnderlyingObjToAccessMap::iterator Prev =
4285 ObjToLastAccess.find(UnderlyingObj);
4286 if (Prev != ObjToLastAccess.end())
4287 DepCands.unionSets(Access, Prev->second);
4289 ObjToLastAccess[UnderlyingObj] = Access;
4297 /// \brief Checks memory dependences among accesses to the same underlying
4298 /// object to determine whether there vectorization is legal or not (and at
4299 /// which vectorization factor).
4301 /// This class works under the assumption that we already checked that memory
4302 /// locations with different underlying pointers are "must-not alias".
4303 /// We use the ScalarEvolution framework to symbolically evalutate access
4304 /// functions pairs. Since we currently don't restructure the loop we can rely
4305 /// on the program order of memory accesses to determine their safety.
4306 /// At the moment we will only deem accesses as safe for:
4307 /// * A negative constant distance assuming program order.
4309 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
4310 /// a[i] = tmp; y = a[i];
4312 /// The latter case is safe because later checks guarantuee that there can't
4313 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
4314 /// the same variable: a header phi can only be an induction or a reduction, a
4315 /// reduction can't have a memory sink, an induction can't have a memory
4316 /// source). This is important and must not be violated (or we have to
4317 /// resort to checking for cycles through memory).
4319 /// * A positive constant distance assuming program order that is bigger
4320 /// than the biggest memory access.
4322 /// tmp = a[i] OR b[i] = x
4323 /// a[i+2] = tmp y = b[i+2];
4325 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
4327 /// * Zero distances and all accesses have the same size.
4329 class MemoryDepChecker {
4331 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
4332 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
4334 MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
4335 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
4336 ShouldRetryWithRuntimeCheck(false) {}
4338 /// \brief Register the location (instructions are given increasing numbers)
4339 /// of a write access.
4340 void addAccess(StoreInst *SI) {
4341 Value *Ptr = SI->getPointerOperand();
4342 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
4343 InstMap.push_back(SI);
4347 /// \brief Register the location (instructions are given increasing numbers)
4348 /// of a write access.
4349 void addAccess(LoadInst *LI) {
4350 Value *Ptr = LI->getPointerOperand();
4351 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
4352 InstMap.push_back(LI);
4356 /// \brief Check whether the dependencies between the accesses are safe.
4358 /// Only checks sets with elements in \p CheckDeps.
4359 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4360 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
4362 /// \brief The maximum number of bytes of a vector register we can vectorize
4363 /// the accesses safely with.
4364 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
4366 /// \brief In same cases when the dependency check fails we can still
4367 /// vectorize the loop with a dynamic array access check.
4368 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
4371 ScalarEvolution *SE;
4372 const DataLayout *DL;
4373 const Loop *InnermostLoop;
4375 /// \brief Maps access locations (ptr, read/write) to program order.
4376 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
4378 /// \brief Memory access instructions in program order.
4379 SmallVector<Instruction *, 16> InstMap;
4381 /// \brief The program order index to be used for the next instruction.
4384 // We can access this many bytes in parallel safely.
4385 unsigned MaxSafeDepDistBytes;
4387 /// \brief If we see a non-constant dependence distance we can still try to
4388 /// vectorize this loop with runtime checks.
4389 bool ShouldRetryWithRuntimeCheck;
4391 /// \brief Check whether there is a plausible dependence between the two
4394 /// Access \p A must happen before \p B in program order. The two indices
4395 /// identify the index into the program order map.
4397 /// This function checks whether there is a plausible dependence (or the
4398 /// absence of such can't be proved) between the two accesses. If there is a
4399 /// plausible dependence but the dependence distance is bigger than one
4400 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
4401 /// distance is smaller than any other distance encountered so far).
4402 /// Otherwise, this function returns true signaling a possible dependence.
4403 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
4404 const MemAccessInfo &B, unsigned BIdx,
4405 ValueToValueMap &Strides);
4407 /// \brief Check whether the data dependence could prevent store-load
4409 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
4412 } // end anonymous namespace
4414 static bool isInBoundsGep(Value *Ptr) {
4415 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
4416 return GEP->isInBounds();
4420 /// \brief Check whether the access through \p Ptr has a constant stride.
4421 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
4422 const Loop *Lp, ValueToValueMap &StridesMap) {
4423 const Type *Ty = Ptr->getType();
4424 assert(Ty->isPointerTy() && "Unexpected non-ptr");
4426 // Make sure that the pointer does not point to aggregate types.
4427 const PointerType *PtrTy = cast<PointerType>(Ty);
4428 if (PtrTy->getElementType()->isAggregateType()) {
4429 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
4434 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
4436 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4438 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
4439 << *Ptr << " SCEV: " << *PtrScev << "\n");
4443 // The accesss function must stride over the innermost loop.
4444 if (Lp != AR->getLoop()) {
4445 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
4446 *Ptr << " SCEV: " << *PtrScev << "\n");
4449 // The address calculation must not wrap. Otherwise, a dependence could be
4451 // An inbounds getelementptr that is a AddRec with a unit stride
4452 // cannot wrap per definition. The unit stride requirement is checked later.
4453 // An getelementptr without an inbounds attribute and unit stride would have
4454 // to access the pointer value "0" which is undefined behavior in address
4455 // space 0, therefore we can also vectorize this case.
4456 bool IsInBoundsGEP = isInBoundsGep(Ptr);
4457 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
4458 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
4459 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
4460 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
4461 << *Ptr << " SCEV: " << *PtrScev << "\n");
4465 // Check the step is constant.
4466 const SCEV *Step = AR->getStepRecurrence(*SE);
4468 // Calculate the pointer stride and check if it is consecutive.
4469 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4471 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
4472 " SCEV: " << *PtrScev << "\n");
4476 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
4477 const APInt &APStepVal = C->getValue()->getValue();
4479 // Huge step value - give up.
4480 if (APStepVal.getBitWidth() > 64)
4483 int64_t StepVal = APStepVal.getSExtValue();
4486 int64_t Stride = StepVal / Size;
4487 int64_t Rem = StepVal % Size;
4491 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
4492 // know we can't "wrap around the address space". In case of address space
4493 // zero we know that this won't happen without triggering undefined behavior.
4494 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
4495 Stride != 1 && Stride != -1)
4501 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
4502 unsigned TypeByteSize) {
4503 // If loads occur at a distance that is not a multiple of a feasible vector
4504 // factor store-load forwarding does not take place.
4505 // Positive dependences might cause troubles because vectorizing them might
4506 // prevent store-load forwarding making vectorized code run a lot slower.
4507 // a[i] = a[i-3] ^ a[i-8];
4508 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
4509 // hence on your typical architecture store-load forwarding does not take
4510 // place. Vectorizing in such cases does not make sense.
4511 // Store-load forwarding distance.
4512 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
4513 // Maximum vector factor.
4514 unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
4515 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
4516 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
4518 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
4520 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
4521 MaxVFWithoutSLForwardIssues = (vf >>=1);
4526 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4527 DEBUG(dbgs() << "LV: Distance " << Distance <<
4528 " that could cause a store-load forwarding conflict\n");
4532 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4533 MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4534 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4538 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4539 const MemAccessInfo &B, unsigned BIdx,
4540 ValueToValueMap &Strides) {
4541 assert (AIdx < BIdx && "Must pass arguments in program order");
4543 Value *APtr = A.getPointer();
4544 Value *BPtr = B.getPointer();
4545 bool AIsWrite = A.getInt();
4546 bool BIsWrite = B.getInt();
4548 // Two reads are independent.
4549 if (!AIsWrite && !BIsWrite)
4552 // We cannot check pointers in different address spaces.
4553 if (APtr->getType()->getPointerAddressSpace() !=
4554 BPtr->getType()->getPointerAddressSpace())
4557 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4558 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4560 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4561 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4563 const SCEV *Src = AScev;
4564 const SCEV *Sink = BScev;
4566 // If the induction step is negative we have to invert source and sink of the
4568 if (StrideAPtr < 0) {
4571 std::swap(APtr, BPtr);
4572 std::swap(Src, Sink);
4573 std::swap(AIsWrite, BIsWrite);
4574 std::swap(AIdx, BIdx);
4575 std::swap(StrideAPtr, StrideBPtr);
4578 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4580 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4581 << "(Induction step: " << StrideAPtr << ")\n");
4582 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4583 << *InstMap[BIdx] << ": " << *Dist << "\n");
4585 // Need consecutive accesses. We don't want to vectorize
4586 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4587 // the address space.
4588 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4589 DEBUG(dbgs() << "Non-consecutive pointer access\n");
4593 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4595 DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4596 ShouldRetryWithRuntimeCheck = true;
4600 Type *ATy = APtr->getType()->getPointerElementType();
4601 Type *BTy = BPtr->getType()->getPointerElementType();
4602 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4604 // Negative distances are not plausible dependencies.
4605 const APInt &Val = C->getValue()->getValue();
4606 if (Val.isNegative()) {
4607 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4608 if (IsTrueDataDependence &&
4609 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4613 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4617 // Write to the same location with the same size.
4618 // Could be improved to assert type sizes are the same (i32 == float, etc).
4622 DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4626 assert(Val.isStrictlyPositive() && "Expect a positive value");
4628 // Positive distance bigger than max vectorization factor.
4631 "LV: ReadWrite-Write positive dependency with different types\n");
4635 unsigned Distance = (unsigned) Val.getZExtValue();
4637 // Bail out early if passed-in parameters make vectorization not feasible.
4638 unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4639 unsigned ForcedUnroll = VectorizationInterleave ? VectorizationInterleave : 1;
4641 // The distance must be bigger than the size needed for a vectorized version
4642 // of the operation and the size of the vectorized operation must not be
4643 // bigger than the currrent maximum size.
4644 if (Distance < 2*TypeByteSize ||
4645 2*TypeByteSize > MaxSafeDepDistBytes ||
4646 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4647 DEBUG(dbgs() << "LV: Failure because of Positive distance "
4648 << Val.getSExtValue() << '\n');
4652 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4653 Distance : MaxSafeDepDistBytes;
4655 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4656 if (IsTrueDataDependence &&
4657 couldPreventStoreLoadForward(Distance, TypeByteSize))
4660 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4661 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4666 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4667 MemAccessInfoSet &CheckDeps,
4668 ValueToValueMap &Strides) {
4670 MaxSafeDepDistBytes = -1U;
4671 while (!CheckDeps.empty()) {
4672 MemAccessInfo CurAccess = *CheckDeps.begin();
4674 // Get the relevant memory access set.
4675 EquivalenceClasses<MemAccessInfo>::iterator I =
4676 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4678 // Check accesses within this set.
4679 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4680 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4682 // Check every access pair.
4684 CheckDeps.erase(*AI);
4685 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
4687 // Check every accessing instruction pair in program order.
4688 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4689 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4690 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4691 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4692 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4694 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4705 bool LoopVectorizationLegality::canVectorizeMemory() {
4707 typedef SmallVector<Value*, 16> ValueVector;
4708 typedef SmallPtrSet<Value*, 16> ValueSet;
4710 // Holds the Load and Store *instructions*.
4714 // Holds all the different accesses in the loop.
4715 unsigned NumReads = 0;
4716 unsigned NumReadWrites = 0;
4718 PtrRtCheck.Pointers.clear();
4719 PtrRtCheck.Need = false;
4721 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4722 MemoryDepChecker DepChecker(SE, DL, TheLoop);
4725 for (Loop::block_iterator bb = TheLoop->block_begin(),
4726 be = TheLoop->block_end(); bb != be; ++bb) {
4728 // Scan the BB and collect legal loads and stores.
4729 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4732 // If this is a load, save it. If this instruction can read from memory
4733 // but is not a load, then we quit. Notice that we don't handle function
4734 // calls that read or write.
4735 if (it->mayReadFromMemory()) {
4736 // Many math library functions read the rounding mode. We will only
4737 // vectorize a loop if it contains known function calls that don't set
4738 // the flag. Therefore, it is safe to ignore this read from memory.
4739 CallInst *Call = dyn_cast<CallInst>(it);
4740 if (Call && getIntrinsicIDForCall(Call, TLI))
4743 LoadInst *Ld = dyn_cast<LoadInst>(it);
4744 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
4745 emitAnalysis(Report(Ld)
4746 << "read with atomic ordering or volatile read");
4747 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4751 Loads.push_back(Ld);
4752 DepChecker.addAccess(Ld);
4756 // Save 'store' instructions. Abort if other instructions write to memory.
4757 if (it->mayWriteToMemory()) {
4758 StoreInst *St = dyn_cast<StoreInst>(it);
4760 emitAnalysis(Report(it) << "instruction cannot be vectorized");
4763 if (!St->isSimple() && !IsAnnotatedParallel) {
4764 emitAnalysis(Report(St)
4765 << "write with atomic ordering or volatile write");
4766 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4770 Stores.push_back(St);
4771 DepChecker.addAccess(St);
4776 // Now we have two lists that hold the loads and the stores.
4777 // Next, we find the pointers that they use.
4779 // Check if we see any stores. If there are no stores, then we don't
4780 // care if the pointers are *restrict*.
4781 if (!Stores.size()) {
4782 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4786 AccessAnalysis::DepCandidates DependentAccesses;
4787 AccessAnalysis Accesses(DL, AA, DependentAccesses);
4789 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4790 // multiple times on the same object. If the ptr is accessed twice, once
4791 // for read and once for write, it will only appear once (on the write
4792 // list). This is okay, since we are going to check for conflicts between
4793 // writes and between reads and writes, but not between reads and reads.
4796 ValueVector::iterator I, IE;
4797 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4798 StoreInst *ST = cast<StoreInst>(*I);
4799 Value* Ptr = ST->getPointerOperand();
4801 if (isUniform(Ptr)) {
4804 << "write to a loop invariant address could not be vectorized");
4805 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4809 // If we did *not* see this pointer before, insert it to the read-write
4810 // list. At this phase it is only a 'write' list.
4811 if (Seen.insert(Ptr).second) {
4814 AliasAnalysis::Location Loc = AA->getLocation(ST);
4815 // The TBAA metadata could have a control dependency on the predication
4816 // condition, so we cannot rely on it when determining whether or not we
4817 // need runtime pointer checks.
4818 if (blockNeedsPredication(ST->getParent()))
4819 Loc.AATags.TBAA = nullptr;
4821 Accesses.addStore(Loc);
4825 if (IsAnnotatedParallel) {
4827 << "LV: A loop annotated parallel, ignore memory dependency "
4832 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4833 LoadInst *LD = cast<LoadInst>(*I);
4834 Value* Ptr = LD->getPointerOperand();
4835 // If we did *not* see this pointer before, insert it to the
4836 // read list. If we *did* see it before, then it is already in
4837 // the read-write list. This allows us to vectorize expressions
4838 // such as A[i] += x; Because the address of A[i] is a read-write
4839 // pointer. This only works if the index of A[i] is consecutive.
4840 // If the address of i is unknown (for example A[B[i]]) then we may
4841 // read a few words, modify, and write a few words, and some of the
4842 // words may be written to the same address.
4843 bool IsReadOnlyPtr = false;
4844 if (Seen.insert(Ptr).second ||
4845 !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4847 IsReadOnlyPtr = true;
4850 AliasAnalysis::Location Loc = AA->getLocation(LD);
4851 // The TBAA metadata could have a control dependency on the predication
4852 // condition, so we cannot rely on it when determining whether or not we
4853 // need runtime pointer checks.
4854 if (blockNeedsPredication(LD->getParent()))
4855 Loc.AATags.TBAA = nullptr;
4857 Accesses.addLoad(Loc, IsReadOnlyPtr);
4860 // If we write (or read-write) to a single destination and there are no
4861 // other reads in this loop then is it safe to vectorize.
4862 if (NumReadWrites == 1 && NumReads == 0) {
4863 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4867 // Build dependence sets and check whether we need a runtime pointer bounds
4869 Accesses.buildDependenceSets();
4870 bool NeedRTCheck = Accesses.isRTCheckNeeded();
4872 // Find pointers with computable bounds. We are going to use this information
4873 // to place a runtime bound check.
4874 unsigned NumComparisons = 0;
4875 bool CanDoRT = false;
4877 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4880 DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4881 " pointer comparisons.\n");
4883 // If we only have one set of dependences to check pointers among we don't
4884 // need a runtime check.
4885 if (NumComparisons == 0 && NeedRTCheck)
4886 NeedRTCheck = false;
4888 // Check that we did not collect too many pointers or found an unsizeable
4890 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4896 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4899 if (NeedRTCheck && !CanDoRT) {
4900 emitAnalysis(Report() << "cannot identify array bounds");
4901 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4902 "the array bounds.\n");
4907 PtrRtCheck.Need = NeedRTCheck;
4909 bool CanVecMem = true;
4910 if (Accesses.isDependencyCheckNeeded()) {
4911 DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4912 CanVecMem = DepChecker.areDepsSafe(
4913 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4914 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4916 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4917 DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4920 // Clear the dependency checks. We assume they are not needed.
4921 Accesses.resetDepChecks();
4924 PtrRtCheck.Need = true;
4926 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4927 TheLoop, Strides, true);
4928 // Check that we did not collect too many pointers or found an unsizeable
4930 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4931 if (!CanDoRT && NumComparisons > 0)
4932 emitAnalysis(Report()
4933 << "cannot check memory dependencies at runtime");
4935 emitAnalysis(Report()
4936 << NumComparisons << " exceeds limit of "
4937 << RuntimeMemoryCheckThreshold
4938 << " dependent memory operations checked at runtime");
4939 DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4949 emitAnalysis(Report() << "unsafe dependent memory operations in loop");
4951 DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4952 " need a runtime memory check.\n");
4957 static bool hasMultipleUsesOf(Instruction *I,
4958 SmallPtrSetImpl<Instruction *> &Insts) {
4959 unsigned NumUses = 0;
4960 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
4961 if (Insts.count(dyn_cast<Instruction>(*Use)))
4970 static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set) {
4971 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4972 if (!Set.count(dyn_cast<Instruction>(*Use)))
4977 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
4978 ReductionKind Kind) {
4979 if (Phi->getNumIncomingValues() != 2)
4982 // Reduction variables are only found in the loop header block.
4983 if (Phi->getParent() != TheLoop->getHeader())
4986 // Obtain the reduction start value from the value that comes from the loop
4988 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
4990 // ExitInstruction is the single value which is used outside the loop.
4991 // We only allow for a single reduction value to be used outside the loop.
4992 // This includes users of the reduction, variables (which form a cycle
4993 // which ends in the phi node).
4994 Instruction *ExitInstruction = nullptr;
4995 // Indicates that we found a reduction operation in our scan.
4996 bool FoundReduxOp = false;
4998 // We start with the PHI node and scan for all of the users of this
4999 // instruction. All users must be instructions that can be used as reduction
5000 // variables (such as ADD). We must have a single out-of-block user. The cycle
5001 // must include the original PHI.
5002 bool FoundStartPHI = false;
5004 // To recognize min/max patterns formed by a icmp select sequence, we store
5005 // the number of instruction we saw from the recognized min/max pattern,
5006 // to make sure we only see exactly the two instructions.
5007 unsigned NumCmpSelectPatternInst = 0;
5008 ReductionInstDesc ReduxDesc(false, nullptr);
5010 SmallPtrSet<Instruction *, 8> VisitedInsts;
5011 SmallVector<Instruction *, 8> Worklist;
5012 Worklist.push_back(Phi);
5013 VisitedInsts.insert(Phi);
5015 // A value in the reduction can be used:
5016 // - By the reduction:
5017 // - Reduction operation:
5018 // - One use of reduction value (safe).
5019 // - Multiple use of reduction value (not safe).
5021 // - All uses of the PHI must be the reduction (safe).
5022 // - Otherwise, not safe.
5023 // - By one instruction outside of the loop (safe).
5024 // - By further instructions outside of the loop (not safe).
5025 // - By an instruction that is not part of the reduction (not safe).
5027 // * An instruction type other than PHI or the reduction operation.
5028 // * A PHI in the header other than the initial PHI.
5029 while (!Worklist.empty()) {
5030 Instruction *Cur = Worklist.back();
5031 Worklist.pop_back();
5034 // If the instruction has no users then this is a broken chain and can't be
5035 // a reduction variable.
5036 if (Cur->use_empty())
5039 bool IsAPhi = isa<PHINode>(Cur);
5041 // A header PHI use other than the original PHI.
5042 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
5045 // Reductions of instructions such as Div, and Sub is only possible if the
5046 // LHS is the reduction variable.
5047 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
5048 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
5049 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
5052 // Any reduction instruction must be of one of the allowed kinds.
5053 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
5054 if (!ReduxDesc.IsReduction)
5057 // A reduction operation must only have one use of the reduction value.
5058 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
5059 hasMultipleUsesOf(Cur, VisitedInsts))
5062 // All inputs to a PHI node must be a reduction value.
5063 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
5066 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
5067 isa<SelectInst>(Cur)))
5068 ++NumCmpSelectPatternInst;
5069 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
5070 isa<SelectInst>(Cur)))
5071 ++NumCmpSelectPatternInst;
5073 // Check whether we found a reduction operator.
5074 FoundReduxOp |= !IsAPhi;
5076 // Process users of current instruction. Push non-PHI nodes after PHI nodes
5077 // onto the stack. This way we are going to have seen all inputs to PHI
5078 // nodes once we get to them.
5079 SmallVector<Instruction *, 8> NonPHIs;
5080 SmallVector<Instruction *, 8> PHIs;
5081 for (User *U : Cur->users()) {
5082 Instruction *UI = cast<Instruction>(U);
5084 // Check if we found the exit user.
5085 BasicBlock *Parent = UI->getParent();
5086 if (!TheLoop->contains(Parent)) {
5087 // Exit if you find multiple outside users or if the header phi node is
5088 // being used. In this case the user uses the value of the previous
5089 // iteration, in which case we would loose "VF-1" iterations of the
5090 // reduction operation if we vectorize.
5091 if (ExitInstruction != nullptr || Cur == Phi)
5094 // The instruction used by an outside user must be the last instruction
5095 // before we feed back to the reduction phi. Otherwise, we loose VF-1
5096 // operations on the value.
5097 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
5100 ExitInstruction = Cur;
5104 // Process instructions only once (termination). Each reduction cycle
5105 // value must only be used once, except by phi nodes and min/max
5106 // reductions which are represented as a cmp followed by a select.
5107 ReductionInstDesc IgnoredVal(false, nullptr);
5108 if (VisitedInsts.insert(UI).second) {
5109 if (isa<PHINode>(UI))
5112 NonPHIs.push_back(UI);
5113 } else if (!isa<PHINode>(UI) &&
5114 ((!isa<FCmpInst>(UI) &&
5115 !isa<ICmpInst>(UI) &&
5116 !isa<SelectInst>(UI)) ||
5117 !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
5120 // Remember that we completed the cycle.
5122 FoundStartPHI = true;
5124 Worklist.append(PHIs.begin(), PHIs.end());
5125 Worklist.append(NonPHIs.begin(), NonPHIs.end());
5128 // This means we have seen one but not the other instruction of the
5129 // pattern or more than just a select and cmp.
5130 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
5131 NumCmpSelectPatternInst != 2)
5134 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
5137 // We found a reduction var if we have reached the original phi node and we
5138 // only have a single instruction with out-of-loop users.
5140 // This instruction is allowed to have out-of-loop users.
5141 AllowedExit.insert(ExitInstruction);
5143 // Save the description of this reduction variable.
5144 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
5145 ReduxDesc.MinMaxKind);
5146 Reductions[Phi] = RD;
5147 // We've ended the cycle. This is a reduction variable if we have an
5148 // outside user and it has a binary op.
5153 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
5154 /// pattern corresponding to a min(X, Y) or max(X, Y).
5155 LoopVectorizationLegality::ReductionInstDesc
5156 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
5157 ReductionInstDesc &Prev) {
5159 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
5160 "Expect a select instruction");
5161 Instruction *Cmp = nullptr;
5162 SelectInst *Select = nullptr;
5164 // We must handle the select(cmp()) as a single instruction. Advance to the
5166 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
5167 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
5168 return ReductionInstDesc(false, I);
5169 return ReductionInstDesc(Select, Prev.MinMaxKind);
5172 // Only handle single use cases for now.
5173 if (!(Select = dyn_cast<SelectInst>(I)))
5174 return ReductionInstDesc(false, I);
5175 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
5176 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
5177 return ReductionInstDesc(false, I);
5178 if (!Cmp->hasOneUse())
5179 return ReductionInstDesc(false, I);
5184 // Look for a min/max pattern.
5185 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5186 return ReductionInstDesc(Select, MRK_UIntMin);
5187 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5188 return ReductionInstDesc(Select, MRK_UIntMax);
5189 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5190 return ReductionInstDesc(Select, MRK_SIntMax);
5191 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5192 return ReductionInstDesc(Select, MRK_SIntMin);
5193 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5194 return ReductionInstDesc(Select, MRK_FloatMin);
5195 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5196 return ReductionInstDesc(Select, MRK_FloatMax);
5197 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5198 return ReductionInstDesc(Select, MRK_FloatMin);
5199 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5200 return ReductionInstDesc(Select, MRK_FloatMax);
5202 return ReductionInstDesc(false, I);
5205 LoopVectorizationLegality::ReductionInstDesc
5206 LoopVectorizationLegality::isReductionInstr(Instruction *I,
5208 ReductionInstDesc &Prev) {
5209 bool FP = I->getType()->isFloatingPointTy();
5210 bool FastMath = FP && I->hasUnsafeAlgebra();
5211 switch (I->getOpcode()) {
5213 return ReductionInstDesc(false, I);
5214 case Instruction::PHI:
5215 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
5216 Kind != RK_FloatMinMax))
5217 return ReductionInstDesc(false, I);
5218 return ReductionInstDesc(I, Prev.MinMaxKind);
5219 case Instruction::Sub:
5220 case Instruction::Add:
5221 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
5222 case Instruction::Mul:
5223 return ReductionInstDesc(Kind == RK_IntegerMult, I);
5224 case Instruction::And:
5225 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
5226 case Instruction::Or:
5227 return ReductionInstDesc(Kind == RK_IntegerOr, I);
5228 case Instruction::Xor:
5229 return ReductionInstDesc(Kind == RK_IntegerXor, I);
5230 case Instruction::FMul:
5231 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
5232 case Instruction::FSub:
5233 case Instruction::FAdd:
5234 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
5235 case Instruction::FCmp:
5236 case Instruction::ICmp:
5237 case Instruction::Select:
5238 if (Kind != RK_IntegerMinMax &&
5239 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
5240 return ReductionInstDesc(false, I);
5241 return isMinMaxSelectCmpPattern(I, Prev);
5245 LoopVectorizationLegality::InductionKind
5246 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
5247 Type *PhiTy = Phi->getType();
5248 // We only handle integer and pointer inductions variables.
5249 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
5250 return IK_NoInduction;
5252 // Check that the PHI is consecutive.
5253 const SCEV *PhiScev = SE->getSCEV(Phi);
5254 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
5256 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
5257 return IK_NoInduction;
5259 const SCEV *Step = AR->getStepRecurrence(*SE);
5261 // Integer inductions need to have a stride of one.
5262 if (PhiTy->isIntegerTy()) {
5264 return IK_IntInduction;
5265 if (Step->isAllOnesValue())
5266 return IK_ReverseIntInduction;
5267 return IK_NoInduction;
5270 // Calculate the pointer stride and check if it is consecutive.
5271 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5273 return IK_NoInduction;
5275 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
5276 Type *PointerElementType = PhiTy->getPointerElementType();
5277 // The pointer stride cannot be determined if the pointer element type is not
5279 if (!PointerElementType->isSized())
5280 return IK_NoInduction;
5282 uint64_t Size = DL->getTypeAllocSize(PointerElementType);
5283 if (C->getValue()->equalsInt(Size))
5284 return IK_PtrInduction;
5285 else if (C->getValue()->equalsInt(0 - Size))
5286 return IK_ReversePtrInduction;
5288 return IK_NoInduction;
5291 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
5292 Value *In0 = const_cast<Value*>(V);
5293 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
5297 return Inductions.count(PN);
5300 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
5301 assert(TheLoop->contains(BB) && "Unknown block used");
5303 // Blocks that do not dominate the latch need predication.
5304 BasicBlock* Latch = TheLoop->getLoopLatch();
5305 return !DT->dominates(BB, Latch);
5308 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
5309 SmallPtrSetImpl<Value *> &SafePtrs) {
5310 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5311 // We might be able to hoist the load.
5312 if (it->mayReadFromMemory()) {
5313 LoadInst *LI = dyn_cast<LoadInst>(it);
5314 if (!LI || !SafePtrs.count(LI->getPointerOperand()))
5318 // We don't predicate stores at the moment.
5319 if (it->mayWriteToMemory()) {
5320 StoreInst *SI = dyn_cast<StoreInst>(it);
5321 // We only support predication of stores in basic blocks with one
5323 if (!SI || ++NumPredStores > NumberOfStoresToPredicate ||
5324 !SafePtrs.count(SI->getPointerOperand()) ||
5325 !SI->getParent()->getSinglePredecessor())
5331 // Check that we don't have a constant expression that can trap as operand.
5332 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
5334 if (Constant *C = dyn_cast<Constant>(*OI))
5339 // The instructions below can trap.
5340 switch (it->getOpcode()) {
5342 case Instruction::UDiv:
5343 case Instruction::SDiv:
5344 case Instruction::URem:
5345 case Instruction::SRem:
5353 LoopVectorizationCostModel::VectorizationFactor
5354 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
5355 // Width 1 means no vectorize
5356 VectorizationFactor Factor = { 1U, 0U };
5357 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
5358 emitAnalysis(Report() << "runtime pointer checks needed. Enable vectorization of this loop with '#pragma clang loop vectorize(enable)' when compiling with -Os");
5359 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
5363 if (!EnableCondStoresVectorization && Legal->NumPredStores) {
5364 emitAnalysis(Report() << "store that is conditionally executed prevents vectorization");
5365 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
5369 // Find the trip count.
5370 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
5371 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5373 unsigned WidestType = getWidestType();
5374 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
5375 unsigned MaxSafeDepDist = -1U;
5376 if (Legal->getMaxSafeDepDistBytes() != -1U)
5377 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5378 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
5379 WidestRegister : MaxSafeDepDist);
5380 unsigned MaxVectorSize = WidestRegister / WidestType;
5381 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
5382 DEBUG(dbgs() << "LV: The Widest register is: "
5383 << WidestRegister << " bits.\n");
5385 if (MaxVectorSize == 0) {
5386 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5390 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
5391 " into one vector!");
5393 unsigned VF = MaxVectorSize;
5395 // If we optimize the program for size, avoid creating the tail loop.
5397 // If we are unable to calculate the trip count then don't try to vectorize.
5399 emitAnalysis(Report() << "unable to calculate the loop count due to complex control flow");
5400 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5404 // Find the maximum SIMD width that can fit within the trip count.
5405 VF = TC % MaxVectorSize;
5410 // If the trip count that we found modulo the vectorization factor is not
5411 // zero then we require a tail.
5413 emitAnalysis(Report() << "cannot optimize for size and vectorize at the "
5414 "same time. Enable vectorization of this loop "
5415 "with '#pragma clang loop vectorize(enable)' "
5416 "when compiling with -Os");
5417 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5422 int UserVF = Hints->getWidth();
5424 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
5425 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5427 Factor.Width = UserVF;
5431 float Cost = expectedCost(1);
5433 const float ScalarCost = Cost;
5436 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
5438 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5439 // Ignore scalar width, because the user explicitly wants vectorization.
5440 if (ForceVectorization && VF > 1) {
5442 Cost = expectedCost(Width) / (float)Width;
5445 for (unsigned i=2; i <= VF; i*=2) {
5446 // Notice that the vector loop needs to be executed less times, so
5447 // we need to divide the cost of the vector loops by the width of
5448 // the vector elements.
5449 float VectorCost = expectedCost(i) / (float)i;
5450 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
5451 (int)VectorCost << ".\n");
5452 if (VectorCost < Cost) {
5458 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
5459 << "LV: Vectorization seems to be not beneficial, "
5460 << "but was forced by a user.\n");
5461 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
5462 Factor.Width = Width;
5463 Factor.Cost = Width * Cost;
5467 unsigned LoopVectorizationCostModel::getWidestType() {
5468 unsigned MaxWidth = 8;
5471 for (Loop::block_iterator bb = TheLoop->block_begin(),
5472 be = TheLoop->block_end(); bb != be; ++bb) {
5473 BasicBlock *BB = *bb;
5475 // For each instruction in the loop.
5476 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5477 Type *T = it->getType();
5479 // Ignore ephemeral values.
5480 if (EphValues.count(it))
5483 // Only examine Loads, Stores and PHINodes.
5484 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
5487 // Examine PHI nodes that are reduction variables.
5488 if (PHINode *PN = dyn_cast<PHINode>(it))
5489 if (!Legal->getReductionVars()->count(PN))
5492 // Examine the stored values.
5493 if (StoreInst *ST = dyn_cast<StoreInst>(it))
5494 T = ST->getValueOperand()->getType();
5496 // Ignore loaded pointer types and stored pointer types that are not
5497 // consecutive. However, we do want to take consecutive stores/loads of
5498 // pointer vectors into account.
5499 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
5502 MaxWidth = std::max(MaxWidth,
5503 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
5511 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
5513 unsigned LoopCost) {
5515 // -- The unroll heuristics --
5516 // We unroll the loop in order to expose ILP and reduce the loop overhead.
5517 // There are many micro-architectural considerations that we can't predict
5518 // at this level. For example, frontend pressure (on decode or fetch) due to
5519 // code size, or the number and capabilities of the execution ports.
5521 // We use the following heuristics to select the unroll factor:
5522 // 1. If the code has reductions, then we unroll in order to break the cross
5523 // iteration dependency.
5524 // 2. If the loop is really small, then we unroll in order to reduce the loop
5526 // 3. We don't unroll if we think that we will spill registers to memory due
5527 // to the increased register pressure.
5529 // Use the user preference, unless 'auto' is selected.
5530 int UserUF = Hints->getInterleave();
5534 // When we optimize for size, we don't unroll.
5538 // We used the distance for the unroll factor.
5539 if (Legal->getMaxSafeDepDistBytes() != -1U)
5542 // Do not unroll loops with a relatively small trip count.
5543 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
5544 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
5547 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5548 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
5552 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5553 TargetNumRegisters = ForceTargetNumScalarRegs;
5555 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5556 TargetNumRegisters = ForceTargetNumVectorRegs;
5559 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
5560 // We divide by these constants so assume that we have at least one
5561 // instruction that uses at least one register.
5562 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5563 R.NumInstructions = std::max(R.NumInstructions, 1U);
5565 // We calculate the unroll factor using the following formula.
5566 // Subtract the number of loop invariants from the number of available
5567 // registers. These registers are used by all of the unrolled instances.
5568 // Next, divide the remaining registers by the number of registers that is
5569 // required by the loop, in order to estimate how many parallel instances
5570 // fit without causing spills. All of this is rounded down if necessary to be
5571 // a power of two. We want power of two unroll factors to simplify any
5572 // addressing operations or alignment considerations.
5573 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5576 // Don't count the induction variable as unrolled.
5577 if (EnableIndVarRegisterHeur)
5578 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
5579 std::max(1U, (R.MaxLocalUsers - 1)));
5581 // Clamp the unroll factor ranges to reasonable factors.
5582 unsigned MaxInterleaveSize = TTI.getMaxInterleaveFactor();
5584 // Check if the user has overridden the unroll max.
5586 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
5587 MaxInterleaveSize = ForceTargetMaxScalarInterleaveFactor;
5589 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
5590 MaxInterleaveSize = ForceTargetMaxVectorInterleaveFactor;
5593 // If we did not calculate the cost for VF (because the user selected the VF)
5594 // then we calculate the cost of VF here.
5596 LoopCost = expectedCost(VF);
5598 // Clamp the calculated UF to be between the 1 and the max unroll factor
5599 // that the target allows.
5600 if (UF > MaxInterleaveSize)
5601 UF = MaxInterleaveSize;
5605 // Unroll if we vectorized this loop and there is a reduction that could
5606 // benefit from unrolling.
5607 if (VF > 1 && Legal->getReductionVars()->size()) {
5608 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
5612 // Note that if we've already vectorized the loop we will have done the
5613 // runtime check and so unrolling won't require further checks.
5614 bool UnrollingRequiresRuntimePointerCheck =
5615 (VF == 1 && Legal->getRuntimePointerCheck()->Need);
5617 // We want to unroll small loops in order to reduce the loop overhead and
5618 // potentially expose ILP opportunities.
5619 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5620 if (!UnrollingRequiresRuntimePointerCheck &&
5621 LoopCost < SmallLoopCost) {
5622 // We assume that the cost overhead is 1 and we use the cost model
5623 // to estimate the cost of the loop and unroll until the cost of the
5624 // loop overhead is about 5% of the cost of the loop.
5625 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5627 // Unroll until store/load ports (estimated by max unroll factor) are
5629 unsigned StoresUF = UF / (Legal->NumStores ? Legal->NumStores : 1);
5630 unsigned LoadsUF = UF / (Legal->NumLoads ? Legal->NumLoads : 1);
5632 // If we have a scalar reduction (vector reductions are already dealt with
5633 // by this point), we can increase the critical path length if the loop
5634 // we're unrolling is inside another loop. Limit, by default to 2, so the
5635 // critical path only gets increased by one reduction operation.
5636 if (Legal->getReductionVars()->size() &&
5637 TheLoop->getLoopDepth() > 1) {
5638 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionUF);
5639 SmallUF = std::min(SmallUF, F);
5640 StoresUF = std::min(StoresUF, F);
5641 LoadsUF = std::min(LoadsUF, F);
5644 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
5645 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
5646 return std::max(StoresUF, LoadsUF);
5649 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
5653 DEBUG(dbgs() << "LV: Not Unrolling.\n");
5657 LoopVectorizationCostModel::RegisterUsage
5658 LoopVectorizationCostModel::calculateRegisterUsage() {
5659 // This function calculates the register usage by measuring the highest number
5660 // of values that are alive at a single location. Obviously, this is a very
5661 // rough estimation. We scan the loop in a topological order in order and
5662 // assign a number to each instruction. We use RPO to ensure that defs are
5663 // met before their users. We assume that each instruction that has in-loop
5664 // users starts an interval. We record every time that an in-loop value is
5665 // used, so we have a list of the first and last occurrences of each
5666 // instruction. Next, we transpose this data structure into a multi map that
5667 // holds the list of intervals that *end* at a specific location. This multi
5668 // map allows us to perform a linear search. We scan the instructions linearly
5669 // and record each time that a new interval starts, by placing it in a set.
5670 // If we find this value in the multi-map then we remove it from the set.
5671 // The max register usage is the maximum size of the set.
5672 // We also search for instructions that are defined outside the loop, but are
5673 // used inside the loop. We need this number separately from the max-interval
5674 // usage number because when we unroll, loop-invariant values do not take
5676 LoopBlocksDFS DFS(TheLoop);
5680 R.NumInstructions = 0;
5682 // Each 'key' in the map opens a new interval. The values
5683 // of the map are the index of the 'last seen' usage of the
5684 // instruction that is the key.
5685 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5686 // Maps instruction to its index.
5687 DenseMap<unsigned, Instruction*> IdxToInstr;
5688 // Marks the end of each interval.
5689 IntervalMap EndPoint;
5690 // Saves the list of instruction indices that are used in the loop.
5691 SmallSet<Instruction*, 8> Ends;
5692 // Saves the list of values that are used in the loop but are
5693 // defined outside the loop, such as arguments and constants.
5694 SmallPtrSet<Value*, 8> LoopInvariants;
5697 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5698 be = DFS.endRPO(); bb != be; ++bb) {
5699 R.NumInstructions += (*bb)->size();
5700 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5702 Instruction *I = it;
5703 IdxToInstr[Index++] = I;
5705 // Save the end location of each USE.
5706 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5707 Value *U = I->getOperand(i);
5708 Instruction *Instr = dyn_cast<Instruction>(U);
5710 // Ignore non-instruction values such as arguments, constants, etc.
5711 if (!Instr) continue;
5713 // If this instruction is outside the loop then record it and continue.
5714 if (!TheLoop->contains(Instr)) {
5715 LoopInvariants.insert(Instr);
5719 // Overwrite previous end points.
5720 EndPoint[Instr] = Index;
5726 // Saves the list of intervals that end with the index in 'key'.
5727 typedef SmallVector<Instruction*, 2> InstrList;
5728 DenseMap<unsigned, InstrList> TransposeEnds;
5730 // Transpose the EndPoints to a list of values that end at each index.
5731 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5733 TransposeEnds[it->second].push_back(it->first);
5735 SmallSet<Instruction*, 8> OpenIntervals;
5736 unsigned MaxUsage = 0;
5739 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5740 for (unsigned int i = 0; i < Index; ++i) {
5741 Instruction *I = IdxToInstr[i];
5742 // Ignore instructions that are never used within the loop.
5743 if (!Ends.count(I)) continue;
5745 // Ignore ephemeral values.
5746 if (EphValues.count(I))
5749 // Remove all of the instructions that end at this location.
5750 InstrList &List = TransposeEnds[i];
5751 for (unsigned int j=0, e = List.size(); j < e; ++j)
5752 OpenIntervals.erase(List[j]);
5754 // Count the number of live interals.
5755 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5757 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5758 OpenIntervals.size() << '\n');
5760 // Add the current instruction to the list of open intervals.
5761 OpenIntervals.insert(I);
5764 unsigned Invariant = LoopInvariants.size();
5765 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5766 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5767 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5769 R.LoopInvariantRegs = Invariant;
5770 R.MaxLocalUsers = MaxUsage;
5774 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5778 for (Loop::block_iterator bb = TheLoop->block_begin(),
5779 be = TheLoop->block_end(); bb != be; ++bb) {
5780 unsigned BlockCost = 0;
5781 BasicBlock *BB = *bb;
5783 // For each instruction in the old loop.
5784 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5785 // Skip dbg intrinsics.
5786 if (isa<DbgInfoIntrinsic>(it))
5789 // Ignore ephemeral values.
5790 if (EphValues.count(it))
5793 unsigned C = getInstructionCost(it, VF);
5795 // Check if we should override the cost.
5796 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5797 C = ForceTargetInstructionCost;
5800 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5801 VF << " For instruction: " << *it << '\n');
5804 // We assume that if-converted blocks have a 50% chance of being executed.
5805 // When the code is scalar then some of the blocks are avoided due to CF.
5806 // When the code is vectorized we execute all code paths.
5807 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5816 /// \brief Check whether the address computation for a non-consecutive memory
5817 /// access looks like an unlikely candidate for being merged into the indexing
5820 /// We look for a GEP which has one index that is an induction variable and all
5821 /// other indices are loop invariant. If the stride of this access is also
5822 /// within a small bound we decide that this address computation can likely be
5823 /// merged into the addressing mode.
5824 /// In all other cases, we identify the address computation as complex.
5825 static bool isLikelyComplexAddressComputation(Value *Ptr,
5826 LoopVectorizationLegality *Legal,
5827 ScalarEvolution *SE,
5828 const Loop *TheLoop) {
5829 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5833 // We are looking for a gep with all loop invariant indices except for one
5834 // which should be an induction variable.
5835 unsigned NumOperands = Gep->getNumOperands();
5836 for (unsigned i = 1; i < NumOperands; ++i) {
5837 Value *Opd = Gep->getOperand(i);
5838 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5839 !Legal->isInductionVariable(Opd))
5843 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5844 // can likely be merged into the address computation.
5845 unsigned MaxMergeDistance = 64;
5847 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5851 // Check the step is constant.
5852 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5853 // Calculate the pointer stride and check if it is consecutive.
5854 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5858 const APInt &APStepVal = C->getValue()->getValue();
5860 // Huge step value - give up.
5861 if (APStepVal.getBitWidth() > 64)
5864 int64_t StepVal = APStepVal.getSExtValue();
5866 return StepVal > MaxMergeDistance;
5869 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5870 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5876 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5877 // If we know that this instruction will remain uniform, check the cost of
5878 // the scalar version.
5879 if (Legal->isUniformAfterVectorization(I))
5882 Type *RetTy = I->getType();
5883 Type *VectorTy = ToVectorTy(RetTy, VF);
5885 // TODO: We need to estimate the cost of intrinsic calls.
5886 switch (I->getOpcode()) {
5887 case Instruction::GetElementPtr:
5888 // We mark this instruction as zero-cost because the cost of GEPs in
5889 // vectorized code depends on whether the corresponding memory instruction
5890 // is scalarized or not. Therefore, we handle GEPs with the memory
5891 // instruction cost.
5893 case Instruction::Br: {
5894 return TTI.getCFInstrCost(I->getOpcode());
5896 case Instruction::PHI:
5897 //TODO: IF-converted IFs become selects.
5899 case Instruction::Add:
5900 case Instruction::FAdd:
5901 case Instruction::Sub:
5902 case Instruction::FSub:
5903 case Instruction::Mul:
5904 case Instruction::FMul:
5905 case Instruction::UDiv:
5906 case Instruction::SDiv:
5907 case Instruction::FDiv:
5908 case Instruction::URem:
5909 case Instruction::SRem:
5910 case Instruction::FRem:
5911 case Instruction::Shl:
5912 case Instruction::LShr:
5913 case Instruction::AShr:
5914 case Instruction::And:
5915 case Instruction::Or:
5916 case Instruction::Xor: {
5917 // Since we will replace the stride by 1 the multiplication should go away.
5918 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5920 // Certain instructions can be cheaper to vectorize if they have a constant
5921 // second vector operand. One example of this are shifts on x86.
5922 TargetTransformInfo::OperandValueKind Op1VK =
5923 TargetTransformInfo::OK_AnyValue;
5924 TargetTransformInfo::OperandValueKind Op2VK =
5925 TargetTransformInfo::OK_AnyValue;
5926 TargetTransformInfo::OperandValueProperties Op1VP =
5927 TargetTransformInfo::OP_None;
5928 TargetTransformInfo::OperandValueProperties Op2VP =
5929 TargetTransformInfo::OP_None;
5930 Value *Op2 = I->getOperand(1);
5932 // Check for a splat of a constant or for a non uniform vector of constants.
5933 if (isa<ConstantInt>(Op2)) {
5934 ConstantInt *CInt = cast<ConstantInt>(Op2);
5935 if (CInt && CInt->getValue().isPowerOf2())
5936 Op2VP = TargetTransformInfo::OP_PowerOf2;
5937 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5938 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5939 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5940 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
5942 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
5943 if (CInt && CInt->getValue().isPowerOf2())
5944 Op2VP = TargetTransformInfo::OP_PowerOf2;
5945 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5949 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
5952 case Instruction::Select: {
5953 SelectInst *SI = cast<SelectInst>(I);
5954 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5955 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5956 Type *CondTy = SI->getCondition()->getType();
5958 CondTy = VectorType::get(CondTy, VF);
5960 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5962 case Instruction::ICmp:
5963 case Instruction::FCmp: {
5964 Type *ValTy = I->getOperand(0)->getType();
5965 VectorTy = ToVectorTy(ValTy, VF);
5966 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5968 case Instruction::Store:
5969 case Instruction::Load: {
5970 StoreInst *SI = dyn_cast<StoreInst>(I);
5971 LoadInst *LI = dyn_cast<LoadInst>(I);
5972 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5974 VectorTy = ToVectorTy(ValTy, VF);
5976 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5977 unsigned AS = SI ? SI->getPointerAddressSpace() :
5978 LI->getPointerAddressSpace();
5979 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5980 // We add the cost of address computation here instead of with the gep
5981 // instruction because only here we know whether the operation is
5984 return TTI.getAddressComputationCost(VectorTy) +
5985 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5987 // Scalarized loads/stores.
5988 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5989 bool Reverse = ConsecutiveStride < 0;
5990 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
5991 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
5992 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5993 bool IsComplexComputation =
5994 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5996 // The cost of extracting from the value vector and pointer vector.
5997 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5998 for (unsigned i = 0; i < VF; ++i) {
5999 // The cost of extracting the pointer operand.
6000 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
6001 // In case of STORE, the cost of ExtractElement from the vector.
6002 // In case of LOAD, the cost of InsertElement into the returned
6004 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
6005 Instruction::InsertElement,
6009 // The cost of the scalar loads/stores.
6010 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
6011 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
6016 // Wide load/stores.
6017 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
6018 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
6021 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
6025 case Instruction::ZExt:
6026 case Instruction::SExt:
6027 case Instruction::FPToUI:
6028 case Instruction::FPToSI:
6029 case Instruction::FPExt:
6030 case Instruction::PtrToInt:
6031 case Instruction::IntToPtr:
6032 case Instruction::SIToFP:
6033 case Instruction::UIToFP:
6034 case Instruction::Trunc:
6035 case Instruction::FPTrunc:
6036 case Instruction::BitCast: {
6037 // We optimize the truncation of induction variable.
6038 // The cost of these is the same as the scalar operation.
6039 if (I->getOpcode() == Instruction::Trunc &&
6040 Legal->isInductionVariable(I->getOperand(0)))
6041 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
6042 I->getOperand(0)->getType());
6044 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
6045 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
6047 case Instruction::Call: {
6048 CallInst *CI = cast<CallInst>(I);
6049 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
6050 assert(ID && "Not an intrinsic call!");
6051 Type *RetTy = ToVectorTy(CI->getType(), VF);
6052 SmallVector<Type*, 4> Tys;
6053 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
6054 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
6055 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
6058 // We are scalarizing the instruction. Return the cost of the scalar
6059 // instruction, plus the cost of insert and extract into vector
6060 // elements, times the vector width.
6063 if (!RetTy->isVoidTy() && VF != 1) {
6064 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
6066 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
6069 // The cost of inserting the results plus extracting each one of the
6071 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
6074 // The cost of executing VF copies of the scalar instruction. This opcode
6075 // is unknown. Assume that it is the same as 'mul'.
6076 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
6082 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
6083 if (Scalar->isVoidTy() || VF == 1)
6085 return VectorType::get(Scalar, VF);
6088 char LoopVectorize::ID = 0;
6089 static const char lv_name[] = "Loop Vectorization";
6090 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
6091 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
6092 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
6093 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
6094 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
6095 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
6096 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
6097 INITIALIZE_PASS_DEPENDENCY(LCSSA)
6098 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
6099 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
6100 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
6103 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
6104 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
6108 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
6109 // Check for a store.
6110 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
6111 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
6113 // Check for a load.
6114 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
6115 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
6121 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
6122 bool IfPredicateStore) {
6123 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
6124 // Holds vector parameters or scalars, in case of uniform vals.
6125 SmallVector<VectorParts, 4> Params;
6127 setDebugLocFromInst(Builder, Instr);
6129 // Find all of the vectorized parameters.
6130 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
6131 Value *SrcOp = Instr->getOperand(op);
6133 // If we are accessing the old induction variable, use the new one.
6134 if (SrcOp == OldInduction) {
6135 Params.push_back(getVectorValue(SrcOp));
6139 // Try using previously calculated values.
6140 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
6142 // If the src is an instruction that appeared earlier in the basic block
6143 // then it should already be vectorized.
6144 if (SrcInst && OrigLoop->contains(SrcInst)) {
6145 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
6146 // The parameter is a vector value from earlier.
6147 Params.push_back(WidenMap.get(SrcInst));
6149 // The parameter is a scalar from outside the loop. Maybe even a constant.
6150 VectorParts Scalars;
6151 Scalars.append(UF, SrcOp);
6152 Params.push_back(Scalars);
6156 assert(Params.size() == Instr->getNumOperands() &&
6157 "Invalid number of operands");
6159 // Does this instruction return a value ?
6160 bool IsVoidRetTy = Instr->getType()->isVoidTy();
6162 Value *UndefVec = IsVoidRetTy ? nullptr :
6163 UndefValue::get(Instr->getType());
6164 // Create a new entry in the WidenMap and initialize it to Undef or Null.
6165 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
6167 Instruction *InsertPt = Builder.GetInsertPoint();
6168 BasicBlock *IfBlock = Builder.GetInsertBlock();
6169 BasicBlock *CondBlock = nullptr;
6172 Loop *VectorLp = nullptr;
6173 if (IfPredicateStore) {
6174 assert(Instr->getParent()->getSinglePredecessor() &&
6175 "Only support single predecessor blocks");
6176 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
6177 Instr->getParent());
6178 VectorLp = LI->getLoopFor(IfBlock);
6179 assert(VectorLp && "Must have a loop for this block");
6182 // For each vector unroll 'part':
6183 for (unsigned Part = 0; Part < UF; ++Part) {
6184 // For each scalar that we create:
6186 // Start an "if (pred) a[i] = ..." block.
6187 Value *Cmp = nullptr;
6188 if (IfPredicateStore) {
6189 if (Cond[Part]->getType()->isVectorTy())
6191 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
6192 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
6193 ConstantInt::get(Cond[Part]->getType(), 1));
6194 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
6195 LoopVectorBody.push_back(CondBlock);
6196 VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
6197 // Update Builder with newly created basic block.
6198 Builder.SetInsertPoint(InsertPt);
6201 Instruction *Cloned = Instr->clone();
6203 Cloned->setName(Instr->getName() + ".cloned");
6204 // Replace the operands of the cloned instructions with extracted scalars.
6205 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
6206 Value *Op = Params[op][Part];
6207 Cloned->setOperand(op, Op);
6210 // Place the cloned scalar in the new loop.
6211 Builder.Insert(Cloned);
6213 // If the original scalar returns a value we need to place it in a vector
6214 // so that future users will be able to use it.
6216 VecResults[Part] = Cloned;
6219 if (IfPredicateStore) {
6220 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
6221 LoopVectorBody.push_back(NewIfBlock);
6222 VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
6223 Builder.SetInsertPoint(InsertPt);
6224 Instruction *OldBr = IfBlock->getTerminator();
6225 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
6226 OldBr->eraseFromParent();
6227 IfBlock = NewIfBlock;
6232 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
6233 StoreInst *SI = dyn_cast<StoreInst>(Instr);
6234 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
6236 return scalarizeInstruction(Instr, IfPredicateStore);
6239 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
6243 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
6247 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
6249 // When unrolling and the VF is 1, we only need to add a simple scalar.
6250 Type *ITy = Val->getType();
6251 assert(!ITy->isVectorTy() && "Val must be a scalar");
6252 Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
6253 return Builder.CreateAdd(Val, C, "induction");