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"
96 #include "llvm/Transforms/Utils/LoopUtils.h"
101 using namespace llvm;
102 using namespace llvm::PatternMatch;
104 #define LV_NAME "loop-vectorize"
105 #define DEBUG_TYPE LV_NAME
107 STATISTIC(LoopsVectorized, "Number of loops vectorized");
108 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
111 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
112 cl::desc("Enable if-conversion during vectorization."));
114 /// We don't vectorize loops with a known constant trip count below this number.
115 static cl::opt<unsigned>
116 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
118 cl::desc("Don't vectorize loops with a constant "
119 "trip count that is smaller than this "
122 /// This enables versioning on the strides of symbolically striding memory
123 /// accesses in code like the following.
124 /// for (i = 0; i < N; ++i)
125 /// A[i * Stride1] += B[i * Stride2] ...
127 /// Will be roughly translated to
128 /// if (Stride1 == 1 && Stride2 == 1) {
129 /// for (i = 0; i < N; i+=4)
133 static cl::opt<bool> EnableMemAccessVersioning(
134 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
135 cl::desc("Enable symblic stride memory access versioning"));
137 /// We don't unroll loops with a known constant trip count below this number.
138 static const unsigned TinyTripCountUnrollThreshold = 128;
140 static cl::opt<unsigned> ForceTargetNumScalarRegs(
141 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
142 cl::desc("A flag that overrides the target's number of scalar registers."));
144 static cl::opt<unsigned> ForceTargetNumVectorRegs(
145 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
146 cl::desc("A flag that overrides the target's number of vector registers."));
148 /// Maximum vectorization interleave count.
149 static const unsigned MaxInterleaveFactor = 16;
151 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
152 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
153 cl::desc("A flag that overrides the target's max interleave factor for "
156 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
157 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
158 cl::desc("A flag that overrides the target's max interleave factor for "
159 "vectorized loops."));
161 static cl::opt<unsigned> ForceTargetInstructionCost(
162 "force-target-instruction-cost", cl::init(0), cl::Hidden,
163 cl::desc("A flag that overrides the target's expected cost for "
164 "an instruction to a single constant value. Mostly "
165 "useful for getting consistent testing."));
167 static cl::opt<unsigned> SmallLoopCost(
168 "small-loop-cost", cl::init(20), cl::Hidden,
169 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
171 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
172 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
173 cl::desc("Enable the use of the block frequency analysis to access PGO "
174 "heuristics minimizing code growth in cold regions and being more "
175 "aggressive in hot regions."));
177 // Runtime unroll loops for load/store throughput.
178 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
179 "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
180 cl::desc("Enable runtime unrolling until load/store ports are saturated"));
182 /// The number of stores in a loop that are allowed to need predication.
183 static cl::opt<unsigned> NumberOfStoresToPredicate(
184 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
185 cl::desc("Max number of stores to be predicated behind an if."));
187 static cl::opt<bool> EnableIndVarRegisterHeur(
188 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
189 cl::desc("Count the induction variable only once when unrolling"));
191 static cl::opt<bool> EnableCondStoresVectorization(
192 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
193 cl::desc("Enable if predication of stores during vectorization."));
195 static cl::opt<unsigned> MaxNestedScalarReductionUF(
196 "max-nested-scalar-reduction-unroll", cl::init(2), cl::Hidden,
197 cl::desc("The maximum unroll factor to use when unrolling a scalar "
198 "reduction in a nested loop."));
202 // Forward declarations.
203 class LoopVectorizationLegality;
204 class LoopVectorizationCostModel;
205 class LoopVectorizeHints;
207 /// \brief This modifies LoopAccessReport to initialize message with
208 /// loop-vectorizer-specific part.
209 class VectorizationReport : public LoopAccessReport {
211 VectorizationReport(Instruction *I = nullptr)
212 : LoopAccessReport("loop not vectorized: ", I) {}
214 /// \brief This allows promotion of the loop-access analysis report into the
215 /// loop-vectorizer report. It modifies the message to add the
216 /// loop-vectorizer-specific part of the message.
217 explicit VectorizationReport(const LoopAccessReport &R)
218 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
222 /// A helper function for converting Scalar types to vector types.
223 /// If the incoming type is void, we return void. If the VF is 1, we return
225 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
226 if (Scalar->isVoidTy() || VF == 1)
228 return VectorType::get(Scalar, VF);
231 /// InnerLoopVectorizer vectorizes loops which contain only one basic
232 /// block to a specified vectorization factor (VF).
233 /// This class performs the widening of scalars into vectors, or multiple
234 /// scalars. This class also implements the following features:
235 /// * It inserts an epilogue loop for handling loops that don't have iteration
236 /// counts that are known to be a multiple of the vectorization factor.
237 /// * It handles the code generation for reduction variables.
238 /// * Scalarization (implementation using scalars) of un-vectorizable
240 /// InnerLoopVectorizer does not perform any vectorization-legality
241 /// checks, and relies on the caller to check for the different legality
242 /// aspects. The InnerLoopVectorizer relies on the
243 /// LoopVectorizationLegality class to provide information about the induction
244 /// and reduction variables that were found to a given vectorization factor.
245 class InnerLoopVectorizer {
247 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
248 DominatorTree *DT, const TargetLibraryInfo *TLI,
249 const TargetTransformInfo *TTI, unsigned VecWidth,
250 unsigned UnrollFactor)
251 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
252 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
253 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
254 Legal(nullptr), AddedSafetyChecks(false) {}
256 // Perform the actual loop widening (vectorization).
257 void vectorize(LoopVectorizationLegality *L) {
259 // Create a new empty loop. Unlink the old loop and connect the new one.
261 // Widen each instruction in the old loop to a new one in the new loop.
262 // Use the Legality module to find the induction and reduction variables.
264 // Register the new loop and update the analysis passes.
268 // Return true if any runtime check is added.
269 bool IsSafetyChecksAdded() {
270 return AddedSafetyChecks;
273 virtual ~InnerLoopVectorizer() {}
276 /// A small list of PHINodes.
277 typedef SmallVector<PHINode*, 4> PhiVector;
278 /// When we unroll loops we have multiple vector values for each scalar.
279 /// This data structure holds the unrolled and vectorized values that
280 /// originated from one scalar instruction.
281 typedef SmallVector<Value*, 2> VectorParts;
283 // When we if-convert we need create edge masks. We have to cache values so
284 // that we don't end up with exponential recursion/IR.
285 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
286 VectorParts> EdgeMaskCache;
288 /// \brief Add checks for strides that where assumed to be 1.
290 /// Returns the last check instruction and the first check instruction in the
291 /// pair as (first, last).
292 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
294 /// Create an empty loop, based on the loop ranges of the old loop.
295 void createEmptyLoop();
296 /// Copy and widen the instructions from the old loop.
297 virtual void vectorizeLoop();
299 /// \brief The Loop exit block may have single value PHI nodes where the
300 /// incoming value is 'Undef'. While vectorizing we only handled real values
301 /// that were defined inside the loop. Here we fix the 'undef case'.
305 /// A helper function that computes the predicate of the block BB, assuming
306 /// that the header block of the loop is set to True. It returns the *entry*
307 /// mask for the block BB.
308 VectorParts createBlockInMask(BasicBlock *BB);
309 /// A helper function that computes the predicate of the edge between SRC
311 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
313 /// A helper function to vectorize a single BB within the innermost loop.
314 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
316 /// Vectorize a single PHINode in a block. This method handles the induction
317 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
318 /// arbitrary length vectors.
319 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
320 unsigned UF, unsigned VF, PhiVector *PV);
322 /// Insert the new loop to the loop hierarchy and pass manager
323 /// and update the analysis passes.
324 void updateAnalysis();
326 /// This instruction is un-vectorizable. Implement it as a sequence
327 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
328 /// scalarized instruction behind an if block predicated on the control
329 /// dependence of the instruction.
330 virtual void scalarizeInstruction(Instruction *Instr,
331 bool IfPredicateStore=false);
333 /// Vectorize Load and Store instructions,
334 virtual void vectorizeMemoryInstruction(Instruction *Instr);
336 /// Create a broadcast instruction. This method generates a broadcast
337 /// instruction (shuffle) for loop invariant values and for the induction
338 /// value. If this is the induction variable then we extend it to N, N+1, ...
339 /// this is needed because each iteration in the loop corresponds to a SIMD
341 virtual Value *getBroadcastInstrs(Value *V);
343 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
344 /// to each vector element of Val. The sequence starts at StartIndex.
345 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
347 /// When we go over instructions in the basic block we rely on previous
348 /// values within the current basic block or on loop invariant values.
349 /// When we widen (vectorize) values we place them in the map. If the values
350 /// are not within the map, they have to be loop invariant, so we simply
351 /// broadcast them into a vector.
352 VectorParts &getVectorValue(Value *V);
354 /// Generate a shuffle sequence that will reverse the vector Vec.
355 virtual Value *reverseVector(Value *Vec);
357 /// This is a helper class that holds the vectorizer state. It maps scalar
358 /// instructions to vector instructions. When the code is 'unrolled' then
359 /// then a single scalar value is mapped to multiple vector parts. The parts
360 /// are stored in the VectorPart type.
362 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
364 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
366 /// \return True if 'Key' is saved in the Value Map.
367 bool has(Value *Key) const { return MapStorage.count(Key); }
369 /// Initializes a new entry in the map. Sets all of the vector parts to the
370 /// save value in 'Val'.
371 /// \return A reference to a vector with splat values.
372 VectorParts &splat(Value *Key, Value *Val) {
373 VectorParts &Entry = MapStorage[Key];
374 Entry.assign(UF, Val);
378 ///\return A reference to the value that is stored at 'Key'.
379 VectorParts &get(Value *Key) {
380 VectorParts &Entry = MapStorage[Key];
383 assert(Entry.size() == UF);
388 /// The unroll factor. Each entry in the map stores this number of vector
392 /// Map storage. We use std::map and not DenseMap because insertions to a
393 /// dense map invalidates its iterators.
394 std::map<Value *, VectorParts> MapStorage;
397 /// The original loop.
399 /// Scev analysis to use.
407 /// Target Library Info.
408 const TargetLibraryInfo *TLI;
409 /// Target Transform Info.
410 const TargetTransformInfo *TTI;
412 /// The vectorization SIMD factor to use. Each vector will have this many
417 /// The vectorization unroll factor to use. Each scalar is vectorized to this
418 /// many different vector instructions.
421 /// The builder that we use
424 // --- Vectorization state ---
426 /// The vector-loop preheader.
427 BasicBlock *LoopVectorPreHeader;
428 /// The scalar-loop preheader.
429 BasicBlock *LoopScalarPreHeader;
430 /// Middle Block between the vector and the scalar.
431 BasicBlock *LoopMiddleBlock;
432 ///The ExitBlock of the scalar loop.
433 BasicBlock *LoopExitBlock;
434 ///The vector loop body.
435 SmallVector<BasicBlock *, 4> LoopVectorBody;
436 ///The scalar loop body.
437 BasicBlock *LoopScalarBody;
438 /// A list of all bypass blocks. The first block is the entry of the loop.
439 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
441 /// The new Induction variable which was added to the new block.
443 /// The induction variable of the old basic block.
444 PHINode *OldInduction;
445 /// Holds the extended (to the widest induction type) start index.
447 /// Maps scalars to widened vectors.
449 EdgeMaskCache MaskCache;
451 LoopVectorizationLegality *Legal;
453 // Record whether runtime check is added.
454 bool AddedSafetyChecks;
457 class InnerLoopUnroller : public InnerLoopVectorizer {
459 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
460 DominatorTree *DT, const TargetLibraryInfo *TLI,
461 const TargetTransformInfo *TTI, unsigned UnrollFactor)
462 : InnerLoopVectorizer(OrigLoop, SE, LI, DT, TLI, TTI, 1, UnrollFactor) {}
465 void scalarizeInstruction(Instruction *Instr,
466 bool IfPredicateStore = false) override;
467 void vectorizeMemoryInstruction(Instruction *Instr) override;
468 Value *getBroadcastInstrs(Value *V) override;
469 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
470 Value *reverseVector(Value *Vec) override;
473 /// \brief Look for a meaningful debug location on the instruction or it's
475 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
480 if (I->getDebugLoc() != Empty)
483 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
484 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
485 if (OpInst->getDebugLoc() != Empty)
492 /// \brief Set the debug location in the builder using the debug location in the
494 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
495 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
496 B.SetCurrentDebugLocation(Inst->getDebugLoc());
498 B.SetCurrentDebugLocation(DebugLoc());
502 /// \return string containing a file name and a line # for the given loop.
503 static std::string getDebugLocString(const Loop *L) {
506 raw_string_ostream OS(Result);
507 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
508 LoopDbgLoc.print(OS);
510 // Just print the module name.
511 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
518 /// \brief Propagate known metadata from one instruction to another.
519 static void propagateMetadata(Instruction *To, const Instruction *From) {
520 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
521 From->getAllMetadataOtherThanDebugLoc(Metadata);
523 for (auto M : Metadata) {
524 unsigned Kind = M.first;
526 // These are safe to transfer (this is safe for TBAA, even when we
527 // if-convert, because should that metadata have had a control dependency
528 // on the condition, and thus actually aliased with some other
529 // non-speculated memory access when the condition was false, this would be
530 // caught by the runtime overlap checks).
531 if (Kind != LLVMContext::MD_tbaa &&
532 Kind != LLVMContext::MD_alias_scope &&
533 Kind != LLVMContext::MD_noalias &&
534 Kind != LLVMContext::MD_fpmath)
537 To->setMetadata(Kind, M.second);
541 /// \brief Propagate known metadata from one instruction to a vector of others.
542 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
544 if (Instruction *I = dyn_cast<Instruction>(V))
545 propagateMetadata(I, From);
548 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
549 /// to what vectorization factor.
550 /// This class does not look at the profitability of vectorization, only the
551 /// legality. This class has two main kinds of checks:
552 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
553 /// will change the order of memory accesses in a way that will change the
554 /// correctness of the program.
555 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
556 /// checks for a number of different conditions, such as the availability of a
557 /// single induction variable, that all types are supported and vectorize-able,
558 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
559 /// This class is also used by InnerLoopVectorizer for identifying
560 /// induction variable and the different reduction variables.
561 class LoopVectorizationLegality {
563 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
564 TargetLibraryInfo *TLI, AliasAnalysis *AA,
565 Function *F, const TargetTransformInfo *TTI,
566 LoopAccessAnalysis *LAA)
567 : NumPredStores(0), TheLoop(L), SE(SE), TLI(TLI), TheFunction(F),
568 TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr), Induction(nullptr),
569 WidestIndTy(nullptr), HasFunNoNaNAttr(false) {}
571 /// This enum represents the kinds of inductions that we support.
573 IK_NoInduction, ///< Not an induction variable.
574 IK_IntInduction, ///< Integer induction variable. Step = C.
575 IK_PtrInduction ///< Pointer induction var. Step = C / sizeof(elem).
578 /// A struct for saving information about induction variables.
579 struct InductionInfo {
580 InductionInfo(Value *Start, InductionKind K, ConstantInt *Step)
581 : StartValue(Start), IK(K), StepValue(Step) {
582 assert(IK != IK_NoInduction && "Not an induction");
583 assert(StartValue && "StartValue is null");
584 assert(StepValue && !StepValue->isZero() && "StepValue is zero");
585 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
586 "StartValue is not a pointer for pointer induction");
587 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
588 "StartValue is not an integer for integer induction");
589 assert(StepValue->getType()->isIntegerTy() &&
590 "StepValue is not an integer");
593 : StartValue(nullptr), IK(IK_NoInduction), StepValue(nullptr) {}
595 /// Get the consecutive direction. Returns:
596 /// 0 - unknown or non-consecutive.
597 /// 1 - consecutive and increasing.
598 /// -1 - consecutive and decreasing.
599 int getConsecutiveDirection() const {
600 if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
601 return StepValue->getSExtValue();
605 /// Compute the transformed value of Index at offset StartValue using step
607 /// For integer induction, returns StartValue + Index * StepValue.
608 /// For pointer induction, returns StartValue[Index * StepValue].
609 /// FIXME: The newly created binary instructions should contain nsw/nuw
610 /// flags, which can be found from the original scalar operations.
611 Value *transform(IRBuilder<> &B, Value *Index) const {
613 case IK_IntInduction:
614 assert(Index->getType() == StartValue->getType() &&
615 "Index type does not match StartValue type");
616 if (StepValue->isMinusOne())
617 return B.CreateSub(StartValue, Index);
618 if (!StepValue->isOne())
619 Index = B.CreateMul(Index, StepValue);
620 return B.CreateAdd(StartValue, Index);
622 case IK_PtrInduction:
623 if (StepValue->isMinusOne())
624 Index = B.CreateNeg(Index);
625 else if (!StepValue->isOne())
626 Index = B.CreateMul(Index, StepValue);
627 return B.CreateGEP(nullptr, StartValue, Index);
632 llvm_unreachable("invalid enum");
636 TrackingVH<Value> StartValue;
640 ConstantInt *StepValue;
643 /// ReductionList contains the reduction descriptors for all
644 /// of the reductions that were found in the loop.
645 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
647 /// InductionList saves induction variables and maps them to the
648 /// induction descriptor.
649 typedef MapVector<PHINode*, InductionInfo> InductionList;
651 /// Returns true if it is legal to vectorize this loop.
652 /// This does not mean that it is profitable to vectorize this
653 /// loop, only that it is legal to do so.
656 /// Returns the Induction variable.
657 PHINode *getInduction() { return Induction; }
659 /// Returns the reduction variables found in the loop.
660 ReductionList *getReductionVars() { return &Reductions; }
662 /// Returns the induction variables found in the loop.
663 InductionList *getInductionVars() { return &Inductions; }
665 /// Returns the widest induction type.
666 Type *getWidestInductionType() { return WidestIndTy; }
668 /// Returns True if V is an induction variable in this loop.
669 bool isInductionVariable(const Value *V);
671 /// Return true if the block BB needs to be predicated in order for the loop
672 /// to be vectorized.
673 bool blockNeedsPredication(BasicBlock *BB);
675 /// Check if this pointer is consecutive when vectorizing. This happens
676 /// when the last index of the GEP is the induction variable, or that the
677 /// pointer itself is an induction variable.
678 /// This check allows us to vectorize A[idx] into a wide load/store.
680 /// 0 - Stride is unknown or non-consecutive.
681 /// 1 - Address is consecutive.
682 /// -1 - Address is consecutive, and decreasing.
683 int isConsecutivePtr(Value *Ptr);
685 /// Returns true if the value V is uniform within the loop.
686 bool isUniform(Value *V);
688 /// Returns true if this instruction will remain scalar after vectorization.
689 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
691 /// Returns the information that we collected about runtime memory check.
692 const LoopAccessInfo::RuntimePointerCheck *getRuntimePointerCheck() const {
693 return LAI->getRuntimePointerCheck();
696 const LoopAccessInfo *getLAI() const {
700 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
702 bool hasStride(Value *V) { return StrideSet.count(V); }
703 bool mustCheckStrides() { return !StrideSet.empty(); }
704 SmallPtrSet<Value *, 8>::iterator strides_begin() {
705 return StrideSet.begin();
707 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
709 /// Returns true if the target machine supports masked store operation
710 /// for the given \p DataType and kind of access to \p Ptr.
711 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
712 return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
714 /// Returns true if the target machine supports masked load operation
715 /// for the given \p DataType and kind of access to \p Ptr.
716 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
717 return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
719 /// Returns true if vector representation of the instruction \p I
721 bool isMaskRequired(const Instruction* I) {
722 return (MaskedOp.count(I) != 0);
724 unsigned getNumStores() const {
725 return LAI->getNumStores();
727 unsigned getNumLoads() const {
728 return LAI->getNumLoads();
730 unsigned getNumPredStores() const {
731 return NumPredStores;
734 /// Check if a single basic block loop is vectorizable.
735 /// At this point we know that this is a loop with a constant trip count
736 /// and we only need to check individual instructions.
737 bool canVectorizeInstrs();
739 /// When we vectorize loops we may change the order in which
740 /// we read and write from memory. This method checks if it is
741 /// legal to vectorize the code, considering only memory constrains.
742 /// Returns true if the loop is vectorizable
743 bool canVectorizeMemory();
745 /// Return true if we can vectorize this loop using the IF-conversion
747 bool canVectorizeWithIfConvert();
749 /// Collect the variables that need to stay uniform after vectorization.
750 void collectLoopUniforms();
752 /// Return true if all of the instructions in the block can be speculatively
753 /// executed. \p SafePtrs is a list of addresses that are known to be legal
754 /// and we know that we can read from them without segfault.
755 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
757 /// Returns the induction kind of Phi and record the step. This function may
758 /// return NoInduction if the PHI is not an induction variable.
759 InductionKind isInductionVariable(PHINode *Phi, ConstantInt *&StepValue);
761 /// \brief Collect memory access with loop invariant strides.
763 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
765 void collectStridedAccess(Value *LoadOrStoreInst);
767 /// Report an analysis message to assist the user in diagnosing loops that are
768 /// not vectorized. These are handled as LoopAccessReport rather than
769 /// VectorizationReport because the << operator of VectorizationReport returns
770 /// LoopAccessReport.
771 void emitAnalysis(const LoopAccessReport &Message) {
772 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
775 unsigned NumPredStores;
777 /// The loop that we evaluate.
781 /// Target Library Info.
782 TargetLibraryInfo *TLI;
784 Function *TheFunction;
785 /// Target Transform Info
786 const TargetTransformInfo *TTI;
789 // LoopAccess analysis.
790 LoopAccessAnalysis *LAA;
791 // And the loop-accesses info corresponding to this loop. This pointer is
792 // null until canVectorizeMemory sets it up.
793 const LoopAccessInfo *LAI;
795 // --- vectorization state --- //
797 /// Holds the integer induction variable. This is the counter of the
800 /// Holds the reduction variables.
801 ReductionList Reductions;
802 /// Holds all of the induction variables that we found in the loop.
803 /// Notice that inductions don't need to start at zero and that induction
804 /// variables can be pointers.
805 InductionList Inductions;
806 /// Holds the widest induction type encountered.
809 /// Allowed outside users. This holds the reduction
810 /// vars which can be accessed from outside the loop.
811 SmallPtrSet<Value*, 4> AllowedExit;
812 /// This set holds the variables which are known to be uniform after
814 SmallPtrSet<Instruction*, 4> Uniforms;
816 /// Can we assume the absence of NaNs.
817 bool HasFunNoNaNAttr;
819 ValueToValueMap Strides;
820 SmallPtrSet<Value *, 8> StrideSet;
822 /// While vectorizing these instructions we have to generate a
823 /// call to the appropriate masked intrinsic
824 SmallPtrSet<const Instruction*, 8> MaskedOp;
827 /// LoopVectorizationCostModel - estimates the expected speedups due to
829 /// In many cases vectorization is not profitable. This can happen because of
830 /// a number of reasons. In this class we mainly attempt to predict the
831 /// expected speedup/slowdowns due to the supported instruction set. We use the
832 /// TargetTransformInfo to query the different backends for the cost of
833 /// different operations.
834 class LoopVectorizationCostModel {
836 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
837 LoopVectorizationLegality *Legal,
838 const TargetTransformInfo &TTI,
839 const TargetLibraryInfo *TLI, AssumptionCache *AC,
840 const Function *F, const LoopVectorizeHints *Hints)
841 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI),
842 TheFunction(F), Hints(Hints) {
843 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
846 /// Information about vectorization costs
847 struct VectorizationFactor {
848 unsigned Width; // Vector width with best cost
849 unsigned Cost; // Cost of the loop with that width
851 /// \return The most profitable vectorization factor and the cost of that VF.
852 /// This method checks every power of two up to VF. If UserVF is not ZERO
853 /// then this vectorization factor will be selected if vectorization is
855 VectorizationFactor selectVectorizationFactor(bool OptForSize);
857 /// \return The size (in bits) of the widest type in the code that
858 /// needs to be vectorized. We ignore values that remain scalar such as
859 /// 64 bit loop indices.
860 unsigned getWidestType();
862 /// \return The most profitable unroll factor.
863 /// If UserUF is non-zero then this method finds the best unroll-factor
864 /// based on register pressure and other parameters.
865 /// VF and LoopCost are the selected vectorization factor and the cost of the
867 unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost);
869 /// \brief A struct that represents some properties of the register usage
871 struct RegisterUsage {
872 /// Holds the number of loop invariant values that are used in the loop.
873 unsigned LoopInvariantRegs;
874 /// Holds the maximum number of concurrent live intervals in the loop.
875 unsigned MaxLocalUsers;
876 /// Holds the number of instructions in the loop.
877 unsigned NumInstructions;
880 /// \return information about the register usage of the loop.
881 RegisterUsage calculateRegisterUsage();
884 /// Returns the expected execution cost. The unit of the cost does
885 /// not matter because we use the 'cost' units to compare different
886 /// vector widths. The cost that is returned is *not* normalized by
887 /// the factor width.
888 unsigned expectedCost(unsigned VF);
890 /// Returns the execution time cost of an instruction for a given vector
891 /// width. Vector width of one means scalar.
892 unsigned getInstructionCost(Instruction *I, unsigned VF);
894 /// Returns whether the instruction is a load or store and will be a emitted
895 /// as a vector operation.
896 bool isConsecutiveLoadOrStore(Instruction *I);
898 /// Report an analysis message to assist the user in diagnosing loops that are
899 /// not vectorized. These are handled as LoopAccessReport rather than
900 /// VectorizationReport because the << operator of VectorizationReport returns
901 /// LoopAccessReport.
902 void emitAnalysis(const LoopAccessReport &Message) {
903 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
906 /// Values used only by @llvm.assume calls.
907 SmallPtrSet<const Value *, 32> EphValues;
909 /// The loop that we evaluate.
913 /// Loop Info analysis.
915 /// Vectorization legality.
916 LoopVectorizationLegality *Legal;
917 /// Vector target information.
918 const TargetTransformInfo &TTI;
919 /// Target Library Info.
920 const TargetLibraryInfo *TLI;
921 const Function *TheFunction;
922 // Loop Vectorize Hint.
923 const LoopVectorizeHints *Hints;
926 /// Utility class for getting and setting loop vectorizer hints in the form
927 /// of loop metadata.
928 /// This class keeps a number of loop annotations locally (as member variables)
929 /// and can, upon request, write them back as metadata on the loop. It will
930 /// initially scan the loop for existing metadata, and will update the local
931 /// values based on information in the loop.
932 /// We cannot write all values to metadata, as the mere presence of some info,
933 /// for example 'force', means a decision has been made. So, we need to be
934 /// careful NOT to add them if the user hasn't specifically asked so.
935 class LoopVectorizeHints {
942 /// Hint - associates name and validation with the hint value.
945 unsigned Value; // This may have to change for non-numeric values.
948 Hint(const char * Name, unsigned Value, HintKind Kind)
949 : Name(Name), Value(Value), Kind(Kind) { }
951 bool validate(unsigned Val) {
954 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
956 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
964 /// Vectorization width.
966 /// Vectorization interleave factor.
968 /// Vectorization forced
971 /// Return the loop metadata prefix.
972 static StringRef Prefix() { return "llvm.loop."; }
976 FK_Undefined = -1, ///< Not selected.
977 FK_Disabled = 0, ///< Forcing disabled.
978 FK_Enabled = 1, ///< Forcing enabled.
981 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
982 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
984 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
985 Force("vectorize.enable", FK_Undefined, HK_FORCE),
987 // Populate values with existing loop metadata.
988 getHintsFromMetadata();
990 // force-vector-interleave overrides DisableInterleaving.
991 if (VectorizerParams::isInterleaveForced())
992 Interleave.Value = VectorizerParams::VectorizationInterleave;
994 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
995 << "LV: Interleaving disabled by the pass manager\n");
998 /// Mark the loop L as already vectorized by setting the width to 1.
999 void setAlreadyVectorized() {
1000 Width.Value = Interleave.Value = 1;
1001 Hint Hints[] = {Width, Interleave};
1002 writeHintsToMetadata(Hints);
1005 /// Dumps all the hint information.
1006 std::string emitRemark() const {
1007 VectorizationReport R;
1008 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1009 R << "vectorization is explicitly disabled";
1011 R << "use -Rpass-analysis=loop-vectorize for more info";
1012 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1013 R << " (Force=true";
1014 if (Width.Value != 0)
1015 R << ", Vector Width=" << Width.Value;
1016 if (Interleave.Value != 0)
1017 R << ", Interleave Count=" << Interleave.Value;
1025 unsigned getWidth() const { return Width.Value; }
1026 unsigned getInterleave() const { return Interleave.Value; }
1027 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1030 /// Find hints specified in the loop metadata and update local values.
1031 void getHintsFromMetadata() {
1032 MDNode *LoopID = TheLoop->getLoopID();
1036 // First operand should refer to the loop id itself.
1037 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1038 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1040 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1041 const MDString *S = nullptr;
1042 SmallVector<Metadata *, 4> Args;
1044 // The expected hint is either a MDString or a MDNode with the first
1045 // operand a MDString.
1046 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1047 if (!MD || MD->getNumOperands() == 0)
1049 S = dyn_cast<MDString>(MD->getOperand(0));
1050 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1051 Args.push_back(MD->getOperand(i));
1053 S = dyn_cast<MDString>(LoopID->getOperand(i));
1054 assert(Args.size() == 0 && "too many arguments for MDString");
1060 // Check if the hint starts with the loop metadata prefix.
1061 StringRef Name = S->getString();
1062 if (Args.size() == 1)
1063 setHint(Name, Args[0]);
1067 /// Checks string hint with one operand and set value if valid.
1068 void setHint(StringRef Name, Metadata *Arg) {
1069 if (!Name.startswith(Prefix()))
1071 Name = Name.substr(Prefix().size(), StringRef::npos);
1073 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1075 unsigned Val = C->getZExtValue();
1077 Hint *Hints[] = {&Width, &Interleave, &Force};
1078 for (auto H : Hints) {
1079 if (Name == H->Name) {
1080 if (H->validate(Val))
1083 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1089 /// Create a new hint from name / value pair.
1090 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1091 LLVMContext &Context = TheLoop->getHeader()->getContext();
1092 Metadata *MDs[] = {MDString::get(Context, Name),
1093 ConstantAsMetadata::get(
1094 ConstantInt::get(Type::getInt32Ty(Context), V))};
1095 return MDNode::get(Context, MDs);
1098 /// Matches metadata with hint name.
1099 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1100 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1104 for (auto H : HintTypes)
1105 if (Name->getString().endswith(H.Name))
1110 /// Sets current hints into loop metadata, keeping other values intact.
1111 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1112 if (HintTypes.size() == 0)
1115 // Reserve the first element to LoopID (see below).
1116 SmallVector<Metadata *, 4> MDs(1);
1117 // If the loop already has metadata, then ignore the existing operands.
1118 MDNode *LoopID = TheLoop->getLoopID();
1120 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1121 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1122 // If node in update list, ignore old value.
1123 if (!matchesHintMetadataName(Node, HintTypes))
1124 MDs.push_back(Node);
1128 // Now, add the missing hints.
1129 for (auto H : HintTypes)
1130 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1132 // Replace current metadata node with new one.
1133 LLVMContext &Context = TheLoop->getHeader()->getContext();
1134 MDNode *NewLoopID = MDNode::get(Context, MDs);
1135 // Set operand 0 to refer to the loop id itself.
1136 NewLoopID->replaceOperandWith(0, NewLoopID);
1138 TheLoop->setLoopID(NewLoopID);
1141 /// The loop these hints belong to.
1142 const Loop *TheLoop;
1145 static void emitMissedWarning(Function *F, Loop *L,
1146 const LoopVectorizeHints &LH) {
1147 emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1148 L->getStartLoc(), LH.emitRemark());
1150 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1151 if (LH.getWidth() != 1)
1152 emitLoopVectorizeWarning(
1153 F->getContext(), *F, L->getStartLoc(),
1154 "failed explicitly specified loop vectorization");
1155 else if (LH.getInterleave() != 1)
1156 emitLoopInterleaveWarning(
1157 F->getContext(), *F, L->getStartLoc(),
1158 "failed explicitly specified loop interleaving");
1162 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1164 return V.push_back(&L);
1166 for (Loop *InnerL : L)
1167 addInnerLoop(*InnerL, V);
1170 /// The LoopVectorize Pass.
1171 struct LoopVectorize : public FunctionPass {
1172 /// Pass identification, replacement for typeid
1175 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1177 DisableUnrolling(NoUnrolling),
1178 AlwaysVectorize(AlwaysVectorize) {
1179 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1182 ScalarEvolution *SE;
1184 TargetTransformInfo *TTI;
1186 BlockFrequencyInfo *BFI;
1187 TargetLibraryInfo *TLI;
1189 AssumptionCache *AC;
1190 LoopAccessAnalysis *LAA;
1191 bool DisableUnrolling;
1192 bool AlwaysVectorize;
1194 BlockFrequency ColdEntryFreq;
1196 bool runOnFunction(Function &F) override {
1197 SE = &getAnalysis<ScalarEvolution>();
1198 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1199 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1200 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1201 BFI = &getAnalysis<BlockFrequencyInfo>();
1202 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1203 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1204 AA = &getAnalysis<AliasAnalysis>();
1205 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1206 LAA = &getAnalysis<LoopAccessAnalysis>();
1208 // Compute some weights outside of the loop over the loops. Compute this
1209 // using a BranchProbability to re-use its scaling math.
1210 const BranchProbability ColdProb(1, 5); // 20%
1211 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1213 // If the target claims to have no vector registers don't attempt
1215 if (!TTI->getNumberOfRegisters(true))
1218 // Build up a worklist of inner-loops to vectorize. This is necessary as
1219 // the act of vectorizing or partially unrolling a loop creates new loops
1220 // and can invalidate iterators across the loops.
1221 SmallVector<Loop *, 8> Worklist;
1224 addInnerLoop(*L, Worklist);
1226 LoopsAnalyzed += Worklist.size();
1228 // Now walk the identified inner loops.
1229 bool Changed = false;
1230 while (!Worklist.empty())
1231 Changed |= processLoop(Worklist.pop_back_val());
1233 // Process each loop nest in the function.
1237 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
1238 SmallVector<Metadata *, 4> MDs;
1239 // Reserve first location for self reference to the LoopID metadata node.
1240 MDs.push_back(nullptr);
1241 bool IsUnrollMetadata = false;
1242 MDNode *LoopID = L->getLoopID();
1244 // First find existing loop unrolling disable metadata.
1245 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1246 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1248 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1250 S && S->getString().startswith("llvm.loop.unroll.disable");
1252 MDs.push_back(LoopID->getOperand(i));
1256 if (!IsUnrollMetadata) {
1257 // Add runtime unroll disable metadata.
1258 LLVMContext &Context = L->getHeader()->getContext();
1259 SmallVector<Metadata *, 1> DisableOperands;
1260 DisableOperands.push_back(
1261 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1262 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1263 MDs.push_back(DisableNode);
1264 MDNode *NewLoopID = MDNode::get(Context, MDs);
1265 // Set operand 0 to refer to the loop id itself.
1266 NewLoopID->replaceOperandWith(0, NewLoopID);
1267 L->setLoopID(NewLoopID);
1271 bool processLoop(Loop *L) {
1272 assert(L->empty() && "Only process inner loops.");
1275 const std::string DebugLocStr = getDebugLocString(L);
1278 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1279 << L->getHeader()->getParent()->getName() << "\" from "
1280 << DebugLocStr << "\n");
1282 LoopVectorizeHints Hints(L, DisableUnrolling);
1284 DEBUG(dbgs() << "LV: Loop hints:"
1286 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1288 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1290 : "?")) << " width=" << Hints.getWidth()
1291 << " unroll=" << Hints.getInterleave() << "\n");
1293 // Function containing loop
1294 Function *F = L->getHeader()->getParent();
1296 // Looking at the diagnostic output is the only way to determine if a loop
1297 // was vectorized (other than looking at the IR or machine code), so it
1298 // is important to generate an optimization remark for each loop. Most of
1299 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1300 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1301 // less verbose reporting vectorized loops and unvectorized loops that may
1302 // benefit from vectorization, respectively.
1304 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1305 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1306 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1307 L->getStartLoc(), Hints.emitRemark());
1311 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1312 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1313 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1314 L->getStartLoc(), Hints.emitRemark());
1318 if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
1319 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1320 emitOptimizationRemarkAnalysis(
1321 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1322 "loop not vectorized: vector width and interleave count are "
1323 "explicitly set to 1");
1327 // Check the loop for a trip count threshold:
1328 // do not vectorize loops with a tiny trip count.
1329 const unsigned TC = SE->getSmallConstantTripCount(L);
1330 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1331 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1332 << "This loop is not worth vectorizing.");
1333 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1334 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1336 DEBUG(dbgs() << "\n");
1337 emitOptimizationRemarkAnalysis(
1338 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1339 "vectorization is not beneficial and is not explicitly forced");
1344 // Check if it is legal to vectorize the loop.
1345 LoopVectorizationLegality LVL(L, SE, DT, TLI, AA, F, TTI, LAA);
1346 if (!LVL.canVectorize()) {
1347 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1348 emitMissedWarning(F, L, Hints);
1352 // Use the cost model.
1353 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, TLI, AC, F, &Hints);
1355 // Check the function attributes to find out if this function should be
1356 // optimized for size.
1357 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1358 F->hasFnAttribute(Attribute::OptimizeForSize);
1360 // Compute the weighted frequency of this loop being executed and see if it
1361 // is less than 20% of the function entry baseline frequency. Note that we
1362 // always have a canonical loop here because we think we *can* vectoriez.
1363 // FIXME: This is hidden behind a flag due to pervasive problems with
1364 // exactly what block frequency models.
1365 if (LoopVectorizeWithBlockFrequency) {
1366 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1367 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1368 LoopEntryFreq < ColdEntryFreq)
1372 // Check the function attributes to see if implicit floats are allowed.a
1373 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1374 // an integer loop and the vector instructions selected are purely integer
1375 // vector instructions?
1376 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1377 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1378 "attribute is used.\n");
1379 emitOptimizationRemarkAnalysis(
1380 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1381 "loop not vectorized due to NoImplicitFloat attribute");
1382 emitMissedWarning(F, L, Hints);
1386 // Select the optimal vectorization factor.
1387 const LoopVectorizationCostModel::VectorizationFactor VF =
1388 CM.selectVectorizationFactor(OptForSize);
1390 // Select the unroll factor.
1392 CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
1394 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1395 << DebugLocStr << '\n');
1396 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1398 if (VF.Width == 1) {
1399 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
1402 emitOptimizationRemarkAnalysis(
1403 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1404 "not beneficial to vectorize and user disabled interleaving");
1407 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1409 // Report the unrolling decision.
1410 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1411 Twine("unrolled with interleaving factor " +
1413 " (vectorization not beneficial)"));
1415 // We decided not to vectorize, but we may want to unroll.
1417 InnerLoopUnroller Unroller(L, SE, LI, DT, TLI, TTI, UF);
1418 Unroller.vectorize(&LVL);
1420 // If we decided that it is *legal* to vectorize the loop then do it.
1421 InnerLoopVectorizer LB(L, SE, LI, DT, TLI, TTI, VF.Width, UF);
1425 // Add metadata to disable runtime unrolling scalar loop when there's no
1426 // runtime check about strides and memory. Because at this situation,
1427 // scalar loop is rarely used not worthy to be unrolled.
1428 if (!LB.IsSafetyChecksAdded())
1429 AddRuntimeUnrollDisableMetaData(L);
1431 // Report the vectorization decision.
1432 emitOptimizationRemark(
1433 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1434 Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1435 ", unrolling interleave factor: " + Twine(UF) + ")");
1438 // Mark the loop as already vectorized to avoid vectorizing again.
1439 Hints.setAlreadyVectorized();
1441 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1445 void getAnalysisUsage(AnalysisUsage &AU) const override {
1446 AU.addRequired<AssumptionCacheTracker>();
1447 AU.addRequiredID(LoopSimplifyID);
1448 AU.addRequiredID(LCSSAID);
1449 AU.addRequired<BlockFrequencyInfo>();
1450 AU.addRequired<DominatorTreeWrapperPass>();
1451 AU.addRequired<LoopInfoWrapperPass>();
1452 AU.addRequired<ScalarEvolution>();
1453 AU.addRequired<TargetTransformInfoWrapperPass>();
1454 AU.addRequired<AliasAnalysis>();
1455 AU.addRequired<LoopAccessAnalysis>();
1456 AU.addPreserved<LoopInfoWrapperPass>();
1457 AU.addPreserved<DominatorTreeWrapperPass>();
1458 AU.addPreserved<AliasAnalysis>();
1463 } // end anonymous namespace
1465 //===----------------------------------------------------------------------===//
1466 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1467 // LoopVectorizationCostModel.
1468 //===----------------------------------------------------------------------===//
1470 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1471 // We need to place the broadcast of invariant variables outside the loop.
1472 Instruction *Instr = dyn_cast<Instruction>(V);
1474 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1475 Instr->getParent()) != LoopVectorBody.end());
1476 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1478 // Place the code for broadcasting invariant variables in the new preheader.
1479 IRBuilder<>::InsertPointGuard Guard(Builder);
1481 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1483 // Broadcast the scalar into all locations in the vector.
1484 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1489 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1491 assert(Val->getType()->isVectorTy() && "Must be a vector");
1492 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1493 "Elem must be an integer");
1494 assert(Step->getType() == Val->getType()->getScalarType() &&
1495 "Step has wrong type");
1496 // Create the types.
1497 Type *ITy = Val->getType()->getScalarType();
1498 VectorType *Ty = cast<VectorType>(Val->getType());
1499 int VLen = Ty->getNumElements();
1500 SmallVector<Constant*, 8> Indices;
1502 // Create a vector of consecutive numbers from zero to VF.
1503 for (int i = 0; i < VLen; ++i)
1504 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1506 // Add the consecutive indices to the vector value.
1507 Constant *Cv = ConstantVector::get(Indices);
1508 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1509 Step = Builder.CreateVectorSplat(VLen, Step);
1510 assert(Step->getType() == Val->getType() && "Invalid step vec");
1511 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1512 // which can be found from the original scalar operations.
1513 Step = Builder.CreateMul(Cv, Step);
1514 return Builder.CreateAdd(Val, Step, "induction");
1517 /// \brief Find the operand of the GEP that should be checked for consecutive
1518 /// stores. This ignores trailing indices that have no effect on the final
1520 static unsigned getGEPInductionOperand(const GetElementPtrInst *Gep) {
1521 const DataLayout &DL = Gep->getModule()->getDataLayout();
1522 unsigned LastOperand = Gep->getNumOperands() - 1;
1523 unsigned GEPAllocSize = DL.getTypeAllocSize(
1524 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1526 // Walk backwards and try to peel off zeros.
1527 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1528 // Find the type we're currently indexing into.
1529 gep_type_iterator GEPTI = gep_type_begin(Gep);
1530 std::advance(GEPTI, LastOperand - 1);
1532 // If it's a type with the same allocation size as the result of the GEP we
1533 // can peel off the zero index.
1534 if (DL.getTypeAllocSize(*GEPTI) != GEPAllocSize)
1542 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1543 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1544 // Make sure that the pointer does not point to structs.
1545 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1548 // If this value is a pointer induction variable we know it is consecutive.
1549 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1550 if (Phi && Inductions.count(Phi)) {
1551 InductionInfo II = Inductions[Phi];
1552 return II.getConsecutiveDirection();
1555 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1559 unsigned NumOperands = Gep->getNumOperands();
1560 Value *GpPtr = Gep->getPointerOperand();
1561 // If this GEP value is a consecutive pointer induction variable and all of
1562 // the indices are constant then we know it is consecutive. We can
1563 Phi = dyn_cast<PHINode>(GpPtr);
1564 if (Phi && Inductions.count(Phi)) {
1566 // Make sure that the pointer does not point to structs.
1567 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1568 if (GepPtrType->getElementType()->isAggregateType())
1571 // Make sure that all of the index operands are loop invariant.
1572 for (unsigned i = 1; i < NumOperands; ++i)
1573 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1576 InductionInfo II = Inductions[Phi];
1577 return II.getConsecutiveDirection();
1580 unsigned InductionOperand = getGEPInductionOperand(Gep);
1582 // Check that all of the gep indices are uniform except for our induction
1584 for (unsigned i = 0; i != NumOperands; ++i)
1585 if (i != InductionOperand &&
1586 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1589 // We can emit wide load/stores only if the last non-zero index is the
1590 // induction variable.
1591 const SCEV *Last = nullptr;
1592 if (!Strides.count(Gep))
1593 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1595 // Because of the multiplication by a stride we can have a s/zext cast.
1596 // We are going to replace this stride by 1 so the cast is safe to ignore.
1598 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1599 // %0 = trunc i64 %indvars.iv to i32
1600 // %mul = mul i32 %0, %Stride1
1601 // %idxprom = zext i32 %mul to i64 << Safe cast.
1602 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1604 Last = replaceSymbolicStrideSCEV(SE, Strides,
1605 Gep->getOperand(InductionOperand), Gep);
1606 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1608 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1612 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1613 const SCEV *Step = AR->getStepRecurrence(*SE);
1615 // The memory is consecutive because the last index is consecutive
1616 // and all other indices are loop invariant.
1619 if (Step->isAllOnesValue())
1626 bool LoopVectorizationLegality::isUniform(Value *V) {
1627 return LAI->isUniform(V);
1630 InnerLoopVectorizer::VectorParts&
1631 InnerLoopVectorizer::getVectorValue(Value *V) {
1632 assert(V != Induction && "The new induction variable should not be used.");
1633 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1635 // If we have a stride that is replaced by one, do it here.
1636 if (Legal->hasStride(V))
1637 V = ConstantInt::get(V->getType(), 1);
1639 // If we have this scalar in the map, return it.
1640 if (WidenMap.has(V))
1641 return WidenMap.get(V);
1643 // If this scalar is unknown, assume that it is a constant or that it is
1644 // loop invariant. Broadcast V and save the value for future uses.
1645 Value *B = getBroadcastInstrs(V);
1646 return WidenMap.splat(V, B);
1649 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1650 assert(Vec->getType()->isVectorTy() && "Invalid type");
1651 SmallVector<Constant*, 8> ShuffleMask;
1652 for (unsigned i = 0; i < VF; ++i)
1653 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1655 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1656 ConstantVector::get(ShuffleMask),
1660 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1661 // Attempt to issue a wide load.
1662 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1663 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1665 assert((LI || SI) && "Invalid Load/Store instruction");
1667 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1668 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1669 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1670 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1671 // An alignment of 0 means target abi alignment. We need to use the scalar's
1672 // target abi alignment in such a case.
1673 const DataLayout &DL = Instr->getModule()->getDataLayout();
1675 Alignment = DL.getABITypeAlignment(ScalarDataTy);
1676 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1677 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
1678 unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
1680 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
1681 !Legal->isMaskRequired(SI))
1682 return scalarizeInstruction(Instr, true);
1684 if (ScalarAllocatedSize != VectorElementSize)
1685 return scalarizeInstruction(Instr);
1687 // If the pointer is loop invariant or if it is non-consecutive,
1688 // scalarize the load.
1689 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1690 bool Reverse = ConsecutiveStride < 0;
1691 bool UniformLoad = LI && Legal->isUniform(Ptr);
1692 if (!ConsecutiveStride || UniformLoad)
1693 return scalarizeInstruction(Instr);
1695 Constant *Zero = Builder.getInt32(0);
1696 VectorParts &Entry = WidenMap.get(Instr);
1698 // Handle consecutive loads/stores.
1699 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1700 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1701 setDebugLocFromInst(Builder, Gep);
1702 Value *PtrOperand = Gep->getPointerOperand();
1703 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1704 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1706 // Create the new GEP with the new induction variable.
1707 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1708 Gep2->setOperand(0, FirstBasePtr);
1709 Gep2->setName("gep.indvar.base");
1710 Ptr = Builder.Insert(Gep2);
1712 setDebugLocFromInst(Builder, Gep);
1713 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1714 OrigLoop) && "Base ptr must be invariant");
1716 // The last index does not have to be the induction. It can be
1717 // consecutive and be a function of the index. For example A[I+1];
1718 unsigned NumOperands = Gep->getNumOperands();
1719 unsigned InductionOperand = getGEPInductionOperand(Gep);
1720 // Create the new GEP with the new induction variable.
1721 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1723 for (unsigned i = 0; i < NumOperands; ++i) {
1724 Value *GepOperand = Gep->getOperand(i);
1725 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1727 // Update last index or loop invariant instruction anchored in loop.
1728 if (i == InductionOperand ||
1729 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1730 assert((i == InductionOperand ||
1731 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1732 "Must be last index or loop invariant");
1734 VectorParts &GEPParts = getVectorValue(GepOperand);
1735 Value *Index = GEPParts[0];
1736 Index = Builder.CreateExtractElement(Index, Zero);
1737 Gep2->setOperand(i, Index);
1738 Gep2->setName("gep.indvar.idx");
1741 Ptr = Builder.Insert(Gep2);
1743 // Use the induction element ptr.
1744 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1745 setDebugLocFromInst(Builder, Ptr);
1746 VectorParts &PtrVal = getVectorValue(Ptr);
1747 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1750 VectorParts Mask = createBlockInMask(Instr->getParent());
1753 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1754 "We do not allow storing to uniform addresses");
1755 setDebugLocFromInst(Builder, SI);
1756 // We don't want to update the value in the map as it might be used in
1757 // another expression. So don't use a reference type for "StoredVal".
1758 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1760 for (unsigned Part = 0; Part < UF; ++Part) {
1761 // Calculate the pointer for the specific unroll-part.
1763 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
1766 // If we store to reverse consecutive memory locations then we need
1767 // to reverse the order of elements in the stored value.
1768 StoredVal[Part] = reverseVector(StoredVal[Part]);
1769 // If the address is consecutive but reversed, then the
1770 // wide store needs to start at the last vector element.
1771 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
1772 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
1773 Mask[Part] = reverseVector(Mask[Part]);
1776 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1777 DataTy->getPointerTo(AddressSpace));
1780 if (Legal->isMaskRequired(SI))
1781 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
1784 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
1785 propagateMetadata(NewSI, SI);
1791 assert(LI && "Must have a load instruction");
1792 setDebugLocFromInst(Builder, LI);
1793 for (unsigned Part = 0; Part < UF; ++Part) {
1794 // Calculate the pointer for the specific unroll-part.
1796 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
1799 // If the address is consecutive but reversed, then the
1800 // wide load needs to start at the last vector element.
1801 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
1802 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
1803 Mask[Part] = reverseVector(Mask[Part]);
1807 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1808 DataTy->getPointerTo(AddressSpace));
1809 if (Legal->isMaskRequired(LI))
1810 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
1811 UndefValue::get(DataTy),
1812 "wide.masked.load");
1814 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
1815 propagateMetadata(NewLI, LI);
1816 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
1820 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1821 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1822 // Holds vector parameters or scalars, in case of uniform vals.
1823 SmallVector<VectorParts, 4> Params;
1825 setDebugLocFromInst(Builder, Instr);
1827 // Find all of the vectorized parameters.
1828 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1829 Value *SrcOp = Instr->getOperand(op);
1831 // If we are accessing the old induction variable, use the new one.
1832 if (SrcOp == OldInduction) {
1833 Params.push_back(getVectorValue(SrcOp));
1837 // Try using previously calculated values.
1838 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1840 // If the src is an instruction that appeared earlier in the basic block
1841 // then it should already be vectorized.
1842 if (SrcInst && OrigLoop->contains(SrcInst)) {
1843 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1844 // The parameter is a vector value from earlier.
1845 Params.push_back(WidenMap.get(SrcInst));
1847 // The parameter is a scalar from outside the loop. Maybe even a constant.
1848 VectorParts Scalars;
1849 Scalars.append(UF, SrcOp);
1850 Params.push_back(Scalars);
1854 assert(Params.size() == Instr->getNumOperands() &&
1855 "Invalid number of operands");
1857 // Does this instruction return a value ?
1858 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1860 Value *UndefVec = IsVoidRetTy ? nullptr :
1861 UndefValue::get(VectorType::get(Instr->getType(), VF));
1862 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1863 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1865 Instruction *InsertPt = Builder.GetInsertPoint();
1866 BasicBlock *IfBlock = Builder.GetInsertBlock();
1867 BasicBlock *CondBlock = nullptr;
1870 Loop *VectorLp = nullptr;
1871 if (IfPredicateStore) {
1872 assert(Instr->getParent()->getSinglePredecessor() &&
1873 "Only support single predecessor blocks");
1874 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
1875 Instr->getParent());
1876 VectorLp = LI->getLoopFor(IfBlock);
1877 assert(VectorLp && "Must have a loop for this block");
1880 // For each vector unroll 'part':
1881 for (unsigned Part = 0; Part < UF; ++Part) {
1882 // For each scalar that we create:
1883 for (unsigned Width = 0; Width < VF; ++Width) {
1886 Value *Cmp = nullptr;
1887 if (IfPredicateStore) {
1888 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
1889 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
1890 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1891 LoopVectorBody.push_back(CondBlock);
1892 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
1893 // Update Builder with newly created basic block.
1894 Builder.SetInsertPoint(InsertPt);
1897 Instruction *Cloned = Instr->clone();
1899 Cloned->setName(Instr->getName() + ".cloned");
1900 // Replace the operands of the cloned instructions with extracted scalars.
1901 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1902 Value *Op = Params[op][Part];
1903 // Param is a vector. Need to extract the right lane.
1904 if (Op->getType()->isVectorTy())
1905 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1906 Cloned->setOperand(op, Op);
1909 // Place the cloned scalar in the new loop.
1910 Builder.Insert(Cloned);
1912 // If the original scalar returns a value we need to place it in a vector
1913 // so that future users will be able to use it.
1915 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1916 Builder.getInt32(Width));
1918 if (IfPredicateStore) {
1919 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1920 LoopVectorBody.push_back(NewIfBlock);
1921 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
1922 Builder.SetInsertPoint(InsertPt);
1923 Instruction *OldBr = IfBlock->getTerminator();
1924 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1925 OldBr->eraseFromParent();
1926 IfBlock = NewIfBlock;
1932 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1936 if (Instruction *I = dyn_cast<Instruction>(V))
1937 return I->getParent() == Loc->getParent() ? I : nullptr;
1941 std::pair<Instruction *, Instruction *>
1942 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1943 Instruction *tnullptr = nullptr;
1944 if (!Legal->mustCheckStrides())
1945 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1947 IRBuilder<> ChkBuilder(Loc);
1950 Value *Check = nullptr;
1951 Instruction *FirstInst = nullptr;
1952 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1953 SE = Legal->strides_end();
1955 Value *Ptr = stripIntegerCast(*SI);
1956 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1958 // Store the first instruction we create.
1959 FirstInst = getFirstInst(FirstInst, C, Loc);
1961 Check = ChkBuilder.CreateOr(Check, C);
1966 // We have to do this trickery because the IRBuilder might fold the check to a
1967 // constant expression in which case there is no Instruction anchored in a
1969 LLVMContext &Ctx = Loc->getContext();
1970 Instruction *TheCheck =
1971 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
1972 ChkBuilder.Insert(TheCheck, "stride.not.one");
1973 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
1975 return std::make_pair(FirstInst, TheCheck);
1978 void InnerLoopVectorizer::createEmptyLoop() {
1980 In this function we generate a new loop. The new loop will contain
1981 the vectorized instructions while the old loop will continue to run the
1984 [ ] <-- Back-edge taken count overflow check.
1987 | [ ] <-- vector loop bypass (may consist of multiple blocks).
1990 || [ ] <-- vector pre header.
1994 || [ ]_| <-- vector loop.
1997 | >[ ] <--- middle-block.
2000 -|- >[ ] <--- new preheader.
2004 | [ ]_| <-- old scalar loop to handle remainder.
2007 >[ ] <-- exit block.
2011 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2012 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
2013 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2014 assert(BypassBlock && "Invalid loop structure");
2015 assert(ExitBlock && "Must have an exit block");
2017 // Some loops have a single integer induction variable, while other loops
2018 // don't. One example is c++ iterators that often have multiple pointer
2019 // induction variables. In the code below we also support a case where we
2020 // don't have a single induction variable.
2021 OldInduction = Legal->getInduction();
2022 Type *IdxTy = Legal->getWidestInductionType();
2024 // Find the loop boundaries.
2025 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2026 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2028 // The exit count might have the type of i64 while the phi is i32. This can
2029 // happen if we have an induction variable that is sign extended before the
2030 // compare. The only way that we get a backedge taken count is that the
2031 // induction variable was signed and as such will not overflow. In such a case
2032 // truncation is legal.
2033 if (ExitCount->getType()->getPrimitiveSizeInBits() >
2034 IdxTy->getPrimitiveSizeInBits())
2035 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2037 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2038 // Get the total trip count from the count by adding 1.
2039 ExitCount = SE->getAddExpr(BackedgeTakeCount,
2040 SE->getConstant(BackedgeTakeCount->getType(), 1));
2042 const DataLayout &DL = OldBasicBlock->getModule()->getDataLayout();
2044 // Expand the trip count and place the new instructions in the preheader.
2045 // Notice that the pre-header does not change, only the loop body.
2046 SCEVExpander Exp(*SE, DL, "induction");
2048 // We need to test whether the backedge-taken count is uint##_max. Adding one
2049 // to it will cause overflow and an incorrect loop trip count in the vector
2050 // body. In case of overflow we want to directly jump to the scalar remainder
2052 Value *BackedgeCount =
2053 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2054 BypassBlock->getTerminator());
2055 if (BackedgeCount->getType()->isPointerTy())
2056 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2057 "backedge.ptrcnt.to.int",
2058 BypassBlock->getTerminator());
2059 Instruction *CheckBCOverflow =
2060 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2061 Constant::getAllOnesValue(BackedgeCount->getType()),
2062 "backedge.overflow", BypassBlock->getTerminator());
2064 // The loop index does not have to start at Zero. Find the original start
2065 // value from the induction PHI node. If we don't have an induction variable
2066 // then we know that it starts at zero.
2067 Builder.SetInsertPoint(BypassBlock->getTerminator());
2068 Value *StartIdx = ExtendedIdx = OldInduction ?
2069 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2071 ConstantInt::get(IdxTy, 0);
2073 // We need an instruction to anchor the overflow check on. StartIdx needs to
2074 // be defined before the overflow check branch. Because the scalar preheader
2075 // is going to merge the start index and so the overflow branch block needs to
2076 // contain a definition of the start index.
2077 Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
2078 StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
2079 BypassBlock->getTerminator());
2081 // Count holds the overall loop count (N).
2082 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2083 BypassBlock->getTerminator());
2085 LoopBypassBlocks.push_back(BypassBlock);
2087 // Split the single block loop into the two loop structure described above.
2088 BasicBlock *VectorPH =
2089 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2090 BasicBlock *VecBody =
2091 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2092 BasicBlock *MiddleBlock =
2093 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2094 BasicBlock *ScalarPH =
2095 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2097 // Create and register the new vector loop.
2098 Loop* Lp = new Loop();
2099 Loop *ParentLoop = OrigLoop->getParentLoop();
2101 // Insert the new loop into the loop nest and register the new basic blocks
2102 // before calling any utilities such as SCEV that require valid LoopInfo.
2104 ParentLoop->addChildLoop(Lp);
2105 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2106 ParentLoop->addBasicBlockToLoop(VectorPH, *LI);
2107 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2109 LI->addTopLevelLoop(Lp);
2111 Lp->addBasicBlockToLoop(VecBody, *LI);
2113 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2115 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2117 // Generate the induction variable.
2118 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2119 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2120 // The loop step is equal to the vectorization factor (num of SIMD elements)
2121 // times the unroll factor (num of SIMD instructions).
2122 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2124 // This is the IR builder that we use to add all of the logic for bypassing
2125 // the new vector loop.
2126 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2127 setDebugLocFromInst(BypassBuilder,
2128 getDebugLocFromInstOrOperands(OldInduction));
2130 // We may need to extend the index in case there is a type mismatch.
2131 // We know that the count starts at zero and does not overflow.
2132 if (Count->getType() != IdxTy) {
2133 // The exit count can be of pointer type. Convert it to the correct
2135 if (ExitCount->getType()->isPointerTy())
2136 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2138 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2141 // Add the start index to the loop count to get the new end index.
2142 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2144 // Now we need to generate the expression for N - (N % VF), which is
2145 // the part that the vectorized body will execute.
2146 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2147 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2148 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2149 "end.idx.rnd.down");
2151 // Now, compare the new count to zero. If it is zero skip the vector loop and
2152 // jump to the scalar loop.
2154 BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2156 BasicBlock *LastBypassBlock = BypassBlock;
2158 // Generate code to check that the loops trip count that we computed by adding
2159 // one to the backedge-taken count will not overflow.
2161 auto PastOverflowCheck =
2162 std::next(BasicBlock::iterator(OverflowCheckAnchor));
2163 BasicBlock *CheckBlock =
2164 LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2166 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2167 LoopBypassBlocks.push_back(CheckBlock);
2168 Instruction *OldTerm = LastBypassBlock->getTerminator();
2169 BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2170 OldTerm->eraseFromParent();
2171 LastBypassBlock = CheckBlock;
2174 // Generate the code to check that the strides we assumed to be one are really
2175 // one. We want the new basic block to start at the first instruction in a
2176 // sequence of instructions that form a check.
2177 Instruction *StrideCheck;
2178 Instruction *FirstCheckInst;
2179 std::tie(FirstCheckInst, StrideCheck) =
2180 addStrideCheck(LastBypassBlock->getTerminator());
2182 AddedSafetyChecks = true;
2183 // Create a new block containing the stride check.
2184 BasicBlock *CheckBlock =
2185 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2187 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2188 LoopBypassBlocks.push_back(CheckBlock);
2190 // Replace the branch into the memory check block with a conditional branch
2191 // for the "few elements case".
2192 Instruction *OldTerm = LastBypassBlock->getTerminator();
2193 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2194 OldTerm->eraseFromParent();
2197 LastBypassBlock = CheckBlock;
2200 // Generate the code that checks in runtime if arrays overlap. We put the
2201 // checks into a separate block to make the more common case of few elements
2203 Instruction *MemRuntimeCheck;
2204 std::tie(FirstCheckInst, MemRuntimeCheck) =
2205 Legal->getLAI()->addRuntimeCheck(LastBypassBlock->getTerminator());
2206 if (MemRuntimeCheck) {
2207 AddedSafetyChecks = true;
2208 // Create a new block containing the memory check.
2209 BasicBlock *CheckBlock =
2210 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.memcheck");
2212 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2213 LoopBypassBlocks.push_back(CheckBlock);
2215 // Replace the branch into the memory check block with a conditional branch
2216 // for the "few elements case".
2217 Instruction *OldTerm = LastBypassBlock->getTerminator();
2218 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2219 OldTerm->eraseFromParent();
2221 Cmp = MemRuntimeCheck;
2222 LastBypassBlock = CheckBlock;
2225 LastBypassBlock->getTerminator()->eraseFromParent();
2226 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2229 // We are going to resume the execution of the scalar loop.
2230 // Go over all of the induction variables that we found and fix the
2231 // PHIs that are left in the scalar version of the loop.
2232 // The starting values of PHI nodes depend on the counter of the last
2233 // iteration in the vectorized loop.
2234 // If we come from a bypass edge then we need to start from the original
2237 // This variable saves the new starting index for the scalar loop.
2238 PHINode *ResumeIndex = nullptr;
2239 LoopVectorizationLegality::InductionList::iterator I, E;
2240 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2241 // Set builder to point to last bypass block.
2242 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2243 for (I = List->begin(), E = List->end(); I != E; ++I) {
2244 PHINode *OrigPhi = I->first;
2245 LoopVectorizationLegality::InductionInfo II = I->second;
2247 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2248 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2249 MiddleBlock->getTerminator());
2250 // We might have extended the type of the induction variable but we need a
2251 // truncated version for the scalar loop.
2252 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2253 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2254 MiddleBlock->getTerminator()) : nullptr;
2256 // Create phi nodes to merge from the backedge-taken check block.
2257 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2258 ScalarPH->getTerminator());
2259 BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2261 PHINode *BCTruncResumeVal = nullptr;
2262 if (OrigPhi == OldInduction) {
2264 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2265 ScalarPH->getTerminator());
2266 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2269 Value *EndValue = nullptr;
2271 case LoopVectorizationLegality::IK_NoInduction:
2272 llvm_unreachable("Unknown induction");
2273 case LoopVectorizationLegality::IK_IntInduction: {
2274 // Handle the integer induction counter.
2275 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2277 // We have the canonical induction variable.
2278 if (OrigPhi == OldInduction) {
2279 // Create a truncated version of the resume value for the scalar loop,
2280 // we might have promoted the type to a larger width.
2282 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2283 // The new PHI merges the original incoming value, in case of a bypass,
2284 // or the value at the end of the vectorized loop.
2285 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2286 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2287 TruncResumeVal->addIncoming(EndValue, VecBody);
2289 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2291 // We know what the end value is.
2292 EndValue = IdxEndRoundDown;
2293 // We also know which PHI node holds it.
2294 ResumeIndex = ResumeVal;
2298 // Not the canonical induction variable - add the vector loop count to the
2300 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2301 II.StartValue->getType(),
2303 EndValue = II.transform(BypassBuilder, CRD);
2304 EndValue->setName("ind.end");
2307 case LoopVectorizationLegality::IK_PtrInduction: {
2308 EndValue = II.transform(BypassBuilder, CountRoundDown);
2309 EndValue->setName("ptr.ind.end");
2314 // The new PHI merges the original incoming value, in case of a bypass,
2315 // or the value at the end of the vectorized loop.
2316 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2317 if (OrigPhi == OldInduction)
2318 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2320 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2322 ResumeVal->addIncoming(EndValue, VecBody);
2324 // Fix the scalar body counter (PHI node).
2325 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2327 // The old induction's phi node in the scalar body needs the truncated
2329 if (OrigPhi == OldInduction) {
2330 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2331 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2333 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2334 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2338 // If we are generating a new induction variable then we also need to
2339 // generate the code that calculates the exit value. This value is not
2340 // simply the end of the counter because we may skip the vectorized body
2341 // in case of a runtime check.
2343 assert(!ResumeIndex && "Unexpected resume value found");
2344 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2345 MiddleBlock->getTerminator());
2346 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2347 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2348 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2351 // Make sure that we found the index where scalar loop needs to continue.
2352 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2353 "Invalid resume Index");
2355 // Add a check in the middle block to see if we have completed
2356 // all of the iterations in the first vector loop.
2357 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2358 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2359 ResumeIndex, "cmp.n",
2360 MiddleBlock->getTerminator());
2362 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2363 // Remove the old terminator.
2364 MiddleBlock->getTerminator()->eraseFromParent();
2366 // Create i+1 and fill the PHINode.
2367 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2368 Induction->addIncoming(StartIdx, VectorPH);
2369 Induction->addIncoming(NextIdx, VecBody);
2370 // Create the compare.
2371 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2372 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2374 // Now we have two terminators. Remove the old one from the block.
2375 VecBody->getTerminator()->eraseFromParent();
2377 // Get ready to start creating new instructions into the vectorized body.
2378 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2381 LoopVectorPreHeader = VectorPH;
2382 LoopScalarPreHeader = ScalarPH;
2383 LoopMiddleBlock = MiddleBlock;
2384 LoopExitBlock = ExitBlock;
2385 LoopVectorBody.push_back(VecBody);
2386 LoopScalarBody = OldBasicBlock;
2388 LoopVectorizeHints Hints(Lp, true);
2389 Hints.setAlreadyVectorized();
2393 struct CSEDenseMapInfo {
2394 static bool canHandle(Instruction *I) {
2395 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2396 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2398 static inline Instruction *getEmptyKey() {
2399 return DenseMapInfo<Instruction *>::getEmptyKey();
2401 static inline Instruction *getTombstoneKey() {
2402 return DenseMapInfo<Instruction *>::getTombstoneKey();
2404 static unsigned getHashValue(Instruction *I) {
2405 assert(canHandle(I) && "Unknown instruction!");
2406 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2407 I->value_op_end()));
2409 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2410 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2411 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2413 return LHS->isIdenticalTo(RHS);
2418 /// \brief Check whether this block is a predicated block.
2419 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2420 /// = ...; " blocks. We start with one vectorized basic block. For every
2421 /// conditional block we split this vectorized block. Therefore, every second
2422 /// block will be a predicated one.
2423 static bool isPredicatedBlock(unsigned BlockNum) {
2424 return BlockNum % 2;
2427 ///\brief Perform cse of induction variable instructions.
2428 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2429 // Perform simple cse.
2430 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2431 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2432 BasicBlock *BB = BBs[i];
2433 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2434 Instruction *In = I++;
2436 if (!CSEDenseMapInfo::canHandle(In))
2439 // Check if we can replace this instruction with any of the
2440 // visited instructions.
2441 if (Instruction *V = CSEMap.lookup(In)) {
2442 In->replaceAllUsesWith(V);
2443 In->eraseFromParent();
2446 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2447 // ...;" blocks for predicated stores. Every second block is a predicated
2449 if (isPredicatedBlock(i))
2457 /// \brief Adds a 'fast' flag to floating point operations.
2458 static Value *addFastMathFlag(Value *V) {
2459 if (isa<FPMathOperator>(V)){
2460 FastMathFlags Flags;
2461 Flags.setUnsafeAlgebra();
2462 cast<Instruction>(V)->setFastMathFlags(Flags);
2467 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
2468 /// the result needs to be inserted and/or extracted from vectors.
2469 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
2470 const TargetTransformInfo &TTI) {
2474 assert(Ty->isVectorTy() && "Can only scalarize vectors");
2477 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
2479 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
2481 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
2487 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
2488 // Return the cost of the instruction, including scalarization overhead if it's
2489 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
2490 // i.e. either vector version isn't available, or is too expensive.
2491 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
2492 const TargetTransformInfo &TTI,
2493 const TargetLibraryInfo *TLI,
2494 bool &NeedToScalarize) {
2495 Function *F = CI->getCalledFunction();
2496 StringRef FnName = CI->getCalledFunction()->getName();
2497 Type *ScalarRetTy = CI->getType();
2498 SmallVector<Type *, 4> Tys, ScalarTys;
2499 for (auto &ArgOp : CI->arg_operands())
2500 ScalarTys.push_back(ArgOp->getType());
2502 // Estimate cost of scalarized vector call. The source operands are assumed
2503 // to be vectors, so we need to extract individual elements from there,
2504 // execute VF scalar calls, and then gather the result into the vector return
2506 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
2508 return ScalarCallCost;
2510 // Compute corresponding vector type for return value and arguments.
2511 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
2512 for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
2513 Tys.push_back(ToVectorTy(ScalarTys[i], VF));
2515 // Compute costs of unpacking argument values for the scalar calls and
2516 // packing the return values to a vector.
2517 unsigned ScalarizationCost =
2518 getScalarizationOverhead(RetTy, true, false, TTI);
2519 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
2520 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
2522 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
2524 // If we can't emit a vector call for this function, then the currently found
2525 // cost is the cost we need to return.
2526 NeedToScalarize = true;
2527 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
2530 // If the corresponding vector cost is cheaper, return its cost.
2531 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
2532 if (VectorCallCost < Cost) {
2533 NeedToScalarize = false;
2534 return VectorCallCost;
2539 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
2540 // factor VF. Return the cost of the instruction, including scalarization
2541 // overhead if it's needed.
2542 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
2543 const TargetTransformInfo &TTI,
2544 const TargetLibraryInfo *TLI) {
2545 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2546 assert(ID && "Expected intrinsic call!");
2548 Type *RetTy = ToVectorTy(CI->getType(), VF);
2549 SmallVector<Type *, 4> Tys;
2550 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
2551 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
2553 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
2556 void InnerLoopVectorizer::vectorizeLoop() {
2557 //===------------------------------------------------===//
2559 // Notice: any optimization or new instruction that go
2560 // into the code below should be also be implemented in
2563 //===------------------------------------------------===//
2564 Constant *Zero = Builder.getInt32(0);
2566 // In order to support reduction variables we need to be able to vectorize
2567 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2568 // stages. First, we create a new vector PHI node with no incoming edges.
2569 // We use this value when we vectorize all of the instructions that use the
2570 // PHI. Next, after all of the instructions in the block are complete we
2571 // add the new incoming edges to the PHI. At this point all of the
2572 // instructions in the basic block are vectorized, so we can use them to
2573 // construct the PHI.
2574 PhiVector RdxPHIsToFix;
2576 // Scan the loop in a topological order to ensure that defs are vectorized
2578 LoopBlocksDFS DFS(OrigLoop);
2581 // Vectorize all of the blocks in the original loop.
2582 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2583 be = DFS.endRPO(); bb != be; ++bb)
2584 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2586 // At this point every instruction in the original loop is widened to
2587 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2588 // that we vectorized. The PHI nodes are currently empty because we did
2589 // not want to introduce cycles. Notice that the remaining PHI nodes
2590 // that we need to fix are reduction variables.
2592 // Create the 'reduced' values for each of the induction vars.
2593 // The reduced values are the vector values that we scalarize and combine
2594 // after the loop is finished.
2595 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2597 PHINode *RdxPhi = *it;
2598 assert(RdxPhi && "Unable to recover vectorized PHI");
2600 // Find the reduction variable descriptor.
2601 assert(Legal->getReductionVars()->count(RdxPhi) &&
2602 "Unable to find the reduction variable");
2603 ReductionDescriptor RdxDesc = (*Legal->getReductionVars())[RdxPhi];
2605 ReductionDescriptor::ReductionKind RK = RdxDesc.getReductionKind();
2606 TrackingVH<Value> ReductionStartValue = RdxDesc.getReductionStartValue();
2607 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
2608 ReductionInstDesc::MinMaxReductionKind MinMaxKind =
2609 RdxDesc.getMinMaxReductionKind();
2610 setDebugLocFromInst(Builder, ReductionStartValue);
2612 // We need to generate a reduction vector from the incoming scalar.
2613 // To do so, we need to generate the 'identity' vector and override
2614 // one of the elements with the incoming scalar reduction. We need
2615 // to do it in the vector-loop preheader.
2616 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2618 // This is the vector-clone of the value that leaves the loop.
2619 VectorParts &VectorExit = getVectorValue(LoopExitInst);
2620 Type *VecTy = VectorExit[0]->getType();
2622 // Find the reduction identity variable. Zero for addition, or, xor,
2623 // one for multiplication, -1 for And.
2626 if (RK == ReductionDescriptor::RK_IntegerMinMax ||
2627 RK == ReductionDescriptor::RK_FloatMinMax) {
2628 // MinMax reduction have the start value as their identify.
2630 VectorStart = Identity = ReductionStartValue;
2632 VectorStart = Identity =
2633 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
2636 // Handle other reduction kinds:
2638 ReductionDescriptor::getReductionIdentity(RK, VecTy->getScalarType());
2641 // This vector is the Identity vector where the first element is the
2642 // incoming scalar reduction.
2643 VectorStart = ReductionStartValue;
2645 Identity = ConstantVector::getSplat(VF, Iden);
2647 // This vector is the Identity vector where the first element is the
2648 // incoming scalar reduction.
2650 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
2654 // Fix the vector-loop phi.
2656 // Reductions do not have to start at zero. They can start with
2657 // any loop invariant values.
2658 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2659 BasicBlock *Latch = OrigLoop->getLoopLatch();
2660 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2661 VectorParts &Val = getVectorValue(LoopVal);
2662 for (unsigned part = 0; part < UF; ++part) {
2663 // Make sure to add the reduction stat value only to the
2664 // first unroll part.
2665 Value *StartVal = (part == 0) ? VectorStart : Identity;
2666 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
2667 LoopVectorPreHeader);
2668 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2669 LoopVectorBody.back());
2672 // Before each round, move the insertion point right between
2673 // the PHIs and the values we are going to write.
2674 // This allows us to write both PHINodes and the extractelement
2676 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2678 VectorParts RdxParts;
2679 setDebugLocFromInst(Builder, LoopExitInst);
2680 for (unsigned part = 0; part < UF; ++part) {
2681 // This PHINode contains the vectorized reduction variable, or
2682 // the initial value vector, if we bypass the vector loop.
2683 VectorParts &RdxExitVal = getVectorValue(LoopExitInst);
2684 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2685 Value *StartVal = (part == 0) ? VectorStart : Identity;
2686 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2687 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2688 NewPhi->addIncoming(RdxExitVal[part],
2689 LoopVectorBody.back());
2690 RdxParts.push_back(NewPhi);
2693 // Reduce all of the unrolled parts into a single vector.
2694 Value *ReducedPartRdx = RdxParts[0];
2695 unsigned Op = ReductionDescriptor::getReductionBinOp(RK);
2696 setDebugLocFromInst(Builder, ReducedPartRdx);
2697 for (unsigned part = 1; part < UF; ++part) {
2698 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2699 // Floating point operations had to be 'fast' to enable the reduction.
2700 ReducedPartRdx = addFastMathFlag(
2701 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2702 ReducedPartRdx, "bin.rdx"));
2704 ReducedPartRdx = ReductionDescriptor::createMinMaxOp(
2705 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
2709 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2710 // and vector ops, reducing the set of values being computed by half each
2712 assert(isPowerOf2_32(VF) &&
2713 "Reduction emission only supported for pow2 vectors!");
2714 Value *TmpVec = ReducedPartRdx;
2715 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2716 for (unsigned i = VF; i != 1; i >>= 1) {
2717 // Move the upper half of the vector to the lower half.
2718 for (unsigned j = 0; j != i/2; ++j)
2719 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2721 // Fill the rest of the mask with undef.
2722 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2723 UndefValue::get(Builder.getInt32Ty()));
2726 Builder.CreateShuffleVector(TmpVec,
2727 UndefValue::get(TmpVec->getType()),
2728 ConstantVector::get(ShuffleMask),
2731 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2732 // Floating point operations had to be 'fast' to enable the reduction.
2733 TmpVec = addFastMathFlag(Builder.CreateBinOp(
2734 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2736 TmpVec = ReductionDescriptor::createMinMaxOp(Builder, MinMaxKind,
2740 // The result is in the first element of the vector.
2741 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2742 Builder.getInt32(0));
2745 // Create a phi node that merges control-flow from the backedge-taken check
2746 // block and the middle block.
2747 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2748 LoopScalarPreHeader->getTerminator());
2749 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[0]);
2750 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2752 // Now, we need to fix the users of the reduction variable
2753 // inside and outside of the scalar remainder loop.
2754 // We know that the loop is in LCSSA form. We need to update the
2755 // PHI nodes in the exit blocks.
2756 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2757 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2758 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2759 if (!LCSSAPhi) break;
2761 // All PHINodes need to have a single entry edge, or two if
2762 // we already fixed them.
2763 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2765 // We found our reduction value exit-PHI. Update it with the
2766 // incoming bypass edge.
2767 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
2768 // Add an edge coming from the bypass.
2769 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2772 }// end of the LCSSA phi scan.
2774 // Fix the scalar loop reduction variable with the incoming reduction sum
2775 // from the vector body and from the backedge value.
2776 int IncomingEdgeBlockIdx =
2777 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2778 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2779 // Pick the other block.
2780 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2781 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
2782 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
2783 }// end of for each redux variable.
2787 // Remove redundant induction instructions.
2788 cse(LoopVectorBody);
2791 void InnerLoopVectorizer::fixLCSSAPHIs() {
2792 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2793 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2794 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2795 if (!LCSSAPhi) break;
2796 if (LCSSAPhi->getNumIncomingValues() == 1)
2797 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2802 InnerLoopVectorizer::VectorParts
2803 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2804 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2807 // Look for cached value.
2808 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2809 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2810 if (ECEntryIt != MaskCache.end())
2811 return ECEntryIt->second;
2813 VectorParts SrcMask = createBlockInMask(Src);
2815 // The terminator has to be a branch inst!
2816 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2817 assert(BI && "Unexpected terminator found");
2819 if (BI->isConditional()) {
2820 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2822 if (BI->getSuccessor(0) != Dst)
2823 for (unsigned part = 0; part < UF; ++part)
2824 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2826 for (unsigned part = 0; part < UF; ++part)
2827 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2829 MaskCache[Edge] = EdgeMask;
2833 MaskCache[Edge] = SrcMask;
2837 InnerLoopVectorizer::VectorParts
2838 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2839 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2841 // Loop incoming mask is all-one.
2842 if (OrigLoop->getHeader() == BB) {
2843 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2844 return getVectorValue(C);
2847 // This is the block mask. We OR all incoming edges, and with zero.
2848 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2849 VectorParts BlockMask = getVectorValue(Zero);
2852 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2853 VectorParts EM = createEdgeMask(*it, BB);
2854 for (unsigned part = 0; part < UF; ++part)
2855 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2861 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2862 InnerLoopVectorizer::VectorParts &Entry,
2863 unsigned UF, unsigned VF, PhiVector *PV) {
2864 PHINode* P = cast<PHINode>(PN);
2865 // Handle reduction variables:
2866 if (Legal->getReductionVars()->count(P)) {
2867 for (unsigned part = 0; part < UF; ++part) {
2868 // This is phase one of vectorizing PHIs.
2869 Type *VecTy = (VF == 1) ? PN->getType() :
2870 VectorType::get(PN->getType(), VF);
2871 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2872 LoopVectorBody.back()-> getFirstInsertionPt());
2878 setDebugLocFromInst(Builder, P);
2879 // Check for PHI nodes that are lowered to vector selects.
2880 if (P->getParent() != OrigLoop->getHeader()) {
2881 // We know that all PHIs in non-header blocks are converted into
2882 // selects, so we don't have to worry about the insertion order and we
2883 // can just use the builder.
2884 // At this point we generate the predication tree. There may be
2885 // duplications since this is a simple recursive scan, but future
2886 // optimizations will clean it up.
2888 unsigned NumIncoming = P->getNumIncomingValues();
2890 // Generate a sequence of selects of the form:
2891 // SELECT(Mask3, In3,
2892 // SELECT(Mask2, In2,
2894 for (unsigned In = 0; In < NumIncoming; In++) {
2895 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2897 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2899 for (unsigned part = 0; part < UF; ++part) {
2900 // We might have single edge PHIs (blocks) - use an identity
2901 // 'select' for the first PHI operand.
2903 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2906 // Select between the current value and the previous incoming edge
2907 // based on the incoming mask.
2908 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2909 Entry[part], "predphi");
2915 // This PHINode must be an induction variable.
2916 // Make sure that we know about it.
2917 assert(Legal->getInductionVars()->count(P) &&
2918 "Not an induction variable");
2920 LoopVectorizationLegality::InductionInfo II =
2921 Legal->getInductionVars()->lookup(P);
2923 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2924 // which can be found from the original scalar operations.
2926 case LoopVectorizationLegality::IK_NoInduction:
2927 llvm_unreachable("Unknown induction");
2928 case LoopVectorizationLegality::IK_IntInduction: {
2929 assert(P->getType() == II.StartValue->getType() && "Types must match");
2930 Type *PhiTy = P->getType();
2932 if (P == OldInduction) {
2933 // Handle the canonical induction variable. We might have had to
2935 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2937 // Handle other induction variables that are now based on the
2939 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2941 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2942 Broadcasted = II.transform(Builder, NormalizedIdx);
2943 Broadcasted->setName("offset.idx");
2945 Broadcasted = getBroadcastInstrs(Broadcasted);
2946 // After broadcasting the induction variable we need to make the vector
2947 // consecutive by adding 0, 1, 2, etc.
2948 for (unsigned part = 0; part < UF; ++part)
2949 Entry[part] = getStepVector(Broadcasted, VF * part, II.StepValue);
2952 case LoopVectorizationLegality::IK_PtrInduction:
2953 // Handle the pointer induction variable case.
2954 assert(P->getType()->isPointerTy() && "Unexpected type.");
2955 // This is the normalized GEP that starts counting at zero.
2956 Value *NormalizedIdx =
2957 Builder.CreateSub(Induction, ExtendedIdx, "normalized.idx");
2958 // This is the vector of results. Notice that we don't generate
2959 // vector geps because scalar geps result in better code.
2960 for (unsigned part = 0; part < UF; ++part) {
2962 int EltIndex = part;
2963 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2964 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
2965 Value *SclrGep = II.transform(Builder, GlobalIdx);
2966 SclrGep->setName("next.gep");
2967 Entry[part] = SclrGep;
2971 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2972 for (unsigned int i = 0; i < VF; ++i) {
2973 int EltIndex = i + part * VF;
2974 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2975 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
2976 Value *SclrGep = II.transform(Builder, GlobalIdx);
2977 SclrGep->setName("next.gep");
2978 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2979 Builder.getInt32(i),
2982 Entry[part] = VecVal;
2988 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
2989 // For each instruction in the old loop.
2990 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2991 VectorParts &Entry = WidenMap.get(it);
2992 switch (it->getOpcode()) {
2993 case Instruction::Br:
2994 // Nothing to do for PHIs and BR, since we already took care of the
2995 // loop control flow instructions.
2997 case Instruction::PHI: {
2998 // Vectorize PHINodes.
2999 widenPHIInstruction(it, Entry, UF, VF, PV);
3003 case Instruction::Add:
3004 case Instruction::FAdd:
3005 case Instruction::Sub:
3006 case Instruction::FSub:
3007 case Instruction::Mul:
3008 case Instruction::FMul:
3009 case Instruction::UDiv:
3010 case Instruction::SDiv:
3011 case Instruction::FDiv:
3012 case Instruction::URem:
3013 case Instruction::SRem:
3014 case Instruction::FRem:
3015 case Instruction::Shl:
3016 case Instruction::LShr:
3017 case Instruction::AShr:
3018 case Instruction::And:
3019 case Instruction::Or:
3020 case Instruction::Xor: {
3021 // Just widen binops.
3022 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3023 setDebugLocFromInst(Builder, BinOp);
3024 VectorParts &A = getVectorValue(it->getOperand(0));
3025 VectorParts &B = getVectorValue(it->getOperand(1));
3027 // Use this vector value for all users of the original instruction.
3028 for (unsigned Part = 0; Part < UF; ++Part) {
3029 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3031 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3032 VecOp->copyIRFlags(BinOp);
3037 propagateMetadata(Entry, it);
3040 case Instruction::Select: {
3042 // If the selector is loop invariant we can create a select
3043 // instruction with a scalar condition. Otherwise, use vector-select.
3044 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3046 setDebugLocFromInst(Builder, it);
3048 // The condition can be loop invariant but still defined inside the
3049 // loop. This means that we can't just use the original 'cond' value.
3050 // We have to take the 'vectorized' value and pick the first lane.
3051 // Instcombine will make this a no-op.
3052 VectorParts &Cond = getVectorValue(it->getOperand(0));
3053 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3054 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3056 Value *ScalarCond = (VF == 1) ? Cond[0] :
3057 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3059 for (unsigned Part = 0; Part < UF; ++Part) {
3060 Entry[Part] = Builder.CreateSelect(
3061 InvariantCond ? ScalarCond : Cond[Part],
3066 propagateMetadata(Entry, it);
3070 case Instruction::ICmp:
3071 case Instruction::FCmp: {
3072 // Widen compares. Generate vector compares.
3073 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3074 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3075 setDebugLocFromInst(Builder, it);
3076 VectorParts &A = getVectorValue(it->getOperand(0));
3077 VectorParts &B = getVectorValue(it->getOperand(1));
3078 for (unsigned Part = 0; Part < UF; ++Part) {
3081 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3083 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3087 propagateMetadata(Entry, it);
3091 case Instruction::Store:
3092 case Instruction::Load:
3093 vectorizeMemoryInstruction(it);
3095 case Instruction::ZExt:
3096 case Instruction::SExt:
3097 case Instruction::FPToUI:
3098 case Instruction::FPToSI:
3099 case Instruction::FPExt:
3100 case Instruction::PtrToInt:
3101 case Instruction::IntToPtr:
3102 case Instruction::SIToFP:
3103 case Instruction::UIToFP:
3104 case Instruction::Trunc:
3105 case Instruction::FPTrunc:
3106 case Instruction::BitCast: {
3107 CastInst *CI = dyn_cast<CastInst>(it);
3108 setDebugLocFromInst(Builder, it);
3109 /// Optimize the special case where the source is the induction
3110 /// variable. Notice that we can only optimize the 'trunc' case
3111 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3112 /// c. other casts depend on pointer size.
3113 if (CI->getOperand(0) == OldInduction &&
3114 it->getOpcode() == Instruction::Trunc) {
3115 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3117 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3118 LoopVectorizationLegality::InductionInfo II =
3119 Legal->getInductionVars()->lookup(OldInduction);
3121 ConstantInt::getSigned(CI->getType(), II.StepValue->getSExtValue());
3122 for (unsigned Part = 0; Part < UF; ++Part)
3123 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3124 propagateMetadata(Entry, it);
3127 /// Vectorize casts.
3128 Type *DestTy = (VF == 1) ? CI->getType() :
3129 VectorType::get(CI->getType(), VF);
3131 VectorParts &A = getVectorValue(it->getOperand(0));
3132 for (unsigned Part = 0; Part < UF; ++Part)
3133 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3134 propagateMetadata(Entry, it);
3138 case Instruction::Call: {
3139 // Ignore dbg intrinsics.
3140 if (isa<DbgInfoIntrinsic>(it))
3142 setDebugLocFromInst(Builder, it);
3144 Module *M = BB->getParent()->getParent();
3145 CallInst *CI = cast<CallInst>(it);
3147 StringRef FnName = CI->getCalledFunction()->getName();
3148 Function *F = CI->getCalledFunction();
3149 Type *RetTy = ToVectorTy(CI->getType(), VF);
3150 SmallVector<Type *, 4> Tys;
3151 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3152 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3154 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3156 (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
3157 ID == Intrinsic::lifetime_start)) {
3158 scalarizeInstruction(it);
3161 // The flag shows whether we use Intrinsic or a usual Call for vectorized
3162 // version of the instruction.
3163 // Is it beneficial to perform intrinsic call compared to lib call?
3164 bool NeedToScalarize;
3165 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
3166 bool UseVectorIntrinsic =
3167 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
3168 if (!UseVectorIntrinsic && NeedToScalarize) {
3169 scalarizeInstruction(it);
3173 for (unsigned Part = 0; Part < UF; ++Part) {
3174 SmallVector<Value *, 4> Args;
3175 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3176 Value *Arg = CI->getArgOperand(i);
3177 // Some intrinsics have a scalar argument - don't replace it with a
3179 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
3180 VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
3181 Arg = VectorArg[Part];
3183 Args.push_back(Arg);
3187 if (UseVectorIntrinsic) {
3188 // Use vector version of the intrinsic.
3189 Type *TysForDecl[] = {CI->getType()};
3191 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3192 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
3194 // Use vector version of the library call.
3195 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
3196 assert(!VFnName.empty() && "Vector function name is empty.");
3197 VectorF = M->getFunction(VFnName);
3199 // Generate a declaration
3200 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
3202 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
3203 VectorF->copyAttributesFrom(F);
3206 assert(VectorF && "Can't create vector function.");
3207 Entry[Part] = Builder.CreateCall(VectorF, Args);
3210 propagateMetadata(Entry, it);
3215 // All other instructions are unsupported. Scalarize them.
3216 scalarizeInstruction(it);
3219 }// end of for_each instr.
3222 void InnerLoopVectorizer::updateAnalysis() {
3223 // Forget the original basic block.
3224 SE->forgetLoop(OrigLoop);
3226 // Update the dominator tree information.
3227 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3228 "Entry does not dominate exit.");
3230 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3231 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3232 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3234 // Due to if predication of stores we might create a sequence of "if(pred)
3235 // a[i] = ...; " blocks.
3236 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3238 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3239 else if (isPredicatedBlock(i)) {
3240 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3242 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3246 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3247 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3248 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3249 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3251 DEBUG(DT->verifyDomTree());
3254 /// \brief Check whether it is safe to if-convert this phi node.
3256 /// Phi nodes with constant expressions that can trap are not safe to if
3258 static bool canIfConvertPHINodes(BasicBlock *BB) {
3259 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3260 PHINode *Phi = dyn_cast<PHINode>(I);
3263 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3264 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3271 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3272 if (!EnableIfConversion) {
3273 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3277 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3279 // A list of pointers that we can safely read and write to.
3280 SmallPtrSet<Value *, 8> SafePointes;
3282 // Collect safe addresses.
3283 for (Loop::block_iterator BI = TheLoop->block_begin(),
3284 BE = TheLoop->block_end(); BI != BE; ++BI) {
3285 BasicBlock *BB = *BI;
3287 if (blockNeedsPredication(BB))
3290 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3291 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3292 SafePointes.insert(LI->getPointerOperand());
3293 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3294 SafePointes.insert(SI->getPointerOperand());
3298 // Collect the blocks that need predication.
3299 BasicBlock *Header = TheLoop->getHeader();
3300 for (Loop::block_iterator BI = TheLoop->block_begin(),
3301 BE = TheLoop->block_end(); BI != BE; ++BI) {
3302 BasicBlock *BB = *BI;
3304 // We don't support switch statements inside loops.
3305 if (!isa<BranchInst>(BB->getTerminator())) {
3306 emitAnalysis(VectorizationReport(BB->getTerminator())
3307 << "loop contains a switch statement");
3311 // We must be able to predicate all blocks that need to be predicated.
3312 if (blockNeedsPredication(BB)) {
3313 if (!blockCanBePredicated(BB, SafePointes)) {
3314 emitAnalysis(VectorizationReport(BB->getTerminator())
3315 << "control flow cannot be substituted for a select");
3318 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3319 emitAnalysis(VectorizationReport(BB->getTerminator())
3320 << "control flow cannot be substituted for a select");
3325 // We can if-convert this loop.
3329 bool LoopVectorizationLegality::canVectorize() {
3330 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3331 // be canonicalized.
3332 if (!TheLoop->getLoopPreheader()) {
3334 VectorizationReport() <<
3335 "loop control flow is not understood by vectorizer");
3339 // We can only vectorize innermost loops.
3340 if (!TheLoop->getSubLoopsVector().empty()) {
3341 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3345 // We must have a single backedge.
3346 if (TheLoop->getNumBackEdges() != 1) {
3348 VectorizationReport() <<
3349 "loop control flow is not understood by vectorizer");
3353 // We must have a single exiting block.
3354 if (!TheLoop->getExitingBlock()) {
3356 VectorizationReport() <<
3357 "loop control flow is not understood by vectorizer");
3361 // We only handle bottom-tested loops, i.e. loop in which the condition is
3362 // checked at the end of each iteration. With that we can assume that all
3363 // instructions in the loop are executed the same number of times.
3364 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3366 VectorizationReport() <<
3367 "loop control flow is not understood by vectorizer");
3371 // We need to have a loop header.
3372 DEBUG(dbgs() << "LV: Found a loop: " <<
3373 TheLoop->getHeader()->getName() << '\n');
3375 // Check if we can if-convert non-single-bb loops.
3376 unsigned NumBlocks = TheLoop->getNumBlocks();
3377 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3378 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3382 // ScalarEvolution needs to be able to find the exit count.
3383 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3384 if (ExitCount == SE->getCouldNotCompute()) {
3385 emitAnalysis(VectorizationReport() <<
3386 "could not determine number of loop iterations");
3387 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3391 // Check if we can vectorize the instructions and CFG in this loop.
3392 if (!canVectorizeInstrs()) {
3393 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3397 // Go over each instruction and look at memory deps.
3398 if (!canVectorizeMemory()) {
3399 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3403 // Collect all of the variables that remain uniform after vectorization.
3404 collectLoopUniforms();
3406 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3407 (LAI->getRuntimePointerCheck()->Need ? " (with a runtime bound check)" :
3411 // Okay! We can vectorize. At this point we don't have any other mem analysis
3412 // which may limit our maximum vectorization factor, so just return true with
3417 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3418 if (Ty->isPointerTy())
3419 return DL.getIntPtrType(Ty);
3421 // It is possible that char's or short's overflow when we ask for the loop's
3422 // trip count, work around this by changing the type size.
3423 if (Ty->getScalarSizeInBits() < 32)
3424 return Type::getInt32Ty(Ty->getContext());
3429 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3430 Ty0 = convertPointerToIntegerType(DL, Ty0);
3431 Ty1 = convertPointerToIntegerType(DL, Ty1);
3432 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3437 /// \brief Check that the instruction has outside loop users and is not an
3438 /// identified reduction variable.
3439 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3440 SmallPtrSetImpl<Value *> &Reductions) {
3441 // Reduction instructions are allowed to have exit users. All other
3442 // instructions must not have external users.
3443 if (!Reductions.count(Inst))
3444 //Check that all of the users of the loop are inside the BB.
3445 for (User *U : Inst->users()) {
3446 Instruction *UI = cast<Instruction>(U);
3447 // This user may be a reduction exit value.
3448 if (!TheLoop->contains(UI)) {
3449 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3456 bool LoopVectorizationLegality::canVectorizeInstrs() {
3457 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3458 BasicBlock *Header = TheLoop->getHeader();
3460 // Look for the attribute signaling the absence of NaNs.
3461 Function &F = *Header->getParent();
3462 const DataLayout &DL = F.getParent()->getDataLayout();
3463 if (F.hasFnAttribute("no-nans-fp-math"))
3465 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
3467 // For each block in the loop.
3468 for (Loop::block_iterator bb = TheLoop->block_begin(),
3469 be = TheLoop->block_end(); bb != be; ++bb) {
3471 // Scan the instructions in the block and look for hazards.
3472 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3475 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3476 Type *PhiTy = Phi->getType();
3477 // Check that this PHI type is allowed.
3478 if (!PhiTy->isIntegerTy() &&
3479 !PhiTy->isFloatingPointTy() &&
3480 !PhiTy->isPointerTy()) {
3481 emitAnalysis(VectorizationReport(it)
3482 << "loop control flow is not understood by vectorizer");
3483 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3487 // If this PHINode is not in the header block, then we know that we
3488 // can convert it to select during if-conversion. No need to check if
3489 // the PHIs in this block are induction or reduction variables.
3490 if (*bb != Header) {
3491 // Check that this instruction has no outside users or is an
3492 // identified reduction value with an outside user.
3493 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3495 emitAnalysis(VectorizationReport(it) <<
3496 "value could not be identified as "
3497 "an induction or reduction variable");
3501 // We only allow if-converted PHIs with exactly two incoming values.
3502 if (Phi->getNumIncomingValues() != 2) {
3503 emitAnalysis(VectorizationReport(it)
3504 << "control flow not understood by vectorizer");
3505 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3509 // This is the value coming from the preheader.
3510 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3511 ConstantInt *StepValue = nullptr;
3512 // Check if this is an induction variable.
3513 InductionKind IK = isInductionVariable(Phi, StepValue);
3515 if (IK_NoInduction != IK) {
3516 // Get the widest type.
3518 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
3520 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
3522 // Int inductions are special because we only allow one IV.
3523 if (IK == IK_IntInduction && StepValue->isOne()) {
3524 // Use the phi node with the widest type as induction. Use the last
3525 // one if there are multiple (no good reason for doing this other
3526 // than it is expedient).
3527 if (!Induction || PhiTy == WidestIndTy)
3531 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3532 Inductions[Phi] = InductionInfo(StartValue, IK, StepValue);
3534 // Until we explicitly handle the case of an induction variable with
3535 // an outside loop user we have to give up vectorizing this loop.
3536 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3537 emitAnalysis(VectorizationReport(it) <<
3538 "use of induction value outside of the "
3539 "loop is not handled by vectorizer");
3546 if (ReductionDescriptor::isReductionPHI(Phi, TheLoop,
3548 AllowedExit.insert(Reductions[Phi].getLoopExitInstr());
3552 emitAnalysis(VectorizationReport(it) <<
3553 "value that could not be identified as "
3554 "reduction is used outside the loop");
3555 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3557 }// end of PHI handling
3559 // We handle calls that:
3560 // * Are debug info intrinsics.
3561 // * Have a mapping to an IR intrinsic.
3562 // * Have a vector version available.
3563 CallInst *CI = dyn_cast<CallInst>(it);
3564 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI) &&
3565 !(CI->getCalledFunction() && TLI &&
3566 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
3567 emitAnalysis(VectorizationReport(it) <<
3568 "call instruction cannot be vectorized");
3569 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
3573 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
3574 // second argument is the same (i.e. loop invariant)
3576 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
3577 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
3578 emitAnalysis(VectorizationReport(it)
3579 << "intrinsic instruction cannot be vectorized");
3580 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
3585 // Check that the instruction return type is vectorizable.
3586 // Also, we can't vectorize extractelement instructions.
3587 if ((!VectorType::isValidElementType(it->getType()) &&
3588 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3589 emitAnalysis(VectorizationReport(it)
3590 << "instruction return type cannot be vectorized");
3591 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3595 // Check that the stored type is vectorizable.
3596 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3597 Type *T = ST->getValueOperand()->getType();
3598 if (!VectorType::isValidElementType(T)) {
3599 emitAnalysis(VectorizationReport(ST) <<
3600 "store instruction cannot be vectorized");
3603 if (EnableMemAccessVersioning)
3604 collectStridedAccess(ST);
3607 if (EnableMemAccessVersioning)
3608 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3609 collectStridedAccess(LI);
3611 // Reduction instructions are allowed to have exit users.
3612 // All other instructions must not have external users.
3613 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3614 emitAnalysis(VectorizationReport(it) <<
3615 "value cannot be used outside the loop");
3624 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3625 if (Inductions.empty()) {
3626 emitAnalysis(VectorizationReport()
3627 << "loop induction variable could not be identified");
3635 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3636 /// return the induction operand of the gep pointer.
3637 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
3638 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3642 unsigned InductionOperand = getGEPInductionOperand(GEP);
3644 // Check that all of the gep indices are uniform except for our induction
3646 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3647 if (i != InductionOperand &&
3648 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3650 return GEP->getOperand(InductionOperand);
3653 ///\brief Look for a cast use of the passed value.
3654 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3655 Value *UniqueCast = nullptr;
3656 for (User *U : Ptr->users()) {
3657 CastInst *CI = dyn_cast<CastInst>(U);
3658 if (CI && CI->getType() == Ty) {
3668 ///\brief Get the stride of a pointer access in a loop.
3669 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3670 /// pointer to the Value, or null otherwise.
3671 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
3672 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3673 if (!PtrTy || PtrTy->isAggregateType())
3676 // Try to remove a gep instruction to make the pointer (actually index at this
3677 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3678 // pointer, otherwise, we are analyzing the index.
3679 Value *OrigPtr = Ptr;
3681 // The size of the pointer access.
3682 int64_t PtrAccessSize = 1;
3684 Ptr = stripGetElementPtr(Ptr, SE, Lp);
3685 const SCEV *V = SE->getSCEV(Ptr);
3689 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3690 V = C->getOperand();
3692 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3696 V = S->getStepRecurrence(*SE);
3700 // Strip off the size of access multiplication if we are still analyzing the
3702 if (OrigPtr == Ptr) {
3703 const DataLayout &DL = Lp->getHeader()->getModule()->getDataLayout();
3704 DL.getTypeAllocSize(PtrTy->getElementType());
3705 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3706 if (M->getOperand(0)->getSCEVType() != scConstant)
3709 const APInt &APStepVal =
3710 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3712 // Huge step value - give up.
3713 if (APStepVal.getBitWidth() > 64)
3716 int64_t StepVal = APStepVal.getSExtValue();
3717 if (PtrAccessSize != StepVal)
3719 V = M->getOperand(1);
3724 Type *StripedOffRecurrenceCast = nullptr;
3725 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3726 StripedOffRecurrenceCast = C->getType();
3727 V = C->getOperand();
3730 // Look for the loop invariant symbolic value.
3731 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3735 Value *Stride = U->getValue();
3736 if (!Lp->isLoopInvariant(Stride))
3739 // If we have stripped off the recurrence cast we have to make sure that we
3740 // return the value that is used in this loop so that we can replace it later.
3741 if (StripedOffRecurrenceCast)
3742 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3747 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
3748 Value *Ptr = nullptr;
3749 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3750 Ptr = LI->getPointerOperand();
3751 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3752 Ptr = SI->getPointerOperand();
3756 Value *Stride = getStrideFromPointer(Ptr, SE, TheLoop);
3760 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3761 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3762 Strides[Ptr] = Stride;
3763 StrideSet.insert(Stride);
3766 void LoopVectorizationLegality::collectLoopUniforms() {
3767 // We now know that the loop is vectorizable!
3768 // Collect variables that will remain uniform after vectorization.
3769 std::vector<Value*> Worklist;
3770 BasicBlock *Latch = TheLoop->getLoopLatch();
3772 // Start with the conditional branch and walk up the block.
3773 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3775 // Also add all consecutive pointer values; these values will be uniform
3776 // after vectorization (and subsequent cleanup) and, until revectorization is
3777 // supported, all dependencies must also be uniform.
3778 for (Loop::block_iterator B = TheLoop->block_begin(),
3779 BE = TheLoop->block_end(); B != BE; ++B)
3780 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
3782 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
3783 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3785 while (!Worklist.empty()) {
3786 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3787 Worklist.pop_back();
3789 // Look at instructions inside this loop.
3790 // Stop when reaching PHI nodes.
3791 // TODO: we need to follow values all over the loop, not only in this block.
3792 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3795 // This is a known uniform.
3798 // Insert all operands.
3799 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3803 bool LoopVectorizationLegality::canVectorizeMemory() {
3804 LAI = &LAA->getInfo(TheLoop, Strides);
3805 auto &OptionalReport = LAI->getReport();
3807 emitAnalysis(VectorizationReport(*OptionalReport));
3808 if (!LAI->canVectorizeMemory())
3811 if (LAI->hasStoreToLoopInvariantAddress()) {
3813 VectorizationReport()
3814 << "write to a loop invariant address could not be vectorized");
3815 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
3819 if (LAI->getNumRuntimePointerChecks() >
3820 VectorizerParams::RuntimeMemoryCheckThreshold) {
3821 emitAnalysis(VectorizationReport()
3822 << LAI->getNumRuntimePointerChecks() << " exceeds limit of "
3823 << VectorizerParams::RuntimeMemoryCheckThreshold
3824 << " dependent memory operations checked at runtime");
3825 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
3831 bool llvm::isInductionPHI(PHINode *Phi, ScalarEvolution *SE,
3832 ConstantInt *&StepValue) {
3833 Type *PhiTy = Phi->getType();
3834 // We only handle integer and pointer inductions variables.
3835 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
3838 // Check that the PHI is consecutive.
3839 const SCEV *PhiScev = SE->getSCEV(Phi);
3840 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
3842 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
3846 const SCEV *Step = AR->getStepRecurrence(*SE);
3847 // Calculate the pointer stride and check if it is consecutive.
3848 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
3852 ConstantInt *CV = C->getValue();
3853 if (PhiTy->isIntegerTy()) {
3858 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
3859 Type *PointerElementType = PhiTy->getPointerElementType();
3860 // The pointer stride cannot be determined if the pointer element type is not
3862 if (!PointerElementType->isSized())
3865 const DataLayout &DL = Phi->getModule()->getDataLayout();
3866 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
3867 int64_t CVSize = CV->getSExtValue();
3870 StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
3874 LoopVectorizationLegality::InductionKind
3875 LoopVectorizationLegality::isInductionVariable(PHINode *Phi,
3876 ConstantInt *&StepValue) {
3877 if (!isInductionPHI(Phi, SE, StepValue))
3878 return IK_NoInduction;
3880 Type *PhiTy = Phi->getType();
3881 // Found an Integer induction variable.
3882 if (PhiTy->isIntegerTy())
3883 return IK_IntInduction;
3884 // Found an Pointer induction variable.
3885 return IK_PtrInduction;
3888 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
3889 Value *In0 = const_cast<Value*>(V);
3890 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
3894 return Inductions.count(PN);
3897 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
3898 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
3901 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
3902 SmallPtrSetImpl<Value *> &SafePtrs) {
3904 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3905 // Check that we don't have a constant expression that can trap as operand.
3906 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
3908 if (Constant *C = dyn_cast<Constant>(*OI))
3912 // We might be able to hoist the load.
3913 if (it->mayReadFromMemory()) {
3914 LoadInst *LI = dyn_cast<LoadInst>(it);
3917 if (!SafePtrs.count(LI->getPointerOperand())) {
3918 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
3919 MaskedOp.insert(LI);
3926 // We don't predicate stores at the moment.
3927 if (it->mayWriteToMemory()) {
3928 StoreInst *SI = dyn_cast<StoreInst>(it);
3929 // We only support predication of stores in basic blocks with one
3934 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
3935 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
3937 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
3938 !isSinglePredecessor) {
3939 // Build a masked store if it is legal for the target, otherwise scalarize
3941 bool isLegalMaskedOp =
3942 isLegalMaskedStore(SI->getValueOperand()->getType(),
3943 SI->getPointerOperand());
3944 if (isLegalMaskedOp) {
3946 MaskedOp.insert(SI);
3955 // The instructions below can trap.
3956 switch (it->getOpcode()) {
3958 case Instruction::UDiv:
3959 case Instruction::SDiv:
3960 case Instruction::URem:
3961 case Instruction::SRem:
3969 LoopVectorizationCostModel::VectorizationFactor
3970 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
3971 // Width 1 means no vectorize
3972 VectorizationFactor Factor = { 1U, 0U };
3973 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
3974 emitAnalysis(VectorizationReport() <<
3975 "runtime pointer checks needed. Enable vectorization of this "
3976 "loop with '#pragma clang loop vectorize(enable)' when "
3977 "compiling with -Os");
3978 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
3982 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
3983 emitAnalysis(VectorizationReport() <<
3984 "store that is conditionally executed prevents vectorization");
3985 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
3989 // Find the trip count.
3990 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
3991 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
3993 unsigned WidestType = getWidestType();
3994 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
3995 unsigned MaxSafeDepDist = -1U;
3996 if (Legal->getMaxSafeDepDistBytes() != -1U)
3997 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
3998 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
3999 WidestRegister : MaxSafeDepDist);
4000 unsigned MaxVectorSize = WidestRegister / WidestType;
4001 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4002 DEBUG(dbgs() << "LV: The Widest register is: "
4003 << WidestRegister << " bits.\n");
4005 if (MaxVectorSize == 0) {
4006 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4010 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4011 " into one vector!");
4013 unsigned VF = MaxVectorSize;
4015 // If we optimize the program for size, avoid creating the tail loop.
4017 // If we are unable to calculate the trip count then don't try to vectorize.
4020 (VectorizationReport() <<
4021 "unable to calculate the loop count due to complex control flow");
4022 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4026 // Find the maximum SIMD width that can fit within the trip count.
4027 VF = TC % MaxVectorSize;
4032 // If the trip count that we found modulo the vectorization factor is not
4033 // zero then we require a tail.
4035 emitAnalysis(VectorizationReport() <<
4036 "cannot optimize for size and vectorize at the "
4037 "same time. Enable vectorization of this loop "
4038 "with '#pragma clang loop vectorize(enable)' "
4039 "when compiling with -Os");
4040 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4045 int UserVF = Hints->getWidth();
4047 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4048 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4050 Factor.Width = UserVF;
4054 float Cost = expectedCost(1);
4056 const float ScalarCost = Cost;
4059 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4061 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4062 // Ignore scalar width, because the user explicitly wants vectorization.
4063 if (ForceVectorization && VF > 1) {
4065 Cost = expectedCost(Width) / (float)Width;
4068 for (unsigned i=2; i <= VF; i*=2) {
4069 // Notice that the vector loop needs to be executed less times, so
4070 // we need to divide the cost of the vector loops by the width of
4071 // the vector elements.
4072 float VectorCost = expectedCost(i) / (float)i;
4073 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4074 (int)VectorCost << ".\n");
4075 if (VectorCost < Cost) {
4081 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4082 << "LV: Vectorization seems to be not beneficial, "
4083 << "but was forced by a user.\n");
4084 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4085 Factor.Width = Width;
4086 Factor.Cost = Width * Cost;
4090 unsigned LoopVectorizationCostModel::getWidestType() {
4091 unsigned MaxWidth = 8;
4092 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4095 for (Loop::block_iterator bb = TheLoop->block_begin(),
4096 be = TheLoop->block_end(); bb != be; ++bb) {
4097 BasicBlock *BB = *bb;
4099 // For each instruction in the loop.
4100 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4101 Type *T = it->getType();
4103 // Ignore ephemeral values.
4104 if (EphValues.count(it))
4107 // Only examine Loads, Stores and PHINodes.
4108 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4111 // Examine PHI nodes that are reduction variables.
4112 if (PHINode *PN = dyn_cast<PHINode>(it))
4113 if (!Legal->getReductionVars()->count(PN))
4116 // Examine the stored values.
4117 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4118 T = ST->getValueOperand()->getType();
4120 // Ignore loaded pointer types and stored pointer types that are not
4121 // consecutive. However, we do want to take consecutive stores/loads of
4122 // pointer vectors into account.
4123 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4126 MaxWidth = std::max(MaxWidth,
4127 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4135 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
4137 unsigned LoopCost) {
4139 // -- The unroll heuristics --
4140 // We unroll the loop in order to expose ILP and reduce the loop overhead.
4141 // There are many micro-architectural considerations that we can't predict
4142 // at this level. For example, frontend pressure (on decode or fetch) due to
4143 // code size, or the number and capabilities of the execution ports.
4145 // We use the following heuristics to select the unroll factor:
4146 // 1. If the code has reductions, then we unroll in order to break the cross
4147 // iteration dependency.
4148 // 2. If the loop is really small, then we unroll in order to reduce the loop
4150 // 3. We don't unroll if we think that we will spill registers to memory due
4151 // to the increased register pressure.
4153 // Use the user preference, unless 'auto' is selected.
4154 int UserUF = Hints->getInterleave();
4158 // When we optimize for size, we don't unroll.
4162 // We used the distance for the unroll factor.
4163 if (Legal->getMaxSafeDepDistBytes() != -1U)
4166 // Do not unroll loops with a relatively small trip count.
4167 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4168 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
4171 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4172 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4176 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4177 TargetNumRegisters = ForceTargetNumScalarRegs;
4179 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4180 TargetNumRegisters = ForceTargetNumVectorRegs;
4183 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4184 // We divide by these constants so assume that we have at least one
4185 // instruction that uses at least one register.
4186 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4187 R.NumInstructions = std::max(R.NumInstructions, 1U);
4189 // We calculate the unroll factor using the following formula.
4190 // Subtract the number of loop invariants from the number of available
4191 // registers. These registers are used by all of the unrolled instances.
4192 // Next, divide the remaining registers by the number of registers that is
4193 // required by the loop, in order to estimate how many parallel instances
4194 // fit without causing spills. All of this is rounded down if necessary to be
4195 // a power of two. We want power of two unroll factors to simplify any
4196 // addressing operations or alignment considerations.
4197 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4200 // Don't count the induction variable as unrolled.
4201 if (EnableIndVarRegisterHeur)
4202 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4203 std::max(1U, (R.MaxLocalUsers - 1)));
4205 // Clamp the unroll factor ranges to reasonable factors.
4206 unsigned MaxInterleaveSize = TTI.getMaxInterleaveFactor();
4208 // Check if the user has overridden the unroll max.
4210 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4211 MaxInterleaveSize = ForceTargetMaxScalarInterleaveFactor;
4213 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4214 MaxInterleaveSize = ForceTargetMaxVectorInterleaveFactor;
4217 // If we did not calculate the cost for VF (because the user selected the VF)
4218 // then we calculate the cost of VF here.
4220 LoopCost = expectedCost(VF);
4222 // Clamp the calculated UF to be between the 1 and the max unroll factor
4223 // that the target allows.
4224 if (UF > MaxInterleaveSize)
4225 UF = MaxInterleaveSize;
4229 // Unroll if we vectorized this loop and there is a reduction that could
4230 // benefit from unrolling.
4231 if (VF > 1 && Legal->getReductionVars()->size()) {
4232 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
4236 // Note that if we've already vectorized the loop we will have done the
4237 // runtime check and so unrolling won't require further checks.
4238 bool UnrollingRequiresRuntimePointerCheck =
4239 (VF == 1 && Legal->getRuntimePointerCheck()->Need);
4241 // We want to unroll small loops in order to reduce the loop overhead and
4242 // potentially expose ILP opportunities.
4243 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4244 if (!UnrollingRequiresRuntimePointerCheck &&
4245 LoopCost < SmallLoopCost) {
4246 // We assume that the cost overhead is 1 and we use the cost model
4247 // to estimate the cost of the loop and unroll until the cost of the
4248 // loop overhead is about 5% of the cost of the loop.
4249 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4251 // Unroll until store/load ports (estimated by max unroll factor) are
4253 unsigned NumStores = Legal->getNumStores();
4254 unsigned NumLoads = Legal->getNumLoads();
4255 unsigned StoresUF = UF / (NumStores ? NumStores : 1);
4256 unsigned LoadsUF = UF / (NumLoads ? NumLoads : 1);
4258 // If we have a scalar reduction (vector reductions are already dealt with
4259 // by this point), we can increase the critical path length if the loop
4260 // we're unrolling is inside another loop. Limit, by default to 2, so the
4261 // critical path only gets increased by one reduction operation.
4262 if (Legal->getReductionVars()->size() &&
4263 TheLoop->getLoopDepth() > 1) {
4264 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionUF);
4265 SmallUF = std::min(SmallUF, F);
4266 StoresUF = std::min(StoresUF, F);
4267 LoadsUF = std::min(LoadsUF, F);
4270 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
4271 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
4272 return std::max(StoresUF, LoadsUF);
4275 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
4279 // Unroll if this is a large loop (small loops are already dealt with by this
4280 // point) that could benefit from interleaved unrolling.
4281 bool HasReductions = (Legal->getReductionVars()->size() > 0);
4282 if (TTI.enableAggressiveInterleaving(HasReductions)) {
4283 DEBUG(dbgs() << "LV: Unrolling to expose ILP.\n");
4287 DEBUG(dbgs() << "LV: Not Unrolling.\n");
4291 LoopVectorizationCostModel::RegisterUsage
4292 LoopVectorizationCostModel::calculateRegisterUsage() {
4293 // This function calculates the register usage by measuring the highest number
4294 // of values that are alive at a single location. Obviously, this is a very
4295 // rough estimation. We scan the loop in a topological order in order and
4296 // assign a number to each instruction. We use RPO to ensure that defs are
4297 // met before their users. We assume that each instruction that has in-loop
4298 // users starts an interval. We record every time that an in-loop value is
4299 // used, so we have a list of the first and last occurrences of each
4300 // instruction. Next, we transpose this data structure into a multi map that
4301 // holds the list of intervals that *end* at a specific location. This multi
4302 // map allows us to perform a linear search. We scan the instructions linearly
4303 // and record each time that a new interval starts, by placing it in a set.
4304 // If we find this value in the multi-map then we remove it from the set.
4305 // The max register usage is the maximum size of the set.
4306 // We also search for instructions that are defined outside the loop, but are
4307 // used inside the loop. We need this number separately from the max-interval
4308 // usage number because when we unroll, loop-invariant values do not take
4310 LoopBlocksDFS DFS(TheLoop);
4314 R.NumInstructions = 0;
4316 // Each 'key' in the map opens a new interval. The values
4317 // of the map are the index of the 'last seen' usage of the
4318 // instruction that is the key.
4319 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4320 // Maps instruction to its index.
4321 DenseMap<unsigned, Instruction*> IdxToInstr;
4322 // Marks the end of each interval.
4323 IntervalMap EndPoint;
4324 // Saves the list of instruction indices that are used in the loop.
4325 SmallSet<Instruction*, 8> Ends;
4326 // Saves the list of values that are used in the loop but are
4327 // defined outside the loop, such as arguments and constants.
4328 SmallPtrSet<Value*, 8> LoopInvariants;
4331 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4332 be = DFS.endRPO(); bb != be; ++bb) {
4333 R.NumInstructions += (*bb)->size();
4334 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4336 Instruction *I = it;
4337 IdxToInstr[Index++] = I;
4339 // Save the end location of each USE.
4340 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4341 Value *U = I->getOperand(i);
4342 Instruction *Instr = dyn_cast<Instruction>(U);
4344 // Ignore non-instruction values such as arguments, constants, etc.
4345 if (!Instr) continue;
4347 // If this instruction is outside the loop then record it and continue.
4348 if (!TheLoop->contains(Instr)) {
4349 LoopInvariants.insert(Instr);
4353 // Overwrite previous end points.
4354 EndPoint[Instr] = Index;
4360 // Saves the list of intervals that end with the index in 'key'.
4361 typedef SmallVector<Instruction*, 2> InstrList;
4362 DenseMap<unsigned, InstrList> TransposeEnds;
4364 // Transpose the EndPoints to a list of values that end at each index.
4365 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4367 TransposeEnds[it->second].push_back(it->first);
4369 SmallSet<Instruction*, 8> OpenIntervals;
4370 unsigned MaxUsage = 0;
4373 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4374 for (unsigned int i = 0; i < Index; ++i) {
4375 Instruction *I = IdxToInstr[i];
4376 // Ignore instructions that are never used within the loop.
4377 if (!Ends.count(I)) continue;
4379 // Ignore ephemeral values.
4380 if (EphValues.count(I))
4383 // Remove all of the instructions that end at this location.
4384 InstrList &List = TransposeEnds[i];
4385 for (unsigned int j=0, e = List.size(); j < e; ++j)
4386 OpenIntervals.erase(List[j]);
4388 // Count the number of live interals.
4389 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4391 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4392 OpenIntervals.size() << '\n');
4394 // Add the current instruction to the list of open intervals.
4395 OpenIntervals.insert(I);
4398 unsigned Invariant = LoopInvariants.size();
4399 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
4400 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
4401 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
4403 R.LoopInvariantRegs = Invariant;
4404 R.MaxLocalUsers = MaxUsage;
4408 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4412 for (Loop::block_iterator bb = TheLoop->block_begin(),
4413 be = TheLoop->block_end(); bb != be; ++bb) {
4414 unsigned BlockCost = 0;
4415 BasicBlock *BB = *bb;
4417 // For each instruction in the old loop.
4418 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4419 // Skip dbg intrinsics.
4420 if (isa<DbgInfoIntrinsic>(it))
4423 // Ignore ephemeral values.
4424 if (EphValues.count(it))
4427 unsigned C = getInstructionCost(it, VF);
4429 // Check if we should override the cost.
4430 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
4431 C = ForceTargetInstructionCost;
4434 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
4435 VF << " For instruction: " << *it << '\n');
4438 // We assume that if-converted blocks have a 50% chance of being executed.
4439 // When the code is scalar then some of the blocks are avoided due to CF.
4440 // When the code is vectorized we execute all code paths.
4441 if (VF == 1 && Legal->blockNeedsPredication(*bb))
4450 /// \brief Check whether the address computation for a non-consecutive memory
4451 /// access looks like an unlikely candidate for being merged into the indexing
4454 /// We look for a GEP which has one index that is an induction variable and all
4455 /// other indices are loop invariant. If the stride of this access is also
4456 /// within a small bound we decide that this address computation can likely be
4457 /// merged into the addressing mode.
4458 /// In all other cases, we identify the address computation as complex.
4459 static bool isLikelyComplexAddressComputation(Value *Ptr,
4460 LoopVectorizationLegality *Legal,
4461 ScalarEvolution *SE,
4462 const Loop *TheLoop) {
4463 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
4467 // We are looking for a gep with all loop invariant indices except for one
4468 // which should be an induction variable.
4469 unsigned NumOperands = Gep->getNumOperands();
4470 for (unsigned i = 1; i < NumOperands; ++i) {
4471 Value *Opd = Gep->getOperand(i);
4472 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
4473 !Legal->isInductionVariable(Opd))
4477 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
4478 // can likely be merged into the address computation.
4479 unsigned MaxMergeDistance = 64;
4481 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
4485 // Check the step is constant.
4486 const SCEV *Step = AddRec->getStepRecurrence(*SE);
4487 // Calculate the pointer stride and check if it is consecutive.
4488 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4492 const APInt &APStepVal = C->getValue()->getValue();
4494 // Huge step value - give up.
4495 if (APStepVal.getBitWidth() > 64)
4498 int64_t StepVal = APStepVal.getSExtValue();
4500 return StepVal > MaxMergeDistance;
4503 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
4504 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
4510 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
4511 // If we know that this instruction will remain uniform, check the cost of
4512 // the scalar version.
4513 if (Legal->isUniformAfterVectorization(I))
4516 Type *RetTy = I->getType();
4517 Type *VectorTy = ToVectorTy(RetTy, VF);
4519 // TODO: We need to estimate the cost of intrinsic calls.
4520 switch (I->getOpcode()) {
4521 case Instruction::GetElementPtr:
4522 // We mark this instruction as zero-cost because the cost of GEPs in
4523 // vectorized code depends on whether the corresponding memory instruction
4524 // is scalarized or not. Therefore, we handle GEPs with the memory
4525 // instruction cost.
4527 case Instruction::Br: {
4528 return TTI.getCFInstrCost(I->getOpcode());
4530 case Instruction::PHI:
4531 //TODO: IF-converted IFs become selects.
4533 case Instruction::Add:
4534 case Instruction::FAdd:
4535 case Instruction::Sub:
4536 case Instruction::FSub:
4537 case Instruction::Mul:
4538 case Instruction::FMul:
4539 case Instruction::UDiv:
4540 case Instruction::SDiv:
4541 case Instruction::FDiv:
4542 case Instruction::URem:
4543 case Instruction::SRem:
4544 case Instruction::FRem:
4545 case Instruction::Shl:
4546 case Instruction::LShr:
4547 case Instruction::AShr:
4548 case Instruction::And:
4549 case Instruction::Or:
4550 case Instruction::Xor: {
4551 // Since we will replace the stride by 1 the multiplication should go away.
4552 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
4554 // Certain instructions can be cheaper to vectorize if they have a constant
4555 // second vector operand. One example of this are shifts on x86.
4556 TargetTransformInfo::OperandValueKind Op1VK =
4557 TargetTransformInfo::OK_AnyValue;
4558 TargetTransformInfo::OperandValueKind Op2VK =
4559 TargetTransformInfo::OK_AnyValue;
4560 TargetTransformInfo::OperandValueProperties Op1VP =
4561 TargetTransformInfo::OP_None;
4562 TargetTransformInfo::OperandValueProperties Op2VP =
4563 TargetTransformInfo::OP_None;
4564 Value *Op2 = I->getOperand(1);
4566 // Check for a splat of a constant or for a non uniform vector of constants.
4567 if (isa<ConstantInt>(Op2)) {
4568 ConstantInt *CInt = cast<ConstantInt>(Op2);
4569 if (CInt && CInt->getValue().isPowerOf2())
4570 Op2VP = TargetTransformInfo::OP_PowerOf2;
4571 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4572 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
4573 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
4574 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
4576 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
4577 if (CInt && CInt->getValue().isPowerOf2())
4578 Op2VP = TargetTransformInfo::OP_PowerOf2;
4579 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4583 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
4586 case Instruction::Select: {
4587 SelectInst *SI = cast<SelectInst>(I);
4588 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
4589 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
4590 Type *CondTy = SI->getCondition()->getType();
4592 CondTy = VectorType::get(CondTy, VF);
4594 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
4596 case Instruction::ICmp:
4597 case Instruction::FCmp: {
4598 Type *ValTy = I->getOperand(0)->getType();
4599 VectorTy = ToVectorTy(ValTy, VF);
4600 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
4602 case Instruction::Store:
4603 case Instruction::Load: {
4604 StoreInst *SI = dyn_cast<StoreInst>(I);
4605 LoadInst *LI = dyn_cast<LoadInst>(I);
4606 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
4608 VectorTy = ToVectorTy(ValTy, VF);
4610 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
4611 unsigned AS = SI ? SI->getPointerAddressSpace() :
4612 LI->getPointerAddressSpace();
4613 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
4614 // We add the cost of address computation here instead of with the gep
4615 // instruction because only here we know whether the operation is
4618 return TTI.getAddressComputationCost(VectorTy) +
4619 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4621 // Scalarized loads/stores.
4622 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
4623 bool Reverse = ConsecutiveStride < 0;
4624 const DataLayout &DL = I->getModule()->getDataLayout();
4625 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
4626 unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
4627 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
4628 bool IsComplexComputation =
4629 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
4631 // The cost of extracting from the value vector and pointer vector.
4632 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
4633 for (unsigned i = 0; i < VF; ++i) {
4634 // The cost of extracting the pointer operand.
4635 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
4636 // In case of STORE, the cost of ExtractElement from the vector.
4637 // In case of LOAD, the cost of InsertElement into the returned
4639 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
4640 Instruction::InsertElement,
4644 // The cost of the scalar loads/stores.
4645 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
4646 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
4651 // Wide load/stores.
4652 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
4653 if (Legal->isMaskRequired(I))
4654 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
4657 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4660 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4664 case Instruction::ZExt:
4665 case Instruction::SExt:
4666 case Instruction::FPToUI:
4667 case Instruction::FPToSI:
4668 case Instruction::FPExt:
4669 case Instruction::PtrToInt:
4670 case Instruction::IntToPtr:
4671 case Instruction::SIToFP:
4672 case Instruction::UIToFP:
4673 case Instruction::Trunc:
4674 case Instruction::FPTrunc:
4675 case Instruction::BitCast: {
4676 // We optimize the truncation of induction variable.
4677 // The cost of these is the same as the scalar operation.
4678 if (I->getOpcode() == Instruction::Trunc &&
4679 Legal->isInductionVariable(I->getOperand(0)))
4680 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
4681 I->getOperand(0)->getType());
4683 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
4684 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
4686 case Instruction::Call: {
4687 bool NeedToScalarize;
4688 CallInst *CI = cast<CallInst>(I);
4689 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
4690 if (getIntrinsicIDForCall(CI, TLI))
4691 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
4695 // We are scalarizing the instruction. Return the cost of the scalar
4696 // instruction, plus the cost of insert and extract into vector
4697 // elements, times the vector width.
4700 if (!RetTy->isVoidTy() && VF != 1) {
4701 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
4703 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
4706 // The cost of inserting the results plus extracting each one of the
4708 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
4711 // The cost of executing VF copies of the scalar instruction. This opcode
4712 // is unknown. Assume that it is the same as 'mul'.
4713 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
4719 char LoopVectorize::ID = 0;
4720 static const char lv_name[] = "Loop Vectorization";
4721 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
4722 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
4723 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4724 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4725 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
4726 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4727 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
4728 INITIALIZE_PASS_DEPENDENCY(LCSSA)
4729 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
4730 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
4731 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
4732 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
4735 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
4736 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
4740 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
4741 // Check for a store.
4742 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
4743 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
4745 // Check for a load.
4746 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
4747 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
4753 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
4754 bool IfPredicateStore) {
4755 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
4756 // Holds vector parameters or scalars, in case of uniform vals.
4757 SmallVector<VectorParts, 4> Params;
4759 setDebugLocFromInst(Builder, Instr);
4761 // Find all of the vectorized parameters.
4762 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
4763 Value *SrcOp = Instr->getOperand(op);
4765 // If we are accessing the old induction variable, use the new one.
4766 if (SrcOp == OldInduction) {
4767 Params.push_back(getVectorValue(SrcOp));
4771 // Try using previously calculated values.
4772 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
4774 // If the src is an instruction that appeared earlier in the basic block
4775 // then it should already be vectorized.
4776 if (SrcInst && OrigLoop->contains(SrcInst)) {
4777 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
4778 // The parameter is a vector value from earlier.
4779 Params.push_back(WidenMap.get(SrcInst));
4781 // The parameter is a scalar from outside the loop. Maybe even a constant.
4782 VectorParts Scalars;
4783 Scalars.append(UF, SrcOp);
4784 Params.push_back(Scalars);
4788 assert(Params.size() == Instr->getNumOperands() &&
4789 "Invalid number of operands");
4791 // Does this instruction return a value ?
4792 bool IsVoidRetTy = Instr->getType()->isVoidTy();
4794 Value *UndefVec = IsVoidRetTy ? nullptr :
4795 UndefValue::get(Instr->getType());
4796 // Create a new entry in the WidenMap and initialize it to Undef or Null.
4797 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
4799 Instruction *InsertPt = Builder.GetInsertPoint();
4800 BasicBlock *IfBlock = Builder.GetInsertBlock();
4801 BasicBlock *CondBlock = nullptr;
4804 Loop *VectorLp = nullptr;
4805 if (IfPredicateStore) {
4806 assert(Instr->getParent()->getSinglePredecessor() &&
4807 "Only support single predecessor blocks");
4808 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
4809 Instr->getParent());
4810 VectorLp = LI->getLoopFor(IfBlock);
4811 assert(VectorLp && "Must have a loop for this block");
4814 // For each vector unroll 'part':
4815 for (unsigned Part = 0; Part < UF; ++Part) {
4816 // For each scalar that we create:
4818 // Start an "if (pred) a[i] = ..." block.
4819 Value *Cmp = nullptr;
4820 if (IfPredicateStore) {
4821 if (Cond[Part]->getType()->isVectorTy())
4823 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
4824 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
4825 ConstantInt::get(Cond[Part]->getType(), 1));
4826 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
4827 LoopVectorBody.push_back(CondBlock);
4828 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
4829 // Update Builder with newly created basic block.
4830 Builder.SetInsertPoint(InsertPt);
4833 Instruction *Cloned = Instr->clone();
4835 Cloned->setName(Instr->getName() + ".cloned");
4836 // Replace the operands of the cloned instructions with extracted scalars.
4837 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
4838 Value *Op = Params[op][Part];
4839 Cloned->setOperand(op, Op);
4842 // Place the cloned scalar in the new loop.
4843 Builder.Insert(Cloned);
4845 // If the original scalar returns a value we need to place it in a vector
4846 // so that future users will be able to use it.
4848 VecResults[Part] = Cloned;
4851 if (IfPredicateStore) {
4852 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
4853 LoopVectorBody.push_back(NewIfBlock);
4854 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
4855 Builder.SetInsertPoint(InsertPt);
4856 Instruction *OldBr = IfBlock->getTerminator();
4857 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
4858 OldBr->eraseFromParent();
4859 IfBlock = NewIfBlock;
4864 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
4865 StoreInst *SI = dyn_cast<StoreInst>(Instr);
4866 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
4868 return scalarizeInstruction(Instr, IfPredicateStore);
4871 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
4875 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
4879 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
4880 // When unrolling and the VF is 1, we only need to add a simple scalar.
4881 Type *ITy = Val->getType();
4882 assert(!ITy->isVectorTy() && "Val must be a scalar");
4883 Constant *C = ConstantInt::get(ITy, StartIdx);
4884 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");