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 // The interleaved access vectorization is based on the paper:
38 // Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
41 // Other ideas/concepts are from:
42 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
44 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
45 // Vectorizing Compilers.
47 //===----------------------------------------------------------------------===//
49 #include "llvm/Transforms/Vectorize.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/Hashing.h"
52 #include "llvm/ADT/MapVector.h"
53 #include "llvm/ADT/SetVector.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallSet.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/Statistic.h"
58 #include "llvm/ADT/StringExtras.h"
59 #include "llvm/Analysis/AliasAnalysis.h"
60 #include "llvm/Analysis/BasicAliasAnalysis.h"
61 #include "llvm/Analysis/AliasSetTracker.h"
62 #include "llvm/Analysis/AssumptionCache.h"
63 #include "llvm/Analysis/BlockFrequencyInfo.h"
64 #include "llvm/Analysis/CodeMetrics.h"
65 #include "llvm/Analysis/DemandedBits.h"
66 #include "llvm/Analysis/GlobalsModRef.h"
67 #include "llvm/Analysis/LoopAccessAnalysis.h"
68 #include "llvm/Analysis/LoopInfo.h"
69 #include "llvm/Analysis/LoopIterator.h"
70 #include "llvm/Analysis/LoopPass.h"
71 #include "llvm/Analysis/ScalarEvolution.h"
72 #include "llvm/Analysis/ScalarEvolutionExpander.h"
73 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
74 #include "llvm/Analysis/TargetTransformInfo.h"
75 #include "llvm/Analysis/ValueTracking.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DebugInfo.h"
79 #include "llvm/IR/DerivedTypes.h"
80 #include "llvm/IR/DiagnosticInfo.h"
81 #include "llvm/IR/Dominators.h"
82 #include "llvm/IR/Function.h"
83 #include "llvm/IR/IRBuilder.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/LLVMContext.h"
87 #include "llvm/IR/Module.h"
88 #include "llvm/IR/PatternMatch.h"
89 #include "llvm/IR/Type.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/IR/ValueHandle.h"
92 #include "llvm/IR/Verifier.h"
93 #include "llvm/Pass.h"
94 #include "llvm/Support/BranchProbability.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/raw_ostream.h"
98 #include "llvm/Transforms/Scalar.h"
99 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
100 #include "llvm/Transforms/Utils/Local.h"
101 #include "llvm/Analysis/VectorUtils.h"
102 #include "llvm/Transforms/Utils/LoopUtils.h"
104 #include <functional>
108 using namespace llvm;
109 using namespace llvm::PatternMatch;
111 #define LV_NAME "loop-vectorize"
112 #define DEBUG_TYPE LV_NAME
114 STATISTIC(LoopsVectorized, "Number of loops vectorized");
115 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
118 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
119 cl::desc("Enable if-conversion during vectorization."));
121 /// We don't vectorize loops with a known constant trip count below this number.
122 static cl::opt<unsigned>
123 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
125 cl::desc("Don't vectorize loops with a constant "
126 "trip count that is smaller than this "
129 static cl::opt<bool> MaximizeBandwidth(
130 "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
131 cl::desc("Maximize bandwidth when selecting vectorization factor which "
132 "will be determined by the smallest type in loop."));
134 /// This enables versioning on the strides of symbolically striding memory
135 /// accesses in code like the following.
136 /// for (i = 0; i < N; ++i)
137 /// A[i * Stride1] += B[i * Stride2] ...
139 /// Will be roughly translated to
140 /// if (Stride1 == 1 && Stride2 == 1) {
141 /// for (i = 0; i < N; i+=4)
145 static cl::opt<bool> EnableMemAccessVersioning(
146 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
147 cl::desc("Enable symblic stride memory access versioning"));
149 static cl::opt<bool> EnableInterleavedMemAccesses(
150 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
151 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
153 /// Maximum factor for an interleaved memory access.
154 static cl::opt<unsigned> MaxInterleaveGroupFactor(
155 "max-interleave-group-factor", cl::Hidden,
156 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
159 /// We don't interleave loops with a known constant trip count below this
161 static const unsigned TinyTripCountInterleaveThreshold = 128;
163 static cl::opt<unsigned> ForceTargetNumScalarRegs(
164 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
165 cl::desc("A flag that overrides the target's number of scalar registers."));
167 static cl::opt<unsigned> ForceTargetNumVectorRegs(
168 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
169 cl::desc("A flag that overrides the target's number of vector registers."));
171 /// Maximum vectorization interleave count.
172 static const unsigned MaxInterleaveFactor = 16;
174 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
175 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
176 cl::desc("A flag that overrides the target's max interleave factor for "
179 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
180 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
181 cl::desc("A flag that overrides the target's max interleave factor for "
182 "vectorized loops."));
184 static cl::opt<unsigned> ForceTargetInstructionCost(
185 "force-target-instruction-cost", cl::init(0), cl::Hidden,
186 cl::desc("A flag that overrides the target's expected cost for "
187 "an instruction to a single constant value. Mostly "
188 "useful for getting consistent testing."));
190 static cl::opt<unsigned> SmallLoopCost(
191 "small-loop-cost", cl::init(20), cl::Hidden,
193 "The cost of a loop that is considered 'small' by the interleaver."));
195 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
196 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
197 cl::desc("Enable the use of the block frequency analysis to access PGO "
198 "heuristics minimizing code growth in cold regions and being more "
199 "aggressive in hot regions."));
201 // Runtime interleave loops for load/store throughput.
202 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
203 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
205 "Enable runtime interleaving until load/store ports are saturated"));
207 /// The number of stores in a loop that are allowed to need predication.
208 static cl::opt<unsigned> NumberOfStoresToPredicate(
209 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
210 cl::desc("Max number of stores to be predicated behind an if."));
212 static cl::opt<bool> EnableIndVarRegisterHeur(
213 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
214 cl::desc("Count the induction variable only once when interleaving"));
216 static cl::opt<bool> EnableCondStoresVectorization(
217 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
218 cl::desc("Enable if predication of stores during vectorization."));
220 static cl::opt<unsigned> MaxNestedScalarReductionIC(
221 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
222 cl::desc("The maximum interleave count to use when interleaving a scalar "
223 "reduction in a nested loop."));
225 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
226 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
227 cl::desc("The maximum allowed number of runtime memory checks with a "
228 "vectorize(enable) pragma."));
230 static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
231 "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
232 cl::desc("The maximum number of SCEV checks allowed."));
234 static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
235 "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
236 cl::desc("The maximum number of SCEV checks allowed with a "
237 "vectorize(enable) pragma"));
241 // Forward declarations.
242 class LoopVectorizeHints;
243 class LoopVectorizationLegality;
244 class LoopVectorizationCostModel;
245 class LoopVectorizationRequirements;
247 /// \brief This modifies LoopAccessReport to initialize message with
248 /// loop-vectorizer-specific part.
249 class VectorizationReport : public LoopAccessReport {
251 VectorizationReport(Instruction *I = nullptr)
252 : LoopAccessReport("loop not vectorized: ", I) {}
254 /// \brief This allows promotion of the loop-access analysis report into the
255 /// loop-vectorizer report. It modifies the message to add the
256 /// loop-vectorizer-specific part of the message.
257 explicit VectorizationReport(const LoopAccessReport &R)
258 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
262 /// A helper function for converting Scalar types to vector types.
263 /// If the incoming type is void, we return void. If the VF is 1, we return
265 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
266 if (Scalar->isVoidTy() || VF == 1)
268 return VectorType::get(Scalar, VF);
271 /// A helper function that returns GEP instruction and knows to skip a
272 /// 'bitcast'. The 'bitcast' may be skipped if the source and the destination
273 /// pointee types of the 'bitcast' have the same size.
275 /// bitcast double** %var to i64* - can be skipped
276 /// bitcast double** %var to i8* - can not
277 static GetElementPtrInst *getGEPInstruction(Value *Ptr) {
279 if (isa<GetElementPtrInst>(Ptr))
280 return cast<GetElementPtrInst>(Ptr);
282 if (isa<BitCastInst>(Ptr) &&
283 isa<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0))) {
284 Type *BitcastTy = Ptr->getType();
285 Type *GEPTy = cast<BitCastInst>(Ptr)->getSrcTy();
286 if (!isa<PointerType>(BitcastTy) || !isa<PointerType>(GEPTy))
288 Type *Pointee1Ty = cast<PointerType>(BitcastTy)->getPointerElementType();
289 Type *Pointee2Ty = cast<PointerType>(GEPTy)->getPointerElementType();
290 const DataLayout &DL = cast<BitCastInst>(Ptr)->getModule()->getDataLayout();
291 if (DL.getTypeSizeInBits(Pointee1Ty) == DL.getTypeSizeInBits(Pointee2Ty))
292 return cast<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0));
297 /// InnerLoopVectorizer vectorizes loops which contain only one basic
298 /// block to a specified vectorization factor (VF).
299 /// This class performs the widening of scalars into vectors, or multiple
300 /// scalars. This class also implements the following features:
301 /// * It inserts an epilogue loop for handling loops that don't have iteration
302 /// counts that are known to be a multiple of the vectorization factor.
303 /// * It handles the code generation for reduction variables.
304 /// * Scalarization (implementation using scalars) of un-vectorizable
306 /// InnerLoopVectorizer does not perform any vectorization-legality
307 /// checks, and relies on the caller to check for the different legality
308 /// aspects. The InnerLoopVectorizer relies on the
309 /// LoopVectorizationLegality class to provide information about the induction
310 /// and reduction variables that were found to a given vectorization factor.
311 class InnerLoopVectorizer {
313 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
314 DominatorTree *DT, const TargetLibraryInfo *TLI,
315 const TargetTransformInfo *TTI, unsigned VecWidth,
316 unsigned UnrollFactor, SCEVUnionPredicate &Preds)
317 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
318 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
319 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
320 TripCount(nullptr), VectorTripCount(nullptr), Legal(nullptr),
321 AddedSafetyChecks(false), Preds(Preds) {}
323 // Perform the actual loop widening (vectorization).
324 // MinimumBitWidths maps scalar integer values to the smallest bitwidth they
325 // can be validly truncated to. The cost model has assumed this truncation
326 // will happen when vectorizing.
327 void vectorize(LoopVectorizationLegality *L,
328 DenseMap<Instruction*,uint64_t> MinimumBitWidths) {
329 MinBWs = MinimumBitWidths;
331 // Create a new empty loop. Unlink the old loop and connect the new one.
333 // Widen each instruction in the old loop to a new one in the new loop.
334 // Use the Legality module to find the induction and reduction variables.
338 // Return true if any runtime check is added.
339 bool IsSafetyChecksAdded() {
340 return AddedSafetyChecks;
343 virtual ~InnerLoopVectorizer() {}
346 /// A small list of PHINodes.
347 typedef SmallVector<PHINode*, 4> PhiVector;
348 /// When we unroll loops we have multiple vector values for each scalar.
349 /// This data structure holds the unrolled and vectorized values that
350 /// originated from one scalar instruction.
351 typedef SmallVector<Value*, 2> VectorParts;
353 // When we if-convert we need to create edge masks. We have to cache values
354 // so that we don't end up with exponential recursion/IR.
355 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
356 VectorParts> EdgeMaskCache;
358 /// Create an empty loop, based on the loop ranges of the old loop.
359 void createEmptyLoop();
360 /// Create a new induction variable inside L.
361 PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
362 Value *Step, Instruction *DL);
363 /// Copy and widen the instructions from the old loop.
364 virtual void vectorizeLoop();
366 /// \brief The Loop exit block may have single value PHI nodes where the
367 /// incoming value is 'Undef'. While vectorizing we only handled real values
368 /// that were defined inside the loop. Here we fix the 'undef case'.
372 /// Shrinks vector element sizes based on information in "MinBWs".
373 void truncateToMinimalBitwidths();
375 /// A helper function that computes the predicate of the block BB, assuming
376 /// that the header block of the loop is set to True. It returns the *entry*
377 /// mask for the block BB.
378 VectorParts createBlockInMask(BasicBlock *BB);
379 /// A helper function that computes the predicate of the edge between SRC
381 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
383 /// A helper function to vectorize a single BB within the innermost loop.
384 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
386 /// Vectorize a single PHINode in a block. This method handles the induction
387 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
388 /// arbitrary length vectors.
389 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
390 unsigned UF, unsigned VF, PhiVector *PV);
392 /// Insert the new loop to the loop hierarchy and pass manager
393 /// and update the analysis passes.
394 void updateAnalysis();
396 /// This instruction is un-vectorizable. Implement it as a sequence
397 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
398 /// scalarized instruction behind an if block predicated on the control
399 /// dependence of the instruction.
400 virtual void scalarizeInstruction(Instruction *Instr,
401 bool IfPredicateStore=false);
403 /// Vectorize Load and Store instructions,
404 virtual void vectorizeMemoryInstruction(Instruction *Instr);
406 /// Create a broadcast instruction. This method generates a broadcast
407 /// instruction (shuffle) for loop invariant values and for the induction
408 /// value. If this is the induction variable then we extend it to N, N+1, ...
409 /// this is needed because each iteration in the loop corresponds to a SIMD
411 virtual Value *getBroadcastInstrs(Value *V);
413 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
414 /// to each vector element of Val. The sequence starts at StartIndex.
415 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
417 /// When we go over instructions in the basic block we rely on previous
418 /// values within the current basic block or on loop invariant values.
419 /// When we widen (vectorize) values we place them in the map. If the values
420 /// are not within the map, they have to be loop invariant, so we simply
421 /// broadcast them into a vector.
422 VectorParts &getVectorValue(Value *V);
424 /// Try to vectorize the interleaved access group that \p Instr belongs to.
425 void vectorizeInterleaveGroup(Instruction *Instr);
427 /// Generate a shuffle sequence that will reverse the vector Vec.
428 virtual Value *reverseVector(Value *Vec);
430 /// Returns (and creates if needed) the original loop trip count.
431 Value *getOrCreateTripCount(Loop *NewLoop);
433 /// Returns (and creates if needed) the trip count of the widened loop.
434 Value *getOrCreateVectorTripCount(Loop *NewLoop);
436 /// Emit a bypass check to see if the trip count would overflow, or we
437 /// wouldn't have enough iterations to execute one vector loop.
438 void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
439 /// Emit a bypass check to see if the vector trip count is nonzero.
440 void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass);
441 /// Emit a bypass check to see if all of the SCEV assumptions we've
442 /// had to make are correct.
443 void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
444 /// Emit bypass checks to check any memory assumptions we may have made.
445 void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
447 /// This is a helper class that holds the vectorizer state. It maps scalar
448 /// instructions to vector instructions. When the code is 'unrolled' then
449 /// then a single scalar value is mapped to multiple vector parts. The parts
450 /// are stored in the VectorPart type.
452 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
454 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
456 /// \return True if 'Key' is saved in the Value Map.
457 bool has(Value *Key) const { return MapStorage.count(Key); }
459 /// Initializes a new entry in the map. Sets all of the vector parts to the
460 /// save value in 'Val'.
461 /// \return A reference to a vector with splat values.
462 VectorParts &splat(Value *Key, Value *Val) {
463 VectorParts &Entry = MapStorage[Key];
464 Entry.assign(UF, Val);
468 ///\return A reference to the value that is stored at 'Key'.
469 VectorParts &get(Value *Key) {
470 VectorParts &Entry = MapStorage[Key];
473 assert(Entry.size() == UF);
478 /// The unroll factor. Each entry in the map stores this number of vector
482 /// Map storage. We use std::map and not DenseMap because insertions to a
483 /// dense map invalidates its iterators.
484 std::map<Value *, VectorParts> MapStorage;
487 /// The original loop.
489 /// Scev analysis to use.
497 /// Target Library Info.
498 const TargetLibraryInfo *TLI;
499 /// Target Transform Info.
500 const TargetTransformInfo *TTI;
502 /// The vectorization SIMD factor to use. Each vector will have this many
507 /// The vectorization unroll factor to use. Each scalar is vectorized to this
508 /// many different vector instructions.
511 /// The builder that we use
514 // --- Vectorization state ---
516 /// The vector-loop preheader.
517 BasicBlock *LoopVectorPreHeader;
518 /// The scalar-loop preheader.
519 BasicBlock *LoopScalarPreHeader;
520 /// Middle Block between the vector and the scalar.
521 BasicBlock *LoopMiddleBlock;
522 ///The ExitBlock of the scalar loop.
523 BasicBlock *LoopExitBlock;
524 ///The vector loop body.
525 SmallVector<BasicBlock *, 4> LoopVectorBody;
526 ///The scalar loop body.
527 BasicBlock *LoopScalarBody;
528 /// A list of all bypass blocks. The first block is the entry of the loop.
529 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
531 /// The new Induction variable which was added to the new block.
533 /// The induction variable of the old basic block.
534 PHINode *OldInduction;
535 /// Maps scalars to widened vectors.
537 /// Store instructions that should be predicated, as a pair
538 /// <StoreInst, Predicate>
539 SmallVector<std::pair<StoreInst*,Value*>, 4> PredicatedStores;
540 EdgeMaskCache MaskCache;
541 /// Trip count of the original loop.
543 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
544 Value *VectorTripCount;
546 /// Map of scalar integer values to the smallest bitwidth they can be legally
547 /// represented as. The vector equivalents of these values should be truncated
549 DenseMap<Instruction*,uint64_t> MinBWs;
550 LoopVectorizationLegality *Legal;
552 // Record whether runtime check is added.
553 bool AddedSafetyChecks;
555 /// The SCEV predicate containing all the SCEV-related assumptions.
556 /// The predicate is used to simplify existing expressions in the
557 /// context of existing SCEV assumptions. Since legality checking is
558 /// not done here, we don't need to use this predicate to record
559 /// further assumptions.
560 SCEVUnionPredicate &Preds;
563 class InnerLoopUnroller : public InnerLoopVectorizer {
565 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
566 DominatorTree *DT, const TargetLibraryInfo *TLI,
567 const TargetTransformInfo *TTI, unsigned UnrollFactor,
568 SCEVUnionPredicate &Preds)
569 : InnerLoopVectorizer(OrigLoop, SE, LI, DT, TLI, TTI, 1, UnrollFactor,
573 void scalarizeInstruction(Instruction *Instr,
574 bool IfPredicateStore = false) override;
575 void vectorizeMemoryInstruction(Instruction *Instr) override;
576 Value *getBroadcastInstrs(Value *V) override;
577 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
578 Value *reverseVector(Value *Vec) override;
581 /// \brief Look for a meaningful debug location on the instruction or it's
583 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
588 if (I->getDebugLoc() != Empty)
591 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
592 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
593 if (OpInst->getDebugLoc() != Empty)
600 /// \brief Set the debug location in the builder using the debug location in the
602 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
603 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
604 B.SetCurrentDebugLocation(Inst->getDebugLoc());
606 B.SetCurrentDebugLocation(DebugLoc());
610 /// \return string containing a file name and a line # for the given loop.
611 static std::string getDebugLocString(const Loop *L) {
614 raw_string_ostream OS(Result);
615 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
616 LoopDbgLoc.print(OS);
618 // Just print the module name.
619 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
626 /// \brief Propagate known metadata from one instruction to another.
627 static void propagateMetadata(Instruction *To, const Instruction *From) {
628 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
629 From->getAllMetadataOtherThanDebugLoc(Metadata);
631 for (auto M : Metadata) {
632 unsigned Kind = M.first;
634 // These are safe to transfer (this is safe for TBAA, even when we
635 // if-convert, because should that metadata have had a control dependency
636 // on the condition, and thus actually aliased with some other
637 // non-speculated memory access when the condition was false, this would be
638 // caught by the runtime overlap checks).
639 if (Kind != LLVMContext::MD_tbaa &&
640 Kind != LLVMContext::MD_alias_scope &&
641 Kind != LLVMContext::MD_noalias &&
642 Kind != LLVMContext::MD_fpmath &&
643 Kind != LLVMContext::MD_nontemporal)
646 To->setMetadata(Kind, M.second);
650 /// \brief Propagate known metadata from one instruction to a vector of others.
651 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
653 if (Instruction *I = dyn_cast<Instruction>(V))
654 propagateMetadata(I, From);
657 /// \brief The group of interleaved loads/stores sharing the same stride and
658 /// close to each other.
660 /// Each member in this group has an index starting from 0, and the largest
661 /// index should be less than interleaved factor, which is equal to the absolute
662 /// value of the access's stride.
664 /// E.g. An interleaved load group of factor 4:
665 /// for (unsigned i = 0; i < 1024; i+=4) {
666 /// a = A[i]; // Member of index 0
667 /// b = A[i+1]; // Member of index 1
668 /// d = A[i+3]; // Member of index 3
672 /// An interleaved store group of factor 4:
673 /// for (unsigned i = 0; i < 1024; i+=4) {
675 /// A[i] = a; // Member of index 0
676 /// A[i+1] = b; // Member of index 1
677 /// A[i+2] = c; // Member of index 2
678 /// A[i+3] = d; // Member of index 3
681 /// Note: the interleaved load group could have gaps (missing members), but
682 /// the interleaved store group doesn't allow gaps.
683 class InterleaveGroup {
685 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
686 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
687 assert(Align && "The alignment should be non-zero");
689 Factor = std::abs(Stride);
690 assert(Factor > 1 && "Invalid interleave factor");
692 Reverse = Stride < 0;
696 bool isReverse() const { return Reverse; }
697 unsigned getFactor() const { return Factor; }
698 unsigned getAlignment() const { return Align; }
699 unsigned getNumMembers() const { return Members.size(); }
701 /// \brief Try to insert a new member \p Instr with index \p Index and
702 /// alignment \p NewAlign. The index is related to the leader and it could be
703 /// negative if it is the new leader.
705 /// \returns false if the instruction doesn't belong to the group.
706 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
707 assert(NewAlign && "The new member's alignment should be non-zero");
709 int Key = Index + SmallestKey;
711 // Skip if there is already a member with the same index.
712 if (Members.count(Key))
715 if (Key > LargestKey) {
716 // The largest index is always less than the interleave factor.
717 if (Index >= static_cast<int>(Factor))
721 } else if (Key < SmallestKey) {
722 // The largest index is always less than the interleave factor.
723 if (LargestKey - Key >= static_cast<int>(Factor))
729 // It's always safe to select the minimum alignment.
730 Align = std::min(Align, NewAlign);
731 Members[Key] = Instr;
735 /// \brief Get the member with the given index \p Index
737 /// \returns nullptr if contains no such member.
738 Instruction *getMember(unsigned Index) const {
739 int Key = SmallestKey + Index;
740 if (!Members.count(Key))
743 return Members.find(Key)->second;
746 /// \brief Get the index for the given member. Unlike the key in the member
747 /// map, the index starts from 0.
748 unsigned getIndex(Instruction *Instr) const {
749 for (auto I : Members)
750 if (I.second == Instr)
751 return I.first - SmallestKey;
753 llvm_unreachable("InterleaveGroup contains no such member");
756 Instruction *getInsertPos() const { return InsertPos; }
757 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
760 unsigned Factor; // Interleave Factor.
763 DenseMap<int, Instruction *> Members;
767 // To avoid breaking dependences, vectorized instructions of an interleave
768 // group should be inserted at either the first load or the last store in
771 // E.g. %even = load i32 // Insert Position
772 // %add = add i32 %even // Use of %even
776 // %odd = add i32 // Def of %odd
777 // store i32 %odd // Insert Position
778 Instruction *InsertPos;
781 /// \brief Drive the analysis of interleaved memory accesses in the loop.
783 /// Use this class to analyze interleaved accesses only when we can vectorize
784 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
785 /// on interleaved accesses is unsafe.
787 /// The analysis collects interleave groups and records the relationships
788 /// between the member and the group in a map.
789 class InterleavedAccessInfo {
791 InterleavedAccessInfo(ScalarEvolution *SE, Loop *L, DominatorTree *DT,
792 SCEVUnionPredicate &Preds)
793 : SE(SE), TheLoop(L), DT(DT), Preds(Preds) {}
795 ~InterleavedAccessInfo() {
796 SmallSet<InterleaveGroup *, 4> DelSet;
797 // Avoid releasing a pointer twice.
798 for (auto &I : InterleaveGroupMap)
799 DelSet.insert(I.second);
800 for (auto *Ptr : DelSet)
804 /// \brief Analyze the interleaved accesses and collect them in interleave
805 /// groups. Substitute symbolic strides using \p Strides.
806 void analyzeInterleaving(const ValueToValueMap &Strides);
808 /// \brief Check if \p Instr belongs to any interleave group.
809 bool isInterleaved(Instruction *Instr) const {
810 return InterleaveGroupMap.count(Instr);
813 /// \brief Get the interleave group that \p Instr belongs to.
815 /// \returns nullptr if doesn't have such group.
816 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
817 if (InterleaveGroupMap.count(Instr))
818 return InterleaveGroupMap.find(Instr)->second;
827 /// The SCEV predicate containing all the SCEV-related assumptions.
828 /// The predicate is used to simplify SCEV expressions in the
829 /// context of existing SCEV assumptions. The interleaved access
830 /// analysis can also add new predicates (for example by versioning
831 /// strides of pointers).
832 SCEVUnionPredicate &Preds;
834 /// Holds the relationships between the members and the interleave group.
835 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
837 /// \brief The descriptor for a strided memory access.
838 struct StrideDescriptor {
839 StrideDescriptor(int Stride, const SCEV *Scev, unsigned Size,
841 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
843 StrideDescriptor() : Stride(0), Scev(nullptr), Size(0), Align(0) {}
845 int Stride; // The access's stride. It is negative for a reverse access.
846 const SCEV *Scev; // The scalar expression of this access
847 unsigned Size; // The size of the memory object.
848 unsigned Align; // The alignment of this access.
851 /// \brief Create a new interleave group with the given instruction \p Instr,
852 /// stride \p Stride and alignment \p Align.
854 /// \returns the newly created interleave group.
855 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
857 assert(!InterleaveGroupMap.count(Instr) &&
858 "Already in an interleaved access group");
859 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
860 return InterleaveGroupMap[Instr];
863 /// \brief Release the group and remove all the relationships.
864 void releaseGroup(InterleaveGroup *Group) {
865 for (unsigned i = 0; i < Group->getFactor(); i++)
866 if (Instruction *Member = Group->getMember(i))
867 InterleaveGroupMap.erase(Member);
872 /// \brief Collect all the accesses with a constant stride in program order.
873 void collectConstStridedAccesses(
874 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
875 const ValueToValueMap &Strides);
878 /// Utility class for getting and setting loop vectorizer hints in the form
879 /// of loop metadata.
880 /// This class keeps a number of loop annotations locally (as member variables)
881 /// and can, upon request, write them back as metadata on the loop. It will
882 /// initially scan the loop for existing metadata, and will update the local
883 /// values based on information in the loop.
884 /// We cannot write all values to metadata, as the mere presence of some info,
885 /// for example 'force', means a decision has been made. So, we need to be
886 /// careful NOT to add them if the user hasn't specifically asked so.
887 class LoopVectorizeHints {
894 /// Hint - associates name and validation with the hint value.
897 unsigned Value; // This may have to change for non-numeric values.
900 Hint(const char * Name, unsigned Value, HintKind Kind)
901 : Name(Name), Value(Value), Kind(Kind) { }
903 bool validate(unsigned Val) {
906 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
908 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
916 /// Vectorization width.
918 /// Vectorization interleave factor.
920 /// Vectorization forced
923 /// Return the loop metadata prefix.
924 static StringRef Prefix() { return "llvm.loop."; }
928 FK_Undefined = -1, ///< Not selected.
929 FK_Disabled = 0, ///< Forcing disabled.
930 FK_Enabled = 1, ///< Forcing enabled.
933 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
934 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
936 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
937 Force("vectorize.enable", FK_Undefined, HK_FORCE),
939 // Populate values with existing loop metadata.
940 getHintsFromMetadata();
942 // force-vector-interleave overrides DisableInterleaving.
943 if (VectorizerParams::isInterleaveForced())
944 Interleave.Value = VectorizerParams::VectorizationInterleave;
946 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
947 << "LV: Interleaving disabled by the pass manager\n");
950 /// Mark the loop L as already vectorized by setting the width to 1.
951 void setAlreadyVectorized() {
952 Width.Value = Interleave.Value = 1;
953 Hint Hints[] = {Width, Interleave};
954 writeHintsToMetadata(Hints);
957 bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
958 if (getForce() == LoopVectorizeHints::FK_Disabled) {
959 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
960 emitOptimizationRemarkAnalysis(F->getContext(),
961 vectorizeAnalysisPassName(), *F,
962 L->getStartLoc(), emitRemark());
966 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
967 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
968 emitOptimizationRemarkAnalysis(F->getContext(),
969 vectorizeAnalysisPassName(), *F,
970 L->getStartLoc(), emitRemark());
974 if (getWidth() == 1 && getInterleave() == 1) {
975 // FIXME: Add a separate metadata to indicate when the loop has already
976 // been vectorized instead of setting width and count to 1.
977 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
978 // FIXME: Add interleave.disable metadata. This will allow
979 // vectorize.disable to be used without disabling the pass and errors
980 // to differentiate between disabled vectorization and a width of 1.
981 emitOptimizationRemarkAnalysis(
982 F->getContext(), vectorizeAnalysisPassName(), *F, L->getStartLoc(),
983 "loop not vectorized: vectorization and interleaving are explicitly "
984 "disabled, or vectorize width and interleave count are both set to "
992 /// Dumps all the hint information.
993 std::string emitRemark() const {
994 VectorizationReport R;
995 if (Force.Value == LoopVectorizeHints::FK_Disabled)
996 R << "vectorization is explicitly disabled";
998 R << "use -Rpass-analysis=loop-vectorize for more info";
999 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1000 R << " (Force=true";
1001 if (Width.Value != 0)
1002 R << ", Vector Width=" << Width.Value;
1003 if (Interleave.Value != 0)
1004 R << ", Interleave Count=" << Interleave.Value;
1012 unsigned getWidth() const { return Width.Value; }
1013 unsigned getInterleave() const { return Interleave.Value; }
1014 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1015 const char *vectorizeAnalysisPassName() const {
1016 // If hints are provided that don't disable vectorization use the
1017 // AlwaysPrint pass name to force the frontend to print the diagnostic.
1018 if (getWidth() == 1)
1020 if (getForce() == LoopVectorizeHints::FK_Disabled)
1022 if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
1024 return DiagnosticInfo::AlwaysPrint;
1027 bool allowReordering() const {
1028 // When enabling loop hints are provided we allow the vectorizer to change
1029 // the order of operations that is given by the scalar loop. This is not
1030 // enabled by default because can be unsafe or inefficient. For example,
1031 // reordering floating-point operations will change the way round-off
1032 // error accumulates in the loop.
1033 return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
1037 /// Find hints specified in the loop metadata and update local values.
1038 void getHintsFromMetadata() {
1039 MDNode *LoopID = TheLoop->getLoopID();
1043 // First operand should refer to the loop id itself.
1044 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1045 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1047 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1048 const MDString *S = nullptr;
1049 SmallVector<Metadata *, 4> Args;
1051 // The expected hint is either a MDString or a MDNode with the first
1052 // operand a MDString.
1053 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1054 if (!MD || MD->getNumOperands() == 0)
1056 S = dyn_cast<MDString>(MD->getOperand(0));
1057 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1058 Args.push_back(MD->getOperand(i));
1060 S = dyn_cast<MDString>(LoopID->getOperand(i));
1061 assert(Args.size() == 0 && "too many arguments for MDString");
1067 // Check if the hint starts with the loop metadata prefix.
1068 StringRef Name = S->getString();
1069 if (Args.size() == 1)
1070 setHint(Name, Args[0]);
1074 /// Checks string hint with one operand and set value if valid.
1075 void setHint(StringRef Name, Metadata *Arg) {
1076 if (!Name.startswith(Prefix()))
1078 Name = Name.substr(Prefix().size(), StringRef::npos);
1080 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1082 unsigned Val = C->getZExtValue();
1084 Hint *Hints[] = {&Width, &Interleave, &Force};
1085 for (auto H : Hints) {
1086 if (Name == H->Name) {
1087 if (H->validate(Val))
1090 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1096 /// Create a new hint from name / value pair.
1097 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1098 LLVMContext &Context = TheLoop->getHeader()->getContext();
1099 Metadata *MDs[] = {MDString::get(Context, Name),
1100 ConstantAsMetadata::get(
1101 ConstantInt::get(Type::getInt32Ty(Context), V))};
1102 return MDNode::get(Context, MDs);
1105 /// Matches metadata with hint name.
1106 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1107 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1111 for (auto H : HintTypes)
1112 if (Name->getString().endswith(H.Name))
1117 /// Sets current hints into loop metadata, keeping other values intact.
1118 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1119 if (HintTypes.size() == 0)
1122 // Reserve the first element to LoopID (see below).
1123 SmallVector<Metadata *, 4> MDs(1);
1124 // If the loop already has metadata, then ignore the existing operands.
1125 MDNode *LoopID = TheLoop->getLoopID();
1127 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1128 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1129 // If node in update list, ignore old value.
1130 if (!matchesHintMetadataName(Node, HintTypes))
1131 MDs.push_back(Node);
1135 // Now, add the missing hints.
1136 for (auto H : HintTypes)
1137 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1139 // Replace current metadata node with new one.
1140 LLVMContext &Context = TheLoop->getHeader()->getContext();
1141 MDNode *NewLoopID = MDNode::get(Context, MDs);
1142 // Set operand 0 to refer to the loop id itself.
1143 NewLoopID->replaceOperandWith(0, NewLoopID);
1145 TheLoop->setLoopID(NewLoopID);
1148 /// The loop these hints belong to.
1149 const Loop *TheLoop;
1152 static void emitAnalysisDiag(const Function *TheFunction, const Loop *TheLoop,
1153 const LoopVectorizeHints &Hints,
1154 const LoopAccessReport &Message) {
1155 const char *Name = Hints.vectorizeAnalysisPassName();
1156 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, Name);
1159 static void emitMissedWarning(Function *F, Loop *L,
1160 const LoopVectorizeHints &LH) {
1161 emitOptimizationRemarkMissed(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1164 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1165 if (LH.getWidth() != 1)
1166 emitLoopVectorizeWarning(
1167 F->getContext(), *F, L->getStartLoc(),
1168 "failed explicitly specified loop vectorization");
1169 else if (LH.getInterleave() != 1)
1170 emitLoopInterleaveWarning(
1171 F->getContext(), *F, L->getStartLoc(),
1172 "failed explicitly specified loop interleaving");
1176 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1177 /// to what vectorization factor.
1178 /// This class does not look at the profitability of vectorization, only the
1179 /// legality. This class has two main kinds of checks:
1180 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
1181 /// will change the order of memory accesses in a way that will change the
1182 /// correctness of the program.
1183 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1184 /// checks for a number of different conditions, such as the availability of a
1185 /// single induction variable, that all types are supported and vectorize-able,
1186 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
1187 /// This class is also used by InnerLoopVectorizer for identifying
1188 /// induction variable and the different reduction variables.
1189 class LoopVectorizationLegality {
1191 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
1192 TargetLibraryInfo *TLI, AliasAnalysis *AA,
1193 Function *F, const TargetTransformInfo *TTI,
1194 LoopAccessAnalysis *LAA,
1195 LoopVectorizationRequirements *R,
1196 const LoopVectorizeHints *H,
1197 SCEVUnionPredicate &Preds)
1198 : NumPredStores(0), TheLoop(L), SE(SE), TLI(TLI), TheFunction(F),
1199 TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr),
1200 InterleaveInfo(SE, L, DT, Preds), Induction(nullptr),
1201 WidestIndTy(nullptr), HasFunNoNaNAttr(false), Requirements(R), Hints(H),
1204 /// ReductionList contains the reduction descriptors for all
1205 /// of the reductions that were found in the loop.
1206 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
1208 /// InductionList saves induction variables and maps them to the
1209 /// induction descriptor.
1210 typedef MapVector<PHINode*, InductionDescriptor> InductionList;
1212 /// Returns true if it is legal to vectorize this loop.
1213 /// This does not mean that it is profitable to vectorize this
1214 /// loop, only that it is legal to do so.
1215 bool canVectorize();
1217 /// Returns the Induction variable.
1218 PHINode *getInduction() { return Induction; }
1220 /// Returns the reduction variables found in the loop.
1221 ReductionList *getReductionVars() { return &Reductions; }
1223 /// Returns the induction variables found in the loop.
1224 InductionList *getInductionVars() { return &Inductions; }
1226 /// Returns the widest induction type.
1227 Type *getWidestInductionType() { return WidestIndTy; }
1229 /// Returns True if V is an induction variable in this loop.
1230 bool isInductionVariable(const Value *V);
1232 /// Return true if the block BB needs to be predicated in order for the loop
1233 /// to be vectorized.
1234 bool blockNeedsPredication(BasicBlock *BB);
1236 /// Check if this pointer is consecutive when vectorizing. This happens
1237 /// when the last index of the GEP is the induction variable, or that the
1238 /// pointer itself is an induction variable.
1239 /// This check allows us to vectorize A[idx] into a wide load/store.
1241 /// 0 - Stride is unknown or non-consecutive.
1242 /// 1 - Address is consecutive.
1243 /// -1 - Address is consecutive, and decreasing.
1244 int isConsecutivePtr(Value *Ptr);
1246 /// Returns true if the value V is uniform within the loop.
1247 bool isUniform(Value *V);
1249 /// Returns true if this instruction will remain scalar after vectorization.
1250 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
1252 /// Returns the information that we collected about runtime memory check.
1253 const RuntimePointerChecking *getRuntimePointerChecking() const {
1254 return LAI->getRuntimePointerChecking();
1257 const LoopAccessInfo *getLAI() const {
1261 /// \brief Check if \p Instr belongs to any interleaved access group.
1262 bool isAccessInterleaved(Instruction *Instr) {
1263 return InterleaveInfo.isInterleaved(Instr);
1266 /// \brief Get the interleaved access group that \p Instr belongs to.
1267 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1268 return InterleaveInfo.getInterleaveGroup(Instr);
1271 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1273 bool hasStride(Value *V) { return StrideSet.count(V); }
1274 bool mustCheckStrides() { return !StrideSet.empty(); }
1275 SmallPtrSet<Value *, 8>::iterator strides_begin() {
1276 return StrideSet.begin();
1278 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
1280 /// Returns true if the target machine supports masked store operation
1281 /// for the given \p DataType and kind of access to \p Ptr.
1282 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
1283 return isConsecutivePtr(Ptr) && TTI->isLegalMaskedStore(DataType);
1285 /// Returns true if the target machine supports masked load operation
1286 /// for the given \p DataType and kind of access to \p Ptr.
1287 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
1288 return isConsecutivePtr(Ptr) && TTI->isLegalMaskedLoad(DataType);
1290 /// Returns true if vector representation of the instruction \p I
1292 bool isMaskRequired(const Instruction* I) {
1293 return (MaskedOp.count(I) != 0);
1295 unsigned getNumStores() const {
1296 return LAI->getNumStores();
1298 unsigned getNumLoads() const {
1299 return LAI->getNumLoads();
1301 unsigned getNumPredStores() const {
1302 return NumPredStores;
1305 /// Check if a single basic block loop is vectorizable.
1306 /// At this point we know that this is a loop with a constant trip count
1307 /// and we only need to check individual instructions.
1308 bool canVectorizeInstrs();
1310 /// When we vectorize loops we may change the order in which
1311 /// we read and write from memory. This method checks if it is
1312 /// legal to vectorize the code, considering only memory constrains.
1313 /// Returns true if the loop is vectorizable
1314 bool canVectorizeMemory();
1316 /// Return true if we can vectorize this loop using the IF-conversion
1318 bool canVectorizeWithIfConvert();
1320 /// Collect the variables that need to stay uniform after vectorization.
1321 void collectLoopUniforms();
1323 /// Return true if all of the instructions in the block can be speculatively
1324 /// executed. \p SafePtrs is a list of addresses that are known to be legal
1325 /// and we know that we can read from them without segfault.
1326 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1328 /// \brief Collect memory access with loop invariant strides.
1330 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
1332 void collectStridedAccess(Value *LoadOrStoreInst);
1334 /// Report an analysis message to assist the user in diagnosing loops that are
1335 /// not vectorized. These are handled as LoopAccessReport rather than
1336 /// VectorizationReport because the << operator of VectorizationReport returns
1337 /// LoopAccessReport.
1338 void emitAnalysis(const LoopAccessReport &Message) const {
1339 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1342 unsigned NumPredStores;
1344 /// The loop that we evaluate.
1347 ScalarEvolution *SE;
1348 /// Target Library Info.
1349 TargetLibraryInfo *TLI;
1351 Function *TheFunction;
1352 /// Target Transform Info
1353 const TargetTransformInfo *TTI;
1356 // LoopAccess analysis.
1357 LoopAccessAnalysis *LAA;
1358 // And the loop-accesses info corresponding to this loop. This pointer is
1359 // null until canVectorizeMemory sets it up.
1360 const LoopAccessInfo *LAI;
1362 /// The interleave access information contains groups of interleaved accesses
1363 /// with the same stride and close to each other.
1364 InterleavedAccessInfo InterleaveInfo;
1366 // --- vectorization state --- //
1368 /// Holds the integer induction variable. This is the counter of the
1371 /// Holds the reduction variables.
1372 ReductionList Reductions;
1373 /// Holds all of the induction variables that we found in the loop.
1374 /// Notice that inductions don't need to start at zero and that induction
1375 /// variables can be pointers.
1376 InductionList Inductions;
1377 /// Holds the widest induction type encountered.
1380 /// Allowed outside users. This holds the reduction
1381 /// vars which can be accessed from outside the loop.
1382 SmallPtrSet<Value*, 4> AllowedExit;
1383 /// This set holds the variables which are known to be uniform after
1385 SmallPtrSet<Instruction*, 4> Uniforms;
1387 /// Can we assume the absence of NaNs.
1388 bool HasFunNoNaNAttr;
1390 /// Vectorization requirements that will go through late-evaluation.
1391 LoopVectorizationRequirements *Requirements;
1393 /// Used to emit an analysis of any legality issues.
1394 const LoopVectorizeHints *Hints;
1396 ValueToValueMap Strides;
1397 SmallPtrSet<Value *, 8> StrideSet;
1399 /// While vectorizing these instructions we have to generate a
1400 /// call to the appropriate masked intrinsic
1401 SmallPtrSet<const Instruction *, 8> MaskedOp;
1403 /// The SCEV predicate containing all the SCEV-related assumptions.
1404 /// The predicate is used to simplify SCEV expressions in the
1405 /// context of existing SCEV assumptions. The analysis will also
1406 /// add a minimal set of new predicates if this is required to
1407 /// enable vectorization/unrolling.
1408 SCEVUnionPredicate &Preds;
1411 /// LoopVectorizationCostModel - estimates the expected speedups due to
1413 /// In many cases vectorization is not profitable. This can happen because of
1414 /// a number of reasons. In this class we mainly attempt to predict the
1415 /// expected speedup/slowdowns due to the supported instruction set. We use the
1416 /// TargetTransformInfo to query the different backends for the cost of
1417 /// different operations.
1418 class LoopVectorizationCostModel {
1420 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
1421 LoopVectorizationLegality *Legal,
1422 const TargetTransformInfo &TTI,
1423 const TargetLibraryInfo *TLI, DemandedBits *DB,
1424 AssumptionCache *AC, const Function *F,
1425 const LoopVectorizeHints *Hints,
1426 SmallPtrSetImpl<const Value *> &ValuesToIgnore,
1427 SCEVUnionPredicate &Preds)
1428 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
1429 TheFunction(F), Hints(Hints), ValuesToIgnore(ValuesToIgnore) {}
1431 /// Information about vectorization costs
1432 struct VectorizationFactor {
1433 unsigned Width; // Vector width with best cost
1434 unsigned Cost; // Cost of the loop with that width
1436 /// \return The most profitable vectorization factor and the cost of that VF.
1437 /// This method checks every power of two up to VF. If UserVF is not ZERO
1438 /// then this vectorization factor will be selected if vectorization is
1440 VectorizationFactor selectVectorizationFactor(bool OptForSize);
1442 /// \return The size (in bits) of the smallest and widest types in the code
1443 /// that needs to be vectorized. We ignore values that remain scalar such as
1444 /// 64 bit loop indices.
1445 std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1447 /// \return The desired interleave count.
1448 /// If interleave count has been specified by metadata it will be returned.
1449 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1450 /// are the selected vectorization factor and the cost of the selected VF.
1451 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1454 /// \return The most profitable unroll factor.
1455 /// This method finds the best unroll-factor based on register pressure and
1456 /// other parameters. VF and LoopCost are the selected vectorization factor
1457 /// and the cost of the selected VF.
1458 unsigned computeInterleaveCount(bool OptForSize, unsigned VF,
1461 /// \brief A struct that represents some properties of the register usage
1463 struct RegisterUsage {
1464 /// Holds the number of loop invariant values that are used in the loop.
1465 unsigned LoopInvariantRegs;
1466 /// Holds the maximum number of concurrent live intervals in the loop.
1467 unsigned MaxLocalUsers;
1468 /// Holds the number of instructions in the loop.
1469 unsigned NumInstructions;
1472 /// \return Returns information about the register usages of the loop for the
1473 /// given vectorization factors.
1474 SmallVector<RegisterUsage, 8>
1475 calculateRegisterUsage(const SmallVector<unsigned, 8> &VFs);
1478 /// Returns the expected execution cost. The unit of the cost does
1479 /// not matter because we use the 'cost' units to compare different
1480 /// vector widths. The cost that is returned is *not* normalized by
1481 /// the factor width.
1482 unsigned expectedCost(unsigned VF);
1484 /// Returns the execution time cost of an instruction for a given vector
1485 /// width. Vector width of one means scalar.
1486 unsigned getInstructionCost(Instruction *I, unsigned VF);
1488 /// Returns whether the instruction is a load or store and will be a emitted
1489 /// as a vector operation.
1490 bool isConsecutiveLoadOrStore(Instruction *I);
1492 /// Report an analysis message to assist the user in diagnosing loops that are
1493 /// not vectorized. These are handled as LoopAccessReport rather than
1494 /// VectorizationReport because the << operator of VectorizationReport returns
1495 /// LoopAccessReport.
1496 void emitAnalysis(const LoopAccessReport &Message) const {
1497 emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
1501 /// Map of scalar integer values to the smallest bitwidth they can be legally
1502 /// represented as. The vector equivalents of these values should be truncated
1504 DenseMap<Instruction*,uint64_t> MinBWs;
1506 /// The loop that we evaluate.
1509 ScalarEvolution *SE;
1510 /// Loop Info analysis.
1512 /// Vectorization legality.
1513 LoopVectorizationLegality *Legal;
1514 /// Vector target information.
1515 const TargetTransformInfo &TTI;
1516 /// Target Library Info.
1517 const TargetLibraryInfo *TLI;
1518 /// Demanded bits analysis
1520 const Function *TheFunction;
1521 // Loop Vectorize Hint.
1522 const LoopVectorizeHints *Hints;
1523 // Values to ignore in the cost model.
1524 const SmallPtrSetImpl<const Value *> &ValuesToIgnore;
1527 /// \brief This holds vectorization requirements that must be verified late in
1528 /// the process. The requirements are set by legalize and costmodel. Once
1529 /// vectorization has been determined to be possible and profitable the
1530 /// requirements can be verified by looking for metadata or compiler options.
1531 /// For example, some loops require FP commutativity which is only allowed if
1532 /// vectorization is explicitly specified or if the fast-math compiler option
1533 /// has been provided.
1534 /// Late evaluation of these requirements allows helpful diagnostics to be
1535 /// composed that tells the user what need to be done to vectorize the loop. For
1536 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
1537 /// evaluation should be used only when diagnostics can generated that can be
1538 /// followed by a non-expert user.
1539 class LoopVectorizationRequirements {
1541 LoopVectorizationRequirements()
1542 : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr) {}
1544 void addUnsafeAlgebraInst(Instruction *I) {
1545 // First unsafe algebra instruction.
1546 if (!UnsafeAlgebraInst)
1547 UnsafeAlgebraInst = I;
1550 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
1552 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
1553 const char *Name = Hints.vectorizeAnalysisPassName();
1554 bool Failed = false;
1555 if (UnsafeAlgebraInst && !Hints.allowReordering()) {
1556 emitOptimizationRemarkAnalysisFPCommute(
1557 F->getContext(), Name, *F, UnsafeAlgebraInst->getDebugLoc(),
1558 VectorizationReport() << "cannot prove it is safe to reorder "
1559 "floating-point operations");
1563 // Test if runtime memcheck thresholds are exceeded.
1564 bool PragmaThresholdReached =
1565 NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
1566 bool ThresholdReached =
1567 NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
1568 if ((ThresholdReached && !Hints.allowReordering()) ||
1569 PragmaThresholdReached) {
1570 emitOptimizationRemarkAnalysisAliasing(
1571 F->getContext(), Name, *F, L->getStartLoc(),
1572 VectorizationReport()
1573 << "cannot prove it is safe to reorder memory operations");
1574 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1582 unsigned NumRuntimePointerChecks;
1583 Instruction *UnsafeAlgebraInst;
1586 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1588 return V.push_back(&L);
1590 for (Loop *InnerL : L)
1591 addInnerLoop(*InnerL, V);
1594 /// The LoopVectorize Pass.
1595 struct LoopVectorize : public FunctionPass {
1596 /// Pass identification, replacement for typeid
1599 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1601 DisableUnrolling(NoUnrolling),
1602 AlwaysVectorize(AlwaysVectorize) {
1603 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1606 ScalarEvolution *SE;
1608 TargetTransformInfo *TTI;
1610 BlockFrequencyInfo *BFI;
1611 TargetLibraryInfo *TLI;
1614 AssumptionCache *AC;
1615 LoopAccessAnalysis *LAA;
1616 bool DisableUnrolling;
1617 bool AlwaysVectorize;
1619 BlockFrequency ColdEntryFreq;
1621 bool runOnFunction(Function &F) override {
1622 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1623 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1624 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1625 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1626 BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1627 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1628 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1629 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1630 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1631 LAA = &getAnalysis<LoopAccessAnalysis>();
1632 DB = &getAnalysis<DemandedBits>();
1634 // Compute some weights outside of the loop over the loops. Compute this
1635 // using a BranchProbability to re-use its scaling math.
1636 const BranchProbability ColdProb(1, 5); // 20%
1637 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1640 // 1. the target claims to have no vector registers, and
1641 // 2. interleaving won't help ILP.
1643 // The second condition is necessary because, even if the target has no
1644 // vector registers, loop vectorization may still enable scalar
1646 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
1649 // Build up a worklist of inner-loops to vectorize. This is necessary as
1650 // the act of vectorizing or partially unrolling a loop creates new loops
1651 // and can invalidate iterators across the loops.
1652 SmallVector<Loop *, 8> Worklist;
1655 addInnerLoop(*L, Worklist);
1657 LoopsAnalyzed += Worklist.size();
1659 // Now walk the identified inner loops.
1660 bool Changed = false;
1661 while (!Worklist.empty())
1662 Changed |= processLoop(Worklist.pop_back_val());
1664 // Process each loop nest in the function.
1668 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
1669 SmallVector<Metadata *, 4> MDs;
1670 // Reserve first location for self reference to the LoopID metadata node.
1671 MDs.push_back(nullptr);
1672 bool IsUnrollMetadata = false;
1673 MDNode *LoopID = L->getLoopID();
1675 // First find existing loop unrolling disable metadata.
1676 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1677 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1679 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1681 S && S->getString().startswith("llvm.loop.unroll.disable");
1683 MDs.push_back(LoopID->getOperand(i));
1687 if (!IsUnrollMetadata) {
1688 // Add runtime unroll disable metadata.
1689 LLVMContext &Context = L->getHeader()->getContext();
1690 SmallVector<Metadata *, 1> DisableOperands;
1691 DisableOperands.push_back(
1692 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1693 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1694 MDs.push_back(DisableNode);
1695 MDNode *NewLoopID = MDNode::get(Context, MDs);
1696 // Set operand 0 to refer to the loop id itself.
1697 NewLoopID->replaceOperandWith(0, NewLoopID);
1698 L->setLoopID(NewLoopID);
1702 bool processLoop(Loop *L) {
1703 assert(L->empty() && "Only process inner loops.");
1706 const std::string DebugLocStr = getDebugLocString(L);
1709 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1710 << L->getHeader()->getParent()->getName() << "\" from "
1711 << DebugLocStr << "\n");
1713 LoopVectorizeHints Hints(L, DisableUnrolling);
1715 DEBUG(dbgs() << "LV: Loop hints:"
1717 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1719 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1721 : "?")) << " width=" << Hints.getWidth()
1722 << " unroll=" << Hints.getInterleave() << "\n");
1724 // Function containing loop
1725 Function *F = L->getHeader()->getParent();
1727 // Looking at the diagnostic output is the only way to determine if a loop
1728 // was vectorized (other than looking at the IR or machine code), so it
1729 // is important to generate an optimization remark for each loop. Most of
1730 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1731 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1732 // less verbose reporting vectorized loops and unvectorized loops that may
1733 // benefit from vectorization, respectively.
1735 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
1736 DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
1740 // Check the loop for a trip count threshold:
1741 // do not vectorize loops with a tiny trip count.
1742 const unsigned TC = SE->getSmallConstantTripCount(L);
1743 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1744 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1745 << "This loop is not worth vectorizing.");
1746 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1747 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1749 DEBUG(dbgs() << "\n");
1750 emitAnalysisDiag(F, L, Hints, VectorizationReport()
1751 << "vectorization is not beneficial "
1752 "and is not explicitly forced");
1757 SCEVUnionPredicate Preds;
1759 // Check if it is legal to vectorize the loop.
1760 LoopVectorizationRequirements Requirements;
1761 LoopVectorizationLegality LVL(L, SE, DT, TLI, AA, F, TTI, LAA,
1762 &Requirements, &Hints, Preds);
1763 if (!LVL.canVectorize()) {
1764 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1765 emitMissedWarning(F, L, Hints);
1769 // Collect values we want to ignore in the cost model. This includes
1770 // type-promoting instructions we identified during reduction detection.
1771 SmallPtrSet<const Value *, 32> ValuesToIgnore;
1772 CodeMetrics::collectEphemeralValues(L, AC, ValuesToIgnore);
1773 for (auto &Reduction : *LVL.getReductionVars()) {
1774 RecurrenceDescriptor &RedDes = Reduction.second;
1775 SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
1776 ValuesToIgnore.insert(Casts.begin(), Casts.end());
1779 // Use the cost model.
1780 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, TLI, DB, AC, F, &Hints,
1781 ValuesToIgnore, Preds);
1783 // Check the function attributes to find out if this function should be
1784 // optimized for size.
1785 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1788 // Compute the weighted frequency of this loop being executed and see if it
1789 // is less than 20% of the function entry baseline frequency. Note that we
1790 // always have a canonical loop here because we think we *can* vectorize.
1791 // FIXME: This is hidden behind a flag due to pervasive problems with
1792 // exactly what block frequency models.
1793 if (LoopVectorizeWithBlockFrequency) {
1794 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1795 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1796 LoopEntryFreq < ColdEntryFreq)
1800 // Check the function attributes to see if implicit floats are allowed.
1801 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1802 // an integer loop and the vector instructions selected are purely integer
1803 // vector instructions?
1804 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1805 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1806 "attribute is used.\n");
1809 VectorizationReport()
1810 << "loop not vectorized due to NoImplicitFloat attribute");
1811 emitMissedWarning(F, L, Hints);
1815 // Select the optimal vectorization factor.
1816 const LoopVectorizationCostModel::VectorizationFactor VF =
1817 CM.selectVectorizationFactor(OptForSize);
1819 // Select the interleave count.
1820 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
1822 // Get user interleave count.
1823 unsigned UserIC = Hints.getInterleave();
1825 // Identify the diagnostic messages that should be produced.
1826 std::string VecDiagMsg, IntDiagMsg;
1827 bool VectorizeLoop = true, InterleaveLoop = true;
1829 if (Requirements.doesNotMeet(F, L, Hints)) {
1830 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
1832 emitMissedWarning(F, L, Hints);
1836 if (VF.Width == 1) {
1837 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1839 "the cost-model indicates that vectorization is not beneficial";
1840 VectorizeLoop = false;
1843 if (IC == 1 && UserIC <= 1) {
1844 // Tell the user interleaving is not beneficial.
1845 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
1847 "the cost-model indicates that interleaving is not beneficial";
1848 InterleaveLoop = false;
1851 " and is explicitly disabled or interleave count is set to 1";
1852 } else if (IC > 1 && UserIC == 1) {
1853 // Tell the user interleaving is beneficial, but it explicitly disabled.
1855 << "LV: Interleaving is beneficial but is explicitly disabled.");
1856 IntDiagMsg = "the cost-model indicates that interleaving is beneficial "
1857 "but is explicitly disabled or interleave count is set to 1";
1858 InterleaveLoop = false;
1861 // Override IC if user provided an interleave count.
1862 IC = UserIC > 0 ? UserIC : IC;
1864 // Emit diagnostic messages, if any.
1865 const char *VAPassName = Hints.vectorizeAnalysisPassName();
1866 if (!VectorizeLoop && !InterleaveLoop) {
1867 // Do not vectorize or interleaving the loop.
1868 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1869 L->getStartLoc(), VecDiagMsg);
1870 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1871 L->getStartLoc(), IntDiagMsg);
1873 } else if (!VectorizeLoop && InterleaveLoop) {
1874 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1875 emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
1876 L->getStartLoc(), VecDiagMsg);
1877 } else if (VectorizeLoop && !InterleaveLoop) {
1878 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1879 << DebugLocStr << '\n');
1880 emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
1881 L->getStartLoc(), IntDiagMsg);
1882 } else if (VectorizeLoop && InterleaveLoop) {
1883 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1884 << DebugLocStr << '\n');
1885 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1888 if (!VectorizeLoop) {
1889 assert(IC > 1 && "interleave count should not be 1 or 0");
1890 // If we decided that it is not legal to vectorize the loop then
1892 InnerLoopUnroller Unroller(L, SE, LI, DT, TLI, TTI, IC, Preds);
1893 Unroller.vectorize(&LVL, CM.MinBWs);
1895 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1896 Twine("interleaved loop (interleaved count: ") +
1899 // If we decided that it is *legal* to vectorize the loop then do it.
1900 InnerLoopVectorizer LB(L, SE, LI, DT, TLI, TTI, VF.Width, IC, Preds);
1901 LB.vectorize(&LVL, CM.MinBWs);
1904 // Add metadata to disable runtime unrolling scalar loop when there's no
1905 // runtime check about strides and memory. Because at this situation,
1906 // scalar loop is rarely used not worthy to be unrolled.
1907 if (!LB.IsSafetyChecksAdded())
1908 AddRuntimeUnrollDisableMetaData(L);
1910 // Report the vectorization decision.
1911 emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
1912 Twine("vectorized loop (vectorization width: ") +
1913 Twine(VF.Width) + ", interleaved count: " +
1917 // Mark the loop as already vectorized to avoid vectorizing again.
1918 Hints.setAlreadyVectorized();
1920 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1924 void getAnalysisUsage(AnalysisUsage &AU) const override {
1925 AU.addRequired<AssumptionCacheTracker>();
1926 AU.addRequiredID(LoopSimplifyID);
1927 AU.addRequiredID(LCSSAID);
1928 AU.addRequired<BlockFrequencyInfoWrapperPass>();
1929 AU.addRequired<DominatorTreeWrapperPass>();
1930 AU.addRequired<LoopInfoWrapperPass>();
1931 AU.addRequired<ScalarEvolutionWrapperPass>();
1932 AU.addRequired<TargetTransformInfoWrapperPass>();
1933 AU.addRequired<AAResultsWrapperPass>();
1934 AU.addRequired<LoopAccessAnalysis>();
1935 AU.addRequired<DemandedBits>();
1936 AU.addPreserved<LoopInfoWrapperPass>();
1937 AU.addPreserved<DominatorTreeWrapperPass>();
1938 AU.addPreserved<BasicAAWrapperPass>();
1939 AU.addPreserved<AAResultsWrapperPass>();
1940 AU.addPreserved<GlobalsAAWrapperPass>();
1945 } // end anonymous namespace
1947 //===----------------------------------------------------------------------===//
1948 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1949 // LoopVectorizationCostModel.
1950 //===----------------------------------------------------------------------===//
1952 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1953 // We need to place the broadcast of invariant variables outside the loop.
1954 Instruction *Instr = dyn_cast<Instruction>(V);
1956 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1957 Instr->getParent()) != LoopVectorBody.end());
1958 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1960 // Place the code for broadcasting invariant variables in the new preheader.
1961 IRBuilder<>::InsertPointGuard Guard(Builder);
1963 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1965 // Broadcast the scalar into all locations in the vector.
1966 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1971 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1973 assert(Val->getType()->isVectorTy() && "Must be a vector");
1974 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1975 "Elem must be an integer");
1976 assert(Step->getType() == Val->getType()->getScalarType() &&
1977 "Step has wrong type");
1978 // Create the types.
1979 Type *ITy = Val->getType()->getScalarType();
1980 VectorType *Ty = cast<VectorType>(Val->getType());
1981 int VLen = Ty->getNumElements();
1982 SmallVector<Constant*, 8> Indices;
1984 // Create a vector of consecutive numbers from zero to VF.
1985 for (int i = 0; i < VLen; ++i)
1986 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1988 // Add the consecutive indices to the vector value.
1989 Constant *Cv = ConstantVector::get(Indices);
1990 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1991 Step = Builder.CreateVectorSplat(VLen, Step);
1992 assert(Step->getType() == Val->getType() && "Invalid step vec");
1993 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1994 // which can be found from the original scalar operations.
1995 Step = Builder.CreateMul(Cv, Step);
1996 return Builder.CreateAdd(Val, Step, "induction");
1999 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
2000 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
2001 // Make sure that the pointer does not point to structs.
2002 if (Ptr->getType()->getPointerElementType()->isAggregateType())
2005 // If this value is a pointer induction variable we know it is consecutive.
2006 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
2007 if (Phi && Inductions.count(Phi)) {
2008 InductionDescriptor II = Inductions[Phi];
2009 return II.getConsecutiveDirection();
2012 GetElementPtrInst *Gep = getGEPInstruction(Ptr);
2016 unsigned NumOperands = Gep->getNumOperands();
2017 Value *GpPtr = Gep->getPointerOperand();
2018 // If this GEP value is a consecutive pointer induction variable and all of
2019 // the indices are constant then we know it is consecutive. We can
2020 Phi = dyn_cast<PHINode>(GpPtr);
2021 if (Phi && Inductions.count(Phi)) {
2023 // Make sure that the pointer does not point to structs.
2024 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
2025 if (GepPtrType->getElementType()->isAggregateType())
2028 // Make sure that all of the index operands are loop invariant.
2029 for (unsigned i = 1; i < NumOperands; ++i)
2030 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
2033 InductionDescriptor II = Inductions[Phi];
2034 return II.getConsecutiveDirection();
2037 unsigned InductionOperand = getGEPInductionOperand(Gep);
2039 // Check that all of the gep indices are uniform except for our induction
2041 for (unsigned i = 0; i != NumOperands; ++i)
2042 if (i != InductionOperand &&
2043 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
2046 // We can emit wide load/stores only if the last non-zero index is the
2047 // induction variable.
2048 const SCEV *Last = nullptr;
2049 if (!Strides.count(Gep))
2050 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
2052 // Because of the multiplication by a stride we can have a s/zext cast.
2053 // We are going to replace this stride by 1 so the cast is safe to ignore.
2055 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
2056 // %0 = trunc i64 %indvars.iv to i32
2057 // %mul = mul i32 %0, %Stride1
2058 // %idxprom = zext i32 %mul to i64 << Safe cast.
2059 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
2061 Last = replaceSymbolicStrideSCEV(SE, Strides, Preds,
2062 Gep->getOperand(InductionOperand), Gep);
2063 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
2065 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
2069 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
2070 const SCEV *Step = AR->getStepRecurrence(*SE);
2072 // The memory is consecutive because the last index is consecutive
2073 // and all other indices are loop invariant.
2076 if (Step->isAllOnesValue())
2083 bool LoopVectorizationLegality::isUniform(Value *V) {
2084 return LAI->isUniform(V);
2087 InnerLoopVectorizer::VectorParts&
2088 InnerLoopVectorizer::getVectorValue(Value *V) {
2089 assert(V != Induction && "The new induction variable should not be used.");
2090 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2092 // If we have a stride that is replaced by one, do it here.
2093 if (Legal->hasStride(V))
2094 V = ConstantInt::get(V->getType(), 1);
2096 // If we have this scalar in the map, return it.
2097 if (WidenMap.has(V))
2098 return WidenMap.get(V);
2100 // If this scalar is unknown, assume that it is a constant or that it is
2101 // loop invariant. Broadcast V and save the value for future uses.
2102 Value *B = getBroadcastInstrs(V);
2104 return WidenMap.splat(V, B);
2107 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2108 assert(Vec->getType()->isVectorTy() && "Invalid type");
2109 SmallVector<Constant*, 8> ShuffleMask;
2110 for (unsigned i = 0; i < VF; ++i)
2111 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2113 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2114 ConstantVector::get(ShuffleMask),
2118 // Get a mask to interleave \p NumVec vectors into a wide vector.
2119 // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
2120 // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
2121 // <0, 4, 1, 5, 2, 6, 3, 7>
2122 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
2124 SmallVector<Constant *, 16> Mask;
2125 for (unsigned i = 0; i < VF; i++)
2126 for (unsigned j = 0; j < NumVec; j++)
2127 Mask.push_back(Builder.getInt32(j * VF + i));
2129 return ConstantVector::get(Mask);
2132 // Get the strided mask starting from index \p Start.
2133 // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)>
2134 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
2135 unsigned Stride, unsigned VF) {
2136 SmallVector<Constant *, 16> Mask;
2137 for (unsigned i = 0; i < VF; i++)
2138 Mask.push_back(Builder.getInt32(Start + i * Stride));
2140 return ConstantVector::get(Mask);
2143 // Get a mask of two parts: The first part consists of sequential integers
2144 // starting from 0, The second part consists of UNDEFs.
2145 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
2146 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
2147 unsigned NumUndef) {
2148 SmallVector<Constant *, 16> Mask;
2149 for (unsigned i = 0; i < NumInt; i++)
2150 Mask.push_back(Builder.getInt32(i));
2152 Constant *Undef = UndefValue::get(Builder.getInt32Ty());
2153 for (unsigned i = 0; i < NumUndef; i++)
2154 Mask.push_back(Undef);
2156 return ConstantVector::get(Mask);
2159 // Concatenate two vectors with the same element type. The 2nd vector should
2160 // not have more elements than the 1st vector. If the 2nd vector has less
2161 // elements, extend it with UNDEFs.
2162 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
2164 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
2165 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
2166 assert(VecTy1 && VecTy2 &&
2167 VecTy1->getScalarType() == VecTy2->getScalarType() &&
2168 "Expect two vectors with the same element type");
2170 unsigned NumElts1 = VecTy1->getNumElements();
2171 unsigned NumElts2 = VecTy2->getNumElements();
2172 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
2174 if (NumElts1 > NumElts2) {
2175 // Extend with UNDEFs.
2177 getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
2178 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
2181 Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
2182 return Builder.CreateShuffleVector(V1, V2, Mask);
2185 // Concatenate vectors in the given list. All vectors have the same type.
2186 static Value *ConcatenateVectors(IRBuilder<> &Builder,
2187 ArrayRef<Value *> InputList) {
2188 unsigned NumVec = InputList.size();
2189 assert(NumVec > 1 && "Should be at least two vectors");
2191 SmallVector<Value *, 8> ResList;
2192 ResList.append(InputList.begin(), InputList.end());
2194 SmallVector<Value *, 8> TmpList;
2195 for (unsigned i = 0; i < NumVec - 1; i += 2) {
2196 Value *V0 = ResList[i], *V1 = ResList[i + 1];
2197 assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
2198 "Only the last vector may have a different type");
2200 TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
2203 // Push the last vector if the total number of vectors is odd.
2204 if (NumVec % 2 != 0)
2205 TmpList.push_back(ResList[NumVec - 1]);
2208 NumVec = ResList.size();
2209 } while (NumVec > 1);
2214 // Try to vectorize the interleave group that \p Instr belongs to.
2216 // E.g. Translate following interleaved load group (factor = 3):
2217 // for (i = 0; i < N; i+=3) {
2218 // R = Pic[i]; // Member of index 0
2219 // G = Pic[i+1]; // Member of index 1
2220 // B = Pic[i+2]; // Member of index 2
2221 // ... // do something to R, G, B
2224 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2225 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2226 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2227 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2229 // Or translate following interleaved store group (factor = 3):
2230 // for (i = 0; i < N; i+=3) {
2231 // ... do something to R, G, B
2232 // Pic[i] = R; // Member of index 0
2233 // Pic[i+1] = G; // Member of index 1
2234 // Pic[i+2] = B; // Member of index 2
2237 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2238 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2239 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2240 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2241 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2242 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2243 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2244 assert(Group && "Fail to get an interleaved access group.");
2246 // Skip if current instruction is not the insert position.
2247 if (Instr != Group->getInsertPos())
2250 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2251 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2252 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2254 // Prepare for the vector type of the interleaved load/store.
2255 Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2256 unsigned InterleaveFactor = Group->getFactor();
2257 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2258 Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
2260 // Prepare for the new pointers.
2261 setDebugLocFromInst(Builder, Ptr);
2262 VectorParts &PtrParts = getVectorValue(Ptr);
2263 SmallVector<Value *, 2> NewPtrs;
2264 unsigned Index = Group->getIndex(Instr);
2265 for (unsigned Part = 0; Part < UF; Part++) {
2266 // Extract the pointer for current instruction from the pointer vector. A
2267 // reverse access uses the pointer in the last lane.
2268 Value *NewPtr = Builder.CreateExtractElement(
2270 Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
2272 // Notice current instruction could be any index. Need to adjust the address
2273 // to the member of index 0.
2275 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2276 // b = A[i]; // Member of index 0
2277 // Current pointer is pointed to A[i+1], adjust it to A[i].
2279 // E.g. A[i+1] = a; // Member of index 1
2280 // A[i] = b; // Member of index 0
2281 // A[i+2] = c; // Member of index 2 (Current instruction)
2282 // Current pointer is pointed to A[i+2], adjust it to A[i].
2283 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2285 // Cast to the vector pointer type.
2286 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2289 setDebugLocFromInst(Builder, Instr);
2290 Value *UndefVec = UndefValue::get(VecTy);
2292 // Vectorize the interleaved load group.
2294 for (unsigned Part = 0; Part < UF; Part++) {
2295 Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
2296 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2298 for (unsigned i = 0; i < InterleaveFactor; i++) {
2299 Instruction *Member = Group->getMember(i);
2301 // Skip the gaps in the group.
2305 Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
2306 Value *StridedVec = Builder.CreateShuffleVector(
2307 NewLoadInstr, UndefVec, StrideMask, "strided.vec");
2309 // If this member has different type, cast the result type.
2310 if (Member->getType() != ScalarTy) {
2311 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2312 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2315 VectorParts &Entry = WidenMap.get(Member);
2317 Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2320 propagateMetadata(NewLoadInstr, Instr);
2325 // The sub vector type for current instruction.
2326 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2328 // Vectorize the interleaved store group.
2329 for (unsigned Part = 0; Part < UF; Part++) {
2330 // Collect the stored vector from each member.
2331 SmallVector<Value *, 4> StoredVecs;
2332 for (unsigned i = 0; i < InterleaveFactor; i++) {
2333 // Interleaved store group doesn't allow a gap, so each index has a member
2334 Instruction *Member = Group->getMember(i);
2335 assert(Member && "Fail to get a member from an interleaved store group");
2338 getVectorValue(dyn_cast<StoreInst>(Member)->getValueOperand())[Part];
2339 if (Group->isReverse())
2340 StoredVec = reverseVector(StoredVec);
2342 // If this member has different type, cast it to an unified type.
2343 if (StoredVec->getType() != SubVT)
2344 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2346 StoredVecs.push_back(StoredVec);
2349 // Concatenate all vectors into a wide vector.
2350 Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
2352 // Interleave the elements in the wide vector.
2353 Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
2354 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2357 Instruction *NewStoreInstr =
2358 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2359 propagateMetadata(NewStoreInstr, Instr);
2363 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2364 // Attempt to issue a wide load.
2365 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2366 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2368 assert((LI || SI) && "Invalid Load/Store instruction");
2370 // Try to vectorize the interleave group if this access is interleaved.
2371 if (Legal->isAccessInterleaved(Instr))
2372 return vectorizeInterleaveGroup(Instr);
2374 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2375 Type *DataTy = VectorType::get(ScalarDataTy, VF);
2376 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2377 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
2378 // An alignment of 0 means target abi alignment. We need to use the scalar's
2379 // target abi alignment in such a case.
2380 const DataLayout &DL = Instr->getModule()->getDataLayout();
2382 Alignment = DL.getABITypeAlignment(ScalarDataTy);
2383 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2384 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
2385 unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
2387 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
2388 !Legal->isMaskRequired(SI))
2389 return scalarizeInstruction(Instr, true);
2391 if (ScalarAllocatedSize != VectorElementSize)
2392 return scalarizeInstruction(Instr);
2394 // If the pointer is loop invariant or if it is non-consecutive,
2395 // scalarize the load.
2396 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2397 bool Reverse = ConsecutiveStride < 0;
2398 bool UniformLoad = LI && Legal->isUniform(Ptr);
2399 if (!ConsecutiveStride || UniformLoad)
2400 return scalarizeInstruction(Instr);
2402 Constant *Zero = Builder.getInt32(0);
2403 VectorParts &Entry = WidenMap.get(Instr);
2405 // Handle consecutive loads/stores.
2406 GetElementPtrInst *Gep = getGEPInstruction(Ptr);
2407 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
2408 setDebugLocFromInst(Builder, Gep);
2409 Value *PtrOperand = Gep->getPointerOperand();
2410 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
2411 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
2413 // Create the new GEP with the new induction variable.
2414 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2415 Gep2->setOperand(0, FirstBasePtr);
2416 Gep2->setName("gep.indvar.base");
2417 Ptr = Builder.Insert(Gep2);
2419 setDebugLocFromInst(Builder, Gep);
2420 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
2421 OrigLoop) && "Base ptr must be invariant");
2423 // The last index does not have to be the induction. It can be
2424 // consecutive and be a function of the index. For example A[I+1];
2425 unsigned NumOperands = Gep->getNumOperands();
2426 unsigned InductionOperand = getGEPInductionOperand(Gep);
2427 // Create the new GEP with the new induction variable.
2428 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2430 for (unsigned i = 0; i < NumOperands; ++i) {
2431 Value *GepOperand = Gep->getOperand(i);
2432 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
2434 // Update last index or loop invariant instruction anchored in loop.
2435 if (i == InductionOperand ||
2436 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
2437 assert((i == InductionOperand ||
2438 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
2439 "Must be last index or loop invariant");
2441 VectorParts &GEPParts = getVectorValue(GepOperand);
2442 Value *Index = GEPParts[0];
2443 Index = Builder.CreateExtractElement(Index, Zero);
2444 Gep2->setOperand(i, Index);
2445 Gep2->setName("gep.indvar.idx");
2448 Ptr = Builder.Insert(Gep2);
2450 // Use the induction element ptr.
2451 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
2452 setDebugLocFromInst(Builder, Ptr);
2453 VectorParts &PtrVal = getVectorValue(Ptr);
2454 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
2457 VectorParts Mask = createBlockInMask(Instr->getParent());
2460 assert(!Legal->isUniform(SI->getPointerOperand()) &&
2461 "We do not allow storing to uniform addresses");
2462 setDebugLocFromInst(Builder, SI);
2463 // We don't want to update the value in the map as it might be used in
2464 // another expression. So don't use a reference type for "StoredVal".
2465 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
2467 for (unsigned Part = 0; Part < UF; ++Part) {
2468 // Calculate the pointer for the specific unroll-part.
2470 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2473 // If we store to reverse consecutive memory locations, then we need
2474 // to reverse the order of elements in the stored value.
2475 StoredVal[Part] = reverseVector(StoredVal[Part]);
2476 // If the address is consecutive but reversed, then the
2477 // wide store needs to start at the last vector element.
2478 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2479 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2480 Mask[Part] = reverseVector(Mask[Part]);
2483 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2484 DataTy->getPointerTo(AddressSpace));
2487 if (Legal->isMaskRequired(SI))
2488 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
2491 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
2492 propagateMetadata(NewSI, SI);
2498 assert(LI && "Must have a load instruction");
2499 setDebugLocFromInst(Builder, LI);
2500 for (unsigned Part = 0; Part < UF; ++Part) {
2501 // Calculate the pointer for the specific unroll-part.
2503 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2506 // If the address is consecutive but reversed, then the
2507 // wide load needs to start at the last vector element.
2508 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2509 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2510 Mask[Part] = reverseVector(Mask[Part]);
2514 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2515 DataTy->getPointerTo(AddressSpace));
2516 if (Legal->isMaskRequired(LI))
2517 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2518 UndefValue::get(DataTy),
2519 "wide.masked.load");
2521 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2522 propagateMetadata(NewLI, LI);
2523 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
2527 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
2528 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2529 // Holds vector parameters or scalars, in case of uniform vals.
2530 SmallVector<VectorParts, 4> Params;
2532 setDebugLocFromInst(Builder, Instr);
2534 // Find all of the vectorized parameters.
2535 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2536 Value *SrcOp = Instr->getOperand(op);
2538 // If we are accessing the old induction variable, use the new one.
2539 if (SrcOp == OldInduction) {
2540 Params.push_back(getVectorValue(SrcOp));
2544 // Try using previously calculated values.
2545 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
2547 // If the src is an instruction that appeared earlier in the basic block,
2548 // then it should already be vectorized.
2549 if (SrcInst && OrigLoop->contains(SrcInst)) {
2550 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
2551 // The parameter is a vector value from earlier.
2552 Params.push_back(WidenMap.get(SrcInst));
2554 // The parameter is a scalar from outside the loop. Maybe even a constant.
2555 VectorParts Scalars;
2556 Scalars.append(UF, SrcOp);
2557 Params.push_back(Scalars);
2561 assert(Params.size() == Instr->getNumOperands() &&
2562 "Invalid number of operands");
2564 // Does this instruction return a value ?
2565 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2567 Value *UndefVec = IsVoidRetTy ? nullptr :
2568 UndefValue::get(VectorType::get(Instr->getType(), VF));
2569 // Create a new entry in the WidenMap and initialize it to Undef or Null.
2570 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
2573 if (IfPredicateStore) {
2574 assert(Instr->getParent()->getSinglePredecessor() &&
2575 "Only support single predecessor blocks");
2576 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
2577 Instr->getParent());
2580 // For each vector unroll 'part':
2581 for (unsigned Part = 0; Part < UF; ++Part) {
2582 // For each scalar that we create:
2583 for (unsigned Width = 0; Width < VF; ++Width) {
2586 Value *Cmp = nullptr;
2587 if (IfPredicateStore) {
2588 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
2589 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
2592 Instruction *Cloned = Instr->clone();
2594 Cloned->setName(Instr->getName() + ".cloned");
2595 // Replace the operands of the cloned instructions with extracted scalars.
2596 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2597 Value *Op = Params[op][Part];
2598 // Param is a vector. Need to extract the right lane.
2599 if (Op->getType()->isVectorTy())
2600 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
2601 Cloned->setOperand(op, Op);
2604 // Place the cloned scalar in the new loop.
2605 Builder.Insert(Cloned);
2607 // If the original scalar returns a value we need to place it in a vector
2608 // so that future users will be able to use it.
2610 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
2611 Builder.getInt32(Width));
2613 if (IfPredicateStore)
2614 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
2620 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
2621 Value *End, Value *Step,
2623 BasicBlock *Header = L->getHeader();
2624 BasicBlock *Latch = L->getLoopLatch();
2625 // As we're just creating this loop, it's possible no latch exists
2626 // yet. If so, use the header as this will be a single block loop.
2630 IRBuilder<> Builder(&*Header->getFirstInsertionPt());
2631 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2632 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
2634 Builder.SetInsertPoint(Latch->getTerminator());
2636 // Create i+1 and fill the PHINode.
2637 Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
2638 Induction->addIncoming(Start, L->getLoopPreheader());
2639 Induction->addIncoming(Next, Latch);
2640 // Create the compare.
2641 Value *ICmp = Builder.CreateICmpEQ(Next, End);
2642 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
2644 // Now we have two terminators. Remove the old one from the block.
2645 Latch->getTerminator()->eraseFromParent();
2650 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
2654 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2655 // Find the loop boundaries.
2656 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(OrigLoop);
2657 assert(BackedgeTakenCount != SE->getCouldNotCompute() && "Invalid loop count");
2659 Type *IdxTy = Legal->getWidestInductionType();
2661 // The exit count might have the type of i64 while the phi is i32. This can
2662 // happen if we have an induction variable that is sign extended before the
2663 // compare. The only way that we get a backedge taken count is that the
2664 // induction variable was signed and as such will not overflow. In such a case
2665 // truncation is legal.
2666 if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
2667 IdxTy->getPrimitiveSizeInBits())
2668 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2669 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2671 // Get the total trip count from the count by adding 1.
2672 const SCEV *ExitCount = SE->getAddExpr(
2673 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2675 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2677 // Expand the trip count and place the new instructions in the preheader.
2678 // Notice that the pre-header does not change, only the loop body.
2679 SCEVExpander Exp(*SE, DL, "induction");
2681 // Count holds the overall loop count (N).
2682 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2683 L->getLoopPreheader()->getTerminator());
2685 if (TripCount->getType()->isPointerTy())
2687 CastInst::CreatePointerCast(TripCount, IdxTy,
2688 "exitcount.ptrcnt.to.int",
2689 L->getLoopPreheader()->getTerminator());
2694 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
2695 if (VectorTripCount)
2696 return VectorTripCount;
2698 Value *TC = getOrCreateTripCount(L);
2699 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2701 // Now we need to generate the expression for N - (N % VF), which is
2702 // the part that the vectorized body will execute.
2703 // The loop step is equal to the vectorization factor (num of SIMD elements)
2704 // times the unroll factor (num of SIMD instructions).
2705 Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
2706 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2707 VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2709 return VectorTripCount;
2712 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
2713 BasicBlock *Bypass) {
2714 Value *Count = getOrCreateTripCount(L);
2715 BasicBlock *BB = L->getLoopPreheader();
2716 IRBuilder<> Builder(BB->getTerminator());
2718 // Generate code to check that the loop's trip count that we computed by
2719 // adding one to the backedge-taken count will not overflow.
2720 Value *CheckMinIters =
2721 Builder.CreateICmpULT(Count,
2722 ConstantInt::get(Count->getType(), VF * UF),
2725 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2726 "min.iters.checked");
2727 if (L->getParentLoop())
2728 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2729 ReplaceInstWithInst(BB->getTerminator(),
2730 BranchInst::Create(Bypass, NewBB, CheckMinIters));
2731 LoopBypassBlocks.push_back(BB);
2734 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L,
2735 BasicBlock *Bypass) {
2736 Value *TC = getOrCreateVectorTripCount(L);
2737 BasicBlock *BB = L->getLoopPreheader();
2738 IRBuilder<> Builder(BB->getTerminator());
2740 // Now, compare the new count to zero. If it is zero skip the vector loop and
2741 // jump to the scalar loop.
2742 Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()),
2745 // Generate code to check that the loop's trip count that we computed by
2746 // adding one to the backedge-taken count will not overflow.
2747 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
2749 if (L->getParentLoop())
2750 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2751 ReplaceInstWithInst(BB->getTerminator(),
2752 BranchInst::Create(Bypass, NewBB, Cmp));
2753 LoopBypassBlocks.push_back(BB);
2756 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
2757 BasicBlock *BB = L->getLoopPreheader();
2759 // Generate the code to check that the SCEV assumptions that we made.
2760 // We want the new basic block to start at the first instruction in a
2761 // sequence of instructions that form a check.
2762 SCEVExpander Exp(*SE, Bypass->getModule()->getDataLayout(), "scev.check");
2763 Value *SCEVCheck = Exp.expandCodeForPredicate(&Preds, BB->getTerminator());
2765 if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
2769 // Create a new block containing the stride check.
2770 BB->setName("vector.scevcheck");
2771 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2772 if (L->getParentLoop())
2773 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2774 ReplaceInstWithInst(BB->getTerminator(),
2775 BranchInst::Create(Bypass, NewBB, SCEVCheck));
2776 LoopBypassBlocks.push_back(BB);
2777 AddedSafetyChecks = true;
2780 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
2781 BasicBlock *Bypass) {
2782 BasicBlock *BB = L->getLoopPreheader();
2784 // Generate the code that checks in runtime if arrays overlap. We put the
2785 // checks into a separate block to make the more common case of few elements
2787 Instruction *FirstCheckInst;
2788 Instruction *MemRuntimeCheck;
2789 std::tie(FirstCheckInst, MemRuntimeCheck) =
2790 Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
2791 if (!MemRuntimeCheck)
2794 // Create a new block containing the memory check.
2795 BB->setName("vector.memcheck");
2796 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
2797 if (L->getParentLoop())
2798 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
2799 ReplaceInstWithInst(BB->getTerminator(),
2800 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
2801 LoopBypassBlocks.push_back(BB);
2802 AddedSafetyChecks = true;
2806 void InnerLoopVectorizer::createEmptyLoop() {
2808 In this function we generate a new loop. The new loop will contain
2809 the vectorized instructions while the old loop will continue to run the
2812 [ ] <-- loop iteration number check.
2815 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2818 || [ ] <-- vector pre header.
2822 | [ ]_| <-- vector loop.
2825 | -[ ] <--- middle-block.
2828 -|- >[ ] <--- new preheader.
2832 | [ ]_| <-- old scalar loop to handle remainder.
2835 >[ ] <-- exit block.
2839 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2840 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2841 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2842 assert(VectorPH && "Invalid loop structure");
2843 assert(ExitBlock && "Must have an exit block");
2845 // Some loops have a single integer induction variable, while other loops
2846 // don't. One example is c++ iterators that often have multiple pointer
2847 // induction variables. In the code below we also support a case where we
2848 // don't have a single induction variable.
2850 // We try to obtain an induction variable from the original loop as hard
2851 // as possible. However if we don't find one that:
2853 // - counts from zero, stepping by one
2854 // - is the size of the widest induction variable type
2855 // then we create a new one.
2856 OldInduction = Legal->getInduction();
2857 Type *IdxTy = Legal->getWidestInductionType();
2859 // Split the single block loop into the two loop structure described above.
2860 BasicBlock *VecBody =
2861 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2862 BasicBlock *MiddleBlock =
2863 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2864 BasicBlock *ScalarPH =
2865 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2867 // Create and register the new vector loop.
2868 Loop* Lp = new Loop();
2869 Loop *ParentLoop = OrigLoop->getParentLoop();
2871 // Insert the new loop into the loop nest and register the new basic blocks
2872 // before calling any utilities such as SCEV that require valid LoopInfo.
2874 ParentLoop->addChildLoop(Lp);
2875 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2876 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2878 LI->addTopLevelLoop(Lp);
2880 Lp->addBasicBlockToLoop(VecBody, *LI);
2882 // Find the loop boundaries.
2883 Value *Count = getOrCreateTripCount(Lp);
2885 Value *StartIdx = ConstantInt::get(IdxTy, 0);
2887 // We need to test whether the backedge-taken count is uint##_max. Adding one
2888 // to it will cause overflow and an incorrect loop trip count in the vector
2889 // body. In case of overflow we want to directly jump to the scalar remainder
2891 emitMinimumIterationCountCheck(Lp, ScalarPH);
2892 // Now, compare the new count to zero. If it is zero skip the vector loop and
2893 // jump to the scalar loop.
2894 emitVectorLoopEnteredCheck(Lp, ScalarPH);
2895 // Generate the code to check any assumptions that we've made for SCEV
2897 emitSCEVChecks(Lp, ScalarPH);
2899 // Generate the code that checks in runtime if arrays overlap. We put the
2900 // checks into a separate block to make the more common case of few elements
2902 emitMemRuntimeChecks(Lp, ScalarPH);
2904 // Generate the induction variable.
2905 // The loop step is equal to the vectorization factor (num of SIMD elements)
2906 // times the unroll factor (num of SIMD instructions).
2907 Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
2908 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2910 createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
2911 getDebugLocFromInstOrOperands(OldInduction));
2913 // We are going to resume the execution of the scalar loop.
2914 // Go over all of the induction variables that we found and fix the
2915 // PHIs that are left in the scalar version of the loop.
2916 // The starting values of PHI nodes depend on the counter of the last
2917 // iteration in the vectorized loop.
2918 // If we come from a bypass edge then we need to start from the original
2921 // This variable saves the new starting index for the scalar loop. It is used
2922 // to test if there are any tail iterations left once the vector loop has
2924 LoopVectorizationLegality::InductionList::iterator I, E;
2925 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2926 for (I = List->begin(), E = List->end(); I != E; ++I) {
2927 PHINode *OrigPhi = I->first;
2928 InductionDescriptor II = I->second;
2930 // Create phi nodes to merge from the backedge-taken check block.
2931 PHINode *BCResumeVal = PHINode::Create(OrigPhi->getType(), 3,
2933 ScalarPH->getTerminator());
2935 if (OrigPhi == OldInduction) {
2936 // We know what the end value is.
2937 EndValue = CountRoundDown;
2939 IRBuilder<> B(LoopBypassBlocks.back()->getTerminator());
2940 Value *CRD = B.CreateSExtOrTrunc(CountRoundDown,
2941 II.getStepValue()->getType(),
2943 EndValue = II.transform(B, CRD);
2944 EndValue->setName("ind.end");
2947 // The new PHI merges the original incoming value, in case of a bypass,
2948 // or the value at the end of the vectorized loop.
2949 BCResumeVal->addIncoming(EndValue, MiddleBlock);
2951 // Fix the scalar body counter (PHI node).
2952 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2954 // The old induction's phi node in the scalar body needs the truncated
2956 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2957 BCResumeVal->addIncoming(II.getStartValue(), LoopBypassBlocks[I]);
2958 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2961 // Add a check in the middle block to see if we have completed
2962 // all of the iterations in the first vector loop.
2963 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2964 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
2965 CountRoundDown, "cmp.n",
2966 MiddleBlock->getTerminator());
2967 ReplaceInstWithInst(MiddleBlock->getTerminator(),
2968 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2970 // Get ready to start creating new instructions into the vectorized body.
2971 Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
2974 LoopVectorPreHeader = Lp->getLoopPreheader();
2975 LoopScalarPreHeader = ScalarPH;
2976 LoopMiddleBlock = MiddleBlock;
2977 LoopExitBlock = ExitBlock;
2978 LoopVectorBody.push_back(VecBody);
2979 LoopScalarBody = OldBasicBlock;
2981 LoopVectorizeHints Hints(Lp, true);
2982 Hints.setAlreadyVectorized();
2986 struct CSEDenseMapInfo {
2987 static bool canHandle(Instruction *I) {
2988 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2989 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2991 static inline Instruction *getEmptyKey() {
2992 return DenseMapInfo<Instruction *>::getEmptyKey();
2994 static inline Instruction *getTombstoneKey() {
2995 return DenseMapInfo<Instruction *>::getTombstoneKey();
2997 static unsigned getHashValue(Instruction *I) {
2998 assert(canHandle(I) && "Unknown instruction!");
2999 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3000 I->value_op_end()));
3002 static bool isEqual(Instruction *LHS, Instruction *RHS) {
3003 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3004 LHS == getTombstoneKey() || RHS == getTombstoneKey())
3006 return LHS->isIdenticalTo(RHS);
3011 /// \brief Check whether this block is a predicated block.
3012 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
3013 /// = ...; " blocks. We start with one vectorized basic block. For every
3014 /// conditional block we split this vectorized block. Therefore, every second
3015 /// block will be a predicated one.
3016 static bool isPredicatedBlock(unsigned BlockNum) {
3017 return BlockNum % 2;
3020 ///\brief Perform cse of induction variable instructions.
3021 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
3022 // Perform simple cse.
3023 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3024 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
3025 BasicBlock *BB = BBs[i];
3026 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3027 Instruction *In = &*I++;
3029 if (!CSEDenseMapInfo::canHandle(In))
3032 // Check if we can replace this instruction with any of the
3033 // visited instructions.
3034 if (Instruction *V = CSEMap.lookup(In)) {
3035 In->replaceAllUsesWith(V);
3036 In->eraseFromParent();
3039 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
3040 // ...;" blocks for predicated stores. Every second block is a predicated
3042 if (isPredicatedBlock(i))
3050 /// \brief Adds a 'fast' flag to floating point operations.
3051 static Value *addFastMathFlag(Value *V) {
3052 if (isa<FPMathOperator>(V)){
3053 FastMathFlags Flags;
3054 Flags.setUnsafeAlgebra();
3055 cast<Instruction>(V)->setFastMathFlags(Flags);
3060 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
3061 /// the result needs to be inserted and/or extracted from vectors.
3062 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
3063 const TargetTransformInfo &TTI) {
3067 assert(Ty->isVectorTy() && "Can only scalarize vectors");
3070 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
3072 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
3074 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
3080 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3081 // Return the cost of the instruction, including scalarization overhead if it's
3082 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3083 // i.e. either vector version isn't available, or is too expensive.
3084 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3085 const TargetTransformInfo &TTI,
3086 const TargetLibraryInfo *TLI,
3087 bool &NeedToScalarize) {
3088 Function *F = CI->getCalledFunction();
3089 StringRef FnName = CI->getCalledFunction()->getName();
3090 Type *ScalarRetTy = CI->getType();
3091 SmallVector<Type *, 4> Tys, ScalarTys;
3092 for (auto &ArgOp : CI->arg_operands())
3093 ScalarTys.push_back(ArgOp->getType());
3095 // Estimate cost of scalarized vector call. The source operands are assumed
3096 // to be vectors, so we need to extract individual elements from there,
3097 // execute VF scalar calls, and then gather the result into the vector return
3099 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3101 return ScalarCallCost;
3103 // Compute corresponding vector type for return value and arguments.
3104 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3105 for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
3106 Tys.push_back(ToVectorTy(ScalarTys[i], VF));
3108 // Compute costs of unpacking argument values for the scalar calls and
3109 // packing the return values to a vector.
3110 unsigned ScalarizationCost =
3111 getScalarizationOverhead(RetTy, true, false, TTI);
3112 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
3113 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
3115 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3117 // If we can't emit a vector call for this function, then the currently found
3118 // cost is the cost we need to return.
3119 NeedToScalarize = true;
3120 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3123 // If the corresponding vector cost is cheaper, return its cost.
3124 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3125 if (VectorCallCost < Cost) {
3126 NeedToScalarize = false;
3127 return VectorCallCost;
3132 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3133 // factor VF. Return the cost of the instruction, including scalarization
3134 // overhead if it's needed.
3135 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3136 const TargetTransformInfo &TTI,
3137 const TargetLibraryInfo *TLI) {
3138 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3139 assert(ID && "Expected intrinsic call!");
3141 Type *RetTy = ToVectorTy(CI->getType(), VF);
3142 SmallVector<Type *, 4> Tys;
3143 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3144 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3146 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3149 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3150 IntegerType *I1 = cast<IntegerType>(T1->getVectorElementType());
3151 IntegerType *I2 = cast<IntegerType>(T2->getVectorElementType());
3152 return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3154 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3155 IntegerType *I1 = cast<IntegerType>(T1->getVectorElementType());
3156 IntegerType *I2 = cast<IntegerType>(T2->getVectorElementType());
3157 return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3160 void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3161 // For every instruction `I` in MinBWs, truncate the operands, create a
3162 // truncated version of `I` and reextend its result. InstCombine runs
3163 // later and will remove any ext/trunc pairs.
3165 for (auto &KV : MinBWs) {
3166 VectorParts &Parts = WidenMap.get(KV.first);
3167 for (Value *&I : Parts) {
3170 Type *OriginalTy = I->getType();
3171 Type *ScalarTruncatedTy = IntegerType::get(OriginalTy->getContext(),
3173 Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3174 OriginalTy->getVectorNumElements());
3175 if (TruncatedTy == OriginalTy)
3178 IRBuilder<> B(cast<Instruction>(I));
3179 auto ShrinkOperand = [&](Value *V) -> Value* {
3180 if (auto *ZI = dyn_cast<ZExtInst>(V))
3181 if (ZI->getSrcTy() == TruncatedTy)
3182 return ZI->getOperand(0);
3183 return B.CreateZExtOrTrunc(V, TruncatedTy);
3186 // The actual instruction modification depends on the instruction type,
3188 Value *NewI = nullptr;
3189 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
3190 NewI = B.CreateBinOp(BO->getOpcode(),
3191 ShrinkOperand(BO->getOperand(0)),
3192 ShrinkOperand(BO->getOperand(1)));
3193 cast<BinaryOperator>(NewI)->copyIRFlags(I);
3194 } else if (ICmpInst *CI = dyn_cast<ICmpInst>(I)) {
3195 NewI = B.CreateICmp(CI->getPredicate(),
3196 ShrinkOperand(CI->getOperand(0)),
3197 ShrinkOperand(CI->getOperand(1)));
3198 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
3199 NewI = B.CreateSelect(SI->getCondition(),
3200 ShrinkOperand(SI->getTrueValue()),
3201 ShrinkOperand(SI->getFalseValue()));
3202 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3203 switch (CI->getOpcode()) {
3204 default: llvm_unreachable("Unhandled cast!");
3205 case Instruction::Trunc:
3206 NewI = ShrinkOperand(CI->getOperand(0));
3208 case Instruction::SExt:
3209 NewI = B.CreateSExtOrTrunc(CI->getOperand(0),
3210 smallestIntegerVectorType(OriginalTy,
3213 case Instruction::ZExt:
3214 NewI = B.CreateZExtOrTrunc(CI->getOperand(0),
3215 smallestIntegerVectorType(OriginalTy,
3219 } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
3220 auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3222 B.CreateZExtOrTrunc(SI->getOperand(0),
3223 VectorType::get(ScalarTruncatedTy, Elements0));
3224 auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3226 B.CreateZExtOrTrunc(SI->getOperand(1),
3227 VectorType::get(ScalarTruncatedTy, Elements1));
3229 NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3230 } else if (isa<LoadInst>(I)) {
3231 // Don't do anything with the operands, just extend the result.
3234 llvm_unreachable("Unhandled instruction type!");
3237 // Lastly, extend the result.
3238 NewI->takeName(cast<Instruction>(I));
3239 Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3240 I->replaceAllUsesWith(Res);
3241 cast<Instruction>(I)->eraseFromParent();
3246 // We'll have created a bunch of ZExts that are now parentless. Clean up.
3247 for (auto &KV : MinBWs) {
3248 VectorParts &Parts = WidenMap.get(KV.first);
3249 for (Value *&I : Parts) {
3250 ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3251 if (Inst && Inst->use_empty()) {
3252 Value *NewI = Inst->getOperand(0);
3253 Inst->eraseFromParent();
3260 void InnerLoopVectorizer::vectorizeLoop() {
3261 //===------------------------------------------------===//
3263 // Notice: any optimization or new instruction that go
3264 // into the code below should be also be implemented in
3267 //===------------------------------------------------===//
3268 Constant *Zero = Builder.getInt32(0);
3270 // In order to support reduction variables we need to be able to vectorize
3271 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
3272 // stages. First, we create a new vector PHI node with no incoming edges.
3273 // We use this value when we vectorize all of the instructions that use the
3274 // PHI. Next, after all of the instructions in the block are complete we
3275 // add the new incoming edges to the PHI. At this point all of the
3276 // instructions in the basic block are vectorized, so we can use them to
3277 // construct the PHI.
3278 PhiVector RdxPHIsToFix;
3280 // Scan the loop in a topological order to ensure that defs are vectorized
3282 LoopBlocksDFS DFS(OrigLoop);
3285 // Vectorize all of the blocks in the original loop.
3286 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3287 be = DFS.endRPO(); bb != be; ++bb)
3288 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
3290 // Insert truncates and extends for any truncated instructions as hints to
3293 truncateToMinimalBitwidths();
3295 // At this point every instruction in the original loop is widened to
3296 // a vector form. We are almost done. Now, we need to fix the PHI nodes
3297 // that we vectorized. The PHI nodes are currently empty because we did
3298 // not want to introduce cycles. Notice that the remaining PHI nodes
3299 // that we need to fix are reduction variables.
3301 // Create the 'reduced' values for each of the induction vars.
3302 // The reduced values are the vector values that we scalarize and combine
3303 // after the loop is finished.
3304 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
3306 PHINode *RdxPhi = *it;
3307 assert(RdxPhi && "Unable to recover vectorized PHI");
3309 // Find the reduction variable descriptor.
3310 assert(Legal->getReductionVars()->count(RdxPhi) &&
3311 "Unable to find the reduction variable");
3312 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[RdxPhi];
3314 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3315 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3316 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3317 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3318 RdxDesc.getMinMaxRecurrenceKind();
3319 setDebugLocFromInst(Builder, ReductionStartValue);
3321 // We need to generate a reduction vector from the incoming scalar.
3322 // To do so, we need to generate the 'identity' vector and override
3323 // one of the elements with the incoming scalar reduction. We need
3324 // to do it in the vector-loop preheader.
3325 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
3327 // This is the vector-clone of the value that leaves the loop.
3328 VectorParts &VectorExit = getVectorValue(LoopExitInst);
3329 Type *VecTy = VectorExit[0]->getType();
3331 // Find the reduction identity variable. Zero for addition, or, xor,
3332 // one for multiplication, -1 for And.
3335 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3336 RK == RecurrenceDescriptor::RK_FloatMinMax) {
3337 // MinMax reduction have the start value as their identify.
3339 VectorStart = Identity = ReductionStartValue;
3341 VectorStart = Identity =
3342 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3345 // Handle other reduction kinds:
3346 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3347 RK, VecTy->getScalarType());
3350 // This vector is the Identity vector where the first element is the
3351 // incoming scalar reduction.
3352 VectorStart = ReductionStartValue;
3354 Identity = ConstantVector::getSplat(VF, Iden);
3356 // This vector is the Identity vector where the first element is the
3357 // incoming scalar reduction.
3359 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3363 // Fix the vector-loop phi.
3365 // Reductions do not have to start at zero. They can start with
3366 // any loop invariant values.
3367 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
3368 BasicBlock *Latch = OrigLoop->getLoopLatch();
3369 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
3370 VectorParts &Val = getVectorValue(LoopVal);
3371 for (unsigned part = 0; part < UF; ++part) {
3372 // Make sure to add the reduction stat value only to the
3373 // first unroll part.
3374 Value *StartVal = (part == 0) ? VectorStart : Identity;
3375 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
3376 LoopVectorPreHeader);
3377 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
3378 LoopVectorBody.back());
3381 // Before each round, move the insertion point right between
3382 // the PHIs and the values we are going to write.
3383 // This allows us to write both PHINodes and the extractelement
3385 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3387 VectorParts RdxParts = getVectorValue(LoopExitInst);
3388 setDebugLocFromInst(Builder, LoopExitInst);
3390 // If the vector reduction can be performed in a smaller type, we truncate
3391 // then extend the loop exit value to enable InstCombine to evaluate the
3392 // entire expression in the smaller type.
3393 if (VF > 1 && RdxPhi->getType() != RdxDesc.getRecurrenceType()) {
3394 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3395 Builder.SetInsertPoint(LoopVectorBody.back()->getTerminator());
3396 for (unsigned part = 0; part < UF; ++part) {
3397 Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3398 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3399 : Builder.CreateZExt(Trunc, VecTy);
3400 for (Value::user_iterator UI = RdxParts[part]->user_begin();
3401 UI != RdxParts[part]->user_end();)
3403 (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd);
3404 RdxParts[part] = Extnd;
3409 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3410 for (unsigned part = 0; part < UF; ++part)
3411 RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3414 // Reduce all of the unrolled parts into a single vector.
3415 Value *ReducedPartRdx = RdxParts[0];
3416 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3417 setDebugLocFromInst(Builder, ReducedPartRdx);
3418 for (unsigned part = 1; part < UF; ++part) {
3419 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3420 // Floating point operations had to be 'fast' to enable the reduction.
3421 ReducedPartRdx = addFastMathFlag(
3422 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
3423 ReducedPartRdx, "bin.rdx"));
3425 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3426 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
3430 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3431 // and vector ops, reducing the set of values being computed by half each
3433 assert(isPowerOf2_32(VF) &&
3434 "Reduction emission only supported for pow2 vectors!");
3435 Value *TmpVec = ReducedPartRdx;
3436 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
3437 for (unsigned i = VF; i != 1; i >>= 1) {
3438 // Move the upper half of the vector to the lower half.
3439 for (unsigned j = 0; j != i/2; ++j)
3440 ShuffleMask[j] = Builder.getInt32(i/2 + j);
3442 // Fill the rest of the mask with undef.
3443 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
3444 UndefValue::get(Builder.getInt32Ty()));
3447 Builder.CreateShuffleVector(TmpVec,
3448 UndefValue::get(TmpVec->getType()),
3449 ConstantVector::get(ShuffleMask),
3452 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3453 // Floating point operations had to be 'fast' to enable the reduction.
3454 TmpVec = addFastMathFlag(Builder.CreateBinOp(
3455 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
3457 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
3461 // The result is in the first element of the vector.
3462 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
3463 Builder.getInt32(0));
3465 // If the reduction can be performed in a smaller type, we need to extend
3466 // the reduction to the wider type before we branch to the original loop.
3467 if (RdxPhi->getType() != RdxDesc.getRecurrenceType())
3470 ? Builder.CreateSExt(ReducedPartRdx, RdxPhi->getType())
3471 : Builder.CreateZExt(ReducedPartRdx, RdxPhi->getType());
3474 // Create a phi node that merges control-flow from the backedge-taken check
3475 // block and the middle block.
3476 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
3477 LoopScalarPreHeader->getTerminator());
3478 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
3479 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
3480 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3482 // Now, we need to fix the users of the reduction variable
3483 // inside and outside of the scalar remainder loop.
3484 // We know that the loop is in LCSSA form. We need to update the
3485 // PHI nodes in the exit blocks.
3486 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3487 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3488 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3489 if (!LCSSAPhi) break;
3491 // All PHINodes need to have a single entry edge, or two if
3492 // we already fixed them.
3493 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3495 // We found our reduction value exit-PHI. Update it with the
3496 // incoming bypass edge.
3497 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
3498 // Add an edge coming from the bypass.
3499 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3502 }// end of the LCSSA phi scan.
3504 // Fix the scalar loop reduction variable with the incoming reduction sum
3505 // from the vector body and from the backedge value.
3506 int IncomingEdgeBlockIdx =
3507 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
3508 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3509 // Pick the other block.
3510 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3511 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3512 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3513 }// end of for each redux variable.
3517 // Make sure DomTree is updated.
3520 // Predicate any stores.
3521 for (auto KV : PredicatedStores) {
3522 BasicBlock::iterator I(KV.first);
3523 auto *BB = SplitBlock(I->getParent(), &*std::next(I), DT, LI);
3524 auto *T = SplitBlockAndInsertIfThen(KV.second, &*I, /*Unreachable=*/false,
3525 /*BranchWeights=*/nullptr, DT);
3527 I->getParent()->setName("pred.store.if");
3528 BB->setName("pred.store.continue");
3530 DEBUG(DT->verifyDomTree());
3531 // Remove redundant induction instructions.
3532 cse(LoopVectorBody);
3535 void InnerLoopVectorizer::fixLCSSAPHIs() {
3536 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3537 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3538 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3539 if (!LCSSAPhi) break;
3540 if (LCSSAPhi->getNumIncomingValues() == 1)
3541 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
3546 InnerLoopVectorizer::VectorParts
3547 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3548 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3551 // Look for cached value.
3552 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
3553 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3554 if (ECEntryIt != MaskCache.end())
3555 return ECEntryIt->second;
3557 VectorParts SrcMask = createBlockInMask(Src);
3559 // The terminator has to be a branch inst!
3560 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3561 assert(BI && "Unexpected terminator found");
3563 if (BI->isConditional()) {
3564 VectorParts EdgeMask = getVectorValue(BI->getCondition());
3566 if (BI->getSuccessor(0) != Dst)
3567 for (unsigned part = 0; part < UF; ++part)
3568 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3570 for (unsigned part = 0; part < UF; ++part)
3571 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3573 MaskCache[Edge] = EdgeMask;
3577 MaskCache[Edge] = SrcMask;
3581 InnerLoopVectorizer::VectorParts
3582 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3583 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3585 // Loop incoming mask is all-one.
3586 if (OrigLoop->getHeader() == BB) {
3587 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3588 return getVectorValue(C);
3591 // This is the block mask. We OR all incoming edges, and with zero.
3592 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3593 VectorParts BlockMask = getVectorValue(Zero);
3596 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3597 VectorParts EM = createEdgeMask(*it, BB);
3598 for (unsigned part = 0; part < UF; ++part)
3599 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3605 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3606 InnerLoopVectorizer::VectorParts &Entry,
3607 unsigned UF, unsigned VF, PhiVector *PV) {
3608 PHINode* P = cast<PHINode>(PN);
3609 // Handle reduction variables:
3610 if (Legal->getReductionVars()->count(P)) {
3611 for (unsigned part = 0; part < UF; ++part) {
3612 // This is phase one of vectorizing PHIs.
3613 Type *VecTy = (VF == 1) ? PN->getType() :
3614 VectorType::get(PN->getType(), VF);
3615 Entry[part] = PHINode::Create(
3616 VecTy, 2, "vec.phi", &*LoopVectorBody.back()->getFirstInsertionPt());
3622 setDebugLocFromInst(Builder, P);
3623 // Check for PHI nodes that are lowered to vector selects.
3624 if (P->getParent() != OrigLoop->getHeader()) {
3625 // We know that all PHIs in non-header blocks are converted into
3626 // selects, so we don't have to worry about the insertion order and we
3627 // can just use the builder.
3628 // At this point we generate the predication tree. There may be
3629 // duplications since this is a simple recursive scan, but future
3630 // optimizations will clean it up.
3632 unsigned NumIncoming = P->getNumIncomingValues();
3634 // Generate a sequence of selects of the form:
3635 // SELECT(Mask3, In3,
3636 // SELECT(Mask2, In2,
3638 for (unsigned In = 0; In < NumIncoming; In++) {
3639 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3641 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3643 for (unsigned part = 0; part < UF; ++part) {
3644 // We might have single edge PHIs (blocks) - use an identity
3645 // 'select' for the first PHI operand.
3647 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3650 // Select between the current value and the previous incoming edge
3651 // based on the incoming mask.
3652 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3653 Entry[part], "predphi");
3659 // This PHINode must be an induction variable.
3660 // Make sure that we know about it.
3661 assert(Legal->getInductionVars()->count(P) &&
3662 "Not an induction variable");
3664 InductionDescriptor II = Legal->getInductionVars()->lookup(P);
3666 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3667 // which can be found from the original scalar operations.
3668 switch (II.getKind()) {
3669 case InductionDescriptor::IK_NoInduction:
3670 llvm_unreachable("Unknown induction");
3671 case InductionDescriptor::IK_IntInduction: {
3672 assert(P->getType() == II.getStartValue()->getType() && "Types must match");
3673 // Handle other induction variables that are now based on the
3675 Value *V = Induction;
3676 if (P != OldInduction) {
3677 V = Builder.CreateSExtOrTrunc(Induction, P->getType());
3678 V = II.transform(Builder, V);
3679 V->setName("offset.idx");
3681 Value *Broadcasted = getBroadcastInstrs(V);
3682 // After broadcasting the induction variable we need to make the vector
3683 // consecutive by adding 0, 1, 2, etc.
3684 for (unsigned part = 0; part < UF; ++part)
3685 Entry[part] = getStepVector(Broadcasted, VF * part, II.getStepValue());
3688 case InductionDescriptor::IK_PtrInduction:
3689 // Handle the pointer induction variable case.
3690 assert(P->getType()->isPointerTy() && "Unexpected type.");
3691 // This is the normalized GEP that starts counting at zero.
3692 Value *PtrInd = Induction;
3693 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStepValue()->getType());
3694 // This is the vector of results. Notice that we don't generate
3695 // vector geps because scalar geps result in better code.
3696 for (unsigned part = 0; part < UF; ++part) {
3698 int EltIndex = part;
3699 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3700 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3701 Value *SclrGep = II.transform(Builder, GlobalIdx);
3702 SclrGep->setName("next.gep");
3703 Entry[part] = SclrGep;
3707 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3708 for (unsigned int i = 0; i < VF; ++i) {
3709 int EltIndex = i + part * VF;
3710 Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
3711 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
3712 Value *SclrGep = II.transform(Builder, GlobalIdx);
3713 SclrGep->setName("next.gep");
3714 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3715 Builder.getInt32(i),
3718 Entry[part] = VecVal;
3724 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3725 // For each instruction in the old loop.
3726 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3727 VectorParts &Entry = WidenMap.get(&*it);
3729 switch (it->getOpcode()) {
3730 case Instruction::Br:
3731 // Nothing to do for PHIs and BR, since we already took care of the
3732 // loop control flow instructions.
3734 case Instruction::PHI: {
3735 // Vectorize PHINodes.
3736 widenPHIInstruction(&*it, Entry, UF, VF, PV);
3740 case Instruction::Add:
3741 case Instruction::FAdd:
3742 case Instruction::Sub:
3743 case Instruction::FSub:
3744 case Instruction::Mul:
3745 case Instruction::FMul:
3746 case Instruction::UDiv:
3747 case Instruction::SDiv:
3748 case Instruction::FDiv:
3749 case Instruction::URem:
3750 case Instruction::SRem:
3751 case Instruction::FRem:
3752 case Instruction::Shl:
3753 case Instruction::LShr:
3754 case Instruction::AShr:
3755 case Instruction::And:
3756 case Instruction::Or:
3757 case Instruction::Xor: {
3758 // Just widen binops.
3759 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3760 setDebugLocFromInst(Builder, BinOp);
3761 VectorParts &A = getVectorValue(it->getOperand(0));
3762 VectorParts &B = getVectorValue(it->getOperand(1));
3764 // Use this vector value for all users of the original instruction.
3765 for (unsigned Part = 0; Part < UF; ++Part) {
3766 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3768 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3769 VecOp->copyIRFlags(BinOp);
3774 propagateMetadata(Entry, &*it);
3777 case Instruction::Select: {
3779 // If the selector is loop invariant we can create a select
3780 // instruction with a scalar condition. Otherwise, use vector-select.
3781 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3783 setDebugLocFromInst(Builder, &*it);
3785 // The condition can be loop invariant but still defined inside the
3786 // loop. This means that we can't just use the original 'cond' value.
3787 // We have to take the 'vectorized' value and pick the first lane.
3788 // Instcombine will make this a no-op.
3789 VectorParts &Cond = getVectorValue(it->getOperand(0));
3790 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3791 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3793 Value *ScalarCond = (VF == 1) ? Cond[0] :
3794 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3796 for (unsigned Part = 0; Part < UF; ++Part) {
3797 Entry[Part] = Builder.CreateSelect(
3798 InvariantCond ? ScalarCond : Cond[Part],
3803 propagateMetadata(Entry, &*it);
3807 case Instruction::ICmp:
3808 case Instruction::FCmp: {
3809 // Widen compares. Generate vector compares.
3810 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3811 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3812 setDebugLocFromInst(Builder, &*it);
3813 VectorParts &A = getVectorValue(it->getOperand(0));
3814 VectorParts &B = getVectorValue(it->getOperand(1));
3815 for (unsigned Part = 0; Part < UF; ++Part) {
3818 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3819 cast<FCmpInst>(C)->copyFastMathFlags(&*it);
3821 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3826 propagateMetadata(Entry, &*it);
3830 case Instruction::Store:
3831 case Instruction::Load:
3832 vectorizeMemoryInstruction(&*it);
3834 case Instruction::ZExt:
3835 case Instruction::SExt:
3836 case Instruction::FPToUI:
3837 case Instruction::FPToSI:
3838 case Instruction::FPExt:
3839 case Instruction::PtrToInt:
3840 case Instruction::IntToPtr:
3841 case Instruction::SIToFP:
3842 case Instruction::UIToFP:
3843 case Instruction::Trunc:
3844 case Instruction::FPTrunc:
3845 case Instruction::BitCast: {
3846 CastInst *CI = dyn_cast<CastInst>(it);
3847 setDebugLocFromInst(Builder, &*it);
3848 /// Optimize the special case where the source is the induction
3849 /// variable. Notice that we can only optimize the 'trunc' case
3850 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3851 /// c. other casts depend on pointer size.
3852 if (CI->getOperand(0) == OldInduction &&
3853 it->getOpcode() == Instruction::Trunc) {
3854 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3856 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3857 InductionDescriptor II = Legal->getInductionVars()->lookup(OldInduction);
3859 ConstantInt::getSigned(CI->getType(), II.getStepValue()->getSExtValue());
3860 for (unsigned Part = 0; Part < UF; ++Part)
3861 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3862 propagateMetadata(Entry, &*it);
3865 /// Vectorize casts.
3866 Type *DestTy = (VF == 1) ? CI->getType() :
3867 VectorType::get(CI->getType(), VF);
3869 VectorParts &A = getVectorValue(it->getOperand(0));
3870 for (unsigned Part = 0; Part < UF; ++Part)
3871 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3872 propagateMetadata(Entry, &*it);
3876 case Instruction::Call: {
3877 // Ignore dbg intrinsics.
3878 if (isa<DbgInfoIntrinsic>(it))
3880 setDebugLocFromInst(Builder, &*it);
3882 Module *M = BB->getParent()->getParent();
3883 CallInst *CI = cast<CallInst>(it);
3885 StringRef FnName = CI->getCalledFunction()->getName();
3886 Function *F = CI->getCalledFunction();
3887 Type *RetTy = ToVectorTy(CI->getType(), VF);
3888 SmallVector<Type *, 4> Tys;
3889 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3890 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3892 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3894 (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
3895 ID == Intrinsic::lifetime_start)) {
3896 scalarizeInstruction(&*it);
3899 // The flag shows whether we use Intrinsic or a usual Call for vectorized
3900 // version of the instruction.
3901 // Is it beneficial to perform intrinsic call compared to lib call?
3902 bool NeedToScalarize;
3903 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
3904 bool UseVectorIntrinsic =
3905 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
3906 if (!UseVectorIntrinsic && NeedToScalarize) {
3907 scalarizeInstruction(&*it);
3911 for (unsigned Part = 0; Part < UF; ++Part) {
3912 SmallVector<Value *, 4> Args;
3913 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3914 Value *Arg = CI->getArgOperand(i);
3915 // Some intrinsics have a scalar argument - don't replace it with a
3917 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
3918 VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
3919 Arg = VectorArg[Part];
3921 Args.push_back(Arg);
3925 if (UseVectorIntrinsic) {
3926 // Use vector version of the intrinsic.
3927 Type *TysForDecl[] = {CI->getType()};
3929 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3930 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
3932 // Use vector version of the library call.
3933 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
3934 assert(!VFnName.empty() && "Vector function name is empty.");
3935 VectorF = M->getFunction(VFnName);
3937 // Generate a declaration
3938 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
3940 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
3941 VectorF->copyAttributesFrom(F);
3944 assert(VectorF && "Can't create vector function.");
3945 Entry[Part] = Builder.CreateCall(VectorF, Args);
3948 propagateMetadata(Entry, &*it);
3953 // All other instructions are unsupported. Scalarize them.
3954 scalarizeInstruction(&*it);
3957 }// end of for_each instr.
3960 void InnerLoopVectorizer::updateAnalysis() {
3961 // Forget the original basic block.
3962 SE->forgetLoop(OrigLoop);
3964 // Update the dominator tree information.
3965 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3966 "Entry does not dominate exit.");
3968 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3969 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3970 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3972 // We don't predicate stores by this point, so the vector body should be a
3974 assert(LoopVectorBody.size() == 1 && "Expected single block loop!");
3975 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3977 DT->addNewBlock(LoopMiddleBlock, LoopVectorBody.back());
3978 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3979 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3980 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3982 DEBUG(DT->verifyDomTree());
3985 /// \brief Check whether it is safe to if-convert this phi node.
3987 /// Phi nodes with constant expressions that can trap are not safe to if
3989 static bool canIfConvertPHINodes(BasicBlock *BB) {
3990 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3991 PHINode *Phi = dyn_cast<PHINode>(I);
3994 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3995 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
4002 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
4003 if (!EnableIfConversion) {
4004 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
4008 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
4010 // A list of pointers that we can safely read and write to.
4011 SmallPtrSet<Value *, 8> SafePointes;
4013 // Collect safe addresses.
4014 for (Loop::block_iterator BI = TheLoop->block_begin(),
4015 BE = TheLoop->block_end(); BI != BE; ++BI) {
4016 BasicBlock *BB = *BI;
4018 if (blockNeedsPredication(BB))
4021 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
4022 if (LoadInst *LI = dyn_cast<LoadInst>(I))
4023 SafePointes.insert(LI->getPointerOperand());
4024 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
4025 SafePointes.insert(SI->getPointerOperand());
4029 // Collect the blocks that need predication.
4030 BasicBlock *Header = TheLoop->getHeader();
4031 for (Loop::block_iterator BI = TheLoop->block_begin(),
4032 BE = TheLoop->block_end(); BI != BE; ++BI) {
4033 BasicBlock *BB = *BI;
4035 // We don't support switch statements inside loops.
4036 if (!isa<BranchInst>(BB->getTerminator())) {
4037 emitAnalysis(VectorizationReport(BB->getTerminator())
4038 << "loop contains a switch statement");
4042 // We must be able to predicate all blocks that need to be predicated.
4043 if (blockNeedsPredication(BB)) {
4044 if (!blockCanBePredicated(BB, SafePointes)) {
4045 emitAnalysis(VectorizationReport(BB->getTerminator())
4046 << "control flow cannot be substituted for a select");
4049 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
4050 emitAnalysis(VectorizationReport(BB->getTerminator())
4051 << "control flow cannot be substituted for a select");
4056 // We can if-convert this loop.
4060 bool LoopVectorizationLegality::canVectorize() {
4061 // We must have a loop in canonical form. Loops with indirectbr in them cannot
4062 // be canonicalized.
4063 if (!TheLoop->getLoopPreheader()) {
4065 VectorizationReport() <<
4066 "loop control flow is not understood by vectorizer");
4070 // We can only vectorize innermost loops.
4071 if (!TheLoop->empty()) {
4072 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
4076 // We must have a single backedge.
4077 if (TheLoop->getNumBackEdges() != 1) {
4079 VectorizationReport() <<
4080 "loop control flow is not understood by vectorizer");
4084 // We must have a single exiting block.
4085 if (!TheLoop->getExitingBlock()) {
4087 VectorizationReport() <<
4088 "loop control flow is not understood by vectorizer");
4092 // We only handle bottom-tested loops, i.e. loop in which the condition is
4093 // checked at the end of each iteration. With that we can assume that all
4094 // instructions in the loop are executed the same number of times.
4095 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
4097 VectorizationReport() <<
4098 "loop control flow is not understood by vectorizer");
4102 // We need to have a loop header.
4103 DEBUG(dbgs() << "LV: Found a loop: " <<
4104 TheLoop->getHeader()->getName() << '\n');
4106 // Check if we can if-convert non-single-bb loops.
4107 unsigned NumBlocks = TheLoop->getNumBlocks();
4108 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
4109 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
4113 // ScalarEvolution needs to be able to find the exit count.
4114 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
4115 if (ExitCount == SE->getCouldNotCompute()) {
4116 emitAnalysis(VectorizationReport() <<
4117 "could not determine number of loop iterations");
4118 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
4122 // Check if we can vectorize the instructions and CFG in this loop.
4123 if (!canVectorizeInstrs()) {
4124 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
4128 // Go over each instruction and look at memory deps.
4129 if (!canVectorizeMemory()) {
4130 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
4134 // Collect all of the variables that remain uniform after vectorization.
4135 collectLoopUniforms();
4137 DEBUG(dbgs() << "LV: We can vectorize this loop"
4138 << (LAI->getRuntimePointerChecking()->Need
4139 ? " (with a runtime bound check)"
4143 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
4145 // If an override option has been passed in for interleaved accesses, use it.
4146 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
4147 UseInterleaved = EnableInterleavedMemAccesses;
4149 // Analyze interleaved memory accesses.
4151 InterleaveInfo.analyzeInterleaving(Strides);
4153 unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
4154 if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
4155 SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
4157 if (Preds.getComplexity() > SCEVThreshold) {
4158 emitAnalysis(VectorizationReport()
4159 << "Too many SCEV assumptions need to be made and checked "
4161 DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
4165 // Okay! We can vectorize. At this point we don't have any other mem analysis
4166 // which may limit our maximum vectorization factor, so just return true with
4171 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
4172 if (Ty->isPointerTy())
4173 return DL.getIntPtrType(Ty);
4175 // It is possible that char's or short's overflow when we ask for the loop's
4176 // trip count, work around this by changing the type size.
4177 if (Ty->getScalarSizeInBits() < 32)
4178 return Type::getInt32Ty(Ty->getContext());
4183 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4184 Ty0 = convertPointerToIntegerType(DL, Ty0);
4185 Ty1 = convertPointerToIntegerType(DL, Ty1);
4186 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4191 /// \brief Check that the instruction has outside loop users and is not an
4192 /// identified reduction variable.
4193 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
4194 SmallPtrSetImpl<Value *> &Reductions) {
4195 // Reduction instructions are allowed to have exit users. All other
4196 // instructions must not have external users.
4197 if (!Reductions.count(Inst))
4198 //Check that all of the users of the loop are inside the BB.
4199 for (User *U : Inst->users()) {
4200 Instruction *UI = cast<Instruction>(U);
4201 // This user may be a reduction exit value.
4202 if (!TheLoop->contains(UI)) {
4203 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
4210 bool LoopVectorizationLegality::canVectorizeInstrs() {
4211 BasicBlock *Header = TheLoop->getHeader();
4213 // Look for the attribute signaling the absence of NaNs.
4214 Function &F = *Header->getParent();
4215 const DataLayout &DL = F.getParent()->getDataLayout();
4216 if (F.hasFnAttribute("no-nans-fp-math"))
4218 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
4220 // For each block in the loop.
4221 for (Loop::block_iterator bb = TheLoop->block_begin(),
4222 be = TheLoop->block_end(); bb != be; ++bb) {
4224 // Scan the instructions in the block and look for hazards.
4225 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4228 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
4229 Type *PhiTy = Phi->getType();
4230 // Check that this PHI type is allowed.
4231 if (!PhiTy->isIntegerTy() &&
4232 !PhiTy->isFloatingPointTy() &&
4233 !PhiTy->isPointerTy()) {
4234 emitAnalysis(VectorizationReport(&*it)
4235 << "loop control flow is not understood by vectorizer");
4236 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
4240 // If this PHINode is not in the header block, then we know that we
4241 // can convert it to select during if-conversion. No need to check if
4242 // the PHIs in this block are induction or reduction variables.
4243 if (*bb != Header) {
4244 // Check that this instruction has no outside users or is an
4245 // identified reduction value with an outside user.
4246 if (!hasOutsideLoopUser(TheLoop, &*it, AllowedExit))
4248 emitAnalysis(VectorizationReport(&*it) <<
4249 "value could not be identified as "
4250 "an induction or reduction variable");
4254 // We only allow if-converted PHIs with exactly two incoming values.
4255 if (Phi->getNumIncomingValues() != 2) {
4256 emitAnalysis(VectorizationReport(&*it)
4257 << "control flow not understood by vectorizer");
4258 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
4262 InductionDescriptor ID;
4263 if (InductionDescriptor::isInductionPHI(Phi, SE, ID)) {
4264 Inductions[Phi] = ID;
4265 // Get the widest type.
4267 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
4269 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
4271 // Int inductions are special because we only allow one IV.
4272 if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
4273 ID.getStepValue()->isOne() &&
4274 isa<Constant>(ID.getStartValue()) &&
4275 cast<Constant>(ID.getStartValue())->isNullValue()) {
4276 // Use the phi node with the widest type as induction. Use the last
4277 // one if there are multiple (no good reason for doing this other
4278 // than it is expedient). We've checked that it begins at zero and
4279 // steps by one, so this is a canonical induction variable.
4280 if (!Induction || PhiTy == WidestIndTy)
4284 DEBUG(dbgs() << "LV: Found an induction variable.\n");
4286 // Until we explicitly handle the case of an induction variable with
4287 // an outside loop user we have to give up vectorizing this loop.
4288 if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
4289 emitAnalysis(VectorizationReport(&*it) <<
4290 "use of induction value outside of the "
4291 "loop is not handled by vectorizer");
4298 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop,
4300 if (Reductions[Phi].hasUnsafeAlgebra())
4301 Requirements->addUnsafeAlgebraInst(
4302 Reductions[Phi].getUnsafeAlgebraInst());
4303 AllowedExit.insert(Reductions[Phi].getLoopExitInstr());
4307 emitAnalysis(VectorizationReport(&*it) <<
4308 "value that could not be identified as "
4309 "reduction is used outside the loop");
4310 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
4312 }// end of PHI handling
4314 // We handle calls that:
4315 // * Are debug info intrinsics.
4316 // * Have a mapping to an IR intrinsic.
4317 // * Have a vector version available.
4318 CallInst *CI = dyn_cast<CallInst>(it);
4319 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI) &&
4320 !(CI->getCalledFunction() && TLI &&
4321 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
4322 emitAnalysis(VectorizationReport(&*it)
4323 << "call instruction cannot be vectorized");
4324 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
4328 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
4329 // second argument is the same (i.e. loop invariant)
4331 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
4332 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
4333 emitAnalysis(VectorizationReport(&*it)
4334 << "intrinsic instruction cannot be vectorized");
4335 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
4340 // Check that the instruction return type is vectorizable.
4341 // Also, we can't vectorize extractelement instructions.
4342 if ((!VectorType::isValidElementType(it->getType()) &&
4343 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
4344 emitAnalysis(VectorizationReport(&*it)
4345 << "instruction return type cannot be vectorized");
4346 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
4350 // Check that the stored type is vectorizable.
4351 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
4352 Type *T = ST->getValueOperand()->getType();
4353 if (!VectorType::isValidElementType(T)) {
4354 emitAnalysis(VectorizationReport(ST) <<
4355 "store instruction cannot be vectorized");
4358 if (EnableMemAccessVersioning)
4359 collectStridedAccess(ST);
4362 if (EnableMemAccessVersioning)
4363 if (LoadInst *LI = dyn_cast<LoadInst>(it))
4364 collectStridedAccess(LI);
4366 // Reduction instructions are allowed to have exit users.
4367 // All other instructions must not have external users.
4368 if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
4369 emitAnalysis(VectorizationReport(&*it) <<
4370 "value cannot be used outside the loop");
4379 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
4380 if (Inductions.empty()) {
4381 emitAnalysis(VectorizationReport()
4382 << "loop induction variable could not be identified");
4387 // Now we know the widest induction type, check if our found induction
4388 // is the same size. If it's not, unset it here and InnerLoopVectorizer
4389 // will create another.
4390 if (Induction && WidestIndTy != Induction->getType())
4391 Induction = nullptr;
4396 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
4397 Value *Ptr = nullptr;
4398 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
4399 Ptr = LI->getPointerOperand();
4400 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
4401 Ptr = SI->getPointerOperand();
4405 Value *Stride = getStrideFromPointer(Ptr, SE, TheLoop);
4409 DEBUG(dbgs() << "LV: Found a strided access that we can version");
4410 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
4411 Strides[Ptr] = Stride;
4412 StrideSet.insert(Stride);
4415 void LoopVectorizationLegality::collectLoopUniforms() {
4416 // We now know that the loop is vectorizable!
4417 // Collect variables that will remain uniform after vectorization.
4418 std::vector<Value*> Worklist;
4419 BasicBlock *Latch = TheLoop->getLoopLatch();
4421 // Start with the conditional branch and walk up the block.
4422 Worklist.push_back(Latch->getTerminator()->getOperand(0));
4424 // Also add all consecutive pointer values; these values will be uniform
4425 // after vectorization (and subsequent cleanup) and, until revectorization is
4426 // supported, all dependencies must also be uniform.
4427 for (Loop::block_iterator B = TheLoop->block_begin(),
4428 BE = TheLoop->block_end(); B != BE; ++B)
4429 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
4431 if (I->getType()->isPointerTy() && isConsecutivePtr(&*I))
4432 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4434 while (!Worklist.empty()) {
4435 Instruction *I = dyn_cast<Instruction>(Worklist.back());
4436 Worklist.pop_back();
4438 // Look at instructions inside this loop.
4439 // Stop when reaching PHI nodes.
4440 // TODO: we need to follow values all over the loop, not only in this block.
4441 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
4444 // This is a known uniform.
4447 // Insert all operands.
4448 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4452 bool LoopVectorizationLegality::canVectorizeMemory() {
4453 LAI = &LAA->getInfo(TheLoop, Strides);
4454 auto &OptionalReport = LAI->getReport();
4456 emitAnalysis(VectorizationReport(*OptionalReport));
4457 if (!LAI->canVectorizeMemory())
4460 if (LAI->hasStoreToLoopInvariantAddress()) {
4462 VectorizationReport()
4463 << "write to a loop invariant address could not be vectorized");
4464 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4468 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
4469 Preds.add(&LAI->Preds);
4474 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4475 Value *In0 = const_cast<Value*>(V);
4476 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4480 return Inductions.count(PN);
4483 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4484 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4487 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4488 SmallPtrSetImpl<Value *> &SafePtrs) {
4490 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4491 // Check that we don't have a constant expression that can trap as operand.
4492 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4494 if (Constant *C = dyn_cast<Constant>(*OI))
4498 // We might be able to hoist the load.
4499 if (it->mayReadFromMemory()) {
4500 LoadInst *LI = dyn_cast<LoadInst>(it);
4503 if (!SafePtrs.count(LI->getPointerOperand())) {
4504 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4505 MaskedOp.insert(LI);
4512 // We don't predicate stores at the moment.
4513 if (it->mayWriteToMemory()) {
4514 StoreInst *SI = dyn_cast<StoreInst>(it);
4515 // We only support predication of stores in basic blocks with one
4520 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4521 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4523 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4524 !isSinglePredecessor) {
4525 // Build a masked store if it is legal for the target, otherwise scalarize
4527 bool isLegalMaskedOp =
4528 isLegalMaskedStore(SI->getValueOperand()->getType(),
4529 SI->getPointerOperand());
4530 if (isLegalMaskedOp) {
4532 MaskedOp.insert(SI);
4541 // The instructions below can trap.
4542 switch (it->getOpcode()) {
4544 case Instruction::UDiv:
4545 case Instruction::SDiv:
4546 case Instruction::URem:
4547 case Instruction::SRem:
4555 void InterleavedAccessInfo::collectConstStridedAccesses(
4556 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
4557 const ValueToValueMap &Strides) {
4558 // Holds load/store instructions in program order.
4559 SmallVector<Instruction *, 16> AccessList;
4561 for (auto *BB : TheLoop->getBlocks()) {
4562 bool IsPred = LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4564 for (auto &I : *BB) {
4565 if (!isa<LoadInst>(&I) && !isa<StoreInst>(&I))
4567 // FIXME: Currently we can't handle mixed accesses and predicated accesses
4571 AccessList.push_back(&I);
4575 if (AccessList.empty())
4578 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4579 for (auto I : AccessList) {
4580 LoadInst *LI = dyn_cast<LoadInst>(I);
4581 StoreInst *SI = dyn_cast<StoreInst>(I);
4583 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
4584 int Stride = isStridedPtr(SE, Ptr, TheLoop, Strides, Preds);
4586 // The factor of the corresponding interleave group.
4587 unsigned Factor = std::abs(Stride);
4589 // Ignore the access if the factor is too small or too large.
4590 if (Factor < 2 || Factor > MaxInterleaveGroupFactor)
4593 const SCEV *Scev = replaceSymbolicStrideSCEV(SE, Strides, Preds, Ptr);
4594 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4595 unsigned Size = DL.getTypeAllocSize(PtrTy->getElementType());
4597 // An alignment of 0 means target ABI alignment.
4598 unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
4600 Align = DL.getABITypeAlignment(PtrTy->getElementType());
4602 StrideAccesses[I] = StrideDescriptor(Stride, Scev, Size, Align);
4606 // Analyze interleaved accesses and collect them into interleave groups.
4608 // Notice that the vectorization on interleaved groups will change instruction
4609 // orders and may break dependences. But the memory dependence check guarantees
4610 // that there is no overlap between two pointers of different strides, element
4611 // sizes or underlying bases.
4613 // For pointers sharing the same stride, element size and underlying base, no
4614 // need to worry about Read-After-Write dependences and Write-After-Read
4617 // E.g. The RAW dependence: A[i] = a;
4619 // This won't exist as it is a store-load forwarding conflict, which has
4620 // already been checked and forbidden in the dependence check.
4622 // E.g. The WAR dependence: a = A[i]; // (1)
4624 // The store group of (2) is always inserted at or below (2), and the load group
4625 // of (1) is always inserted at or above (1). The dependence is safe.
4626 void InterleavedAccessInfo::analyzeInterleaving(
4627 const ValueToValueMap &Strides) {
4628 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
4630 // Holds all the stride accesses.
4631 MapVector<Instruction *, StrideDescriptor> StrideAccesses;
4632 collectConstStridedAccesses(StrideAccesses, Strides);
4634 if (StrideAccesses.empty())
4637 // Holds all interleaved store groups temporarily.
4638 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
4640 // Search the load-load/write-write pair B-A in bottom-up order and try to
4641 // insert B into the interleave group of A according to 3 rules:
4642 // 1. A and B have the same stride.
4643 // 2. A and B have the same memory object size.
4644 // 3. B belongs to the group according to the distance.
4646 // The bottom-up order can avoid breaking the Write-After-Write dependences
4647 // between two pointers of the same base.
4648 // E.g. A[i] = a; (1)
4651 // We form the group (2)+(3) in front, so (1) has to form groups with accesses
4652 // above (1), which guarantees that (1) is always above (2).
4653 for (auto I = StrideAccesses.rbegin(), E = StrideAccesses.rend(); I != E;
4655 Instruction *A = I->first;
4656 StrideDescriptor DesA = I->second;
4658 InterleaveGroup *Group = getInterleaveGroup(A);
4660 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
4661 Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
4664 if (A->mayWriteToMemory())
4665 StoreGroups.insert(Group);
4667 for (auto II = std::next(I); II != E; ++II) {
4668 Instruction *B = II->first;
4669 StrideDescriptor DesB = II->second;
4671 // Ignore if B is already in a group or B is a different memory operation.
4672 if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
4675 // Check the rule 1 and 2.
4676 if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
4679 // Calculate the distance and prepare for the rule 3.
4680 const SCEVConstant *DistToA =
4681 dyn_cast<SCEVConstant>(SE->getMinusSCEV(DesB.Scev, DesA.Scev));
4685 int DistanceToA = DistToA->getValue()->getValue().getSExtValue();
4687 // Skip if the distance is not multiple of size as they are not in the
4689 if (DistanceToA % static_cast<int>(DesA.Size))
4692 // The index of B is the index of A plus the related index to A.
4694 Group->getIndex(A) + DistanceToA / static_cast<int>(DesA.Size);
4696 // Try to insert B into the group.
4697 if (Group->insertMember(B, IndexB, DesB.Align)) {
4698 DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
4699 << " into the interleave group with" << *A << '\n');
4700 InterleaveGroupMap[B] = Group;
4702 // Set the first load in program order as the insert position.
4703 if (B->mayReadFromMemory())
4704 Group->setInsertPos(B);
4706 } // Iteration on instruction B
4707 } // Iteration on instruction A
4709 // Remove interleaved store groups with gaps.
4710 for (InterleaveGroup *Group : StoreGroups)
4711 if (Group->getNumMembers() != Group->getFactor())
4712 releaseGroup(Group);
4715 LoopVectorizationCostModel::VectorizationFactor
4716 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4717 // Width 1 means no vectorize
4718 VectorizationFactor Factor = { 1U, 0U };
4719 if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
4720 emitAnalysis(VectorizationReport() <<
4721 "runtime pointer checks needed. Enable vectorization of this "
4722 "loop with '#pragma clang loop vectorize(enable)' when "
4723 "compiling with -Os/-Oz");
4725 "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
4729 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4730 emitAnalysis(VectorizationReport() <<
4731 "store that is conditionally executed prevents vectorization");
4732 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4736 // Find the trip count.
4737 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4738 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4740 MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
4741 unsigned SmallestType, WidestType;
4742 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
4743 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4744 unsigned MaxSafeDepDist = -1U;
4745 if (Legal->getMaxSafeDepDistBytes() != -1U)
4746 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4747 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4748 WidestRegister : MaxSafeDepDist);
4749 unsigned MaxVectorSize = WidestRegister / WidestType;
4751 DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / "
4752 << WidestType << " bits.\n");
4753 DEBUG(dbgs() << "LV: The Widest register is: "
4754 << WidestRegister << " bits.\n");
4756 if (MaxVectorSize == 0) {
4757 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4761 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4762 " into one vector!");
4764 unsigned VF = MaxVectorSize;
4765 if (MaximizeBandwidth && !OptForSize) {
4766 // Collect all viable vectorization factors.
4767 SmallVector<unsigned, 8> VFs;
4768 unsigned NewMaxVectorSize = WidestRegister / SmallestType;
4769 for (unsigned VS = MaxVectorSize; VS <= NewMaxVectorSize; VS *= 2)
4772 // For each VF calculate its register usage.
4773 auto RUs = calculateRegisterUsage(VFs);
4775 // Select the largest VF which doesn't require more registers than existing
4777 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
4778 for (int i = RUs.size() - 1; i >= 0; --i) {
4779 if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
4786 // If we optimize the program for size, avoid creating the tail loop.
4788 // If we are unable to calculate the trip count then don't try to vectorize.
4791 (VectorizationReport() <<
4792 "unable to calculate the loop count due to complex control flow");
4793 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4797 // Find the maximum SIMD width that can fit within the trip count.
4798 VF = TC % MaxVectorSize;
4803 // If the trip count that we found modulo the vectorization factor is not
4804 // zero then we require a tail.
4805 emitAnalysis(VectorizationReport() <<
4806 "cannot optimize for size and vectorize at the "
4807 "same time. Enable vectorization of this loop "
4808 "with '#pragma clang loop vectorize(enable)' "
4809 "when compiling with -Os/-Oz");
4810 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
4815 int UserVF = Hints->getWidth();
4817 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4818 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4820 Factor.Width = UserVF;
4824 float Cost = expectedCost(1);
4826 const float ScalarCost = Cost;
4829 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4831 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4832 // Ignore scalar width, because the user explicitly wants vectorization.
4833 if (ForceVectorization && VF > 1) {
4835 Cost = expectedCost(Width) / (float)Width;
4838 for (unsigned i=2; i <= VF; i*=2) {
4839 // Notice that the vector loop needs to be executed less times, so
4840 // we need to divide the cost of the vector loops by the width of
4841 // the vector elements.
4842 float VectorCost = expectedCost(i) / (float)i;
4843 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4844 (int)VectorCost << ".\n");
4845 if (VectorCost < Cost) {
4851 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4852 << "LV: Vectorization seems to be not beneficial, "
4853 << "but was forced by a user.\n");
4854 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4855 Factor.Width = Width;
4856 Factor.Cost = Width * Cost;
4860 std::pair<unsigned, unsigned>
4861 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
4862 unsigned MinWidth = -1U;
4863 unsigned MaxWidth = 8;
4864 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4867 for (Loop::block_iterator bb = TheLoop->block_begin(),
4868 be = TheLoop->block_end(); bb != be; ++bb) {
4869 BasicBlock *BB = *bb;
4871 // For each instruction in the loop.
4872 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4873 Type *T = it->getType();
4875 // Skip ignored values.
4876 if (ValuesToIgnore.count(&*it))
4879 // Only examine Loads, Stores and PHINodes.
4880 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4883 // Examine PHI nodes that are reduction variables. Update the type to
4884 // account for the recurrence type.
4885 if (PHINode *PN = dyn_cast<PHINode>(it)) {
4886 if (!Legal->getReductionVars()->count(PN))
4888 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
4889 T = RdxDesc.getRecurrenceType();
4892 // Examine the stored values.
4893 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4894 T = ST->getValueOperand()->getType();
4896 // Ignore loaded pointer types and stored pointer types that are not
4897 // consecutive. However, we do want to take consecutive stores/loads of
4898 // pointer vectors into account.
4899 if (T->isPointerTy() && !isConsecutiveLoadOrStore(&*it))
4902 MinWidth = std::min(MinWidth,
4903 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4904 MaxWidth = std::max(MaxWidth,
4905 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4909 return {MinWidth, MaxWidth};
4912 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
4914 unsigned LoopCost) {
4916 // -- The interleave heuristics --
4917 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4918 // There are many micro-architectural considerations that we can't predict
4919 // at this level. For example, frontend pressure (on decode or fetch) due to
4920 // code size, or the number and capabilities of the execution ports.
4922 // We use the following heuristics to select the interleave count:
4923 // 1. If the code has reductions, then we interleave to break the cross
4924 // iteration dependency.
4925 // 2. If the loop is really small, then we interleave to reduce the loop
4927 // 3. We don't interleave if we think that we will spill registers to memory
4928 // due to the increased register pressure.
4930 // When we optimize for size, we don't interleave.
4934 // We used the distance for the interleave count.
4935 if (Legal->getMaxSafeDepDistBytes() != -1U)
4938 // Do not interleave loops with a relatively small trip count.
4939 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4940 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
4943 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4944 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4948 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4949 TargetNumRegisters = ForceTargetNumScalarRegs;
4951 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4952 TargetNumRegisters = ForceTargetNumVectorRegs;
4955 RegisterUsage R = calculateRegisterUsage({VF})[0];
4956 // We divide by these constants so assume that we have at least one
4957 // instruction that uses at least one register.
4958 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4959 R.NumInstructions = std::max(R.NumInstructions, 1U);
4961 // We calculate the interleave count using the following formula.
4962 // Subtract the number of loop invariants from the number of available
4963 // registers. These registers are used by all of the interleaved instances.
4964 // Next, divide the remaining registers by the number of registers that is
4965 // required by the loop, in order to estimate how many parallel instances
4966 // fit without causing spills. All of this is rounded down if necessary to be
4967 // a power of two. We want power of two interleave count to simplify any
4968 // addressing operations or alignment considerations.
4969 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4972 // Don't count the induction variable as interleaved.
4973 if (EnableIndVarRegisterHeur)
4974 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4975 std::max(1U, (R.MaxLocalUsers - 1)));
4977 // Clamp the interleave ranges to reasonable counts.
4978 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4980 // Check if the user has overridden the max.
4982 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4983 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4985 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4986 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4989 // If we did not calculate the cost for VF (because the user selected the VF)
4990 // then we calculate the cost of VF here.
4992 LoopCost = expectedCost(VF);
4994 // Clamp the calculated IC to be between the 1 and the max interleave count
4995 // that the target allows.
4996 if (IC > MaxInterleaveCount)
4997 IC = MaxInterleaveCount;
5001 // Interleave if we vectorized this loop and there is a reduction that could
5002 // benefit from interleaving.
5003 if (VF > 1 && Legal->getReductionVars()->size()) {
5004 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
5008 // Note that if we've already vectorized the loop we will have done the
5009 // runtime check and so interleaving won't require further checks.
5010 bool InterleavingRequiresRuntimePointerCheck =
5011 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
5013 // We want to interleave small loops in order to reduce the loop overhead and
5014 // potentially expose ILP opportunities.
5015 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5016 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
5017 // We assume that the cost overhead is 1 and we use the cost model
5018 // to estimate the cost of the loop and interleave until the cost of the
5019 // loop overhead is about 5% of the cost of the loop.
5021 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5023 // Interleave until store/load ports (estimated by max interleave count) are
5025 unsigned NumStores = Legal->getNumStores();
5026 unsigned NumLoads = Legal->getNumLoads();
5027 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5028 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5030 // If we have a scalar reduction (vector reductions are already dealt with
5031 // by this point), we can increase the critical path length if the loop
5032 // we're interleaving is inside another loop. Limit, by default to 2, so the
5033 // critical path only gets increased by one reduction operation.
5034 if (Legal->getReductionVars()->size() &&
5035 TheLoop->getLoopDepth() > 1) {
5036 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
5037 SmallIC = std::min(SmallIC, F);
5038 StoresIC = std::min(StoresIC, F);
5039 LoadsIC = std::min(LoadsIC, F);
5042 if (EnableLoadStoreRuntimeInterleave &&
5043 std::max(StoresIC, LoadsIC) > SmallIC) {
5044 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
5045 return std::max(StoresIC, LoadsIC);
5048 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
5052 // Interleave if this is a large loop (small loops are already dealt with by
5054 // point) that could benefit from interleaving.
5055 bool HasReductions = (Legal->getReductionVars()->size() > 0);
5056 if (TTI.enableAggressiveInterleaving(HasReductions)) {
5057 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5061 DEBUG(dbgs() << "LV: Not Interleaving.\n");
5065 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
5066 LoopVectorizationCostModel::calculateRegisterUsage(
5067 const SmallVector<unsigned, 8> &VFs) {
5068 // This function calculates the register usage by measuring the highest number
5069 // of values that are alive at a single location. Obviously, this is a very
5070 // rough estimation. We scan the loop in a topological order in order and
5071 // assign a number to each instruction. We use RPO to ensure that defs are
5072 // met before their users. We assume that each instruction that has in-loop
5073 // users starts an interval. We record every time that an in-loop value is
5074 // used, so we have a list of the first and last occurrences of each
5075 // instruction. Next, we transpose this data structure into a multi map that
5076 // holds the list of intervals that *end* at a specific location. This multi
5077 // map allows us to perform a linear search. We scan the instructions linearly
5078 // and record each time that a new interval starts, by placing it in a set.
5079 // If we find this value in the multi-map then we remove it from the set.
5080 // The max register usage is the maximum size of the set.
5081 // We also search for instructions that are defined outside the loop, but are
5082 // used inside the loop. We need this number separately from the max-interval
5083 // usage number because when we unroll, loop-invariant values do not take
5085 LoopBlocksDFS DFS(TheLoop);
5089 RU.NumInstructions = 0;
5091 // Each 'key' in the map opens a new interval. The values
5092 // of the map are the index of the 'last seen' usage of the
5093 // instruction that is the key.
5094 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5095 // Maps instruction to its index.
5096 DenseMap<unsigned, Instruction*> IdxToInstr;
5097 // Marks the end of each interval.
5098 IntervalMap EndPoint;
5099 // Saves the list of instruction indices that are used in the loop.
5100 SmallSet<Instruction*, 8> Ends;
5101 // Saves the list of values that are used in the loop but are
5102 // defined outside the loop, such as arguments and constants.
5103 SmallPtrSet<Value*, 8> LoopInvariants;
5106 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5107 be = DFS.endRPO(); bb != be; ++bb) {
5108 RU.NumInstructions += (*bb)->size();
5109 for (Instruction &I : **bb) {
5110 IdxToInstr[Index++] = &I;
5112 // Save the end location of each USE.
5113 for (unsigned i = 0; i < I.getNumOperands(); ++i) {
5114 Value *U = I.getOperand(i);
5115 Instruction *Instr = dyn_cast<Instruction>(U);
5117 // Ignore non-instruction values such as arguments, constants, etc.
5118 if (!Instr) continue;
5120 // If this instruction is outside the loop then record it and continue.
5121 if (!TheLoop->contains(Instr)) {
5122 LoopInvariants.insert(Instr);
5126 // Overwrite previous end points.
5127 EndPoint[Instr] = Index;
5133 // Saves the list of intervals that end with the index in 'key'.
5134 typedef SmallVector<Instruction*, 2> InstrList;
5135 DenseMap<unsigned, InstrList> TransposeEnds;
5137 // Transpose the EndPoints to a list of values that end at each index.
5138 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5140 TransposeEnds[it->second].push_back(it->first);
5142 SmallSet<Instruction*, 8> OpenIntervals;
5144 // Get the size of the widest register.
5145 unsigned MaxSafeDepDist = -1U;
5146 if (Legal->getMaxSafeDepDistBytes() != -1U)
5147 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5148 unsigned WidestRegister =
5149 std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
5150 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5152 SmallVector<RegisterUsage, 8> RUs(VFs.size());
5153 SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
5155 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5157 // A lambda that gets the register usage for the given type and VF.
5158 auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
5159 unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
5160 return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
5163 for (unsigned int i = 0; i < Index; ++i) {
5164 Instruction *I = IdxToInstr[i];
5165 // Ignore instructions that are never used within the loop.
5166 if (!Ends.count(I)) continue;
5168 // Skip ignored values.
5169 if (ValuesToIgnore.count(I))
5172 // Remove all of the instructions that end at this location.
5173 InstrList &List = TransposeEnds[i];
5174 for (unsigned int j = 0, e = List.size(); j < e; ++j)
5175 OpenIntervals.erase(List[j]);
5177 // For each VF find the maximum usage of registers.
5178 for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
5180 MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
5184 // Count the number of live interals.
5185 unsigned RegUsage = 0;
5186 for (auto Inst : OpenIntervals)
5187 RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
5188 MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
5191 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
5192 << OpenIntervals.size() << '\n');
5194 // Add the current instruction to the list of open intervals.
5195 OpenIntervals.insert(I);
5198 for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
5199 unsigned Invariant = 0;
5201 Invariant = LoopInvariants.size();
5203 for (auto Inst : LoopInvariants)
5204 Invariant += GetRegUsage(Inst->getType(), VFs[i]);
5207 DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
5208 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
5209 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5210 DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n');
5212 RU.LoopInvariantRegs = Invariant;
5213 RU.MaxLocalUsers = MaxUsages[i];
5220 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5224 for (Loop::block_iterator bb = TheLoop->block_begin(),
5225 be = TheLoop->block_end(); bb != be; ++bb) {
5226 unsigned BlockCost = 0;
5227 BasicBlock *BB = *bb;
5229 // For each instruction in the old loop.
5230 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5231 // Skip dbg intrinsics.
5232 if (isa<DbgInfoIntrinsic>(it))
5235 // Skip ignored values.
5236 if (ValuesToIgnore.count(&*it))
5239 unsigned C = getInstructionCost(&*it, VF);
5241 // Check if we should override the cost.
5242 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5243 C = ForceTargetInstructionCost;
5246 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5247 VF << " For instruction: " << *it << '\n');
5250 // We assume that if-converted blocks have a 50% chance of being executed.
5251 // When the code is scalar then some of the blocks are avoided due to CF.
5252 // When the code is vectorized we execute all code paths.
5253 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5262 /// \brief Check whether the address computation for a non-consecutive memory
5263 /// access looks like an unlikely candidate for being merged into the indexing
5266 /// We look for a GEP which has one index that is an induction variable and all
5267 /// other indices are loop invariant. If the stride of this access is also
5268 /// within a small bound we decide that this address computation can likely be
5269 /// merged into the addressing mode.
5270 /// In all other cases, we identify the address computation as complex.
5271 static bool isLikelyComplexAddressComputation(Value *Ptr,
5272 LoopVectorizationLegality *Legal,
5273 ScalarEvolution *SE,
5274 const Loop *TheLoop) {
5275 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5279 // We are looking for a gep with all loop invariant indices except for one
5280 // which should be an induction variable.
5281 unsigned NumOperands = Gep->getNumOperands();
5282 for (unsigned i = 1; i < NumOperands; ++i) {
5283 Value *Opd = Gep->getOperand(i);
5284 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5285 !Legal->isInductionVariable(Opd))
5289 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5290 // can likely be merged into the address computation.
5291 unsigned MaxMergeDistance = 64;
5293 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5297 // Check the step is constant.
5298 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5299 // Calculate the pointer stride and check if it is consecutive.
5300 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5304 const APInt &APStepVal = C->getValue()->getValue();
5306 // Huge step value - give up.
5307 if (APStepVal.getBitWidth() > 64)
5310 int64_t StepVal = APStepVal.getSExtValue();
5312 return StepVal > MaxMergeDistance;
5315 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5316 return Legal->hasStride(I->getOperand(0)) ||
5317 Legal->hasStride(I->getOperand(1));
5321 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5322 // If we know that this instruction will remain uniform, check the cost of
5323 // the scalar version.
5324 if (Legal->isUniformAfterVectorization(I))
5327 Type *RetTy = I->getType();
5328 if (VF > 1 && MinBWs.count(I))
5329 RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
5330 Type *VectorTy = ToVectorTy(RetTy, VF);
5332 // TODO: We need to estimate the cost of intrinsic calls.
5333 switch (I->getOpcode()) {
5334 case Instruction::GetElementPtr:
5335 // We mark this instruction as zero-cost because the cost of GEPs in
5336 // vectorized code depends on whether the corresponding memory instruction
5337 // is scalarized or not. Therefore, we handle GEPs with the memory
5338 // instruction cost.
5340 case Instruction::Br: {
5341 return TTI.getCFInstrCost(I->getOpcode());
5343 case Instruction::PHI:
5344 //TODO: IF-converted IFs become selects.
5346 case Instruction::Add:
5347 case Instruction::FAdd:
5348 case Instruction::Sub:
5349 case Instruction::FSub:
5350 case Instruction::Mul:
5351 case Instruction::FMul:
5352 case Instruction::UDiv:
5353 case Instruction::SDiv:
5354 case Instruction::FDiv:
5355 case Instruction::URem:
5356 case Instruction::SRem:
5357 case Instruction::FRem:
5358 case Instruction::Shl:
5359 case Instruction::LShr:
5360 case Instruction::AShr:
5361 case Instruction::And:
5362 case Instruction::Or:
5363 case Instruction::Xor: {
5364 // Since we will replace the stride by 1 the multiplication should go away.
5365 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5367 // Certain instructions can be cheaper to vectorize if they have a constant
5368 // second vector operand. One example of this are shifts on x86.
5369 TargetTransformInfo::OperandValueKind Op1VK =
5370 TargetTransformInfo::OK_AnyValue;
5371 TargetTransformInfo::OperandValueKind Op2VK =
5372 TargetTransformInfo::OK_AnyValue;
5373 TargetTransformInfo::OperandValueProperties Op1VP =
5374 TargetTransformInfo::OP_None;
5375 TargetTransformInfo::OperandValueProperties Op2VP =
5376 TargetTransformInfo::OP_None;
5377 Value *Op2 = I->getOperand(1);
5379 // Check for a splat of a constant or for a non uniform vector of constants.
5380 if (isa<ConstantInt>(Op2)) {
5381 ConstantInt *CInt = cast<ConstantInt>(Op2);
5382 if (CInt && CInt->getValue().isPowerOf2())
5383 Op2VP = TargetTransformInfo::OP_PowerOf2;
5384 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5385 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5386 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5387 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
5389 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
5390 if (CInt && CInt->getValue().isPowerOf2())
5391 Op2VP = TargetTransformInfo::OP_PowerOf2;
5392 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5396 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
5399 case Instruction::Select: {
5400 SelectInst *SI = cast<SelectInst>(I);
5401 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5402 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5403 Type *CondTy = SI->getCondition()->getType();
5405 CondTy = VectorType::get(CondTy, VF);
5407 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5409 case Instruction::ICmp:
5410 case Instruction::FCmp: {
5411 Type *ValTy = I->getOperand(0)->getType();
5412 if (VF > 1 && MinBWs.count(dyn_cast<Instruction>(I->getOperand(0))))
5413 ValTy = IntegerType::get(ValTy->getContext(), MinBWs[I]);
5414 VectorTy = ToVectorTy(ValTy, VF);
5415 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5417 case Instruction::Store:
5418 case Instruction::Load: {
5419 StoreInst *SI = dyn_cast<StoreInst>(I);
5420 LoadInst *LI = dyn_cast<LoadInst>(I);
5421 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5423 VectorTy = ToVectorTy(ValTy, VF);
5425 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5426 unsigned AS = SI ? SI->getPointerAddressSpace() :
5427 LI->getPointerAddressSpace();
5428 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5429 // We add the cost of address computation here instead of with the gep
5430 // instruction because only here we know whether the operation is
5433 return TTI.getAddressComputationCost(VectorTy) +
5434 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5436 // For an interleaved access, calculate the total cost of the whole
5437 // interleave group.
5438 if (Legal->isAccessInterleaved(I)) {
5439 auto Group = Legal->getInterleavedAccessGroup(I);
5440 assert(Group && "Fail to get an interleaved access group.");
5442 // Only calculate the cost once at the insert position.
5443 if (Group->getInsertPos() != I)
5446 unsigned InterleaveFactor = Group->getFactor();
5448 VectorType::get(VectorTy->getVectorElementType(),
5449 VectorTy->getVectorNumElements() * InterleaveFactor);
5451 // Holds the indices of existing members in an interleaved load group.
5452 // An interleaved store group doesn't need this as it dones't allow gaps.
5453 SmallVector<unsigned, 4> Indices;
5455 for (unsigned i = 0; i < InterleaveFactor; i++)
5456 if (Group->getMember(i))
5457 Indices.push_back(i);
5460 // Calculate the cost of the whole interleaved group.
5461 unsigned Cost = TTI.getInterleavedMemoryOpCost(
5462 I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5463 Group->getAlignment(), AS);
5465 if (Group->isReverse())
5467 Group->getNumMembers() *
5468 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5470 // FIXME: The interleaved load group with a huge gap could be even more
5471 // expensive than scalar operations. Then we could ignore such group and
5472 // use scalar operations instead.
5476 // Scalarized loads/stores.
5477 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5478 bool Reverse = ConsecutiveStride < 0;
5479 const DataLayout &DL = I->getModule()->getDataLayout();
5480 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
5481 unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
5482 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5483 bool IsComplexComputation =
5484 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5486 // The cost of extracting from the value vector and pointer vector.
5487 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5488 for (unsigned i = 0; i < VF; ++i) {
5489 // The cost of extracting the pointer operand.
5490 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5491 // In case of STORE, the cost of ExtractElement from the vector.
5492 // In case of LOAD, the cost of InsertElement into the returned
5494 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5495 Instruction::InsertElement,
5499 // The cost of the scalar loads/stores.
5500 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5501 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5506 // Wide load/stores.
5507 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5508 if (Legal->isMaskRequired(I))
5509 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
5512 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5515 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5519 case Instruction::ZExt:
5520 case Instruction::SExt:
5521 case Instruction::FPToUI:
5522 case Instruction::FPToSI:
5523 case Instruction::FPExt:
5524 case Instruction::PtrToInt:
5525 case Instruction::IntToPtr:
5526 case Instruction::SIToFP:
5527 case Instruction::UIToFP:
5528 case Instruction::Trunc:
5529 case Instruction::FPTrunc:
5530 case Instruction::BitCast: {
5531 // We optimize the truncation of induction variable.
5532 // The cost of these is the same as the scalar operation.
5533 if (I->getOpcode() == Instruction::Trunc &&
5534 Legal->isInductionVariable(I->getOperand(0)))
5535 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5536 I->getOperand(0)->getType());
5538 Type *SrcScalarTy = I->getOperand(0)->getType();
5539 Type *SrcVecTy = ToVectorTy(SrcScalarTy, VF);
5540 if (VF > 1 && MinBWs.count(I)) {
5541 // This cast is going to be shrunk. This may remove the cast or it might
5542 // turn it into slightly different cast. For example, if MinBW == 16,
5543 // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
5545 // Calculate the modified src and dest types.
5546 Type *MinVecTy = VectorTy;
5547 if (I->getOpcode() == Instruction::Trunc) {
5548 SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
5549 VectorTy = largestIntegerVectorType(ToVectorTy(I->getType(), VF),
5551 } else if (I->getOpcode() == Instruction::ZExt ||
5552 I->getOpcode() == Instruction::SExt) {
5553 SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
5554 VectorTy = smallestIntegerVectorType(ToVectorTy(I->getType(), VF),
5559 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5561 case Instruction::Call: {
5562 bool NeedToScalarize;
5563 CallInst *CI = cast<CallInst>(I);
5564 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
5565 if (getIntrinsicIDForCall(CI, TLI))
5566 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
5570 // We are scalarizing the instruction. Return the cost of the scalar
5571 // instruction, plus the cost of insert and extract into vector
5572 // elements, times the vector width.
5575 if (!RetTy->isVoidTy() && VF != 1) {
5576 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5578 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5581 // The cost of inserting the results plus extracting each one of the
5583 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5586 // The cost of executing VF copies of the scalar instruction. This opcode
5587 // is unknown. Assume that it is the same as 'mul'.
5588 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5594 char LoopVectorize::ID = 0;
5595 static const char lv_name[] = "Loop Vectorization";
5596 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5597 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5598 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
5599 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
5600 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
5601 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5602 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
5603 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5604 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5605 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5606 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5607 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5608 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
5609 INITIALIZE_PASS_DEPENDENCY(DemandedBits)
5610 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5613 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5614 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5618 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5619 // Check for a store.
5620 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5621 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5623 // Check for a load.
5624 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5625 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5631 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5632 bool IfPredicateStore) {
5633 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5634 // Holds vector parameters or scalars, in case of uniform vals.
5635 SmallVector<VectorParts, 4> Params;
5637 setDebugLocFromInst(Builder, Instr);
5639 // Find all of the vectorized parameters.
5640 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5641 Value *SrcOp = Instr->getOperand(op);
5643 // If we are accessing the old induction variable, use the new one.
5644 if (SrcOp == OldInduction) {
5645 Params.push_back(getVectorValue(SrcOp));
5649 // Try using previously calculated values.
5650 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5652 // If the src is an instruction that appeared earlier in the basic block
5653 // then it should already be vectorized.
5654 if (SrcInst && OrigLoop->contains(SrcInst)) {
5655 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5656 // The parameter is a vector value from earlier.
5657 Params.push_back(WidenMap.get(SrcInst));
5659 // The parameter is a scalar from outside the loop. Maybe even a constant.
5660 VectorParts Scalars;
5661 Scalars.append(UF, SrcOp);
5662 Params.push_back(Scalars);
5666 assert(Params.size() == Instr->getNumOperands() &&
5667 "Invalid number of operands");
5669 // Does this instruction return a value ?
5670 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5672 Value *UndefVec = IsVoidRetTy ? nullptr :
5673 UndefValue::get(Instr->getType());
5674 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5675 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5678 if (IfPredicateStore) {
5679 assert(Instr->getParent()->getSinglePredecessor() &&
5680 "Only support single predecessor blocks");
5681 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5682 Instr->getParent());
5685 // For each vector unroll 'part':
5686 for (unsigned Part = 0; Part < UF; ++Part) {
5687 // For each scalar that we create:
5689 // Start an "if (pred) a[i] = ..." block.
5690 Value *Cmp = nullptr;
5691 if (IfPredicateStore) {
5692 if (Cond[Part]->getType()->isVectorTy())
5694 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5695 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5696 ConstantInt::get(Cond[Part]->getType(), 1));
5699 Instruction *Cloned = Instr->clone();
5701 Cloned->setName(Instr->getName() + ".cloned");
5702 // Replace the operands of the cloned instructions with extracted scalars.
5703 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5704 Value *Op = Params[op][Part];
5705 Cloned->setOperand(op, Op);
5708 // Place the cloned scalar in the new loop.
5709 Builder.Insert(Cloned);
5711 // If the original scalar returns a value we need to place it in a vector
5712 // so that future users will be able to use it.
5714 VecResults[Part] = Cloned;
5717 if (IfPredicateStore)
5718 PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
5723 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5724 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5725 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5727 return scalarizeInstruction(Instr, IfPredicateStore);
5730 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5734 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5738 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5739 // When unrolling and the VF is 1, we only need to add a simple scalar.
5740 Type *ITy = Val->getType();
5741 assert(!ITy->isVectorTy() && "Val must be a scalar");
5742 Constant *C = ConstantInt::get(ITy, StartIdx);
5743 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");