1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR.
12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
13 // of instructions in order to estimate the profitability of vectorization.
15 // The loop vectorizer combines consecutive loop iterations into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A unit that checks for the legality
22 // of the vectorization.
23 // 3. InnerLoopVectorizer - A unit that performs the actual
24 // widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 // of vectorization. It decides on the optimal vector width, which
27 // can be one, if vectorization is not profitable.
29 //===----------------------------------------------------------------------===//
31 // The reduction-variable vectorization is based on the paper:
32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
37 // Other ideas/concepts are from:
38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
41 // Vectorizing Compilers.
43 //===----------------------------------------------------------------------===//
45 #include "llvm/Transforms/Vectorize.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/EquivalenceClasses.h"
48 #include "llvm/ADT/Hashing.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/ADT/StringExtras.h"
56 #include "llvm/Analysis/AliasAnalysis.h"
57 #include "llvm/Analysis/AliasSetTracker.h"
58 #include "llvm/Analysis/AssumptionCache.h"
59 #include "llvm/Analysis/BlockFrequencyInfo.h"
60 #include "llvm/Analysis/CodeMetrics.h"
61 #include "llvm/Analysis/LoopAccessAnalysis.h"
62 #include "llvm/Analysis/LoopInfo.h"
63 #include "llvm/Analysis/LoopIterator.h"
64 #include "llvm/Analysis/LoopPass.h"
65 #include "llvm/Analysis/ScalarEvolution.h"
66 #include "llvm/Analysis/ScalarEvolutionExpander.h"
67 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
68 #include "llvm/Analysis/TargetTransformInfo.h"
69 #include "llvm/Analysis/ValueTracking.h"
70 #include "llvm/IR/Constants.h"
71 #include "llvm/IR/DataLayout.h"
72 #include "llvm/IR/DebugInfo.h"
73 #include "llvm/IR/DerivedTypes.h"
74 #include "llvm/IR/DiagnosticInfo.h"
75 #include "llvm/IR/Dominators.h"
76 #include "llvm/IR/Function.h"
77 #include "llvm/IR/IRBuilder.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/LLVMContext.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/Value.h"
85 #include "llvm/IR/ValueHandle.h"
86 #include "llvm/IR/Verifier.h"
87 #include "llvm/Pass.h"
88 #include "llvm/Support/BranchProbability.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Transforms/Scalar.h"
93 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
94 #include "llvm/Transforms/Utils/Local.h"
95 #include "llvm/Transforms/Utils/VectorUtils.h"
100 using namespace llvm;
101 using namespace llvm::PatternMatch;
103 #define LV_NAME "loop-vectorize"
104 #define DEBUG_TYPE LV_NAME
106 STATISTIC(LoopsVectorized, "Number of loops vectorized");
107 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
110 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
111 cl::desc("Enable if-conversion during vectorization."));
113 /// We don't vectorize loops with a known constant trip count below this number.
114 static cl::opt<unsigned>
115 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
117 cl::desc("Don't vectorize loops with a constant "
118 "trip count that is smaller than this "
121 /// This enables versioning on the strides of symbolically striding memory
122 /// accesses in code like the following.
123 /// for (i = 0; i < N; ++i)
124 /// A[i * Stride1] += B[i * Stride2] ...
126 /// Will be roughly translated to
127 /// if (Stride1 == 1 && Stride2 == 1) {
128 /// for (i = 0; i < N; i+=4)
132 static cl::opt<bool> EnableMemAccessVersioning(
133 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
134 cl::desc("Enable symblic stride memory access versioning"));
136 /// We don't unroll loops with a known constant trip count below this number.
137 static const unsigned TinyTripCountUnrollThreshold = 128;
139 static cl::opt<unsigned> ForceTargetNumScalarRegs(
140 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
141 cl::desc("A flag that overrides the target's number of scalar registers."));
143 static cl::opt<unsigned> ForceTargetNumVectorRegs(
144 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
145 cl::desc("A flag that overrides the target's number of vector registers."));
147 /// Maximum vectorization interleave count.
148 static const unsigned MaxInterleaveFactor = 16;
150 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
151 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
152 cl::desc("A flag that overrides the target's max interleave factor for "
155 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
156 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
157 cl::desc("A flag that overrides the target's max interleave factor for "
158 "vectorized loops."));
160 static cl::opt<unsigned> ForceTargetInstructionCost(
161 "force-target-instruction-cost", cl::init(0), cl::Hidden,
162 cl::desc("A flag that overrides the target's expected cost for "
163 "an instruction to a single constant value. Mostly "
164 "useful for getting consistent testing."));
166 static cl::opt<unsigned> SmallLoopCost(
167 "small-loop-cost", cl::init(20), cl::Hidden,
168 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
170 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
171 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
172 cl::desc("Enable the use of the block frequency analysis to access PGO "
173 "heuristics minimizing code growth in cold regions and being more "
174 "aggressive in hot regions."));
176 // Runtime unroll loops for load/store throughput.
177 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
178 "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
179 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
181 /// The number of stores in a loop that are allowed to need predication.
182 static cl::opt<unsigned> NumberOfStoresToPredicate(
183 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
184 cl::desc("Max number of stores to be predicated behind an if."));
186 static cl::opt<bool> EnableIndVarRegisterHeur(
187 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
188 cl::desc("Count the induction variable only once when unrolling"));
190 static cl::opt<bool> EnableCondStoresVectorization(
191 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
192 cl::desc("Enable if predication of stores during vectorization."));
194 static cl::opt<unsigned> MaxNestedScalarReductionUF(
195 "max-nested-scalar-reduction-unroll", cl::init(2), cl::Hidden,
196 cl::desc("The maximum unroll factor to use when unrolling a scalar "
197 "reduction in a nested loop."));
201 // Forward declarations.
202 class LoopVectorizationLegality;
203 class LoopVectorizationCostModel;
204 class LoopVectorizeHints;
206 /// \brief This modifies LoopAccessReport to initialize message with
207 /// loop-vectorizer-specific part.
208 class VectorizationReport : public LoopAccessReport {
210 VectorizationReport(Instruction *I = nullptr)
211 : LoopAccessReport("loop not vectorized: ", I) {}
213 /// \brief This allows promotion of the loop-access analysis report into the
214 /// loop-vectorizer report. It modifies the message to add the
215 /// loop-vectorizer-specific part of the message.
216 explicit VectorizationReport(const LoopAccessReport &R)
217 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
221 /// A helper function for converting Scalar types to vector types.
222 /// If the incoming type is void, we return void. If the VF is 1, we return
224 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
225 if (Scalar->isVoidTy() || VF == 1)
227 return VectorType::get(Scalar, VF);
230 /// InnerLoopVectorizer vectorizes loops which contain only one basic
231 /// block to a specified vectorization factor (VF).
232 /// This class performs the widening of scalars into vectors, or multiple
233 /// scalars. This class also implements the following features:
234 /// * It inserts an epilogue loop for handling loops that don't have iteration
235 /// counts that are known to be a multiple of the vectorization factor.
236 /// * It handles the code generation for reduction variables.
237 /// * Scalarization (implementation using scalars) of un-vectorizable
239 /// InnerLoopVectorizer does not perform any vectorization-legality
240 /// checks, and relies on the caller to check for the different legality
241 /// aspects. The InnerLoopVectorizer relies on the
242 /// LoopVectorizationLegality class to provide information about the induction
243 /// and reduction variables that were found to a given vectorization factor.
244 class InnerLoopVectorizer {
246 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
247 DominatorTree *DT, const TargetLibraryInfo *TLI,
248 unsigned VecWidth, unsigned UnrollFactor)
249 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), TLI(TLI), VF(VecWidth),
250 UF(UnrollFactor), Builder(SE->getContext()), Induction(nullptr),
251 OldInduction(nullptr), WidenMap(UnrollFactor), Legal(nullptr),
252 AddedSafetyChecks(false) {}
254 // Perform the actual loop widening (vectorization).
255 void vectorize(LoopVectorizationLegality *L) {
257 // Create a new empty loop. Unlink the old loop and connect the new one.
259 // Widen each instruction in the old loop to a new one in the new loop.
260 // Use the Legality module to find the induction and reduction variables.
262 // Register the new loop and update the analysis passes.
266 // Return true if any runtime check is added.
267 bool IsSafetyChecksAdded() {
268 return AddedSafetyChecks;
271 virtual ~InnerLoopVectorizer() {}
274 /// A small list of PHINodes.
275 typedef SmallVector<PHINode*, 4> PhiVector;
276 /// When we unroll loops we have multiple vector values for each scalar.
277 /// This data structure holds the unrolled and vectorized values that
278 /// originated from one scalar instruction.
279 typedef SmallVector<Value*, 2> VectorParts;
281 // When we if-convert we need create edge masks. We have to cache values so
282 // that we don't end up with exponential recursion/IR.
283 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
284 VectorParts> EdgeMaskCache;
286 /// \brief Add checks for strides that where assumed to be 1.
288 /// Returns the last check instruction and the first check instruction in the
289 /// pair as (first, last).
290 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
292 /// Create an empty loop, based on the loop ranges of the old loop.
293 void createEmptyLoop();
294 /// Copy and widen the instructions from the old loop.
295 virtual void vectorizeLoop();
297 /// \brief The Loop exit block may have single value PHI nodes where the
298 /// incoming value is 'Undef'. While vectorizing we only handled real values
299 /// that were defined inside the loop. Here we fix the 'undef case'.
303 /// A helper function that computes the predicate of the block BB, assuming
304 /// that the header block of the loop is set to True. It returns the *entry*
305 /// mask for the block BB.
306 VectorParts createBlockInMask(BasicBlock *BB);
307 /// A helper function that computes the predicate of the edge between SRC
309 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
311 /// A helper function to vectorize a single BB within the innermost loop.
312 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
314 /// Vectorize a single PHINode in a block. This method handles the induction
315 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
316 /// arbitrary length vectors.
317 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
318 unsigned UF, unsigned VF, PhiVector *PV);
320 /// Insert the new loop to the loop hierarchy and pass manager
321 /// and update the analysis passes.
322 void updateAnalysis();
324 /// This instruction is un-vectorizable. Implement it as a sequence
325 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
326 /// scalarized instruction behind an if block predicated on the control
327 /// dependence of the instruction.
328 virtual void scalarizeInstruction(Instruction *Instr,
329 bool IfPredicateStore=false);
331 /// Vectorize Load and Store instructions,
332 virtual void vectorizeMemoryInstruction(Instruction *Instr);
334 /// Create a broadcast instruction. This method generates a broadcast
335 /// instruction (shuffle) for loop invariant values and for the induction
336 /// value. If this is the induction variable then we extend it to N, N+1, ...
337 /// this is needed because each iteration in the loop corresponds to a SIMD
339 virtual Value *getBroadcastInstrs(Value *V);
341 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
342 /// to each vector element of Val. The sequence starts at StartIndex.
343 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
345 /// When we go over instructions in the basic block we rely on previous
346 /// values within the current basic block or on loop invariant values.
347 /// When we widen (vectorize) values we place them in the map. If the values
348 /// are not within the map, they have to be loop invariant, so we simply
349 /// broadcast them into a vector.
350 VectorParts &getVectorValue(Value *V);
352 /// Generate a shuffle sequence that will reverse the vector Vec.
353 virtual Value *reverseVector(Value *Vec);
355 /// This is a helper class that holds the vectorizer state. It maps scalar
356 /// instructions to vector instructions. When the code is 'unrolled' then
357 /// then a single scalar value is mapped to multiple vector parts. The parts
358 /// are stored in the VectorPart type.
360 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
362 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
364 /// \return True if 'Key' is saved in the Value Map.
365 bool has(Value *Key) const { return MapStorage.count(Key); }
367 /// Initializes a new entry in the map. Sets all of the vector parts to the
368 /// save value in 'Val'.
369 /// \return A reference to a vector with splat values.
370 VectorParts &splat(Value *Key, Value *Val) {
371 VectorParts &Entry = MapStorage[Key];
372 Entry.assign(UF, Val);
376 ///\return A reference to the value that is stored at 'Key'.
377 VectorParts &get(Value *Key) {
378 VectorParts &Entry = MapStorage[Key];
381 assert(Entry.size() == UF);
386 /// The unroll factor. Each entry in the map stores this number of vector
390 /// Map storage. We use std::map and not DenseMap because insertions to a
391 /// dense map invalidates its iterators.
392 std::map<Value *, VectorParts> MapStorage;
395 /// The original loop.
397 /// Scev analysis to use.
405 /// Target Library Info.
406 const TargetLibraryInfo *TLI;
408 /// The vectorization SIMD factor to use. Each vector will have this many
413 /// The vectorization unroll factor to use. Each scalar is vectorized to this
414 /// many different vector instructions.
417 /// The builder that we use
420 // --- Vectorization state ---
422 /// The vector-loop preheader.
423 BasicBlock *LoopVectorPreHeader;
424 /// The scalar-loop preheader.
425 BasicBlock *LoopScalarPreHeader;
426 /// Middle Block between the vector and the scalar.
427 BasicBlock *LoopMiddleBlock;
428 ///The ExitBlock of the scalar loop.
429 BasicBlock *LoopExitBlock;
430 ///The vector loop body.
431 SmallVector<BasicBlock *, 4> LoopVectorBody;
432 ///The scalar loop body.
433 BasicBlock *LoopScalarBody;
434 /// A list of all bypass blocks. The first block is the entry of the loop.
435 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
437 /// The new Induction variable which was added to the new block.
439 /// The induction variable of the old basic block.
440 PHINode *OldInduction;
441 /// Holds the extended (to the widest induction type) start index.
443 /// Maps scalars to widened vectors.
445 EdgeMaskCache MaskCache;
447 LoopVectorizationLegality *Legal;
449 // Record whether runtime check is added.
450 bool AddedSafetyChecks;
453 class InnerLoopUnroller : public InnerLoopVectorizer {
455 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
456 DominatorTree *DT, const TargetLibraryInfo *TLI,
457 unsigned UnrollFactor)
458 : InnerLoopVectorizer(OrigLoop, SE, LI, DT, TLI, 1, UnrollFactor) {}
461 void scalarizeInstruction(Instruction *Instr,
462 bool IfPredicateStore = false) override;
463 void vectorizeMemoryInstruction(Instruction *Instr) override;
464 Value *getBroadcastInstrs(Value *V) override;
465 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
466 Value *reverseVector(Value *Vec) override;
469 /// \brief Look for a meaningful debug location on the instruction or it's
471 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
476 if (I->getDebugLoc() != Empty)
479 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
480 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
481 if (OpInst->getDebugLoc() != Empty)
488 /// \brief Set the debug location in the builder using the debug location in the
490 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
491 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
492 B.SetCurrentDebugLocation(Inst->getDebugLoc());
494 B.SetCurrentDebugLocation(DebugLoc());
498 /// \return string containing a file name and a line # for the given loop.
499 static std::string getDebugLocString(const Loop *L) {
502 raw_string_ostream OS(Result);
503 const DebugLoc LoopDbgLoc = L->getStartLoc();
504 if (!LoopDbgLoc.isUnknown())
505 LoopDbgLoc.print(OS);
507 // Just print the module name.
508 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
515 /// \brief Propagate known metadata from one instruction to another.
516 static void propagateMetadata(Instruction *To, const Instruction *From) {
517 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
518 From->getAllMetadataOtherThanDebugLoc(Metadata);
520 for (auto M : Metadata) {
521 unsigned Kind = M.first;
523 // These are safe to transfer (this is safe for TBAA, even when we
524 // if-convert, because should that metadata have had a control dependency
525 // on the condition, and thus actually aliased with some other
526 // non-speculated memory access when the condition was false, this would be
527 // caught by the runtime overlap checks).
528 if (Kind != LLVMContext::MD_tbaa &&
529 Kind != LLVMContext::MD_alias_scope &&
530 Kind != LLVMContext::MD_noalias &&
531 Kind != LLVMContext::MD_fpmath)
534 To->setMetadata(Kind, M.second);
538 /// \brief Propagate known metadata from one instruction to a vector of others.
539 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
541 if (Instruction *I = dyn_cast<Instruction>(V))
542 propagateMetadata(I, From);
545 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
546 /// to what vectorization factor.
547 /// This class does not look at the profitability of vectorization, only the
548 /// legality. This class has two main kinds of checks:
549 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
550 /// will change the order of memory accesses in a way that will change the
551 /// correctness of the program.
552 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
553 /// checks for a number of different conditions, such as the availability of a
554 /// single induction variable, that all types are supported and vectorize-able,
555 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
556 /// This class is also used by InnerLoopVectorizer for identifying
557 /// induction variable and the different reduction variables.
558 class LoopVectorizationLegality {
560 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
561 TargetLibraryInfo *TLI, AliasAnalysis *AA,
562 Function *F, const TargetTransformInfo *TTI,
563 LoopAccessAnalysis *LAA)
564 : NumPredStores(0), TheLoop(L), SE(SE), TLI(TLI), TheFunction(F),
565 TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr), Induction(nullptr),
566 WidestIndTy(nullptr), HasFunNoNaNAttr(false) {}
568 /// This enum represents the kinds of reductions that we support.
570 RK_NoReduction, ///< Not a reduction.
571 RK_IntegerAdd, ///< Sum of integers.
572 RK_IntegerMult, ///< Product of integers.
573 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
574 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
575 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
576 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
577 RK_FloatAdd, ///< Sum of floats.
578 RK_FloatMult, ///< Product of floats.
579 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
582 /// This enum represents the kinds of inductions that we support.
584 IK_NoInduction, ///< Not an induction variable.
585 IK_IntInduction, ///< Integer induction variable. Step = C.
586 IK_PtrInduction ///< Pointer induction var. Step = C / sizeof(elem).
589 // This enum represents the kind of minmax reduction.
590 enum MinMaxReductionKind {
600 /// This struct holds information about reduction variables.
601 struct ReductionDescriptor {
602 ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
603 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
605 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
606 MinMaxReductionKind MK)
607 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
609 // The starting value of the reduction.
610 // It does not have to be zero!
611 TrackingVH<Value> StartValue;
612 // The instruction who's value is used outside the loop.
613 Instruction *LoopExitInstr;
614 // The kind of the reduction.
616 // If this a min/max reduction the kind of reduction.
617 MinMaxReductionKind MinMaxKind;
620 /// This POD struct holds information about a potential reduction operation.
621 struct ReductionInstDesc {
622 ReductionInstDesc(bool IsRedux, Instruction *I) :
623 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
625 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
626 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
628 // Is this instruction a reduction candidate.
630 // The last instruction in a min/max pattern (select of the select(icmp())
631 // pattern), or the current reduction instruction otherwise.
632 Instruction *PatternLastInst;
633 // If this is a min/max pattern the comparison predicate.
634 MinMaxReductionKind MinMaxKind;
637 /// A struct for saving information about induction variables.
638 struct InductionInfo {
639 InductionInfo(Value *Start, InductionKind K, ConstantInt *Step)
640 : StartValue(Start), IK(K), StepValue(Step) {
641 assert(IK != IK_NoInduction && "Not an induction");
642 assert(StartValue && "StartValue is null");
643 assert(StepValue && !StepValue->isZero() && "StepValue is zero");
644 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
645 "StartValue is not a pointer for pointer induction");
646 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
647 "StartValue is not an integer for integer induction");
648 assert(StepValue->getType()->isIntegerTy() &&
649 "StepValue is not an integer");
652 : StartValue(nullptr), IK(IK_NoInduction), StepValue(nullptr) {}
654 /// Get the consecutive direction. Returns:
655 /// 0 - unknown or non-consecutive.
656 /// 1 - consecutive and increasing.
657 /// -1 - consecutive and decreasing.
658 int getConsecutiveDirection() const {
659 if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
660 return StepValue->getSExtValue();
664 /// Compute the transformed value of Index at offset StartValue using step
666 /// For integer induction, returns StartValue + Index * StepValue.
667 /// For pointer induction, returns StartValue[Index * StepValue].
668 /// FIXME: The newly created binary instructions should contain nsw/nuw
669 /// flags, which can be found from the original scalar operations.
670 Value *transform(IRBuilder<> &B, Value *Index) const {
672 case IK_IntInduction:
673 assert(Index->getType() == StartValue->getType() &&
674 "Index type does not match StartValue type");
675 if (StepValue->isMinusOne())
676 return B.CreateSub(StartValue, Index);
677 if (!StepValue->isOne())
678 Index = B.CreateMul(Index, StepValue);
679 return B.CreateAdd(StartValue, Index);
681 case IK_PtrInduction:
682 if (StepValue->isMinusOne())
683 Index = B.CreateNeg(Index);
684 else if (!StepValue->isOne())
685 Index = B.CreateMul(Index, StepValue);
686 return B.CreateGEP(StartValue, Index);
691 llvm_unreachable("invalid enum");
695 TrackingVH<Value> StartValue;
699 ConstantInt *StepValue;
702 /// ReductionList contains the reduction descriptors for all
703 /// of the reductions that were found in the loop.
704 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
706 /// InductionList saves induction variables and maps them to the
707 /// induction descriptor.
708 typedef MapVector<PHINode*, InductionInfo> InductionList;
710 /// Returns true if it is legal to vectorize this loop.
711 /// This does not mean that it is profitable to vectorize this
712 /// loop, only that it is legal to do so.
715 /// Returns the Induction variable.
716 PHINode *getInduction() { return Induction; }
718 /// Returns the reduction variables found in the loop.
719 ReductionList *getReductionVars() { return &Reductions; }
721 /// Returns the induction variables found in the loop.
722 InductionList *getInductionVars() { return &Inductions; }
724 /// Returns the widest induction type.
725 Type *getWidestInductionType() { return WidestIndTy; }
727 /// Returns True if V is an induction variable in this loop.
728 bool isInductionVariable(const Value *V);
730 /// Return true if the block BB needs to be predicated in order for the loop
731 /// to be vectorized.
732 bool blockNeedsPredication(BasicBlock *BB);
734 /// Check if this pointer is consecutive when vectorizing. This happens
735 /// when the last index of the GEP is the induction variable, or that the
736 /// pointer itself is an induction variable.
737 /// This check allows us to vectorize A[idx] into a wide load/store.
739 /// 0 - Stride is unknown or non-consecutive.
740 /// 1 - Address is consecutive.
741 /// -1 - Address is consecutive, and decreasing.
742 int isConsecutivePtr(Value *Ptr);
744 /// Returns true if the value V is uniform within the loop.
745 bool isUniform(Value *V);
747 /// Returns true if this instruction will remain scalar after vectorization.
748 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
750 /// Returns the information that we collected about runtime memory check.
751 const LoopAccessInfo::RuntimePointerCheck *getRuntimePointerCheck() const {
752 return LAI->getRuntimePointerCheck();
755 const LoopAccessInfo *getLAI() const {
759 /// This function returns the identity element (or neutral element) for
761 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
763 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
765 bool hasStride(Value *V) { return StrideSet.count(V); }
766 bool mustCheckStrides() { return !StrideSet.empty(); }
767 SmallPtrSet<Value *, 8>::iterator strides_begin() {
768 return StrideSet.begin();
770 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
772 /// Returns true if the target machine supports masked store operation
773 /// for the given \p DataType and kind of access to \p Ptr.
774 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
775 return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
777 /// Returns true if the target machine supports masked load operation
778 /// for the given \p DataType and kind of access to \p Ptr.
779 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
780 return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
782 /// Returns true if vector representation of the instruction \p I
784 bool isMaskRequired(const Instruction* I) {
785 return (MaskedOp.count(I) != 0);
787 unsigned getNumStores() const {
788 return LAI->getNumStores();
790 unsigned getNumLoads() const {
791 return LAI->getNumLoads();
793 unsigned getNumPredStores() const {
794 return NumPredStores;
797 /// Check if a single basic block loop is vectorizable.
798 /// At this point we know that this is a loop with a constant trip count
799 /// and we only need to check individual instructions.
800 bool canVectorizeInstrs();
802 /// When we vectorize loops we may change the order in which
803 /// we read and write from memory. This method checks if it is
804 /// legal to vectorize the code, considering only memory constrains.
805 /// Returns true if the loop is vectorizable
806 bool canVectorizeMemory();
808 /// Return true if we can vectorize this loop using the IF-conversion
810 bool canVectorizeWithIfConvert();
812 /// Collect the variables that need to stay uniform after vectorization.
813 void collectLoopUniforms();
815 /// Return true if all of the instructions in the block can be speculatively
816 /// executed. \p SafePtrs is a list of addresses that are known to be legal
817 /// and we know that we can read from them without segfault.
818 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
820 /// Returns True, if 'Phi' is the kind of reduction variable for type
821 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
822 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
823 /// Returns a struct describing if the instruction 'I' can be a reduction
824 /// variable of type 'Kind'. If the reduction is a min/max pattern of
825 /// select(icmp()) this function advances the instruction pointer 'I' from the
826 /// compare instruction to the select instruction and stores this pointer in
827 /// 'PatternLastInst' member of the returned struct.
828 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
829 ReductionInstDesc &Desc);
830 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
831 /// pattern corresponding to a min(X, Y) or max(X, Y).
832 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
833 ReductionInstDesc &Prev);
834 /// Returns the induction kind of Phi and record the step. This function may
835 /// return NoInduction if the PHI is not an induction variable.
836 InductionKind isInductionVariable(PHINode *Phi, ConstantInt *&StepValue);
838 /// \brief Collect memory access with loop invariant strides.
840 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
842 void collectStridedAccess(Value *LoadOrStoreInst);
844 /// Report an analysis message to assist the user in diagnosing loops that are
845 /// not vectorized. These are handled as LoopAccessReport rather than
846 /// VectorizationReport because the << operator of VectorizationReport returns
847 /// LoopAccessReport.
848 void emitAnalysis(const LoopAccessReport &Message) {
849 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
852 unsigned NumPredStores;
854 /// The loop that we evaluate.
858 /// Target Library Info.
859 TargetLibraryInfo *TLI;
861 Function *TheFunction;
862 /// Target Transform Info
863 const TargetTransformInfo *TTI;
866 // LoopAccess analysis.
867 LoopAccessAnalysis *LAA;
868 // And the loop-accesses info corresponding to this loop. This pointer is
869 // null until canVectorizeMemory sets it up.
870 const LoopAccessInfo *LAI;
872 // --- vectorization state --- //
874 /// Holds the integer induction variable. This is the counter of the
877 /// Holds the reduction variables.
878 ReductionList Reductions;
879 /// Holds all of the induction variables that we found in the loop.
880 /// Notice that inductions don't need to start at zero and that induction
881 /// variables can be pointers.
882 InductionList Inductions;
883 /// Holds the widest induction type encountered.
886 /// Allowed outside users. This holds the reduction
887 /// vars which can be accessed from outside the loop.
888 SmallPtrSet<Value*, 4> AllowedExit;
889 /// This set holds the variables which are known to be uniform after
891 SmallPtrSet<Instruction*, 4> Uniforms;
893 /// Can we assume the absence of NaNs.
894 bool HasFunNoNaNAttr;
896 ValueToValueMap Strides;
897 SmallPtrSet<Value *, 8> StrideSet;
899 /// While vectorizing these instructions we have to generate a
900 /// call to the appropriate masked intrinsic
901 SmallPtrSet<const Instruction*, 8> MaskedOp;
904 /// LoopVectorizationCostModel - estimates the expected speedups due to
906 /// In many cases vectorization is not profitable. This can happen because of
907 /// a number of reasons. In this class we mainly attempt to predict the
908 /// expected speedup/slowdowns due to the supported instruction set. We use the
909 /// TargetTransformInfo to query the different backends for the cost of
910 /// different operations.
911 class LoopVectorizationCostModel {
913 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
914 LoopVectorizationLegality *Legal,
915 const TargetTransformInfo &TTI,
916 const TargetLibraryInfo *TLI, AssumptionCache *AC,
917 const Function *F, const LoopVectorizeHints *Hints)
918 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI),
919 TheFunction(F), Hints(Hints) {
920 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
923 /// Information about vectorization costs
924 struct VectorizationFactor {
925 unsigned Width; // Vector width with best cost
926 unsigned Cost; // Cost of the loop with that width
928 /// \return The most profitable vectorization factor and the cost of that VF.
929 /// This method checks every power of two up to VF. If UserVF is not ZERO
930 /// then this vectorization factor will be selected if vectorization is
932 VectorizationFactor selectVectorizationFactor(bool OptForSize);
934 /// \return The size (in bits) of the widest type in the code that
935 /// needs to be vectorized. We ignore values that remain scalar such as
936 /// 64 bit loop indices.
937 unsigned getWidestType();
939 /// \return The most profitable unroll factor.
940 /// If UserUF is non-zero then this method finds the best unroll-factor
941 /// based on register pressure and other parameters.
942 /// VF and LoopCost are the selected vectorization factor and the cost of the
944 unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost);
946 /// \brief A struct that represents some properties of the register usage
948 struct RegisterUsage {
949 /// Holds the number of loop invariant values that are used in the loop.
950 unsigned LoopInvariantRegs;
951 /// Holds the maximum number of concurrent live intervals in the loop.
952 unsigned MaxLocalUsers;
953 /// Holds the number of instructions in the loop.
954 unsigned NumInstructions;
957 /// \return information about the register usage of the loop.
958 RegisterUsage calculateRegisterUsage();
961 /// Returns the expected execution cost. The unit of the cost does
962 /// not matter because we use the 'cost' units to compare different
963 /// vector widths. The cost that is returned is *not* normalized by
964 /// the factor width.
965 unsigned expectedCost(unsigned VF);
967 /// Returns the execution time cost of an instruction for a given vector
968 /// width. Vector width of one means scalar.
969 unsigned getInstructionCost(Instruction *I, unsigned VF);
971 /// Returns whether the instruction is a load or store and will be a emitted
972 /// as a vector operation.
973 bool isConsecutiveLoadOrStore(Instruction *I);
975 /// Report an analysis message to assist the user in diagnosing loops that are
976 /// not vectorized. These are handled as LoopAccessReport rather than
977 /// VectorizationReport because the << operator of VectorizationReport returns
978 /// LoopAccessReport.
979 void emitAnalysis(const LoopAccessReport &Message) {
980 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
983 /// Values used only by @llvm.assume calls.
984 SmallPtrSet<const Value *, 32> EphValues;
986 /// The loop that we evaluate.
990 /// Loop Info analysis.
992 /// Vectorization legality.
993 LoopVectorizationLegality *Legal;
994 /// Vector target information.
995 const TargetTransformInfo &TTI;
996 /// Target Library Info.
997 const TargetLibraryInfo *TLI;
998 const Function *TheFunction;
999 // Loop Vectorize Hint.
1000 const LoopVectorizeHints *Hints;
1003 /// Utility class for getting and setting loop vectorizer hints in the form
1004 /// of loop metadata.
1005 /// This class keeps a number of loop annotations locally (as member variables)
1006 /// and can, upon request, write them back as metadata on the loop. It will
1007 /// initially scan the loop for existing metadata, and will update the local
1008 /// values based on information in the loop.
1009 /// We cannot write all values to metadata, as the mere presence of some info,
1010 /// for example 'force', means a decision has been made. So, we need to be
1011 /// careful NOT to add them if the user hasn't specifically asked so.
1012 class LoopVectorizeHints {
1019 /// Hint - associates name and validation with the hint value.
1022 unsigned Value; // This may have to change for non-numeric values.
1025 Hint(const char * Name, unsigned Value, HintKind Kind)
1026 : Name(Name), Value(Value), Kind(Kind) { }
1028 bool validate(unsigned Val) {
1031 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
1033 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1041 /// Vectorization width.
1043 /// Vectorization interleave factor.
1045 /// Vectorization forced
1048 /// Return the loop metadata prefix.
1049 static StringRef Prefix() { return "llvm.loop."; }
1053 FK_Undefined = -1, ///< Not selected.
1054 FK_Disabled = 0, ///< Forcing disabled.
1055 FK_Enabled = 1, ///< Forcing enabled.
1058 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1059 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
1061 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1062 Force("vectorize.enable", FK_Undefined, HK_FORCE),
1064 // Populate values with existing loop metadata.
1065 getHintsFromMetadata();
1067 // force-vector-interleave overrides DisableInterleaving.
1068 if (VectorizerParams::isInterleaveForced())
1069 Interleave.Value = VectorizerParams::VectorizationInterleave;
1071 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1072 << "LV: Interleaving disabled by the pass manager\n");
1075 /// Mark the loop L as already vectorized by setting the width to 1.
1076 void setAlreadyVectorized() {
1077 Width.Value = Interleave.Value = 1;
1078 Hint Hints[] = {Width, Interleave};
1079 writeHintsToMetadata(Hints);
1082 /// Dumps all the hint information.
1083 std::string emitRemark() const {
1084 VectorizationReport R;
1085 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1086 R << "vectorization is explicitly disabled";
1088 R << "use -Rpass-analysis=loop-vectorize for more info";
1089 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1090 R << " (Force=true";
1091 if (Width.Value != 0)
1092 R << ", Vector Width=" << Width.Value;
1093 if (Interleave.Value != 0)
1094 R << ", Interleave Count=" << Interleave.Value;
1102 unsigned getWidth() const { return Width.Value; }
1103 unsigned getInterleave() const { return Interleave.Value; }
1104 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1107 /// Find hints specified in the loop metadata and update local values.
1108 void getHintsFromMetadata() {
1109 MDNode *LoopID = TheLoop->getLoopID();
1113 // First operand should refer to the loop id itself.
1114 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1115 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1117 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1118 const MDString *S = nullptr;
1119 SmallVector<Metadata *, 4> Args;
1121 // The expected hint is either a MDString or a MDNode with the first
1122 // operand a MDString.
1123 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1124 if (!MD || MD->getNumOperands() == 0)
1126 S = dyn_cast<MDString>(MD->getOperand(0));
1127 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1128 Args.push_back(MD->getOperand(i));
1130 S = dyn_cast<MDString>(LoopID->getOperand(i));
1131 assert(Args.size() == 0 && "too many arguments for MDString");
1137 // Check if the hint starts with the loop metadata prefix.
1138 StringRef Name = S->getString();
1139 if (Args.size() == 1)
1140 setHint(Name, Args[0]);
1144 /// Checks string hint with one operand and set value if valid.
1145 void setHint(StringRef Name, Metadata *Arg) {
1146 if (!Name.startswith(Prefix()))
1148 Name = Name.substr(Prefix().size(), StringRef::npos);
1150 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1152 unsigned Val = C->getZExtValue();
1154 Hint *Hints[] = {&Width, &Interleave, &Force};
1155 for (auto H : Hints) {
1156 if (Name == H->Name) {
1157 if (H->validate(Val))
1160 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1166 /// Create a new hint from name / value pair.
1167 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1168 LLVMContext &Context = TheLoop->getHeader()->getContext();
1169 Metadata *MDs[] = {MDString::get(Context, Name),
1170 ConstantAsMetadata::get(
1171 ConstantInt::get(Type::getInt32Ty(Context), V))};
1172 return MDNode::get(Context, MDs);
1175 /// Matches metadata with hint name.
1176 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1177 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1181 for (auto H : HintTypes)
1182 if (Name->getString().endswith(H.Name))
1187 /// Sets current hints into loop metadata, keeping other values intact.
1188 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1189 if (HintTypes.size() == 0)
1192 // Reserve the first element to LoopID (see below).
1193 SmallVector<Metadata *, 4> MDs(1);
1194 // If the loop already has metadata, then ignore the existing operands.
1195 MDNode *LoopID = TheLoop->getLoopID();
1197 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1198 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1199 // If node in update list, ignore old value.
1200 if (!matchesHintMetadataName(Node, HintTypes))
1201 MDs.push_back(Node);
1205 // Now, add the missing hints.
1206 for (auto H : HintTypes)
1207 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1209 // Replace current metadata node with new one.
1210 LLVMContext &Context = TheLoop->getHeader()->getContext();
1211 MDNode *NewLoopID = MDNode::get(Context, MDs);
1212 // Set operand 0 to refer to the loop id itself.
1213 NewLoopID->replaceOperandWith(0, NewLoopID);
1215 TheLoop->setLoopID(NewLoopID);
1218 /// The loop these hints belong to.
1219 const Loop *TheLoop;
1222 static void emitMissedWarning(Function *F, Loop *L,
1223 const LoopVectorizeHints &LH) {
1224 emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1225 L->getStartLoc(), LH.emitRemark());
1227 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1228 if (LH.getWidth() != 1)
1229 emitLoopVectorizeWarning(
1230 F->getContext(), *F, L->getStartLoc(),
1231 "failed explicitly specified loop vectorization");
1232 else if (LH.getInterleave() != 1)
1233 emitLoopInterleaveWarning(
1234 F->getContext(), *F, L->getStartLoc(),
1235 "failed explicitly specified loop interleaving");
1239 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1241 return V.push_back(&L);
1243 for (Loop *InnerL : L)
1244 addInnerLoop(*InnerL, V);
1247 /// The LoopVectorize Pass.
1248 struct LoopVectorize : public FunctionPass {
1249 /// Pass identification, replacement for typeid
1252 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1254 DisableUnrolling(NoUnrolling),
1255 AlwaysVectorize(AlwaysVectorize) {
1256 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1259 ScalarEvolution *SE;
1261 TargetTransformInfo *TTI;
1263 BlockFrequencyInfo *BFI;
1264 TargetLibraryInfo *TLI;
1266 AssumptionCache *AC;
1267 LoopAccessAnalysis *LAA;
1268 bool DisableUnrolling;
1269 bool AlwaysVectorize;
1271 BlockFrequency ColdEntryFreq;
1273 bool runOnFunction(Function &F) override {
1274 SE = &getAnalysis<ScalarEvolution>();
1275 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1276 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1277 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1278 BFI = &getAnalysis<BlockFrequencyInfo>();
1279 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1280 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1281 AA = &getAnalysis<AliasAnalysis>();
1282 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1283 LAA = &getAnalysis<LoopAccessAnalysis>();
1285 // Compute some weights outside of the loop over the loops. Compute this
1286 // using a BranchProbability to re-use its scaling math.
1287 const BranchProbability ColdProb(1, 5); // 20%
1288 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1290 // If the target claims to have no vector registers don't attempt
1292 if (!TTI->getNumberOfRegisters(true))
1295 // Build up a worklist of inner-loops to vectorize. This is necessary as
1296 // the act of vectorizing or partially unrolling a loop creates new loops
1297 // and can invalidate iterators across the loops.
1298 SmallVector<Loop *, 8> Worklist;
1301 addInnerLoop(*L, Worklist);
1303 LoopsAnalyzed += Worklist.size();
1305 // Now walk the identified inner loops.
1306 bool Changed = false;
1307 while (!Worklist.empty())
1308 Changed |= processLoop(Worklist.pop_back_val());
1310 // Process each loop nest in the function.
1314 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
1315 SmallVector<Metadata *, 4> MDs;
1316 // Reserve first location for self reference to the LoopID metadata node.
1317 MDs.push_back(nullptr);
1318 bool IsUnrollMetadata = false;
1319 MDNode *LoopID = L->getLoopID();
1321 // First find existing loop unrolling disable metadata.
1322 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1323 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1325 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1327 S && S->getString().startswith("llvm.loop.unroll.disable");
1329 MDs.push_back(LoopID->getOperand(i));
1333 if (!IsUnrollMetadata) {
1334 // Add runtime unroll disable metadata.
1335 LLVMContext &Context = L->getHeader()->getContext();
1336 SmallVector<Metadata *, 1> DisableOperands;
1337 DisableOperands.push_back(
1338 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1339 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1340 MDs.push_back(DisableNode);
1341 MDNode *NewLoopID = MDNode::get(Context, MDs);
1342 // Set operand 0 to refer to the loop id itself.
1343 NewLoopID->replaceOperandWith(0, NewLoopID);
1344 L->setLoopID(NewLoopID);
1348 bool processLoop(Loop *L) {
1349 assert(L->empty() && "Only process inner loops.");
1352 const std::string DebugLocStr = getDebugLocString(L);
1355 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1356 << L->getHeader()->getParent()->getName() << "\" from "
1357 << DebugLocStr << "\n");
1359 LoopVectorizeHints Hints(L, DisableUnrolling);
1361 DEBUG(dbgs() << "LV: Loop hints:"
1363 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1365 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1367 : "?")) << " width=" << Hints.getWidth()
1368 << " unroll=" << Hints.getInterleave() << "\n");
1370 // Function containing loop
1371 Function *F = L->getHeader()->getParent();
1373 // Looking at the diagnostic output is the only way to determine if a loop
1374 // was vectorized (other than looking at the IR or machine code), so it
1375 // is important to generate an optimization remark for each loop. Most of
1376 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1377 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1378 // less verbose reporting vectorized loops and unvectorized loops that may
1379 // benefit from vectorization, respectively.
1381 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1382 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1383 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1384 L->getStartLoc(), Hints.emitRemark());
1388 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1389 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1390 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1391 L->getStartLoc(), Hints.emitRemark());
1395 if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
1396 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1397 emitOptimizationRemarkAnalysis(
1398 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1399 "loop not vectorized: vector width and interleave count are "
1400 "explicitly set to 1");
1404 // Check the loop for a trip count threshold:
1405 // do not vectorize loops with a tiny trip count.
1406 const unsigned TC = SE->getSmallConstantTripCount(L);
1407 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1408 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1409 << "This loop is not worth vectorizing.");
1410 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1411 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1413 DEBUG(dbgs() << "\n");
1414 emitOptimizationRemarkAnalysis(
1415 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1416 "vectorization is not beneficial and is not explicitly forced");
1421 // Check if it is legal to vectorize the loop.
1422 LoopVectorizationLegality LVL(L, SE, DT, TLI, AA, F, TTI, LAA);
1423 if (!LVL.canVectorize()) {
1424 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1425 emitMissedWarning(F, L, Hints);
1429 // Use the cost model.
1430 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, TLI, AC, F, &Hints);
1432 // Check the function attributes to find out if this function should be
1433 // optimized for size.
1434 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1435 F->hasFnAttribute(Attribute::OptimizeForSize);
1437 // Compute the weighted frequency of this loop being executed and see if it
1438 // is less than 20% of the function entry baseline frequency. Note that we
1439 // always have a canonical loop here because we think we *can* vectoriez.
1440 // FIXME: This is hidden behind a flag due to pervasive problems with
1441 // exactly what block frequency models.
1442 if (LoopVectorizeWithBlockFrequency) {
1443 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1444 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1445 LoopEntryFreq < ColdEntryFreq)
1449 // Check the function attributes to see if implicit floats are allowed.a
1450 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1451 // an integer loop and the vector instructions selected are purely integer
1452 // vector instructions?
1453 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1454 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1455 "attribute is used.\n");
1456 emitOptimizationRemarkAnalysis(
1457 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1458 "loop not vectorized due to NoImplicitFloat attribute");
1459 emitMissedWarning(F, L, Hints);
1463 // Select the optimal vectorization factor.
1464 const LoopVectorizationCostModel::VectorizationFactor VF =
1465 CM.selectVectorizationFactor(OptForSize);
1467 // Select the unroll factor.
1469 CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
1471 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1472 << DebugLocStr << '\n');
1473 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1475 if (VF.Width == 1) {
1476 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
1479 emitOptimizationRemarkAnalysis(
1480 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1481 "not beneficial to vectorize and user disabled interleaving");
1484 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1486 // Report the unrolling decision.
1487 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1488 Twine("unrolled with interleaving factor " +
1490 " (vectorization not beneficial)"));
1492 // We decided not to vectorize, but we may want to unroll.
1494 InnerLoopUnroller Unroller(L, SE, LI, DT, TLI, UF);
1495 Unroller.vectorize(&LVL);
1497 // If we decided that it is *legal* to vectorize the loop then do it.
1498 InnerLoopVectorizer LB(L, SE, LI, DT, TLI, VF.Width, UF);
1502 // Add metadata to disable runtime unrolling scalar loop when there's no
1503 // runtime check about strides and memory. Because at this situation,
1504 // scalar loop is rarely used not worthy to be unrolled.
1505 if (!LB.IsSafetyChecksAdded())
1506 AddRuntimeUnrollDisableMetaData(L);
1508 // Report the vectorization decision.
1509 emitOptimizationRemark(
1510 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1511 Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1512 ", unrolling interleave factor: " + Twine(UF) + ")");
1515 // Mark the loop as already vectorized to avoid vectorizing again.
1516 Hints.setAlreadyVectorized();
1518 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1522 void getAnalysisUsage(AnalysisUsage &AU) const override {
1523 AU.addRequired<AssumptionCacheTracker>();
1524 AU.addRequiredID(LoopSimplifyID);
1525 AU.addRequiredID(LCSSAID);
1526 AU.addRequired<BlockFrequencyInfo>();
1527 AU.addRequired<DominatorTreeWrapperPass>();
1528 AU.addRequired<LoopInfoWrapperPass>();
1529 AU.addRequired<ScalarEvolution>();
1530 AU.addRequired<TargetTransformInfoWrapperPass>();
1531 AU.addRequired<AliasAnalysis>();
1532 AU.addRequired<LoopAccessAnalysis>();
1533 AU.addPreserved<LoopInfoWrapperPass>();
1534 AU.addPreserved<DominatorTreeWrapperPass>();
1535 AU.addPreserved<AliasAnalysis>();
1540 } // end anonymous namespace
1542 //===----------------------------------------------------------------------===//
1543 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1544 // LoopVectorizationCostModel.
1545 //===----------------------------------------------------------------------===//
1547 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1548 // We need to place the broadcast of invariant variables outside the loop.
1549 Instruction *Instr = dyn_cast<Instruction>(V);
1551 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1552 Instr->getParent()) != LoopVectorBody.end());
1553 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1555 // Place the code for broadcasting invariant variables in the new preheader.
1556 IRBuilder<>::InsertPointGuard Guard(Builder);
1558 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1560 // Broadcast the scalar into all locations in the vector.
1561 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1566 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1568 assert(Val->getType()->isVectorTy() && "Must be a vector");
1569 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1570 "Elem must be an integer");
1571 assert(Step->getType() == Val->getType()->getScalarType() &&
1572 "Step has wrong type");
1573 // Create the types.
1574 Type *ITy = Val->getType()->getScalarType();
1575 VectorType *Ty = cast<VectorType>(Val->getType());
1576 int VLen = Ty->getNumElements();
1577 SmallVector<Constant*, 8> Indices;
1579 // Create a vector of consecutive numbers from zero to VF.
1580 for (int i = 0; i < VLen; ++i)
1581 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1583 // Add the consecutive indices to the vector value.
1584 Constant *Cv = ConstantVector::get(Indices);
1585 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1586 Step = Builder.CreateVectorSplat(VLen, Step);
1587 assert(Step->getType() == Val->getType() && "Invalid step vec");
1588 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1589 // which can be found from the original scalar operations.
1590 Step = Builder.CreateMul(Cv, Step);
1591 return Builder.CreateAdd(Val, Step, "induction");
1594 /// \brief Find the operand of the GEP that should be checked for consecutive
1595 /// stores. This ignores trailing indices that have no effect on the final
1597 static unsigned getGEPInductionOperand(const GetElementPtrInst *Gep) {
1598 const DataLayout &DL = Gep->getModule()->getDataLayout();
1599 unsigned LastOperand = Gep->getNumOperands() - 1;
1600 unsigned GEPAllocSize = DL.getTypeAllocSize(
1601 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1603 // Walk backwards and try to peel off zeros.
1604 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1605 // Find the type we're currently indexing into.
1606 gep_type_iterator GEPTI = gep_type_begin(Gep);
1607 std::advance(GEPTI, LastOperand - 1);
1609 // If it's a type with the same allocation size as the result of the GEP we
1610 // can peel off the zero index.
1611 if (DL.getTypeAllocSize(*GEPTI) != GEPAllocSize)
1619 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1620 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1621 // Make sure that the pointer does not point to structs.
1622 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1625 // If this value is a pointer induction variable we know it is consecutive.
1626 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1627 if (Phi && Inductions.count(Phi)) {
1628 InductionInfo II = Inductions[Phi];
1629 return II.getConsecutiveDirection();
1632 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1636 unsigned NumOperands = Gep->getNumOperands();
1637 Value *GpPtr = Gep->getPointerOperand();
1638 // If this GEP value is a consecutive pointer induction variable and all of
1639 // the indices are constant then we know it is consecutive. We can
1640 Phi = dyn_cast<PHINode>(GpPtr);
1641 if (Phi && Inductions.count(Phi)) {
1643 // Make sure that the pointer does not point to structs.
1644 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1645 if (GepPtrType->getElementType()->isAggregateType())
1648 // Make sure that all of the index operands are loop invariant.
1649 for (unsigned i = 1; i < NumOperands; ++i)
1650 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1653 InductionInfo II = Inductions[Phi];
1654 return II.getConsecutiveDirection();
1657 unsigned InductionOperand = getGEPInductionOperand(Gep);
1659 // Check that all of the gep indices are uniform except for our induction
1661 for (unsigned i = 0; i != NumOperands; ++i)
1662 if (i != InductionOperand &&
1663 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1666 // We can emit wide load/stores only if the last non-zero index is the
1667 // induction variable.
1668 const SCEV *Last = nullptr;
1669 if (!Strides.count(Gep))
1670 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1672 // Because of the multiplication by a stride we can have a s/zext cast.
1673 // We are going to replace this stride by 1 so the cast is safe to ignore.
1675 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1676 // %0 = trunc i64 %indvars.iv to i32
1677 // %mul = mul i32 %0, %Stride1
1678 // %idxprom = zext i32 %mul to i64 << Safe cast.
1679 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1681 Last = replaceSymbolicStrideSCEV(SE, Strides,
1682 Gep->getOperand(InductionOperand), Gep);
1683 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1685 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1689 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1690 const SCEV *Step = AR->getStepRecurrence(*SE);
1692 // The memory is consecutive because the last index is consecutive
1693 // and all other indices are loop invariant.
1696 if (Step->isAllOnesValue())
1703 bool LoopVectorizationLegality::isUniform(Value *V) {
1704 return LAI->isUniform(V);
1707 InnerLoopVectorizer::VectorParts&
1708 InnerLoopVectorizer::getVectorValue(Value *V) {
1709 assert(V != Induction && "The new induction variable should not be used.");
1710 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1712 // If we have a stride that is replaced by one, do it here.
1713 if (Legal->hasStride(V))
1714 V = ConstantInt::get(V->getType(), 1);
1716 // If we have this scalar in the map, return it.
1717 if (WidenMap.has(V))
1718 return WidenMap.get(V);
1720 // If this scalar is unknown, assume that it is a constant or that it is
1721 // loop invariant. Broadcast V and save the value for future uses.
1722 Value *B = getBroadcastInstrs(V);
1723 return WidenMap.splat(V, B);
1726 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1727 assert(Vec->getType()->isVectorTy() && "Invalid type");
1728 SmallVector<Constant*, 8> ShuffleMask;
1729 for (unsigned i = 0; i < VF; ++i)
1730 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1732 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1733 ConstantVector::get(ShuffleMask),
1737 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1738 // Attempt to issue a wide load.
1739 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1740 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1742 assert((LI || SI) && "Invalid Load/Store instruction");
1744 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1745 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1746 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1747 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1748 // An alignment of 0 means target abi alignment. We need to use the scalar's
1749 // target abi alignment in such a case.
1750 const DataLayout &DL = Instr->getModule()->getDataLayout();
1752 Alignment = DL.getABITypeAlignment(ScalarDataTy);
1753 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1754 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
1755 unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
1757 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
1758 !Legal->isMaskRequired(SI))
1759 return scalarizeInstruction(Instr, true);
1761 if (ScalarAllocatedSize != VectorElementSize)
1762 return scalarizeInstruction(Instr);
1764 // If the pointer is loop invariant or if it is non-consecutive,
1765 // scalarize the load.
1766 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1767 bool Reverse = ConsecutiveStride < 0;
1768 bool UniformLoad = LI && Legal->isUniform(Ptr);
1769 if (!ConsecutiveStride || UniformLoad)
1770 return scalarizeInstruction(Instr);
1772 Constant *Zero = Builder.getInt32(0);
1773 VectorParts &Entry = WidenMap.get(Instr);
1775 // Handle consecutive loads/stores.
1776 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1777 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1778 setDebugLocFromInst(Builder, Gep);
1779 Value *PtrOperand = Gep->getPointerOperand();
1780 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1781 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1783 // Create the new GEP with the new induction variable.
1784 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1785 Gep2->setOperand(0, FirstBasePtr);
1786 Gep2->setName("gep.indvar.base");
1787 Ptr = Builder.Insert(Gep2);
1789 setDebugLocFromInst(Builder, Gep);
1790 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1791 OrigLoop) && "Base ptr must be invariant");
1793 // The last index does not have to be the induction. It can be
1794 // consecutive and be a function of the index. For example A[I+1];
1795 unsigned NumOperands = Gep->getNumOperands();
1796 unsigned InductionOperand = getGEPInductionOperand(Gep);
1797 // Create the new GEP with the new induction variable.
1798 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1800 for (unsigned i = 0; i < NumOperands; ++i) {
1801 Value *GepOperand = Gep->getOperand(i);
1802 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1804 // Update last index or loop invariant instruction anchored in loop.
1805 if (i == InductionOperand ||
1806 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1807 assert((i == InductionOperand ||
1808 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1809 "Must be last index or loop invariant");
1811 VectorParts &GEPParts = getVectorValue(GepOperand);
1812 Value *Index = GEPParts[0];
1813 Index = Builder.CreateExtractElement(Index, Zero);
1814 Gep2->setOperand(i, Index);
1815 Gep2->setName("gep.indvar.idx");
1818 Ptr = Builder.Insert(Gep2);
1820 // Use the induction element ptr.
1821 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1822 setDebugLocFromInst(Builder, Ptr);
1823 VectorParts &PtrVal = getVectorValue(Ptr);
1824 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1827 VectorParts Mask = createBlockInMask(Instr->getParent());
1830 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1831 "We do not allow storing to uniform addresses");
1832 setDebugLocFromInst(Builder, SI);
1833 // We don't want to update the value in the map as it might be used in
1834 // another expression. So don't use a reference type for "StoredVal".
1835 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1837 for (unsigned Part = 0; Part < UF; ++Part) {
1838 // Calculate the pointer for the specific unroll-part.
1839 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1842 // If we store to reverse consecutive memory locations then we need
1843 // to reverse the order of elements in the stored value.
1844 StoredVal[Part] = reverseVector(StoredVal[Part]);
1845 // If the address is consecutive but reversed, then the
1846 // wide store needs to start at the last vector element.
1847 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1848 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1849 Mask[Part] = reverseVector(Mask[Part]);
1852 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1853 DataTy->getPointerTo(AddressSpace));
1856 if (Legal->isMaskRequired(SI))
1857 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
1860 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
1861 propagateMetadata(NewSI, SI);
1867 assert(LI && "Must have a load instruction");
1868 setDebugLocFromInst(Builder, LI);
1869 for (unsigned Part = 0; Part < UF; ++Part) {
1870 // Calculate the pointer for the specific unroll-part.
1871 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1874 // If the address is consecutive but reversed, then the
1875 // wide load needs to start at the last vector element.
1876 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1877 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1878 Mask[Part] = reverseVector(Mask[Part]);
1882 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1883 DataTy->getPointerTo(AddressSpace));
1884 if (Legal->isMaskRequired(LI))
1885 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
1886 UndefValue::get(DataTy),
1887 "wide.masked.load");
1889 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
1890 propagateMetadata(NewLI, LI);
1891 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
1895 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1896 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1897 // Holds vector parameters or scalars, in case of uniform vals.
1898 SmallVector<VectorParts, 4> Params;
1900 setDebugLocFromInst(Builder, Instr);
1902 // Find all of the vectorized parameters.
1903 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1904 Value *SrcOp = Instr->getOperand(op);
1906 // If we are accessing the old induction variable, use the new one.
1907 if (SrcOp == OldInduction) {
1908 Params.push_back(getVectorValue(SrcOp));
1912 // Try using previously calculated values.
1913 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1915 // If the src is an instruction that appeared earlier in the basic block
1916 // then it should already be vectorized.
1917 if (SrcInst && OrigLoop->contains(SrcInst)) {
1918 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1919 // The parameter is a vector value from earlier.
1920 Params.push_back(WidenMap.get(SrcInst));
1922 // The parameter is a scalar from outside the loop. Maybe even a constant.
1923 VectorParts Scalars;
1924 Scalars.append(UF, SrcOp);
1925 Params.push_back(Scalars);
1929 assert(Params.size() == Instr->getNumOperands() &&
1930 "Invalid number of operands");
1932 // Does this instruction return a value ?
1933 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1935 Value *UndefVec = IsVoidRetTy ? nullptr :
1936 UndefValue::get(VectorType::get(Instr->getType(), VF));
1937 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1938 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1940 Instruction *InsertPt = Builder.GetInsertPoint();
1941 BasicBlock *IfBlock = Builder.GetInsertBlock();
1942 BasicBlock *CondBlock = nullptr;
1945 Loop *VectorLp = nullptr;
1946 if (IfPredicateStore) {
1947 assert(Instr->getParent()->getSinglePredecessor() &&
1948 "Only support single predecessor blocks");
1949 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1950 Instr->getParent());
1951 VectorLp = LI->getLoopFor(IfBlock);
1952 assert(VectorLp && "Must have a loop for this block");
1955 // For each vector unroll 'part':
1956 for (unsigned Part = 0; Part < UF; ++Part) {
1957 // For each scalar that we create:
1958 for (unsigned Width = 0; Width < VF; ++Width) {
1961 Value *Cmp = nullptr;
1962 if (IfPredicateStore) {
1963 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1964 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1965 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1966 LoopVectorBody.push_back(CondBlock);
1967 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
1968 // Update Builder with newly created basic block.
1969 Builder.SetInsertPoint(InsertPt);
1972 Instruction *Cloned = Instr->clone();
1974 Cloned->setName(Instr->getName() + ".cloned");
1975 // Replace the operands of the cloned instructions with extracted scalars.
1976 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1977 Value *Op = Params[op][Part];
1978 // Param is a vector. Need to extract the right lane.
1979 if (Op->getType()->isVectorTy())
1980 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1981 Cloned->setOperand(op, Op);
1984 // Place the cloned scalar in the new loop.
1985 Builder.Insert(Cloned);
1987 // If the original scalar returns a value we need to place it in a vector
1988 // so that future users will be able to use it.
1990 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1991 Builder.getInt32(Width));
1993 if (IfPredicateStore) {
1994 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1995 LoopVectorBody.push_back(NewIfBlock);
1996 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
1997 Builder.SetInsertPoint(InsertPt);
1998 Instruction *OldBr = IfBlock->getTerminator();
1999 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2000 OldBr->eraseFromParent();
2001 IfBlock = NewIfBlock;
2007 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2011 if (Instruction *I = dyn_cast<Instruction>(V))
2012 return I->getParent() == Loc->getParent() ? I : nullptr;
2016 std::pair<Instruction *, Instruction *>
2017 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
2018 Instruction *tnullptr = nullptr;
2019 if (!Legal->mustCheckStrides())
2020 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2022 IRBuilder<> ChkBuilder(Loc);
2025 Value *Check = nullptr;
2026 Instruction *FirstInst = nullptr;
2027 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
2028 SE = Legal->strides_end();
2030 Value *Ptr = stripIntegerCast(*SI);
2031 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2033 // Store the first instruction we create.
2034 FirstInst = getFirstInst(FirstInst, C, Loc);
2036 Check = ChkBuilder.CreateOr(Check, C);
2041 // We have to do this trickery because the IRBuilder might fold the check to a
2042 // constant expression in which case there is no Instruction anchored in a
2044 LLVMContext &Ctx = Loc->getContext();
2045 Instruction *TheCheck =
2046 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2047 ChkBuilder.Insert(TheCheck, "stride.not.one");
2048 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2050 return std::make_pair(FirstInst, TheCheck);
2053 void InnerLoopVectorizer::createEmptyLoop() {
2055 In this function we generate a new loop. The new loop will contain
2056 the vectorized instructions while the old loop will continue to run the
2059 [ ] <-- Back-edge taken count overflow check.
2062 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2065 || [ ] <-- vector pre header.
2069 || [ ]_| <-- vector loop.
2072 | >[ ] <--- middle-block.
2075 -|- >[ ] <--- new preheader.
2079 | [ ]_| <-- old scalar loop to handle remainder.
2082 >[ ] <-- exit block.
2086 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2087 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
2088 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2089 assert(BypassBlock && "Invalid loop structure");
2090 assert(ExitBlock && "Must have an exit block");
2092 // Some loops have a single integer induction variable, while other loops
2093 // don't. One example is c++ iterators that often have multiple pointer
2094 // induction variables. In the code below we also support a case where we
2095 // don't have a single induction variable.
2096 OldInduction = Legal->getInduction();
2097 Type *IdxTy = Legal->getWidestInductionType();
2099 // Find the loop boundaries.
2100 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2101 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2103 // The exit count might have the type of i64 while the phi is i32. This can
2104 // happen if we have an induction variable that is sign extended before the
2105 // compare. The only way that we get a backedge taken count is that the
2106 // induction variable was signed and as such will not overflow. In such a case
2107 // truncation is legal.
2108 if (ExitCount->getType()->getPrimitiveSizeInBits() >
2109 IdxTy->getPrimitiveSizeInBits())
2110 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2112 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2113 // Get the total trip count from the count by adding 1.
2114 ExitCount = SE->getAddExpr(BackedgeTakeCount,
2115 SE->getConstant(BackedgeTakeCount->getType(), 1));
2117 const DataLayout &DL = OldBasicBlock->getModule()->getDataLayout();
2119 // Expand the trip count and place the new instructions in the preheader.
2120 // Notice that the pre-header does not change, only the loop body.
2121 SCEVExpander Exp(*SE, DL, "induction");
2123 // We need to test whether the backedge-taken count is uint##_max. Adding one
2124 // to it will cause overflow and an incorrect loop trip count in the vector
2125 // body. In case of overflow we want to directly jump to the scalar remainder
2127 Value *BackedgeCount =
2128 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2129 BypassBlock->getTerminator());
2130 if (BackedgeCount->getType()->isPointerTy())
2131 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2132 "backedge.ptrcnt.to.int",
2133 BypassBlock->getTerminator());
2134 Instruction *CheckBCOverflow =
2135 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2136 Constant::getAllOnesValue(BackedgeCount->getType()),
2137 "backedge.overflow", BypassBlock->getTerminator());
2139 // The loop index does not have to start at Zero. Find the original start
2140 // value from the induction PHI node. If we don't have an induction variable
2141 // then we know that it starts at zero.
2142 Builder.SetInsertPoint(BypassBlock->getTerminator());
2143 Value *StartIdx = ExtendedIdx = OldInduction ?
2144 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2146 ConstantInt::get(IdxTy, 0);
2148 // We need an instruction to anchor the overflow check on. StartIdx needs to
2149 // be defined before the overflow check branch. Because the scalar preheader
2150 // is going to merge the start index and so the overflow branch block needs to
2151 // contain a definition of the start index.
2152 Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
2153 StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
2154 BypassBlock->getTerminator());
2156 // Count holds the overall loop count (N).
2157 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2158 BypassBlock->getTerminator());
2160 LoopBypassBlocks.push_back(BypassBlock);
2162 // Split the single block loop into the two loop structure described above.
2163 BasicBlock *VectorPH =
2164 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2165 BasicBlock *VecBody =
2166 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2167 BasicBlock *MiddleBlock =
2168 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2169 BasicBlock *ScalarPH =
2170 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2172 // Create and register the new vector loop.
2173 Loop* Lp = new Loop();
2174 Loop *ParentLoop = OrigLoop->getParentLoop();
2176 // Insert the new loop into the loop nest and register the new basic blocks
2177 // before calling any utilities such as SCEV that require valid LoopInfo.
2179 ParentLoop->addChildLoop(Lp);
2180 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2181 ParentLoop->addBasicBlockToLoop(VectorPH, *LI);
2182 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2184 LI->addTopLevelLoop(Lp);
2186 Lp->addBasicBlockToLoop(VecBody, *LI);
2188 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2190 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2192 // Generate the induction variable.
2193 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2194 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2195 // The loop step is equal to the vectorization factor (num of SIMD elements)
2196 // times the unroll factor (num of SIMD instructions).
2197 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2199 // This is the IR builder that we use to add all of the logic for bypassing
2200 // the new vector loop.
2201 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2202 setDebugLocFromInst(BypassBuilder,
2203 getDebugLocFromInstOrOperands(OldInduction));
2205 // We may need to extend the index in case there is a type mismatch.
2206 // We know that the count starts at zero and does not overflow.
2207 if (Count->getType() != IdxTy) {
2208 // The exit count can be of pointer type. Convert it to the correct
2210 if (ExitCount->getType()->isPointerTy())
2211 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2213 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2216 // Add the start index to the loop count to get the new end index.
2217 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2219 // Now we need to generate the expression for N - (N % VF), which is
2220 // the part that the vectorized body will execute.
2221 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2222 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2223 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2224 "end.idx.rnd.down");
2226 // Now, compare the new count to zero. If it is zero skip the vector loop and
2227 // jump to the scalar loop.
2229 BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2231 BasicBlock *LastBypassBlock = BypassBlock;
2233 // Generate code to check that the loops trip count that we computed by adding
2234 // one to the backedge-taken count will not overflow.
2236 auto PastOverflowCheck =
2237 std::next(BasicBlock::iterator(OverflowCheckAnchor));
2238 BasicBlock *CheckBlock =
2239 LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2241 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2242 LoopBypassBlocks.push_back(CheckBlock);
2243 Instruction *OldTerm = LastBypassBlock->getTerminator();
2244 BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2245 OldTerm->eraseFromParent();
2246 LastBypassBlock = CheckBlock;
2249 // Generate the code to check that the strides we assumed to be one are really
2250 // one. We want the new basic block to start at the first instruction in a
2251 // sequence of instructions that form a check.
2252 Instruction *StrideCheck;
2253 Instruction *FirstCheckInst;
2254 std::tie(FirstCheckInst, StrideCheck) =
2255 addStrideCheck(LastBypassBlock->getTerminator());
2257 AddedSafetyChecks = true;
2258 // Create a new block containing the stride check.
2259 BasicBlock *CheckBlock =
2260 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2262 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2263 LoopBypassBlocks.push_back(CheckBlock);
2265 // Replace the branch into the memory check block with a conditional branch
2266 // for the "few elements case".
2267 Instruction *OldTerm = LastBypassBlock->getTerminator();
2268 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2269 OldTerm->eraseFromParent();
2272 LastBypassBlock = CheckBlock;
2275 // Generate the code that checks in runtime if arrays overlap. We put the
2276 // checks into a separate block to make the more common case of few elements
2278 Instruction *MemRuntimeCheck;
2279 std::tie(FirstCheckInst, MemRuntimeCheck) =
2280 Legal->getLAI()->addRuntimeCheck(LastBypassBlock->getTerminator());
2281 if (MemRuntimeCheck) {
2282 AddedSafetyChecks = true;
2283 // Create a new block containing the memory check.
2284 BasicBlock *CheckBlock =
2285 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.memcheck");
2287 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2288 LoopBypassBlocks.push_back(CheckBlock);
2290 // Replace the branch into the memory check block with a conditional branch
2291 // for the "few elements case".
2292 Instruction *OldTerm = LastBypassBlock->getTerminator();
2293 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2294 OldTerm->eraseFromParent();
2296 Cmp = MemRuntimeCheck;
2297 LastBypassBlock = CheckBlock;
2300 LastBypassBlock->getTerminator()->eraseFromParent();
2301 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2304 // We are going to resume the execution of the scalar loop.
2305 // Go over all of the induction variables that we found and fix the
2306 // PHIs that are left in the scalar version of the loop.
2307 // The starting values of PHI nodes depend on the counter of the last
2308 // iteration in the vectorized loop.
2309 // If we come from a bypass edge then we need to start from the original
2312 // This variable saves the new starting index for the scalar loop.
2313 PHINode *ResumeIndex = nullptr;
2314 LoopVectorizationLegality::InductionList::iterator I, E;
2315 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2316 // Set builder to point to last bypass block.
2317 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2318 for (I = List->begin(), E = List->end(); I != E; ++I) {
2319 PHINode *OrigPhi = I->first;
2320 LoopVectorizationLegality::InductionInfo II = I->second;
2322 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2323 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2324 MiddleBlock->getTerminator());
2325 // We might have extended the type of the induction variable but we need a
2326 // truncated version for the scalar loop.
2327 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2328 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2329 MiddleBlock->getTerminator()) : nullptr;
2331 // Create phi nodes to merge from the backedge-taken check block.
2332 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2333 ScalarPH->getTerminator());
2334 BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2336 PHINode *BCTruncResumeVal = nullptr;
2337 if (OrigPhi == OldInduction) {
2339 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2340 ScalarPH->getTerminator());
2341 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2344 Value *EndValue = nullptr;
2346 case LoopVectorizationLegality::IK_NoInduction:
2347 llvm_unreachable("Unknown induction");
2348 case LoopVectorizationLegality::IK_IntInduction: {
2349 // Handle the integer induction counter.
2350 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2352 // We have the canonical induction variable.
2353 if (OrigPhi == OldInduction) {
2354 // Create a truncated version of the resume value for the scalar loop,
2355 // we might have promoted the type to a larger width.
2357 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2358 // The new PHI merges the original incoming value, in case of a bypass,
2359 // or the value at the end of the vectorized loop.
2360 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2361 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2362 TruncResumeVal->addIncoming(EndValue, VecBody);
2364 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2366 // We know what the end value is.
2367 EndValue = IdxEndRoundDown;
2368 // We also know which PHI node holds it.
2369 ResumeIndex = ResumeVal;
2373 // Not the canonical induction variable - add the vector loop count to the
2375 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2376 II.StartValue->getType(),
2378 EndValue = II.transform(BypassBuilder, CRD);
2379 EndValue->setName("ind.end");
2382 case LoopVectorizationLegality::IK_PtrInduction: {
2383 EndValue = II.transform(BypassBuilder, CountRoundDown);
2384 EndValue->setName("ptr.ind.end");
2389 // The new PHI merges the original incoming value, in case of a bypass,
2390 // or the value at the end of the vectorized loop.
2391 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2392 if (OrigPhi == OldInduction)
2393 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2395 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2397 ResumeVal->addIncoming(EndValue, VecBody);
2399 // Fix the scalar body counter (PHI node).
2400 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2402 // The old induction's phi node in the scalar body needs the truncated
2404 if (OrigPhi == OldInduction) {
2405 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2406 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2408 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2409 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2413 // If we are generating a new induction variable then we also need to
2414 // generate the code that calculates the exit value. This value is not
2415 // simply the end of the counter because we may skip the vectorized body
2416 // in case of a runtime check.
2418 assert(!ResumeIndex && "Unexpected resume value found");
2419 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2420 MiddleBlock->getTerminator());
2421 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2422 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2423 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2426 // Make sure that we found the index where scalar loop needs to continue.
2427 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2428 "Invalid resume Index");
2430 // Add a check in the middle block to see if we have completed
2431 // all of the iterations in the first vector loop.
2432 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2433 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2434 ResumeIndex, "cmp.n",
2435 MiddleBlock->getTerminator());
2437 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2438 // Remove the old terminator.
2439 MiddleBlock->getTerminator()->eraseFromParent();
2441 // Create i+1 and fill the PHINode.
2442 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2443 Induction->addIncoming(StartIdx, VectorPH);
2444 Induction->addIncoming(NextIdx, VecBody);
2445 // Create the compare.
2446 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2447 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2449 // Now we have two terminators. Remove the old one from the block.
2450 VecBody->getTerminator()->eraseFromParent();
2452 // Get ready to start creating new instructions into the vectorized body.
2453 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2456 LoopVectorPreHeader = VectorPH;
2457 LoopScalarPreHeader = ScalarPH;
2458 LoopMiddleBlock = MiddleBlock;
2459 LoopExitBlock = ExitBlock;
2460 LoopVectorBody.push_back(VecBody);
2461 LoopScalarBody = OldBasicBlock;
2463 LoopVectorizeHints Hints(Lp, true);
2464 Hints.setAlreadyVectorized();
2467 /// This function returns the identity element (or neutral element) for
2468 /// the operation K.
2470 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2475 // Adding, Xoring, Oring zero to a number does not change it.
2476 return ConstantInt::get(Tp, 0);
2477 case RK_IntegerMult:
2478 // Multiplying a number by 1 does not change it.
2479 return ConstantInt::get(Tp, 1);
2481 // AND-ing a number with an all-1 value does not change it.
2482 return ConstantInt::get(Tp, -1, true);
2484 // Multiplying a number by 1 does not change it.
2485 return ConstantFP::get(Tp, 1.0L);
2487 // Adding zero to a number does not change it.
2488 return ConstantFP::get(Tp, 0.0L);
2490 llvm_unreachable("Unknown reduction kind");
2494 /// This function translates the reduction kind to an LLVM binary operator.
2496 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2498 case LoopVectorizationLegality::RK_IntegerAdd:
2499 return Instruction::Add;
2500 case LoopVectorizationLegality::RK_IntegerMult:
2501 return Instruction::Mul;
2502 case LoopVectorizationLegality::RK_IntegerOr:
2503 return Instruction::Or;
2504 case LoopVectorizationLegality::RK_IntegerAnd:
2505 return Instruction::And;
2506 case LoopVectorizationLegality::RK_IntegerXor:
2507 return Instruction::Xor;
2508 case LoopVectorizationLegality::RK_FloatMult:
2509 return Instruction::FMul;
2510 case LoopVectorizationLegality::RK_FloatAdd:
2511 return Instruction::FAdd;
2512 case LoopVectorizationLegality::RK_IntegerMinMax:
2513 return Instruction::ICmp;
2514 case LoopVectorizationLegality::RK_FloatMinMax:
2515 return Instruction::FCmp;
2517 llvm_unreachable("Unknown reduction operation");
2521 static Value *createMinMaxOp(IRBuilder<> &Builder,
2522 LoopVectorizationLegality::MinMaxReductionKind RK,
2523 Value *Left, Value *Right) {
2524 CmpInst::Predicate P = CmpInst::ICMP_NE;
2527 llvm_unreachable("Unknown min/max reduction kind");
2528 case LoopVectorizationLegality::MRK_UIntMin:
2529 P = CmpInst::ICMP_ULT;
2531 case LoopVectorizationLegality::MRK_UIntMax:
2532 P = CmpInst::ICMP_UGT;
2534 case LoopVectorizationLegality::MRK_SIntMin:
2535 P = CmpInst::ICMP_SLT;
2537 case LoopVectorizationLegality::MRK_SIntMax:
2538 P = CmpInst::ICMP_SGT;
2540 case LoopVectorizationLegality::MRK_FloatMin:
2541 P = CmpInst::FCMP_OLT;
2543 case LoopVectorizationLegality::MRK_FloatMax:
2544 P = CmpInst::FCMP_OGT;
2549 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2550 RK == LoopVectorizationLegality::MRK_FloatMax)
2551 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2553 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2555 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2560 struct CSEDenseMapInfo {
2561 static bool canHandle(Instruction *I) {
2562 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2563 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2565 static inline Instruction *getEmptyKey() {
2566 return DenseMapInfo<Instruction *>::getEmptyKey();
2568 static inline Instruction *getTombstoneKey() {
2569 return DenseMapInfo<Instruction *>::getTombstoneKey();
2571 static unsigned getHashValue(Instruction *I) {
2572 assert(canHandle(I) && "Unknown instruction!");
2573 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2574 I->value_op_end()));
2576 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2577 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2578 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2580 return LHS->isIdenticalTo(RHS);
2585 /// \brief Check whether this block is a predicated block.
2586 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2587 /// = ...; " blocks. We start with one vectorized basic block. For every
2588 /// conditional block we split this vectorized block. Therefore, every second
2589 /// block will be a predicated one.
2590 static bool isPredicatedBlock(unsigned BlockNum) {
2591 return BlockNum % 2;
2594 ///\brief Perform cse of induction variable instructions.
2595 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2596 // Perform simple cse.
2597 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2598 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2599 BasicBlock *BB = BBs[i];
2600 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2601 Instruction *In = I++;
2603 if (!CSEDenseMapInfo::canHandle(In))
2606 // Check if we can replace this instruction with any of the
2607 // visited instructions.
2608 if (Instruction *V = CSEMap.lookup(In)) {
2609 In->replaceAllUsesWith(V);
2610 In->eraseFromParent();
2613 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2614 // ...;" blocks for predicated stores. Every second block is a predicated
2616 if (isPredicatedBlock(i))
2624 /// \brief Adds a 'fast' flag to floating point operations.
2625 static Value *addFastMathFlag(Value *V) {
2626 if (isa<FPMathOperator>(V)){
2627 FastMathFlags Flags;
2628 Flags.setUnsafeAlgebra();
2629 cast<Instruction>(V)->setFastMathFlags(Flags);
2634 void InnerLoopVectorizer::vectorizeLoop() {
2635 //===------------------------------------------------===//
2637 // Notice: any optimization or new instruction that go
2638 // into the code below should be also be implemented in
2641 //===------------------------------------------------===//
2642 Constant *Zero = Builder.getInt32(0);
2644 // In order to support reduction variables we need to be able to vectorize
2645 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2646 // stages. First, we create a new vector PHI node with no incoming edges.
2647 // We use this value when we vectorize all of the instructions that use the
2648 // PHI. Next, after all of the instructions in the block are complete we
2649 // add the new incoming edges to the PHI. At this point all of the
2650 // instructions in the basic block are vectorized, so we can use them to
2651 // construct the PHI.
2652 PhiVector RdxPHIsToFix;
2654 // Scan the loop in a topological order to ensure that defs are vectorized
2656 LoopBlocksDFS DFS(OrigLoop);
2659 // Vectorize all of the blocks in the original loop.
2660 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2661 be = DFS.endRPO(); bb != be; ++bb)
2662 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2664 // At this point every instruction in the original loop is widened to
2665 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2666 // that we vectorized. The PHI nodes are currently empty because we did
2667 // not want to introduce cycles. Notice that the remaining PHI nodes
2668 // that we need to fix are reduction variables.
2670 // Create the 'reduced' values for each of the induction vars.
2671 // The reduced values are the vector values that we scalarize and combine
2672 // after the loop is finished.
2673 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2675 PHINode *RdxPhi = *it;
2676 assert(RdxPhi && "Unable to recover vectorized PHI");
2678 // Find the reduction variable descriptor.
2679 assert(Legal->getReductionVars()->count(RdxPhi) &&
2680 "Unable to find the reduction variable");
2681 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2682 (*Legal->getReductionVars())[RdxPhi];
2684 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2686 // We need to generate a reduction vector from the incoming scalar.
2687 // To do so, we need to generate the 'identity' vector and override
2688 // one of the elements with the incoming scalar reduction. We need
2689 // to do it in the vector-loop preheader.
2690 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2692 // This is the vector-clone of the value that leaves the loop.
2693 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2694 Type *VecTy = VectorExit[0]->getType();
2696 // Find the reduction identity variable. Zero for addition, or, xor,
2697 // one for multiplication, -1 for And.
2700 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2701 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2702 // MinMax reduction have the start value as their identify.
2704 VectorStart = Identity = RdxDesc.StartValue;
2706 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2711 // Handle other reduction kinds:
2713 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2714 VecTy->getScalarType());
2717 // This vector is the Identity vector where the first element is the
2718 // incoming scalar reduction.
2719 VectorStart = RdxDesc.StartValue;
2721 Identity = ConstantVector::getSplat(VF, Iden);
2723 // This vector is the Identity vector where the first element is the
2724 // incoming scalar reduction.
2725 VectorStart = Builder.CreateInsertElement(Identity,
2726 RdxDesc.StartValue, Zero);
2730 // Fix the vector-loop phi.
2732 // Reductions do not have to start at zero. They can start with
2733 // any loop invariant values.
2734 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2735 BasicBlock *Latch = OrigLoop->getLoopLatch();
2736 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2737 VectorParts &Val = getVectorValue(LoopVal);
2738 for (unsigned part = 0; part < UF; ++part) {
2739 // Make sure to add the reduction stat value only to the
2740 // first unroll part.
2741 Value *StartVal = (part == 0) ? VectorStart : Identity;
2742 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
2743 LoopVectorPreHeader);
2744 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2745 LoopVectorBody.back());
2748 // Before each round, move the insertion point right between
2749 // the PHIs and the values we are going to write.
2750 // This allows us to write both PHINodes and the extractelement
2752 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2754 VectorParts RdxParts;
2755 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2756 for (unsigned part = 0; part < UF; ++part) {
2757 // This PHINode contains the vectorized reduction variable, or
2758 // the initial value vector, if we bypass the vector loop.
2759 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2760 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2761 Value *StartVal = (part == 0) ? VectorStart : Identity;
2762 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2763 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2764 NewPhi->addIncoming(RdxExitVal[part],
2765 LoopVectorBody.back());
2766 RdxParts.push_back(NewPhi);
2769 // Reduce all of the unrolled parts into a single vector.
2770 Value *ReducedPartRdx = RdxParts[0];
2771 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2772 setDebugLocFromInst(Builder, ReducedPartRdx);
2773 for (unsigned part = 1; part < UF; ++part) {
2774 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2775 // Floating point operations had to be 'fast' to enable the reduction.
2776 ReducedPartRdx = addFastMathFlag(
2777 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2778 ReducedPartRdx, "bin.rdx"));
2780 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2781 ReducedPartRdx, RdxParts[part]);
2785 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2786 // and vector ops, reducing the set of values being computed by half each
2788 assert(isPowerOf2_32(VF) &&
2789 "Reduction emission only supported for pow2 vectors!");
2790 Value *TmpVec = ReducedPartRdx;
2791 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2792 for (unsigned i = VF; i != 1; i >>= 1) {
2793 // Move the upper half of the vector to the lower half.
2794 for (unsigned j = 0; j != i/2; ++j)
2795 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2797 // Fill the rest of the mask with undef.
2798 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2799 UndefValue::get(Builder.getInt32Ty()));
2802 Builder.CreateShuffleVector(TmpVec,
2803 UndefValue::get(TmpVec->getType()),
2804 ConstantVector::get(ShuffleMask),
2807 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2808 // Floating point operations had to be 'fast' to enable the reduction.
2809 TmpVec = addFastMathFlag(Builder.CreateBinOp(
2810 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2812 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2815 // The result is in the first element of the vector.
2816 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2817 Builder.getInt32(0));
2820 // Create a phi node that merges control-flow from the backedge-taken check
2821 // block and the middle block.
2822 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2823 LoopScalarPreHeader->getTerminator());
2824 BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
2825 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2827 // Now, we need to fix the users of the reduction variable
2828 // inside and outside of the scalar remainder loop.
2829 // We know that the loop is in LCSSA form. We need to update the
2830 // PHI nodes in the exit blocks.
2831 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2832 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2833 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2834 if (!LCSSAPhi) break;
2836 // All PHINodes need to have a single entry edge, or two if
2837 // we already fixed them.
2838 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2840 // We found our reduction value exit-PHI. Update it with the
2841 // incoming bypass edge.
2842 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2843 // Add an edge coming from the bypass.
2844 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2847 }// end of the LCSSA phi scan.
2849 // Fix the scalar loop reduction variable with the incoming reduction sum
2850 // from the vector body and from the backedge value.
2851 int IncomingEdgeBlockIdx =
2852 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2853 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2854 // Pick the other block.
2855 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2856 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
2857 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2858 }// end of for each redux variable.
2862 // Remove redundant induction instructions.
2863 cse(LoopVectorBody);
2866 void InnerLoopVectorizer::fixLCSSAPHIs() {
2867 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2868 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2869 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2870 if (!LCSSAPhi) break;
2871 if (LCSSAPhi->getNumIncomingValues() == 1)
2872 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2877 InnerLoopVectorizer::VectorParts
2878 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2879 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2882 // Look for cached value.
2883 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2884 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2885 if (ECEntryIt != MaskCache.end())
2886 return ECEntryIt->second;
2888 VectorParts SrcMask = createBlockInMask(Src);
2890 // The terminator has to be a branch inst!
2891 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2892 assert(BI && "Unexpected terminator found");
2894 if (BI->isConditional()) {
2895 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2897 if (BI->getSuccessor(0) != Dst)
2898 for (unsigned part = 0; part < UF; ++part)
2899 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2901 for (unsigned part = 0; part < UF; ++part)
2902 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2904 MaskCache[Edge] = EdgeMask;
2908 MaskCache[Edge] = SrcMask;
2912 InnerLoopVectorizer::VectorParts
2913 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2914 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2916 // Loop incoming mask is all-one.
2917 if (OrigLoop->getHeader() == BB) {
2918 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2919 return getVectorValue(C);
2922 // This is the block mask. We OR all incoming edges, and with zero.
2923 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2924 VectorParts BlockMask = getVectorValue(Zero);
2927 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2928 VectorParts EM = createEdgeMask(*it, BB);
2929 for (unsigned part = 0; part < UF; ++part)
2930 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2936 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2937 InnerLoopVectorizer::VectorParts &Entry,
2938 unsigned UF, unsigned VF, PhiVector *PV) {
2939 PHINode* P = cast<PHINode>(PN);
2940 // Handle reduction variables:
2941 if (Legal->getReductionVars()->count(P)) {
2942 for (unsigned part = 0; part < UF; ++part) {
2943 // This is phase one of vectorizing PHIs.
2944 Type *VecTy = (VF == 1) ? PN->getType() :
2945 VectorType::get(PN->getType(), VF);
2946 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2947 LoopVectorBody.back()-> getFirstInsertionPt());
2953 setDebugLocFromInst(Builder, P);
2954 // Check for PHI nodes that are lowered to vector selects.
2955 if (P->getParent() != OrigLoop->getHeader()) {
2956 // We know that all PHIs in non-header blocks are converted into
2957 // selects, so we don't have to worry about the insertion order and we
2958 // can just use the builder.
2959 // At this point we generate the predication tree. There may be
2960 // duplications since this is a simple recursive scan, but future
2961 // optimizations will clean it up.
2963 unsigned NumIncoming = P->getNumIncomingValues();
2965 // Generate a sequence of selects of the form:
2966 // SELECT(Mask3, In3,
2967 // SELECT(Mask2, In2,
2969 for (unsigned In = 0; In < NumIncoming; In++) {
2970 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2972 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2974 for (unsigned part = 0; part < UF; ++part) {
2975 // We might have single edge PHIs (blocks) - use an identity
2976 // 'select' for the first PHI operand.
2978 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2981 // Select between the current value and the previous incoming edge
2982 // based on the incoming mask.
2983 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2984 Entry[part], "predphi");
2990 // This PHINode must be an induction variable.
2991 // Make sure that we know about it.
2992 assert(Legal->getInductionVars()->count(P) &&
2993 "Not an induction variable");
2995 LoopVectorizationLegality::InductionInfo II =
2996 Legal->getInductionVars()->lookup(P);
2998 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2999 // which can be found from the original scalar operations.
3001 case LoopVectorizationLegality::IK_NoInduction:
3002 llvm_unreachable("Unknown induction");
3003 case LoopVectorizationLegality::IK_IntInduction: {
3004 assert(P->getType() == II.StartValue->getType() && "Types must match");
3005 Type *PhiTy = P->getType();
3007 if (P == OldInduction) {
3008 // Handle the canonical induction variable. We might have had to
3010 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
3012 // Handle other induction variables that are now based on the
3014 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
3016 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
3017 Broadcasted = II.transform(Builder, NormalizedIdx);
3018 Broadcasted->setName("offset.idx");
3020 Broadcasted = getBroadcastInstrs(Broadcasted);
3021 // After broadcasting the induction variable we need to make the vector
3022 // consecutive by adding 0, 1, 2, etc.
3023 for (unsigned part = 0; part < UF; ++part)
3024 Entry[part] = getStepVector(Broadcasted, VF * part, II.StepValue);
3027 case LoopVectorizationLegality::IK_PtrInduction:
3028 // Handle the pointer induction variable case.
3029 assert(P->getType()->isPointerTy() && "Unexpected type.");
3030 // This is the normalized GEP that starts counting at zero.
3031 Value *NormalizedIdx =
3032 Builder.CreateSub(Induction, ExtendedIdx, "normalized.idx");
3033 // This is the vector of results. Notice that we don't generate
3034 // vector geps because scalar geps result in better code.
3035 for (unsigned part = 0; part < UF; ++part) {
3037 int EltIndex = part;
3038 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3039 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3040 Value *SclrGep = II.transform(Builder, GlobalIdx);
3041 SclrGep->setName("next.gep");
3042 Entry[part] = SclrGep;
3046 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3047 for (unsigned int i = 0; i < VF; ++i) {
3048 int EltIndex = i + part * VF;
3049 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3050 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3051 Value *SclrGep = II.transform(Builder, GlobalIdx);
3052 SclrGep->setName("next.gep");
3053 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3054 Builder.getInt32(i),
3057 Entry[part] = VecVal;
3063 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3064 // For each instruction in the old loop.
3065 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3066 VectorParts &Entry = WidenMap.get(it);
3067 switch (it->getOpcode()) {
3068 case Instruction::Br:
3069 // Nothing to do for PHIs and BR, since we already took care of the
3070 // loop control flow instructions.
3072 case Instruction::PHI: {
3073 // Vectorize PHINodes.
3074 widenPHIInstruction(it, Entry, UF, VF, PV);
3078 case Instruction::Add:
3079 case Instruction::FAdd:
3080 case Instruction::Sub:
3081 case Instruction::FSub:
3082 case Instruction::Mul:
3083 case Instruction::FMul:
3084 case Instruction::UDiv:
3085 case Instruction::SDiv:
3086 case Instruction::FDiv:
3087 case Instruction::URem:
3088 case Instruction::SRem:
3089 case Instruction::FRem:
3090 case Instruction::Shl:
3091 case Instruction::LShr:
3092 case Instruction::AShr:
3093 case Instruction::And:
3094 case Instruction::Or:
3095 case Instruction::Xor: {
3096 // Just widen binops.
3097 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3098 setDebugLocFromInst(Builder, BinOp);
3099 VectorParts &A = getVectorValue(it->getOperand(0));
3100 VectorParts &B = getVectorValue(it->getOperand(1));
3102 // Use this vector value for all users of the original instruction.
3103 for (unsigned Part = 0; Part < UF; ++Part) {
3104 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3106 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3107 VecOp->copyIRFlags(BinOp);
3112 propagateMetadata(Entry, it);
3115 case Instruction::Select: {
3117 // If the selector is loop invariant we can create a select
3118 // instruction with a scalar condition. Otherwise, use vector-select.
3119 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3121 setDebugLocFromInst(Builder, it);
3123 // The condition can be loop invariant but still defined inside the
3124 // loop. This means that we can't just use the original 'cond' value.
3125 // We have to take the 'vectorized' value and pick the first lane.
3126 // Instcombine will make this a no-op.
3127 VectorParts &Cond = getVectorValue(it->getOperand(0));
3128 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3129 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3131 Value *ScalarCond = (VF == 1) ? Cond[0] :
3132 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3134 for (unsigned Part = 0; Part < UF; ++Part) {
3135 Entry[Part] = Builder.CreateSelect(
3136 InvariantCond ? ScalarCond : Cond[Part],
3141 propagateMetadata(Entry, it);
3145 case Instruction::ICmp:
3146 case Instruction::FCmp: {
3147 // Widen compares. Generate vector compares.
3148 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3149 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3150 setDebugLocFromInst(Builder, it);
3151 VectorParts &A = getVectorValue(it->getOperand(0));
3152 VectorParts &B = getVectorValue(it->getOperand(1));
3153 for (unsigned Part = 0; Part < UF; ++Part) {
3156 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3158 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3162 propagateMetadata(Entry, it);
3166 case Instruction::Store:
3167 case Instruction::Load:
3168 vectorizeMemoryInstruction(it);
3170 case Instruction::ZExt:
3171 case Instruction::SExt:
3172 case Instruction::FPToUI:
3173 case Instruction::FPToSI:
3174 case Instruction::FPExt:
3175 case Instruction::PtrToInt:
3176 case Instruction::IntToPtr:
3177 case Instruction::SIToFP:
3178 case Instruction::UIToFP:
3179 case Instruction::Trunc:
3180 case Instruction::FPTrunc:
3181 case Instruction::BitCast: {
3182 CastInst *CI = dyn_cast<CastInst>(it);
3183 setDebugLocFromInst(Builder, it);
3184 /// Optimize the special case where the source is the induction
3185 /// variable. Notice that we can only optimize the 'trunc' case
3186 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3187 /// c. other casts depend on pointer size.
3188 if (CI->getOperand(0) == OldInduction &&
3189 it->getOpcode() == Instruction::Trunc) {
3190 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3192 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3193 LoopVectorizationLegality::InductionInfo II =
3194 Legal->getInductionVars()->lookup(OldInduction);
3196 ConstantInt::getSigned(CI->getType(), II.StepValue->getSExtValue());
3197 for (unsigned Part = 0; Part < UF; ++Part)
3198 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3199 propagateMetadata(Entry, it);
3202 /// Vectorize casts.
3203 Type *DestTy = (VF == 1) ? CI->getType() :
3204 VectorType::get(CI->getType(), VF);
3206 VectorParts &A = getVectorValue(it->getOperand(0));
3207 for (unsigned Part = 0; Part < UF; ++Part)
3208 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3209 propagateMetadata(Entry, it);
3213 case Instruction::Call: {
3214 // Ignore dbg intrinsics.
3215 if (isa<DbgInfoIntrinsic>(it))
3217 setDebugLocFromInst(Builder, it);
3219 Module *M = BB->getParent()->getParent();
3220 CallInst *CI = cast<CallInst>(it);
3221 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3222 assert(ID && "Not an intrinsic call!");
3224 case Intrinsic::assume:
3225 case Intrinsic::lifetime_end:
3226 case Intrinsic::lifetime_start:
3227 scalarizeInstruction(it);
3230 bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
3231 for (unsigned Part = 0; Part < UF; ++Part) {
3232 SmallVector<Value *, 4> Args;
3233 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3234 if (HasScalarOpd && i == 1) {
3235 Args.push_back(CI->getArgOperand(i));
3238 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3239 Args.push_back(Arg[Part]);
3241 Type *Tys[] = {CI->getType()};
3243 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3245 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3246 Entry[Part] = Builder.CreateCall(F, Args);
3249 propagateMetadata(Entry, it);
3256 // All other instructions are unsupported. Scalarize them.
3257 scalarizeInstruction(it);
3260 }// end of for_each instr.
3263 void InnerLoopVectorizer::updateAnalysis() {
3264 // Forget the original basic block.
3265 SE->forgetLoop(OrigLoop);
3267 // Update the dominator tree information.
3268 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3269 "Entry does not dominate exit.");
3271 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3272 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3273 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3275 // Due to if predication of stores we might create a sequence of "if(pred)
3276 // a[i] = ...; " blocks.
3277 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3279 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3280 else if (isPredicatedBlock(i)) {
3281 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3283 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3287 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3288 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3289 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3290 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3292 DEBUG(DT->verifyDomTree());
3295 /// \brief Check whether it is safe to if-convert this phi node.
3297 /// Phi nodes with constant expressions that can trap are not safe to if
3299 static bool canIfConvertPHINodes(BasicBlock *BB) {
3300 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3301 PHINode *Phi = dyn_cast<PHINode>(I);
3304 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3305 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3312 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3313 if (!EnableIfConversion) {
3314 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3318 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3320 // A list of pointers that we can safely read and write to.
3321 SmallPtrSet<Value *, 8> SafePointes;
3323 // Collect safe addresses.
3324 for (Loop::block_iterator BI = TheLoop->block_begin(),
3325 BE = TheLoop->block_end(); BI != BE; ++BI) {
3326 BasicBlock *BB = *BI;
3328 if (blockNeedsPredication(BB))
3331 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3332 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3333 SafePointes.insert(LI->getPointerOperand());
3334 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3335 SafePointes.insert(SI->getPointerOperand());
3339 // Collect the blocks that need predication.
3340 BasicBlock *Header = TheLoop->getHeader();
3341 for (Loop::block_iterator BI = TheLoop->block_begin(),
3342 BE = TheLoop->block_end(); BI != BE; ++BI) {
3343 BasicBlock *BB = *BI;
3345 // We don't support switch statements inside loops.
3346 if (!isa<BranchInst>(BB->getTerminator())) {
3347 emitAnalysis(VectorizationReport(BB->getTerminator())
3348 << "loop contains a switch statement");
3352 // We must be able to predicate all blocks that need to be predicated.
3353 if (blockNeedsPredication(BB)) {
3354 if (!blockCanBePredicated(BB, SafePointes)) {
3355 emitAnalysis(VectorizationReport(BB->getTerminator())
3356 << "control flow cannot be substituted for a select");
3359 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3360 emitAnalysis(VectorizationReport(BB->getTerminator())
3361 << "control flow cannot be substituted for a select");
3366 // We can if-convert this loop.
3370 bool LoopVectorizationLegality::canVectorize() {
3371 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3372 // be canonicalized.
3373 if (!TheLoop->getLoopPreheader()) {
3375 VectorizationReport() <<
3376 "loop control flow is not understood by vectorizer");
3380 // We can only vectorize innermost loops.
3381 if (!TheLoop->getSubLoopsVector().empty()) {
3382 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3386 // We must have a single backedge.
3387 if (TheLoop->getNumBackEdges() != 1) {
3389 VectorizationReport() <<
3390 "loop control flow is not understood by vectorizer");
3394 // We must have a single exiting block.
3395 if (!TheLoop->getExitingBlock()) {
3397 VectorizationReport() <<
3398 "loop control flow is not understood by vectorizer");
3402 // We only handle bottom-tested loops, i.e. loop in which the condition is
3403 // checked at the end of each iteration. With that we can assume that all
3404 // instructions in the loop are executed the same number of times.
3405 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3407 VectorizationReport() <<
3408 "loop control flow is not understood by vectorizer");
3412 // We need to have a loop header.
3413 DEBUG(dbgs() << "LV: Found a loop: " <<
3414 TheLoop->getHeader()->getName() << '\n');
3416 // Check if we can if-convert non-single-bb loops.
3417 unsigned NumBlocks = TheLoop->getNumBlocks();
3418 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3419 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3423 // ScalarEvolution needs to be able to find the exit count.
3424 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3425 if (ExitCount == SE->getCouldNotCompute()) {
3426 emitAnalysis(VectorizationReport() <<
3427 "could not determine number of loop iterations");
3428 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3432 // Check if we can vectorize the instructions and CFG in this loop.
3433 if (!canVectorizeInstrs()) {
3434 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3438 // Go over each instruction and look at memory deps.
3439 if (!canVectorizeMemory()) {
3440 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3444 // Collect all of the variables that remain uniform after vectorization.
3445 collectLoopUniforms();
3447 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3448 (LAI->getRuntimePointerCheck()->Need ? " (with a runtime bound check)" :
3452 // Okay! We can vectorize. At this point we don't have any other mem analysis
3453 // which may limit our maximum vectorization factor, so just return true with
3458 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3459 if (Ty->isPointerTy())
3460 return DL.getIntPtrType(Ty);
3462 // It is possible that char's or short's overflow when we ask for the loop's
3463 // trip count, work around this by changing the type size.
3464 if (Ty->getScalarSizeInBits() < 32)
3465 return Type::getInt32Ty(Ty->getContext());
3470 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3471 Ty0 = convertPointerToIntegerType(DL, Ty0);
3472 Ty1 = convertPointerToIntegerType(DL, Ty1);
3473 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3478 /// \brief Check that the instruction has outside loop users and is not an
3479 /// identified reduction variable.
3480 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3481 SmallPtrSetImpl<Value *> &Reductions) {
3482 // Reduction instructions are allowed to have exit users. All other
3483 // instructions must not have external users.
3484 if (!Reductions.count(Inst))
3485 //Check that all of the users of the loop are inside the BB.
3486 for (User *U : Inst->users()) {
3487 Instruction *UI = cast<Instruction>(U);
3488 // This user may be a reduction exit value.
3489 if (!TheLoop->contains(UI)) {
3490 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3497 bool LoopVectorizationLegality::canVectorizeInstrs() {
3498 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3499 BasicBlock *Header = TheLoop->getHeader();
3501 // Look for the attribute signaling the absence of NaNs.
3502 Function &F = *Header->getParent();
3503 const DataLayout &DL = F.getParent()->getDataLayout();
3504 if (F.hasFnAttribute("no-nans-fp-math"))
3506 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
3508 // For each block in the loop.
3509 for (Loop::block_iterator bb = TheLoop->block_begin(),
3510 be = TheLoop->block_end(); bb != be; ++bb) {
3512 // Scan the instructions in the block and look for hazards.
3513 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3516 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3517 Type *PhiTy = Phi->getType();
3518 // Check that this PHI type is allowed.
3519 if (!PhiTy->isIntegerTy() &&
3520 !PhiTy->isFloatingPointTy() &&
3521 !PhiTy->isPointerTy()) {
3522 emitAnalysis(VectorizationReport(it)
3523 << "loop control flow is not understood by vectorizer");
3524 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3528 // If this PHINode is not in the header block, then we know that we
3529 // can convert it to select during if-conversion. No need to check if
3530 // the PHIs in this block are induction or reduction variables.
3531 if (*bb != Header) {
3532 // Check that this instruction has no outside users or is an
3533 // identified reduction value with an outside user.
3534 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3536 emitAnalysis(VectorizationReport(it) <<
3537 "value could not be identified as "
3538 "an induction or reduction variable");
3542 // We only allow if-converted PHIs with exactly two incoming values.
3543 if (Phi->getNumIncomingValues() != 2) {
3544 emitAnalysis(VectorizationReport(it)
3545 << "control flow not understood by vectorizer");
3546 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3550 // This is the value coming from the preheader.
3551 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3552 ConstantInt *StepValue = nullptr;
3553 // Check if this is an induction variable.
3554 InductionKind IK = isInductionVariable(Phi, StepValue);
3556 if (IK_NoInduction != IK) {
3557 // Get the widest type.
3559 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
3561 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
3563 // Int inductions are special because we only allow one IV.
3564 if (IK == IK_IntInduction && StepValue->isOne()) {
3565 // Use the phi node with the widest type as induction. Use the last
3566 // one if there are multiple (no good reason for doing this other
3567 // than it is expedient).
3568 if (!Induction || PhiTy == WidestIndTy)
3572 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3573 Inductions[Phi] = InductionInfo(StartValue, IK, StepValue);
3575 // Until we explicitly handle the case of an induction variable with
3576 // an outside loop user we have to give up vectorizing this loop.
3577 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3578 emitAnalysis(VectorizationReport(it) <<
3579 "use of induction value outside of the "
3580 "loop is not handled by vectorizer");
3587 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3588 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3591 if (AddReductionVar(Phi, RK_IntegerMult)) {
3592 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3595 if (AddReductionVar(Phi, RK_IntegerOr)) {
3596 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3599 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3600 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3603 if (AddReductionVar(Phi, RK_IntegerXor)) {
3604 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3607 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3608 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3611 if (AddReductionVar(Phi, RK_FloatMult)) {
3612 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3615 if (AddReductionVar(Phi, RK_FloatAdd)) {
3616 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3619 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3620 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3625 emitAnalysis(VectorizationReport(it) <<
3626 "value that could not be identified as "
3627 "reduction is used outside the loop");
3628 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3630 }// end of PHI handling
3632 // We still don't handle functions. However, we can ignore dbg intrinsic
3633 // calls and we do handle certain intrinsic and libm functions.
3634 CallInst *CI = dyn_cast<CallInst>(it);
3635 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3636 emitAnalysis(VectorizationReport(it) <<
3637 "call instruction cannot be vectorized");
3638 DEBUG(dbgs() << "LV: Found a call site.\n");
3642 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
3643 // second argument is the same (i.e. loop invariant)
3645 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
3646 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
3647 emitAnalysis(VectorizationReport(it)
3648 << "intrinsic instruction cannot be vectorized");
3649 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
3654 // Check that the instruction return type is vectorizable.
3655 // Also, we can't vectorize extractelement instructions.
3656 if ((!VectorType::isValidElementType(it->getType()) &&
3657 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3658 emitAnalysis(VectorizationReport(it)
3659 << "instruction return type cannot be vectorized");
3660 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3664 // Check that the stored type is vectorizable.
3665 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3666 Type *T = ST->getValueOperand()->getType();
3667 if (!VectorType::isValidElementType(T)) {
3668 emitAnalysis(VectorizationReport(ST) <<
3669 "store instruction cannot be vectorized");
3672 if (EnableMemAccessVersioning)
3673 collectStridedAccess(ST);
3676 if (EnableMemAccessVersioning)
3677 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3678 collectStridedAccess(LI);
3680 // Reduction instructions are allowed to have exit users.
3681 // All other instructions must not have external users.
3682 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3683 emitAnalysis(VectorizationReport(it) <<
3684 "value cannot be used outside the loop");
3693 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3694 if (Inductions.empty()) {
3695 emitAnalysis(VectorizationReport()
3696 << "loop induction variable could not be identified");
3704 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3705 /// return the induction operand of the gep pointer.
3706 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
3707 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3711 unsigned InductionOperand = getGEPInductionOperand(GEP);
3713 // Check that all of the gep indices are uniform except for our induction
3715 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3716 if (i != InductionOperand &&
3717 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3719 return GEP->getOperand(InductionOperand);
3722 ///\brief Look for a cast use of the passed value.
3723 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3724 Value *UniqueCast = nullptr;
3725 for (User *U : Ptr->users()) {
3726 CastInst *CI = dyn_cast<CastInst>(U);
3727 if (CI && CI->getType() == Ty) {
3737 ///\brief Get the stride of a pointer access in a loop.
3738 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3739 /// pointer to the Value, or null otherwise.
3740 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
3741 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3742 if (!PtrTy || PtrTy->isAggregateType())
3745 // Try to remove a gep instruction to make the pointer (actually index at this
3746 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3747 // pointer, otherwise, we are analyzing the index.
3748 Value *OrigPtr = Ptr;
3750 // The size of the pointer access.
3751 int64_t PtrAccessSize = 1;
3753 Ptr = stripGetElementPtr(Ptr, SE, Lp);
3754 const SCEV *V = SE->getSCEV(Ptr);
3758 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3759 V = C->getOperand();
3761 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3765 V = S->getStepRecurrence(*SE);
3769 // Strip off the size of access multiplication if we are still analyzing the
3771 if (OrigPtr == Ptr) {
3772 const DataLayout &DL = Lp->getHeader()->getModule()->getDataLayout();
3773 DL.getTypeAllocSize(PtrTy->getElementType());
3774 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3775 if (M->getOperand(0)->getSCEVType() != scConstant)
3778 const APInt &APStepVal =
3779 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3781 // Huge step value - give up.
3782 if (APStepVal.getBitWidth() > 64)
3785 int64_t StepVal = APStepVal.getSExtValue();
3786 if (PtrAccessSize != StepVal)
3788 V = M->getOperand(1);
3793 Type *StripedOffRecurrenceCast = nullptr;
3794 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3795 StripedOffRecurrenceCast = C->getType();
3796 V = C->getOperand();
3799 // Look for the loop invariant symbolic value.
3800 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3804 Value *Stride = U->getValue();
3805 if (!Lp->isLoopInvariant(Stride))
3808 // If we have stripped off the recurrence cast we have to make sure that we
3809 // return the value that is used in this loop so that we can replace it later.
3810 if (StripedOffRecurrenceCast)
3811 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3816 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
3817 Value *Ptr = nullptr;
3818 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3819 Ptr = LI->getPointerOperand();
3820 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3821 Ptr = SI->getPointerOperand();
3825 Value *Stride = getStrideFromPointer(Ptr, SE, TheLoop);
3829 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3830 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3831 Strides[Ptr] = Stride;
3832 StrideSet.insert(Stride);
3835 void LoopVectorizationLegality::collectLoopUniforms() {
3836 // We now know that the loop is vectorizable!
3837 // Collect variables that will remain uniform after vectorization.
3838 std::vector<Value*> Worklist;
3839 BasicBlock *Latch = TheLoop->getLoopLatch();
3841 // Start with the conditional branch and walk up the block.
3842 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3844 // Also add all consecutive pointer values; these values will be uniform
3845 // after vectorization (and subsequent cleanup) and, until revectorization is
3846 // supported, all dependencies must also be uniform.
3847 for (Loop::block_iterator B = TheLoop->block_begin(),
3848 BE = TheLoop->block_end(); B != BE; ++B)
3849 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3851 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3852 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3854 while (!Worklist.empty()) {
3855 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3856 Worklist.pop_back();
3858 // Look at instructions inside this loop.
3859 // Stop when reaching PHI nodes.
3860 // TODO: we need to follow values all over the loop, not only in this block.
3861 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3864 // This is a known uniform.
3867 // Insert all operands.
3868 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3872 bool LoopVectorizationLegality::canVectorizeMemory() {
3873 LAI = &LAA->getInfo(TheLoop, Strides);
3874 auto &OptionalReport = LAI->getReport();
3876 emitAnalysis(VectorizationReport(*OptionalReport));
3877 if (!LAI->canVectorizeMemory())
3880 if (LAI->getNumRuntimePointerChecks() >
3881 VectorizerParams::RuntimeMemoryCheckThreshold) {
3882 emitAnalysis(VectorizationReport()
3883 << LAI->getNumRuntimePointerChecks() << " exceeds limit of "
3884 << VectorizerParams::RuntimeMemoryCheckThreshold
3885 << " dependent memory operations checked at runtime");
3886 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
3892 static bool hasMultipleUsesOf(Instruction *I,
3893 SmallPtrSetImpl<Instruction *> &Insts) {
3894 unsigned NumUses = 0;
3895 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
3896 if (Insts.count(dyn_cast<Instruction>(*Use)))
3905 static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set) {
3906 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
3907 if (!Set.count(dyn_cast<Instruction>(*Use)))
3912 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
3913 ReductionKind Kind) {
3914 if (Phi->getNumIncomingValues() != 2)
3917 // Reduction variables are only found in the loop header block.
3918 if (Phi->getParent() != TheLoop->getHeader())
3921 // Obtain the reduction start value from the value that comes from the loop
3923 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
3925 // ExitInstruction is the single value which is used outside the loop.
3926 // We only allow for a single reduction value to be used outside the loop.
3927 // This includes users of the reduction, variables (which form a cycle
3928 // which ends in the phi node).
3929 Instruction *ExitInstruction = nullptr;
3930 // Indicates that we found a reduction operation in our scan.
3931 bool FoundReduxOp = false;
3933 // We start with the PHI node and scan for all of the users of this
3934 // instruction. All users must be instructions that can be used as reduction
3935 // variables (such as ADD). We must have a single out-of-block user. The cycle
3936 // must include the original PHI.
3937 bool FoundStartPHI = false;
3939 // To recognize min/max patterns formed by a icmp select sequence, we store
3940 // the number of instruction we saw from the recognized min/max pattern,
3941 // to make sure we only see exactly the two instructions.
3942 unsigned NumCmpSelectPatternInst = 0;
3943 ReductionInstDesc ReduxDesc(false, nullptr);
3945 SmallPtrSet<Instruction *, 8> VisitedInsts;
3946 SmallVector<Instruction *, 8> Worklist;
3947 Worklist.push_back(Phi);
3948 VisitedInsts.insert(Phi);
3950 // A value in the reduction can be used:
3951 // - By the reduction:
3952 // - Reduction operation:
3953 // - One use of reduction value (safe).
3954 // - Multiple use of reduction value (not safe).
3956 // - All uses of the PHI must be the reduction (safe).
3957 // - Otherwise, not safe.
3958 // - By one instruction outside of the loop (safe).
3959 // - By further instructions outside of the loop (not safe).
3960 // - By an instruction that is not part of the reduction (not safe).
3962 // * An instruction type other than PHI or the reduction operation.
3963 // * A PHI in the header other than the initial PHI.
3964 while (!Worklist.empty()) {
3965 Instruction *Cur = Worklist.back();
3966 Worklist.pop_back();
3969 // If the instruction has no users then this is a broken chain and can't be
3970 // a reduction variable.
3971 if (Cur->use_empty())
3974 bool IsAPhi = isa<PHINode>(Cur);
3976 // A header PHI use other than the original PHI.
3977 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
3980 // Reductions of instructions such as Div, and Sub is only possible if the
3981 // LHS is the reduction variable.
3982 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
3983 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
3984 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
3987 // Any reduction instruction must be of one of the allowed kinds.
3988 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
3989 if (!ReduxDesc.IsReduction)
3992 // A reduction operation must only have one use of the reduction value.
3993 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
3994 hasMultipleUsesOf(Cur, VisitedInsts))
3997 // All inputs to a PHI node must be a reduction value.
3998 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4001 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4002 isa<SelectInst>(Cur)))
4003 ++NumCmpSelectPatternInst;
4004 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4005 isa<SelectInst>(Cur)))
4006 ++NumCmpSelectPatternInst;
4008 // Check whether we found a reduction operator.
4009 FoundReduxOp |= !IsAPhi;
4011 // Process users of current instruction. Push non-PHI nodes after PHI nodes
4012 // onto the stack. This way we are going to have seen all inputs to PHI
4013 // nodes once we get to them.
4014 SmallVector<Instruction *, 8> NonPHIs;
4015 SmallVector<Instruction *, 8> PHIs;
4016 for (User *U : Cur->users()) {
4017 Instruction *UI = cast<Instruction>(U);
4019 // Check if we found the exit user.
4020 BasicBlock *Parent = UI->getParent();
4021 if (!TheLoop->contains(Parent)) {
4022 // Exit if you find multiple outside users or if the header phi node is
4023 // being used. In this case the user uses the value of the previous
4024 // iteration, in which case we would loose "VF-1" iterations of the
4025 // reduction operation if we vectorize.
4026 if (ExitInstruction != nullptr || Cur == Phi)
4029 // The instruction used by an outside user must be the last instruction
4030 // before we feed back to the reduction phi. Otherwise, we loose VF-1
4031 // operations on the value.
4032 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
4035 ExitInstruction = Cur;
4039 // Process instructions only once (termination). Each reduction cycle
4040 // value must only be used once, except by phi nodes and min/max
4041 // reductions which are represented as a cmp followed by a select.
4042 ReductionInstDesc IgnoredVal(false, nullptr);
4043 if (VisitedInsts.insert(UI).second) {
4044 if (isa<PHINode>(UI))
4047 NonPHIs.push_back(UI);
4048 } else if (!isa<PHINode>(UI) &&
4049 ((!isa<FCmpInst>(UI) &&
4050 !isa<ICmpInst>(UI) &&
4051 !isa<SelectInst>(UI)) ||
4052 !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
4055 // Remember that we completed the cycle.
4057 FoundStartPHI = true;
4059 Worklist.append(PHIs.begin(), PHIs.end());
4060 Worklist.append(NonPHIs.begin(), NonPHIs.end());
4063 // This means we have seen one but not the other instruction of the
4064 // pattern or more than just a select and cmp.
4065 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4066 NumCmpSelectPatternInst != 2)
4069 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4072 // We found a reduction var if we have reached the original phi node and we
4073 // only have a single instruction with out-of-loop users.
4075 // This instruction is allowed to have out-of-loop users.
4076 AllowedExit.insert(ExitInstruction);
4078 // Save the description of this reduction variable.
4079 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4080 ReduxDesc.MinMaxKind);
4081 Reductions[Phi] = RD;
4082 // We've ended the cycle. This is a reduction variable if we have an
4083 // outside user and it has a binary op.
4088 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4089 /// pattern corresponding to a min(X, Y) or max(X, Y).
4090 LoopVectorizationLegality::ReductionInstDesc
4091 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4092 ReductionInstDesc &Prev) {
4094 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4095 "Expect a select instruction");
4096 Instruction *Cmp = nullptr;
4097 SelectInst *Select = nullptr;
4099 // We must handle the select(cmp()) as a single instruction. Advance to the
4101 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4102 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
4103 return ReductionInstDesc(false, I);
4104 return ReductionInstDesc(Select, Prev.MinMaxKind);
4107 // Only handle single use cases for now.
4108 if (!(Select = dyn_cast<SelectInst>(I)))
4109 return ReductionInstDesc(false, I);
4110 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4111 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4112 return ReductionInstDesc(false, I);
4113 if (!Cmp->hasOneUse())
4114 return ReductionInstDesc(false, I);
4119 // Look for a min/max pattern.
4120 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4121 return ReductionInstDesc(Select, MRK_UIntMin);
4122 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4123 return ReductionInstDesc(Select, MRK_UIntMax);
4124 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4125 return ReductionInstDesc(Select, MRK_SIntMax);
4126 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4127 return ReductionInstDesc(Select, MRK_SIntMin);
4128 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4129 return ReductionInstDesc(Select, MRK_FloatMin);
4130 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4131 return ReductionInstDesc(Select, MRK_FloatMax);
4132 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4133 return ReductionInstDesc(Select, MRK_FloatMin);
4134 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4135 return ReductionInstDesc(Select, MRK_FloatMax);
4137 return ReductionInstDesc(false, I);
4140 LoopVectorizationLegality::ReductionInstDesc
4141 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4143 ReductionInstDesc &Prev) {
4144 bool FP = I->getType()->isFloatingPointTy();
4145 bool FastMath = FP && I->hasUnsafeAlgebra();
4146 switch (I->getOpcode()) {
4148 return ReductionInstDesc(false, I);
4149 case Instruction::PHI:
4150 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4151 Kind != RK_FloatMinMax))
4152 return ReductionInstDesc(false, I);
4153 return ReductionInstDesc(I, Prev.MinMaxKind);
4154 case Instruction::Sub:
4155 case Instruction::Add:
4156 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4157 case Instruction::Mul:
4158 return ReductionInstDesc(Kind == RK_IntegerMult, I);
4159 case Instruction::And:
4160 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4161 case Instruction::Or:
4162 return ReductionInstDesc(Kind == RK_IntegerOr, I);
4163 case Instruction::Xor:
4164 return ReductionInstDesc(Kind == RK_IntegerXor, I);
4165 case Instruction::FMul:
4166 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4167 case Instruction::FSub:
4168 case Instruction::FAdd:
4169 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4170 case Instruction::FCmp:
4171 case Instruction::ICmp:
4172 case Instruction::Select:
4173 if (Kind != RK_IntegerMinMax &&
4174 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4175 return ReductionInstDesc(false, I);
4176 return isMinMaxSelectCmpPattern(I, Prev);
4180 LoopVectorizationLegality::InductionKind
4181 LoopVectorizationLegality::isInductionVariable(PHINode *Phi,
4182 ConstantInt *&StepValue) {
4183 Type *PhiTy = Phi->getType();
4184 // We only handle integer and pointer inductions variables.
4185 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4186 return IK_NoInduction;
4188 // Check that the PHI is consecutive.
4189 const SCEV *PhiScev = SE->getSCEV(Phi);
4190 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4192 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4193 return IK_NoInduction;
4196 const SCEV *Step = AR->getStepRecurrence(*SE);
4197 // Calculate the pointer stride and check if it is consecutive.
4198 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4200 return IK_NoInduction;
4202 ConstantInt *CV = C->getValue();
4203 if (PhiTy->isIntegerTy()) {
4205 return IK_IntInduction;
4208 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4209 Type *PointerElementType = PhiTy->getPointerElementType();
4210 // The pointer stride cannot be determined if the pointer element type is not
4212 if (!PointerElementType->isSized())
4213 return IK_NoInduction;
4215 const DataLayout &DL = Phi->getModule()->getDataLayout();
4216 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
4217 int64_t CVSize = CV->getSExtValue();
4219 return IK_NoInduction;
4220 StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
4221 return IK_PtrInduction;
4224 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4225 Value *In0 = const_cast<Value*>(V);
4226 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4230 return Inductions.count(PN);
4233 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4234 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4237 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4238 SmallPtrSetImpl<Value *> &SafePtrs) {
4240 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4241 // Check that we don't have a constant expression that can trap as operand.
4242 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4244 if (Constant *C = dyn_cast<Constant>(*OI))
4248 // We might be able to hoist the load.
4249 if (it->mayReadFromMemory()) {
4250 LoadInst *LI = dyn_cast<LoadInst>(it);
4253 if (!SafePtrs.count(LI->getPointerOperand())) {
4254 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4255 MaskedOp.insert(LI);
4262 // We don't predicate stores at the moment.
4263 if (it->mayWriteToMemory()) {
4264 StoreInst *SI = dyn_cast<StoreInst>(it);
4265 // We only support predication of stores in basic blocks with one
4270 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4271 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4273 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4274 !isSinglePredecessor) {
4275 // Build a masked store if it is legal for the target, otherwise scalarize
4277 bool isLegalMaskedOp =
4278 isLegalMaskedStore(SI->getValueOperand()->getType(),
4279 SI->getPointerOperand());
4280 if (isLegalMaskedOp) {
4282 MaskedOp.insert(SI);
4291 // The instructions below can trap.
4292 switch (it->getOpcode()) {
4294 case Instruction::UDiv:
4295 case Instruction::SDiv:
4296 case Instruction::URem:
4297 case Instruction::SRem:
4305 LoopVectorizationCostModel::VectorizationFactor
4306 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4307 // Width 1 means no vectorize
4308 VectorizationFactor Factor = { 1U, 0U };
4309 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4310 emitAnalysis(VectorizationReport() <<
4311 "runtime pointer checks needed. Enable vectorization of this "
4312 "loop with '#pragma clang loop vectorize(enable)' when "
4313 "compiling with -Os");
4314 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4318 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4319 emitAnalysis(VectorizationReport() <<
4320 "store that is conditionally executed prevents vectorization");
4321 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4325 // Find the trip count.
4326 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4327 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4329 unsigned WidestType = getWidestType();
4330 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4331 unsigned MaxSafeDepDist = -1U;
4332 if (Legal->getMaxSafeDepDistBytes() != -1U)
4333 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4334 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4335 WidestRegister : MaxSafeDepDist);
4336 unsigned MaxVectorSize = WidestRegister / WidestType;
4337 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4338 DEBUG(dbgs() << "LV: The Widest register is: "
4339 << WidestRegister << " bits.\n");
4341 if (MaxVectorSize == 0) {
4342 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4346 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4347 " into one vector!");
4349 unsigned VF = MaxVectorSize;
4351 // If we optimize the program for size, avoid creating the tail loop.
4353 // If we are unable to calculate the trip count then don't try to vectorize.
4356 (VectorizationReport() <<
4357 "unable to calculate the loop count due to complex control flow");
4358 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4362 // Find the maximum SIMD width that can fit within the trip count.
4363 VF = TC % MaxVectorSize;
4368 // If the trip count that we found modulo the vectorization factor is not
4369 // zero then we require a tail.
4371 emitAnalysis(VectorizationReport() <<
4372 "cannot optimize for size and vectorize at the "
4373 "same time. Enable vectorization of this loop "
4374 "with '#pragma clang loop vectorize(enable)' "
4375 "when compiling with -Os");
4376 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4381 int UserVF = Hints->getWidth();
4383 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4384 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4386 Factor.Width = UserVF;
4390 float Cost = expectedCost(1);
4392 const float ScalarCost = Cost;
4395 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4397 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4398 // Ignore scalar width, because the user explicitly wants vectorization.
4399 if (ForceVectorization && VF > 1) {
4401 Cost = expectedCost(Width) / (float)Width;
4404 for (unsigned i=2; i <= VF; i*=2) {
4405 // Notice that the vector loop needs to be executed less times, so
4406 // we need to divide the cost of the vector loops by the width of
4407 // the vector elements.
4408 float VectorCost = expectedCost(i) / (float)i;
4409 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4410 (int)VectorCost << ".\n");
4411 if (VectorCost < Cost) {
4417 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4418 << "LV: Vectorization seems to be not beneficial, "
4419 << "but was forced by a user.\n");
4420 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4421 Factor.Width = Width;
4422 Factor.Cost = Width * Cost;
4426 unsigned LoopVectorizationCostModel::getWidestType() {
4427 unsigned MaxWidth = 8;
4428 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4431 for (Loop::block_iterator bb = TheLoop->block_begin(),
4432 be = TheLoop->block_end(); bb != be; ++bb) {
4433 BasicBlock *BB = *bb;
4435 // For each instruction in the loop.
4436 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4437 Type *T = it->getType();
4439 // Ignore ephemeral values.
4440 if (EphValues.count(it))
4443 // Only examine Loads, Stores and PHINodes.
4444 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4447 // Examine PHI nodes that are reduction variables.
4448 if (PHINode *PN = dyn_cast<PHINode>(it))
4449 if (!Legal->getReductionVars()->count(PN))
4452 // Examine the stored values.
4453 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4454 T = ST->getValueOperand()->getType();
4456 // Ignore loaded pointer types and stored pointer types that are not
4457 // consecutive. However, we do want to take consecutive stores/loads of
4458 // pointer vectors into account.
4459 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4462 MaxWidth = std::max(MaxWidth,
4463 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4471 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
4473 unsigned LoopCost) {
4475 // -- The unroll heuristics --
4476 // We unroll the loop in order to expose ILP and reduce the loop overhead.
4477 // There are many micro-architectural considerations that we can't predict
4478 // at this level. For example, frontend pressure (on decode or fetch) due to
4479 // code size, or the number and capabilities of the execution ports.
4481 // We use the following heuristics to select the unroll factor:
4482 // 1. If the code has reductions, then we unroll in order to break the cross
4483 // iteration dependency.
4484 // 2. If the loop is really small, then we unroll in order to reduce the loop
4486 // 3. We don't unroll if we think that we will spill registers to memory due
4487 // to the increased register pressure.
4489 // Use the user preference, unless 'auto' is selected.
4490 int UserUF = Hints->getInterleave();
4494 // When we optimize for size, we don't unroll.
4498 // We used the distance for the unroll factor.
4499 if (Legal->getMaxSafeDepDistBytes() != -1U)
4502 // Do not unroll loops with a relatively small trip count.
4503 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4504 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
4507 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4508 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4512 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4513 TargetNumRegisters = ForceTargetNumScalarRegs;
4515 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4516 TargetNumRegisters = ForceTargetNumVectorRegs;
4519 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4520 // We divide by these constants so assume that we have at least one
4521 // instruction that uses at least one register.
4522 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4523 R.NumInstructions = std::max(R.NumInstructions, 1U);
4525 // We calculate the unroll factor using the following formula.
4526 // Subtract the number of loop invariants from the number of available
4527 // registers. These registers are used by all of the unrolled instances.
4528 // Next, divide the remaining registers by the number of registers that is
4529 // required by the loop, in order to estimate how many parallel instances
4530 // fit without causing spills. All of this is rounded down if necessary to be
4531 // a power of two. We want power of two unroll factors to simplify any
4532 // addressing operations or alignment considerations.
4533 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4536 // Don't count the induction variable as unrolled.
4537 if (EnableIndVarRegisterHeur)
4538 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4539 std::max(1U, (R.MaxLocalUsers - 1)));
4541 // Clamp the unroll factor ranges to reasonable factors.
4542 unsigned MaxInterleaveSize = TTI.getMaxInterleaveFactor();
4544 // Check if the user has overridden the unroll max.
4546 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4547 MaxInterleaveSize = ForceTargetMaxScalarInterleaveFactor;
4549 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4550 MaxInterleaveSize = ForceTargetMaxVectorInterleaveFactor;
4553 // If we did not calculate the cost for VF (because the user selected the VF)
4554 // then we calculate the cost of VF here.
4556 LoopCost = expectedCost(VF);
4558 // Clamp the calculated UF to be between the 1 and the max unroll factor
4559 // that the target allows.
4560 if (UF > MaxInterleaveSize)
4561 UF = MaxInterleaveSize;
4565 // Unroll if we vectorized this loop and there is a reduction that could
4566 // benefit from unrolling.
4567 if (VF > 1 && Legal->getReductionVars()->size()) {
4568 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
4572 // Note that if we've already vectorized the loop we will have done the
4573 // runtime check and so unrolling won't require further checks.
4574 bool UnrollingRequiresRuntimePointerCheck =
4575 (VF == 1 && Legal->getRuntimePointerCheck()->Need);
4577 // We want to unroll small loops in order to reduce the loop overhead and
4578 // potentially expose ILP opportunities.
4579 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4580 if (!UnrollingRequiresRuntimePointerCheck &&
4581 LoopCost < SmallLoopCost) {
4582 // We assume that the cost overhead is 1 and we use the cost model
4583 // to estimate the cost of the loop and unroll until the cost of the
4584 // loop overhead is about 5% of the cost of the loop.
4585 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4587 // Unroll until store/load ports (estimated by max unroll factor) are
4589 unsigned NumStores = Legal->getNumStores();
4590 unsigned NumLoads = Legal->getNumLoads();
4591 unsigned StoresUF = UF / (NumStores ? NumStores : 1);
4592 unsigned LoadsUF = UF / (NumLoads ? NumLoads : 1);
4594 // If we have a scalar reduction (vector reductions are already dealt with
4595 // by this point), we can increase the critical path length if the loop
4596 // we're unrolling is inside another loop. Limit, by default to 2, so the
4597 // critical path only gets increased by one reduction operation.
4598 if (Legal->getReductionVars()->size() &&
4599 TheLoop->getLoopDepth() > 1) {
4600 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionUF);
4601 SmallUF = std::min(SmallUF, F);
4602 StoresUF = std::min(StoresUF, F);
4603 LoadsUF = std::min(LoadsUF, F);
4606 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
4607 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
4608 return std::max(StoresUF, LoadsUF);
4611 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
4615 // Unroll if this is a large loop (small loops are already dealt with by this
4616 // point) that could benefit from interleaved unrolling.
4617 bool HasReductions = (Legal->getReductionVars()->size() > 0);
4618 if (TTI.enableAggressiveInterleaving(HasReductions)) {
4619 DEBUG(dbgs() << "LV: Unrolling to expose ILP.\n");
4623 DEBUG(dbgs() << "LV: Not Unrolling.\n");
4627 LoopVectorizationCostModel::RegisterUsage
4628 LoopVectorizationCostModel::calculateRegisterUsage() {
4629 // This function calculates the register usage by measuring the highest number
4630 // of values that are alive at a single location. Obviously, this is a very
4631 // rough estimation. We scan the loop in a topological order in order and
4632 // assign a number to each instruction. We use RPO to ensure that defs are
4633 // met before their users. We assume that each instruction that has in-loop
4634 // users starts an interval. We record every time that an in-loop value is
4635 // used, so we have a list of the first and last occurrences of each
4636 // instruction. Next, we transpose this data structure into a multi map that
4637 // holds the list of intervals that *end* at a specific location. This multi
4638 // map allows us to perform a linear search. We scan the instructions linearly
4639 // and record each time that a new interval starts, by placing it in a set.
4640 // If we find this value in the multi-map then we remove it from the set.
4641 // The max register usage is the maximum size of the set.
4642 // We also search for instructions that are defined outside the loop, but are
4643 // used inside the loop. We need this number separately from the max-interval
4644 // usage number because when we unroll, loop-invariant values do not take
4646 LoopBlocksDFS DFS(TheLoop);
4650 R.NumInstructions = 0;
4652 // Each 'key' in the map opens a new interval. The values
4653 // of the map are the index of the 'last seen' usage of the
4654 // instruction that is the key.
4655 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4656 // Maps instruction to its index.
4657 DenseMap<unsigned, Instruction*> IdxToInstr;
4658 // Marks the end of each interval.
4659 IntervalMap EndPoint;
4660 // Saves the list of instruction indices that are used in the loop.
4661 SmallSet<Instruction*, 8> Ends;
4662 // Saves the list of values that are used in the loop but are
4663 // defined outside the loop, such as arguments and constants.
4664 SmallPtrSet<Value*, 8> LoopInvariants;
4667 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4668 be = DFS.endRPO(); bb != be; ++bb) {
4669 R.NumInstructions += (*bb)->size();
4670 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4672 Instruction *I = it;
4673 IdxToInstr[Index++] = I;
4675 // Save the end location of each USE.
4676 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4677 Value *U = I->getOperand(i);
4678 Instruction *Instr = dyn_cast<Instruction>(U);
4680 // Ignore non-instruction values such as arguments, constants, etc.
4681 if (!Instr) continue;
4683 // If this instruction is outside the loop then record it and continue.
4684 if (!TheLoop->contains(Instr)) {
4685 LoopInvariants.insert(Instr);
4689 // Overwrite previous end points.
4690 EndPoint[Instr] = Index;
4696 // Saves the list of intervals that end with the index in 'key'.
4697 typedef SmallVector<Instruction*, 2> InstrList;
4698 DenseMap<unsigned, InstrList> TransposeEnds;
4700 // Transpose the EndPoints to a list of values that end at each index.
4701 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4703 TransposeEnds[it->second].push_back(it->first);
4705 SmallSet<Instruction*, 8> OpenIntervals;
4706 unsigned MaxUsage = 0;
4709 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4710 for (unsigned int i = 0; i < Index; ++i) {
4711 Instruction *I = IdxToInstr[i];
4712 // Ignore instructions that are never used within the loop.
4713 if (!Ends.count(I)) continue;
4715 // Ignore ephemeral values.
4716 if (EphValues.count(I))
4719 // Remove all of the instructions that end at this location.
4720 InstrList &List = TransposeEnds[i];
4721 for (unsigned int j=0, e = List.size(); j < e; ++j)
4722 OpenIntervals.erase(List[j]);
4724 // Count the number of live interals.
4725 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4727 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4728 OpenIntervals.size() << '\n');
4730 // Add the current instruction to the list of open intervals.
4731 OpenIntervals.insert(I);
4734 unsigned Invariant = LoopInvariants.size();
4735 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
4736 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
4737 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
4739 R.LoopInvariantRegs = Invariant;
4740 R.MaxLocalUsers = MaxUsage;
4744 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4748 for (Loop::block_iterator bb = TheLoop->block_begin(),
4749 be = TheLoop->block_end(); bb != be; ++bb) {
4750 unsigned BlockCost = 0;
4751 BasicBlock *BB = *bb;
4753 // For each instruction in the old loop.
4754 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4755 // Skip dbg intrinsics.
4756 if (isa<DbgInfoIntrinsic>(it))
4759 // Ignore ephemeral values.
4760 if (EphValues.count(it))
4763 unsigned C = getInstructionCost(it, VF);
4765 // Check if we should override the cost.
4766 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
4767 C = ForceTargetInstructionCost;
4770 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
4771 VF << " For instruction: " << *it << '\n');
4774 // We assume that if-converted blocks have a 50% chance of being executed.
4775 // When the code is scalar then some of the blocks are avoided due to CF.
4776 // When the code is vectorized we execute all code paths.
4777 if (VF == 1 && Legal->blockNeedsPredication(*bb))
4786 /// \brief Check whether the address computation for a non-consecutive memory
4787 /// access looks like an unlikely candidate for being merged into the indexing
4790 /// We look for a GEP which has one index that is an induction variable and all
4791 /// other indices are loop invariant. If the stride of this access is also
4792 /// within a small bound we decide that this address computation can likely be
4793 /// merged into the addressing mode.
4794 /// In all other cases, we identify the address computation as complex.
4795 static bool isLikelyComplexAddressComputation(Value *Ptr,
4796 LoopVectorizationLegality *Legal,
4797 ScalarEvolution *SE,
4798 const Loop *TheLoop) {
4799 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
4803 // We are looking for a gep with all loop invariant indices except for one
4804 // which should be an induction variable.
4805 unsigned NumOperands = Gep->getNumOperands();
4806 for (unsigned i = 1; i < NumOperands; ++i) {
4807 Value *Opd = Gep->getOperand(i);
4808 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
4809 !Legal->isInductionVariable(Opd))
4813 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
4814 // can likely be merged into the address computation.
4815 unsigned MaxMergeDistance = 64;
4817 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
4821 // Check the step is constant.
4822 const SCEV *Step = AddRec->getStepRecurrence(*SE);
4823 // Calculate the pointer stride and check if it is consecutive.
4824 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4828 const APInt &APStepVal = C->getValue()->getValue();
4830 // Huge step value - give up.
4831 if (APStepVal.getBitWidth() > 64)
4834 int64_t StepVal = APStepVal.getSExtValue();
4836 return StepVal > MaxMergeDistance;
4839 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
4840 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
4846 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
4847 // If we know that this instruction will remain uniform, check the cost of
4848 // the scalar version.
4849 if (Legal->isUniformAfterVectorization(I))
4852 Type *RetTy = I->getType();
4853 Type *VectorTy = ToVectorTy(RetTy, VF);
4855 // TODO: We need to estimate the cost of intrinsic calls.
4856 switch (I->getOpcode()) {
4857 case Instruction::GetElementPtr:
4858 // We mark this instruction as zero-cost because the cost of GEPs in
4859 // vectorized code depends on whether the corresponding memory instruction
4860 // is scalarized or not. Therefore, we handle GEPs with the memory
4861 // instruction cost.
4863 case Instruction::Br: {
4864 return TTI.getCFInstrCost(I->getOpcode());
4866 case Instruction::PHI:
4867 //TODO: IF-converted IFs become selects.
4869 case Instruction::Add:
4870 case Instruction::FAdd:
4871 case Instruction::Sub:
4872 case Instruction::FSub:
4873 case Instruction::Mul:
4874 case Instruction::FMul:
4875 case Instruction::UDiv:
4876 case Instruction::SDiv:
4877 case Instruction::FDiv:
4878 case Instruction::URem:
4879 case Instruction::SRem:
4880 case Instruction::FRem:
4881 case Instruction::Shl:
4882 case Instruction::LShr:
4883 case Instruction::AShr:
4884 case Instruction::And:
4885 case Instruction::Or:
4886 case Instruction::Xor: {
4887 // Since we will replace the stride by 1 the multiplication should go away.
4888 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
4890 // Certain instructions can be cheaper to vectorize if they have a constant
4891 // second vector operand. One example of this are shifts on x86.
4892 TargetTransformInfo::OperandValueKind Op1VK =
4893 TargetTransformInfo::OK_AnyValue;
4894 TargetTransformInfo::OperandValueKind Op2VK =
4895 TargetTransformInfo::OK_AnyValue;
4896 TargetTransformInfo::OperandValueProperties Op1VP =
4897 TargetTransformInfo::OP_None;
4898 TargetTransformInfo::OperandValueProperties Op2VP =
4899 TargetTransformInfo::OP_None;
4900 Value *Op2 = I->getOperand(1);
4902 // Check for a splat of a constant or for a non uniform vector of constants.
4903 if (isa<ConstantInt>(Op2)) {
4904 ConstantInt *CInt = cast<ConstantInt>(Op2);
4905 if (CInt && CInt->getValue().isPowerOf2())
4906 Op2VP = TargetTransformInfo::OP_PowerOf2;
4907 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4908 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
4909 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
4910 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
4912 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
4913 if (CInt && CInt->getValue().isPowerOf2())
4914 Op2VP = TargetTransformInfo::OP_PowerOf2;
4915 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4919 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
4922 case Instruction::Select: {
4923 SelectInst *SI = cast<SelectInst>(I);
4924 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
4925 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
4926 Type *CondTy = SI->getCondition()->getType();
4928 CondTy = VectorType::get(CondTy, VF);
4930 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
4932 case Instruction::ICmp:
4933 case Instruction::FCmp: {
4934 Type *ValTy = I->getOperand(0)->getType();
4935 VectorTy = ToVectorTy(ValTy, VF);
4936 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
4938 case Instruction::Store:
4939 case Instruction::Load: {
4940 StoreInst *SI = dyn_cast<StoreInst>(I);
4941 LoadInst *LI = dyn_cast<LoadInst>(I);
4942 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
4944 VectorTy = ToVectorTy(ValTy, VF);
4946 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
4947 unsigned AS = SI ? SI->getPointerAddressSpace() :
4948 LI->getPointerAddressSpace();
4949 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
4950 // We add the cost of address computation here instead of with the gep
4951 // instruction because only here we know whether the operation is
4954 return TTI.getAddressComputationCost(VectorTy) +
4955 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4957 // Scalarized loads/stores.
4958 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
4959 bool Reverse = ConsecutiveStride < 0;
4960 const DataLayout &DL = I->getModule()->getDataLayout();
4961 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
4962 unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
4963 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
4964 bool IsComplexComputation =
4965 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
4967 // The cost of extracting from the value vector and pointer vector.
4968 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
4969 for (unsigned i = 0; i < VF; ++i) {
4970 // The cost of extracting the pointer operand.
4971 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
4972 // In case of STORE, the cost of ExtractElement from the vector.
4973 // In case of LOAD, the cost of InsertElement into the returned
4975 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
4976 Instruction::InsertElement,
4980 // The cost of the scalar loads/stores.
4981 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
4982 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
4987 // Wide load/stores.
4988 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
4989 if (Legal->isMaskRequired(I))
4990 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
4993 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4996 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5000 case Instruction::ZExt:
5001 case Instruction::SExt:
5002 case Instruction::FPToUI:
5003 case Instruction::FPToSI:
5004 case Instruction::FPExt:
5005 case Instruction::PtrToInt:
5006 case Instruction::IntToPtr:
5007 case Instruction::SIToFP:
5008 case Instruction::UIToFP:
5009 case Instruction::Trunc:
5010 case Instruction::FPTrunc:
5011 case Instruction::BitCast: {
5012 // We optimize the truncation of induction variable.
5013 // The cost of these is the same as the scalar operation.
5014 if (I->getOpcode() == Instruction::Trunc &&
5015 Legal->isInductionVariable(I->getOperand(0)))
5016 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5017 I->getOperand(0)->getType());
5019 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5020 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5022 case Instruction::Call: {
5023 CallInst *CI = cast<CallInst>(I);
5024 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5025 assert(ID && "Not an intrinsic call!");
5026 Type *RetTy = ToVectorTy(CI->getType(), VF);
5027 SmallVector<Type*, 4> Tys;
5028 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5029 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5030 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5033 // We are scalarizing the instruction. Return the cost of the scalar
5034 // instruction, plus the cost of insert and extract into vector
5035 // elements, times the vector width.
5038 if (!RetTy->isVoidTy() && VF != 1) {
5039 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5041 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5044 // The cost of inserting the results plus extracting each one of the
5046 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5049 // The cost of executing VF copies of the scalar instruction. This opcode
5050 // is unknown. Assume that it is the same as 'mul'.
5051 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5057 char LoopVectorize::ID = 0;
5058 static const char lv_name[] = "Loop Vectorization";
5059 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5060 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5061 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
5062 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5063 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5064 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5065 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5066 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5067 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5068 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5069 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
5070 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5073 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5074 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5078 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5079 // Check for a store.
5080 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5081 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5083 // Check for a load.
5084 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5085 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5091 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5092 bool IfPredicateStore) {
5093 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5094 // Holds vector parameters or scalars, in case of uniform vals.
5095 SmallVector<VectorParts, 4> Params;
5097 setDebugLocFromInst(Builder, Instr);
5099 // Find all of the vectorized parameters.
5100 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5101 Value *SrcOp = Instr->getOperand(op);
5103 // If we are accessing the old induction variable, use the new one.
5104 if (SrcOp == OldInduction) {
5105 Params.push_back(getVectorValue(SrcOp));
5109 // Try using previously calculated values.
5110 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5112 // If the src is an instruction that appeared earlier in the basic block
5113 // then it should already be vectorized.
5114 if (SrcInst && OrigLoop->contains(SrcInst)) {
5115 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5116 // The parameter is a vector value from earlier.
5117 Params.push_back(WidenMap.get(SrcInst));
5119 // The parameter is a scalar from outside the loop. Maybe even a constant.
5120 VectorParts Scalars;
5121 Scalars.append(UF, SrcOp);
5122 Params.push_back(Scalars);
5126 assert(Params.size() == Instr->getNumOperands() &&
5127 "Invalid number of operands");
5129 // Does this instruction return a value ?
5130 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5132 Value *UndefVec = IsVoidRetTy ? nullptr :
5133 UndefValue::get(Instr->getType());
5134 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5135 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5137 Instruction *InsertPt = Builder.GetInsertPoint();
5138 BasicBlock *IfBlock = Builder.GetInsertBlock();
5139 BasicBlock *CondBlock = nullptr;
5142 Loop *VectorLp = nullptr;
5143 if (IfPredicateStore) {
5144 assert(Instr->getParent()->getSinglePredecessor() &&
5145 "Only support single predecessor blocks");
5146 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5147 Instr->getParent());
5148 VectorLp = LI->getLoopFor(IfBlock);
5149 assert(VectorLp && "Must have a loop for this block");
5152 // For each vector unroll 'part':
5153 for (unsigned Part = 0; Part < UF; ++Part) {
5154 // For each scalar that we create:
5156 // Start an "if (pred) a[i] = ..." block.
5157 Value *Cmp = nullptr;
5158 if (IfPredicateStore) {
5159 if (Cond[Part]->getType()->isVectorTy())
5161 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5162 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5163 ConstantInt::get(Cond[Part]->getType(), 1));
5164 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5165 LoopVectorBody.push_back(CondBlock);
5166 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
5167 // Update Builder with newly created basic block.
5168 Builder.SetInsertPoint(InsertPt);
5171 Instruction *Cloned = Instr->clone();
5173 Cloned->setName(Instr->getName() + ".cloned");
5174 // Replace the operands of the cloned instructions with extracted scalars.
5175 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5176 Value *Op = Params[op][Part];
5177 Cloned->setOperand(op, Op);
5180 // Place the cloned scalar in the new loop.
5181 Builder.Insert(Cloned);
5183 // If the original scalar returns a value we need to place it in a vector
5184 // so that future users will be able to use it.
5186 VecResults[Part] = Cloned;
5189 if (IfPredicateStore) {
5190 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5191 LoopVectorBody.push_back(NewIfBlock);
5192 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
5193 Builder.SetInsertPoint(InsertPt);
5194 Instruction *OldBr = IfBlock->getTerminator();
5195 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
5196 OldBr->eraseFromParent();
5197 IfBlock = NewIfBlock;
5202 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5203 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5204 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5206 return scalarizeInstruction(Instr, IfPredicateStore);
5209 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5213 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5217 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5218 // When unrolling and the VF is 1, we only need to add a simple scalar.
5219 Type *ITy = Val->getType();
5220 assert(!ITy->isVectorTy() && "Val must be a scalar");
5221 Constant *C = ConstantInt::get(ITy, StartIdx);
5222 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");