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/EquivalenceClasses.h"
52 #include "llvm/ADT/Hashing.h"
53 #include "llvm/ADT/MapVector.h"
54 #include "llvm/ADT/SetVector.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/SmallSet.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/StringExtras.h"
60 #include "llvm/Analysis/AliasAnalysis.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/LoopAccessAnalysis.h"
66 #include "llvm/Analysis/LoopInfo.h"
67 #include "llvm/Analysis/LoopIterator.h"
68 #include "llvm/Analysis/LoopPass.h"
69 #include "llvm/Analysis/ScalarEvolution.h"
70 #include "llvm/Analysis/ScalarEvolutionExpander.h"
71 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
72 #include "llvm/Analysis/TargetTransformInfo.h"
73 #include "llvm/Analysis/ValueTracking.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DebugInfo.h"
77 #include "llvm/IR/DerivedTypes.h"
78 #include "llvm/IR/DiagnosticInfo.h"
79 #include "llvm/IR/Dominators.h"
80 #include "llvm/IR/Function.h"
81 #include "llvm/IR/IRBuilder.h"
82 #include "llvm/IR/Instructions.h"
83 #include "llvm/IR/IntrinsicInst.h"
84 #include "llvm/IR/LLVMContext.h"
85 #include "llvm/IR/Module.h"
86 #include "llvm/IR/PatternMatch.h"
87 #include "llvm/IR/Type.h"
88 #include "llvm/IR/Value.h"
89 #include "llvm/IR/ValueHandle.h"
90 #include "llvm/IR/Verifier.h"
91 #include "llvm/Pass.h"
92 #include "llvm/Support/BranchProbability.h"
93 #include "llvm/Support/CommandLine.h"
94 #include "llvm/Support/Debug.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include "llvm/Transforms/Scalar.h"
97 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
98 #include "llvm/Transforms/Utils/Local.h"
99 #include "llvm/Analysis/VectorUtils.h"
100 #include "llvm/Transforms/Utils/LoopUtils.h"
105 using namespace llvm;
106 using namespace llvm::PatternMatch;
108 #define LV_NAME "loop-vectorize"
109 #define DEBUG_TYPE LV_NAME
111 STATISTIC(LoopsVectorized, "Number of loops vectorized");
112 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
115 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
116 cl::desc("Enable if-conversion during vectorization."));
118 /// We don't vectorize loops with a known constant trip count below this number.
119 static cl::opt<unsigned>
120 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
122 cl::desc("Don't vectorize loops with a constant "
123 "trip count that is smaller than this "
126 /// This enables versioning on the strides of symbolically striding memory
127 /// accesses in code like the following.
128 /// for (i = 0; i < N; ++i)
129 /// A[i * Stride1] += B[i * Stride2] ...
131 /// Will be roughly translated to
132 /// if (Stride1 == 1 && Stride2 == 1) {
133 /// for (i = 0; i < N; i+=4)
137 static cl::opt<bool> EnableMemAccessVersioning(
138 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
139 cl::desc("Enable symblic stride memory access versioning"));
141 static cl::opt<bool> EnableInterleavedMemAccesses(
142 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
143 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
145 /// Maximum factor for an interleaved memory access.
146 static cl::opt<unsigned> MaxInterleaveGroupFactor(
147 "max-interleave-group-factor", cl::Hidden,
148 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
151 /// We don't interleave loops with a known constant trip count below this
153 static const unsigned TinyTripCountInterleaveThreshold = 128;
155 static cl::opt<unsigned> ForceTargetNumScalarRegs(
156 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
157 cl::desc("A flag that overrides the target's number of scalar registers."));
159 static cl::opt<unsigned> ForceTargetNumVectorRegs(
160 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
161 cl::desc("A flag that overrides the target's number of vector registers."));
163 /// Maximum vectorization interleave count.
164 static const unsigned MaxInterleaveFactor = 16;
166 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
167 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
168 cl::desc("A flag that overrides the target's max interleave factor for "
171 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
172 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
173 cl::desc("A flag that overrides the target's max interleave factor for "
174 "vectorized loops."));
176 static cl::opt<unsigned> ForceTargetInstructionCost(
177 "force-target-instruction-cost", cl::init(0), cl::Hidden,
178 cl::desc("A flag that overrides the target's expected cost for "
179 "an instruction to a single constant value. Mostly "
180 "useful for getting consistent testing."));
182 static cl::opt<unsigned> SmallLoopCost(
183 "small-loop-cost", cl::init(20), cl::Hidden,
185 "The cost of a loop that is considered 'small' by the interleaver."));
187 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
188 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
189 cl::desc("Enable the use of the block frequency analysis to access PGO "
190 "heuristics minimizing code growth in cold regions and being more "
191 "aggressive in hot regions."));
193 // Runtime interleave loops for load/store throughput.
194 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
195 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
197 "Enable runtime interleaving until load/store ports are saturated"));
199 /// The number of stores in a loop that are allowed to need predication.
200 static cl::opt<unsigned> NumberOfStoresToPredicate(
201 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
202 cl::desc("Max number of stores to be predicated behind an if."));
204 static cl::opt<bool> EnableIndVarRegisterHeur(
205 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
206 cl::desc("Count the induction variable only once when interleaving"));
208 static cl::opt<bool> EnableCondStoresVectorization(
209 "enable-cond-stores-vec", cl::init(false), cl::Hidden,
210 cl::desc("Enable if predication of stores during vectorization."));
212 static cl::opt<unsigned> MaxNestedScalarReductionIC(
213 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
214 cl::desc("The maximum interleave count to use when interleaving a scalar "
215 "reduction in a nested loop."));
219 // Forward declarations.
220 class LoopVectorizationLegality;
221 class LoopVectorizationCostModel;
222 class LoopVectorizeHints;
223 class LoopVectorizationRequirements;
225 /// \brief This modifies LoopAccessReport to initialize message with
226 /// loop-vectorizer-specific part.
227 class VectorizationReport : public LoopAccessReport {
229 VectorizationReport(Instruction *I = nullptr)
230 : LoopAccessReport("loop not vectorized: ", I) {}
232 /// \brief This allows promotion of the loop-access analysis report into the
233 /// loop-vectorizer report. It modifies the message to add the
234 /// loop-vectorizer-specific part of the message.
235 explicit VectorizationReport(const LoopAccessReport &R)
236 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
240 /// A helper function for converting Scalar types to vector types.
241 /// If the incoming type is void, we return void. If the VF is 1, we return
243 static Type* ToVectorTy(Type *Scalar, unsigned VF) {
244 if (Scalar->isVoidTy() || VF == 1)
246 return VectorType::get(Scalar, VF);
249 /// InnerLoopVectorizer vectorizes loops which contain only one basic
250 /// block to a specified vectorization factor (VF).
251 /// This class performs the widening of scalars into vectors, or multiple
252 /// scalars. This class also implements the following features:
253 /// * It inserts an epilogue loop for handling loops that don't have iteration
254 /// counts that are known to be a multiple of the vectorization factor.
255 /// * It handles the code generation for reduction variables.
256 /// * Scalarization (implementation using scalars) of un-vectorizable
258 /// InnerLoopVectorizer does not perform any vectorization-legality
259 /// checks, and relies on the caller to check for the different legality
260 /// aspects. The InnerLoopVectorizer relies on the
261 /// LoopVectorizationLegality class to provide information about the induction
262 /// and reduction variables that were found to a given vectorization factor.
263 class InnerLoopVectorizer {
265 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
266 DominatorTree *DT, const TargetLibraryInfo *TLI,
267 const TargetTransformInfo *TTI, unsigned VecWidth,
268 unsigned UnrollFactor)
269 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
270 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
271 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
272 Legal(nullptr), AddedSafetyChecks(false) {}
274 // Perform the actual loop widening (vectorization).
275 void vectorize(LoopVectorizationLegality *L) {
277 // Create a new empty loop. Unlink the old loop and connect the new one.
279 // Widen each instruction in the old loop to a new one in the new loop.
280 // Use the Legality module to find the induction and reduction variables.
282 // Register the new loop and update the analysis passes.
286 // Return true if any runtime check is added.
287 bool IsSafetyChecksAdded() {
288 return AddedSafetyChecks;
291 virtual ~InnerLoopVectorizer() {}
294 /// A small list of PHINodes.
295 typedef SmallVector<PHINode*, 4> PhiVector;
296 /// When we unroll loops we have multiple vector values for each scalar.
297 /// This data structure holds the unrolled and vectorized values that
298 /// originated from one scalar instruction.
299 typedef SmallVector<Value*, 2> VectorParts;
301 // When we if-convert we need to create edge masks. We have to cache values
302 // so that we don't end up with exponential recursion/IR.
303 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
304 VectorParts> EdgeMaskCache;
306 /// \brief Add checks for strides that were assumed to be 1.
308 /// Returns the last check instruction and the first check instruction in the
309 /// pair as (first, last).
310 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
312 /// Create an empty loop, based on the loop ranges of the old loop.
313 void createEmptyLoop();
314 /// Copy and widen the instructions from the old loop.
315 virtual void vectorizeLoop();
317 /// \brief The Loop exit block may have single value PHI nodes where the
318 /// incoming value is 'Undef'. While vectorizing we only handled real values
319 /// that were defined inside the loop. Here we fix the 'undef case'.
323 /// A helper function that computes the predicate of the block BB, assuming
324 /// that the header block of the loop is set to True. It returns the *entry*
325 /// mask for the block BB.
326 VectorParts createBlockInMask(BasicBlock *BB);
327 /// A helper function that computes the predicate of the edge between SRC
329 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
331 /// A helper function to vectorize a single BB within the innermost loop.
332 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
334 /// Vectorize a single PHINode in a block. This method handles the induction
335 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
336 /// arbitrary length vectors.
337 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
338 unsigned UF, unsigned VF, PhiVector *PV);
340 /// Insert the new loop to the loop hierarchy and pass manager
341 /// and update the analysis passes.
342 void updateAnalysis();
344 /// This instruction is un-vectorizable. Implement it as a sequence
345 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
346 /// scalarized instruction behind an if block predicated on the control
347 /// dependence of the instruction.
348 virtual void scalarizeInstruction(Instruction *Instr,
349 bool IfPredicateStore=false);
351 /// Vectorize Load and Store instructions,
352 virtual void vectorizeMemoryInstruction(Instruction *Instr);
354 /// Create a broadcast instruction. This method generates a broadcast
355 /// instruction (shuffle) for loop invariant values and for the induction
356 /// value. If this is the induction variable then we extend it to N, N+1, ...
357 /// this is needed because each iteration in the loop corresponds to a SIMD
359 virtual Value *getBroadcastInstrs(Value *V);
361 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
362 /// to each vector element of Val. The sequence starts at StartIndex.
363 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
365 /// When we go over instructions in the basic block we rely on previous
366 /// values within the current basic block or on loop invariant values.
367 /// When we widen (vectorize) values we place them in the map. If the values
368 /// are not within the map, they have to be loop invariant, so we simply
369 /// broadcast them into a vector.
370 VectorParts &getVectorValue(Value *V);
372 /// Try to vectorize the interleaved access group that \p Instr belongs to.
373 void vectorizeInterleaveGroup(Instruction *Instr);
375 /// Generate a shuffle sequence that will reverse the vector Vec.
376 virtual Value *reverseVector(Value *Vec);
378 /// This is a helper class that holds the vectorizer state. It maps scalar
379 /// instructions to vector instructions. When the code is 'unrolled' then
380 /// then a single scalar value is mapped to multiple vector parts. The parts
381 /// are stored in the VectorPart type.
383 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
385 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
387 /// \return True if 'Key' is saved in the Value Map.
388 bool has(Value *Key) const { return MapStorage.count(Key); }
390 /// Initializes a new entry in the map. Sets all of the vector parts to the
391 /// save value in 'Val'.
392 /// \return A reference to a vector with splat values.
393 VectorParts &splat(Value *Key, Value *Val) {
394 VectorParts &Entry = MapStorage[Key];
395 Entry.assign(UF, Val);
399 ///\return A reference to the value that is stored at 'Key'.
400 VectorParts &get(Value *Key) {
401 VectorParts &Entry = MapStorage[Key];
404 assert(Entry.size() == UF);
409 /// The unroll factor. Each entry in the map stores this number of vector
413 /// Map storage. We use std::map and not DenseMap because insertions to a
414 /// dense map invalidates its iterators.
415 std::map<Value *, VectorParts> MapStorage;
418 /// The original loop.
420 /// Scev analysis to use.
428 /// Target Library Info.
429 const TargetLibraryInfo *TLI;
430 /// Target Transform Info.
431 const TargetTransformInfo *TTI;
433 /// The vectorization SIMD factor to use. Each vector will have this many
438 /// The vectorization unroll factor to use. Each scalar is vectorized to this
439 /// many different vector instructions.
442 /// The builder that we use
445 // --- Vectorization state ---
447 /// The vector-loop preheader.
448 BasicBlock *LoopVectorPreHeader;
449 /// The scalar-loop preheader.
450 BasicBlock *LoopScalarPreHeader;
451 /// Middle Block between the vector and the scalar.
452 BasicBlock *LoopMiddleBlock;
453 ///The ExitBlock of the scalar loop.
454 BasicBlock *LoopExitBlock;
455 ///The vector loop body.
456 SmallVector<BasicBlock *, 4> LoopVectorBody;
457 ///The scalar loop body.
458 BasicBlock *LoopScalarBody;
459 /// A list of all bypass blocks. The first block is the entry of the loop.
460 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
462 /// The new Induction variable which was added to the new block.
464 /// The induction variable of the old basic block.
465 PHINode *OldInduction;
466 /// Holds the extended (to the widest induction type) start index.
468 /// Maps scalars to widened vectors.
470 EdgeMaskCache MaskCache;
472 LoopVectorizationLegality *Legal;
474 // Record whether runtime check is added.
475 bool AddedSafetyChecks;
478 class InnerLoopUnroller : public InnerLoopVectorizer {
480 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
481 DominatorTree *DT, const TargetLibraryInfo *TLI,
482 const TargetTransformInfo *TTI, unsigned UnrollFactor)
483 : InnerLoopVectorizer(OrigLoop, SE, LI, DT, TLI, TTI, 1, UnrollFactor) {}
486 void scalarizeInstruction(Instruction *Instr,
487 bool IfPredicateStore = false) override;
488 void vectorizeMemoryInstruction(Instruction *Instr) override;
489 Value *getBroadcastInstrs(Value *V) override;
490 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
491 Value *reverseVector(Value *Vec) override;
494 /// \brief Look for a meaningful debug location on the instruction or it's
496 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
501 if (I->getDebugLoc() != Empty)
504 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
505 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
506 if (OpInst->getDebugLoc() != Empty)
513 /// \brief Set the debug location in the builder using the debug location in the
515 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
516 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
517 B.SetCurrentDebugLocation(Inst->getDebugLoc());
519 B.SetCurrentDebugLocation(DebugLoc());
523 /// \return string containing a file name and a line # for the given loop.
524 static std::string getDebugLocString(const Loop *L) {
527 raw_string_ostream OS(Result);
528 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
529 LoopDbgLoc.print(OS);
531 // Just print the module name.
532 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
539 /// \brief Propagate known metadata from one instruction to another.
540 static void propagateMetadata(Instruction *To, const Instruction *From) {
541 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
542 From->getAllMetadataOtherThanDebugLoc(Metadata);
544 for (auto M : Metadata) {
545 unsigned Kind = M.first;
547 // These are safe to transfer (this is safe for TBAA, even when we
548 // if-convert, because should that metadata have had a control dependency
549 // on the condition, and thus actually aliased with some other
550 // non-speculated memory access when the condition was false, this would be
551 // caught by the runtime overlap checks).
552 if (Kind != LLVMContext::MD_tbaa &&
553 Kind != LLVMContext::MD_alias_scope &&
554 Kind != LLVMContext::MD_noalias &&
555 Kind != LLVMContext::MD_fpmath)
558 To->setMetadata(Kind, M.second);
562 /// \brief Propagate known metadata from one instruction to a vector of others.
563 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
565 if (Instruction *I = dyn_cast<Instruction>(V))
566 propagateMetadata(I, From);
569 /// \brief The group of interleaved loads/stores sharing the same stride and
570 /// close to each other.
572 /// Each member in this group has an index starting from 0, and the largest
573 /// index should be less than interleaved factor, which is equal to the absolute
574 /// value of the access's stride.
576 /// E.g. An interleaved load group of factor 4:
577 /// for (unsigned i = 0; i < 1024; i+=4) {
578 /// a = A[i]; // Member of index 0
579 /// b = A[i+1]; // Member of index 1
580 /// d = A[i+3]; // Member of index 3
584 /// An interleaved store group of factor 4:
585 /// for (unsigned i = 0; i < 1024; i+=4) {
587 /// A[i] = a; // Member of index 0
588 /// A[i+1] = b; // Member of index 1
589 /// A[i+2] = c; // Member of index 2
590 /// A[i+3] = d; // Member of index 3
593 /// Note: the interleaved load group could have gaps (missing members), but
594 /// the interleaved store group doesn't allow gaps.
595 class InterleaveGroup {
597 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
598 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
599 assert(Align && "The alignment should be non-zero");
601 Factor = std::abs(Stride);
602 assert(Factor > 1 && "Invalid interleave factor");
604 Reverse = Stride < 0;
608 bool isReverse() const { return Reverse; }
609 unsigned getFactor() const { return Factor; }
610 unsigned getAlignment() const { return Align; }
611 unsigned getNumMembers() const { return Members.size(); }
613 /// \brief Try to insert a new member \p Instr with index \p Index and
614 /// alignment \p NewAlign. The index is related to the leader and it could be
615 /// negative if it is the new leader.
617 /// \returns false if the instruction doesn't belong to the group.
618 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
619 assert(NewAlign && "The new member's alignment should be non-zero");
621 int Key = Index + SmallestKey;
623 // Skip if there is already a member with the same index.
624 if (Members.count(Key))
627 if (Key > LargestKey) {
628 // The largest index is always less than the interleave factor.
629 if (Index >= static_cast<int>(Factor))
633 } else if (Key < SmallestKey) {
634 // The largest index is always less than the interleave factor.
635 if (LargestKey - Key >= static_cast<int>(Factor))
641 // It's always safe to select the minimum alignment.
642 Align = std::min(Align, NewAlign);
643 Members[Key] = Instr;
647 /// \brief Get the member with the given index \p Index
649 /// \returns nullptr if contains no such member.
650 Instruction *getMember(unsigned Index) const {
651 int Key = SmallestKey + Index;
652 if (!Members.count(Key))
655 return Members.find(Key)->second;
658 /// \brief Get the index for the given member. Unlike the key in the member
659 /// map, the index starts from 0.
660 unsigned getIndex(Instruction *Instr) const {
661 for (auto I : Members)
662 if (I.second == Instr)
663 return I.first - SmallestKey;
665 llvm_unreachable("InterleaveGroup contains no such member");
668 Instruction *getInsertPos() const { return InsertPos; }
669 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
672 unsigned Factor; // Interleave Factor.
675 DenseMap<int, Instruction *> Members;
679 // To avoid breaking dependences, vectorized instructions of an interleave
680 // group should be inserted at either the first load or the last store in
683 // E.g. %even = load i32 // Insert Position
684 // %add = add i32 %even // Use of %even
688 // %odd = add i32 // Def of %odd
689 // store i32 %odd // Insert Position
690 Instruction *InsertPos;
693 /// \brief Drive the analysis of interleaved memory accesses in the loop.
695 /// Use this class to analyze interleaved accesses only when we can vectorize
696 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
697 /// on interleaved accesses is unsafe.
699 /// The analysis collects interleave groups and records the relationships
700 /// between the member and the group in a map.
701 class InterleavedAccessInfo {
703 InterleavedAccessInfo(ScalarEvolution *SE, Loop *L, DominatorTree *DT)
704 : SE(SE), TheLoop(L), DT(DT) {}
706 ~InterleavedAccessInfo() {
707 SmallSet<InterleaveGroup *, 4> DelSet;
708 // Avoid releasing a pointer twice.
709 for (auto &I : InterleaveGroupMap)
710 DelSet.insert(I.second);
711 for (auto *Ptr : DelSet)
715 /// \brief Analyze the interleaved accesses and collect them in interleave
716 /// groups. Substitute symbolic strides using \p Strides.
717 void analyzeInterleaving(const ValueToValueMap &Strides);
719 /// \brief Check if \p Instr belongs to any interleave group.
720 bool isInterleaved(Instruction *Instr) const {
721 return InterleaveGroupMap.count(Instr);
724 /// \brief Get the interleave group that \p Instr belongs to.
726 /// \returns nullptr if doesn't have such group.
727 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
728 if (InterleaveGroupMap.count(Instr))
729 return InterleaveGroupMap.find(Instr)->second;
738 /// Holds the relationships between the members and the interleave group.
739 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
741 /// \brief The descriptor for a strided memory access.
742 struct StrideDescriptor {
743 StrideDescriptor(int Stride, const SCEV *Scev, unsigned Size,
745 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
747 StrideDescriptor() : Stride(0), Scev(nullptr), Size(0), Align(0) {}
749 int Stride; // The access's stride. It is negative for a reverse access.
750 const SCEV *Scev; // The scalar expression of this access
751 unsigned Size; // The size of the memory object.
752 unsigned Align; // The alignment of this access.
755 /// \brief Create a new interleave group with the given instruction \p Instr,
756 /// stride \p Stride and alignment \p Align.
758 /// \returns the newly created interleave group.
759 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
761 assert(!InterleaveGroupMap.count(Instr) &&
762 "Already in an interleaved access group");
763 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
764 return InterleaveGroupMap[Instr];
767 /// \brief Release the group and remove all the relationships.
768 void releaseGroup(InterleaveGroup *Group) {
769 for (unsigned i = 0; i < Group->getFactor(); i++)
770 if (Instruction *Member = Group->getMember(i))
771 InterleaveGroupMap.erase(Member);
776 /// \brief Collect all the accesses with a constant stride in program order.
777 void collectConstStridedAccesses(
778 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
779 const ValueToValueMap &Strides);
782 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
783 /// to what vectorization factor.
784 /// This class does not look at the profitability of vectorization, only the
785 /// legality. This class has two main kinds of checks:
786 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
787 /// will change the order of memory accesses in a way that will change the
788 /// correctness of the program.
789 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
790 /// checks for a number of different conditions, such as the availability of a
791 /// single induction variable, that all types are supported and vectorize-able,
792 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
793 /// This class is also used by InnerLoopVectorizer for identifying
794 /// induction variable and the different reduction variables.
795 class LoopVectorizationLegality {
797 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
798 TargetLibraryInfo *TLI, AliasAnalysis *AA,
799 Function *F, const TargetTransformInfo *TTI,
800 LoopAccessAnalysis *LAA,
801 LoopVectorizationRequirements *R)
802 : NumPredStores(0), TheLoop(L), SE(SE), TLI(TLI), TheFunction(F),
803 TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr), InterleaveInfo(SE, L, DT),
804 Induction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false),
807 /// This enum represents the kinds of inductions that we support.
809 IK_NoInduction, ///< Not an induction variable.
810 IK_IntInduction, ///< Integer induction variable. Step = C.
811 IK_PtrInduction ///< Pointer induction var. Step = C / sizeof(elem).
814 /// A struct for saving information about induction variables.
815 struct InductionInfo {
816 InductionInfo(Value *Start, InductionKind K, ConstantInt *Step)
817 : StartValue(Start), IK(K), StepValue(Step) {
818 assert(IK != IK_NoInduction && "Not an induction");
819 assert(StartValue && "StartValue is null");
820 assert(StepValue && !StepValue->isZero() && "StepValue is zero");
821 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
822 "StartValue is not a pointer for pointer induction");
823 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
824 "StartValue is not an integer for integer induction");
825 assert(StepValue->getType()->isIntegerTy() &&
826 "StepValue is not an integer");
829 : StartValue(nullptr), IK(IK_NoInduction), StepValue(nullptr) {}
831 /// Get the consecutive direction. Returns:
832 /// 0 - unknown or non-consecutive.
833 /// 1 - consecutive and increasing.
834 /// -1 - consecutive and decreasing.
835 int getConsecutiveDirection() const {
836 if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
837 return StepValue->getSExtValue();
841 /// Compute the transformed value of Index at offset StartValue using step
843 /// For integer induction, returns StartValue + Index * StepValue.
844 /// For pointer induction, returns StartValue[Index * StepValue].
845 /// FIXME: The newly created binary instructions should contain nsw/nuw
846 /// flags, which can be found from the original scalar operations.
847 Value *transform(IRBuilder<> &B, Value *Index) const {
849 case IK_IntInduction:
850 assert(Index->getType() == StartValue->getType() &&
851 "Index type does not match StartValue type");
852 if (StepValue->isMinusOne())
853 return B.CreateSub(StartValue, Index);
854 if (!StepValue->isOne())
855 Index = B.CreateMul(Index, StepValue);
856 return B.CreateAdd(StartValue, Index);
858 case IK_PtrInduction:
859 assert(Index->getType() == StepValue->getType() &&
860 "Index type does not match StepValue type");
861 if (StepValue->isMinusOne())
862 Index = B.CreateNeg(Index);
863 else if (!StepValue->isOne())
864 Index = B.CreateMul(Index, StepValue);
865 return B.CreateGEP(nullptr, StartValue, Index);
870 llvm_unreachable("invalid enum");
874 TrackingVH<Value> StartValue;
878 ConstantInt *StepValue;
881 /// ReductionList contains the reduction descriptors for all
882 /// of the reductions that were found in the loop.
883 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
885 /// InductionList saves induction variables and maps them to the
886 /// induction descriptor.
887 typedef MapVector<PHINode*, InductionInfo> InductionList;
889 /// Returns true if it is legal to vectorize this loop.
890 /// This does not mean that it is profitable to vectorize this
891 /// loop, only that it is legal to do so.
894 /// Returns the Induction variable.
895 PHINode *getInduction() { return Induction; }
897 /// Returns the reduction variables found in the loop.
898 ReductionList *getReductionVars() { return &Reductions; }
900 /// Returns the induction variables found in the loop.
901 InductionList *getInductionVars() { return &Inductions; }
903 /// Returns the widest induction type.
904 Type *getWidestInductionType() { return WidestIndTy; }
906 /// Returns True if V is an induction variable in this loop.
907 bool isInductionVariable(const Value *V);
909 /// Return true if the block BB needs to be predicated in order for the loop
910 /// to be vectorized.
911 bool blockNeedsPredication(BasicBlock *BB);
913 /// Check if this pointer is consecutive when vectorizing. This happens
914 /// when the last index of the GEP is the induction variable, or that the
915 /// pointer itself is an induction variable.
916 /// This check allows us to vectorize A[idx] into a wide load/store.
918 /// 0 - Stride is unknown or non-consecutive.
919 /// 1 - Address is consecutive.
920 /// -1 - Address is consecutive, and decreasing.
921 int isConsecutivePtr(Value *Ptr);
923 /// Returns true if the value V is uniform within the loop.
924 bool isUniform(Value *V);
926 /// Returns true if this instruction will remain scalar after vectorization.
927 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
929 /// Returns the information that we collected about runtime memory check.
930 const RuntimePointerChecking *getRuntimePointerChecking() const {
931 return LAI->getRuntimePointerChecking();
934 const LoopAccessInfo *getLAI() const {
938 /// \brief Check if \p Instr belongs to any interleaved access group.
939 bool isAccessInterleaved(Instruction *Instr) {
940 return InterleaveInfo.isInterleaved(Instr);
943 /// \brief Get the interleaved access group that \p Instr belongs to.
944 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
945 return InterleaveInfo.getInterleaveGroup(Instr);
948 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
950 bool hasStride(Value *V) { return StrideSet.count(V); }
951 bool mustCheckStrides() { return !StrideSet.empty(); }
952 SmallPtrSet<Value *, 8>::iterator strides_begin() {
953 return StrideSet.begin();
955 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
957 /// Returns true if the target machine supports masked store operation
958 /// for the given \p DataType and kind of access to \p Ptr.
959 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
960 return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
962 /// Returns true if the target machine supports masked load operation
963 /// for the given \p DataType and kind of access to \p Ptr.
964 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
965 return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
967 /// Returns true if vector representation of the instruction \p I
969 bool isMaskRequired(const Instruction* I) {
970 return (MaskedOp.count(I) != 0);
972 unsigned getNumStores() const {
973 return LAI->getNumStores();
975 unsigned getNumLoads() const {
976 return LAI->getNumLoads();
978 unsigned getNumPredStores() const {
979 return NumPredStores;
982 /// Check if a single basic block loop is vectorizable.
983 /// At this point we know that this is a loop with a constant trip count
984 /// and we only need to check individual instructions.
985 bool canVectorizeInstrs();
987 /// When we vectorize loops we may change the order in which
988 /// we read and write from memory. This method checks if it is
989 /// legal to vectorize the code, considering only memory constrains.
990 /// Returns true if the loop is vectorizable
991 bool canVectorizeMemory();
993 /// Return true if we can vectorize this loop using the IF-conversion
995 bool canVectorizeWithIfConvert();
997 /// Collect the variables that need to stay uniform after vectorization.
998 void collectLoopUniforms();
1000 /// Return true if all of the instructions in the block can be speculatively
1001 /// executed. \p SafePtrs is a list of addresses that are known to be legal
1002 /// and we know that we can read from them without segfault.
1003 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1005 /// Returns the induction kind of Phi and record the step. This function may
1006 /// return NoInduction if the PHI is not an induction variable.
1007 InductionKind isInductionVariable(PHINode *Phi, ConstantInt *&StepValue);
1009 /// \brief Collect memory access with loop invariant strides.
1011 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
1013 void collectStridedAccess(Value *LoadOrStoreInst);
1015 /// Report an analysis message to assist the user in diagnosing loops that are
1016 /// not vectorized. These are handled as LoopAccessReport rather than
1017 /// VectorizationReport because the << operator of VectorizationReport returns
1018 /// LoopAccessReport.
1019 void emitAnalysis(const LoopAccessReport &Message) {
1020 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
1023 unsigned NumPredStores;
1025 /// The loop that we evaluate.
1028 ScalarEvolution *SE;
1029 /// Target Library Info.
1030 TargetLibraryInfo *TLI;
1032 Function *TheFunction;
1033 /// Target Transform Info
1034 const TargetTransformInfo *TTI;
1037 // LoopAccess analysis.
1038 LoopAccessAnalysis *LAA;
1039 // And the loop-accesses info corresponding to this loop. This pointer is
1040 // null until canVectorizeMemory sets it up.
1041 const LoopAccessInfo *LAI;
1043 /// The interleave access information contains groups of interleaved accesses
1044 /// with the same stride and close to each other.
1045 InterleavedAccessInfo InterleaveInfo;
1047 // --- vectorization state --- //
1049 /// Holds the integer induction variable. This is the counter of the
1052 /// Holds the reduction variables.
1053 ReductionList Reductions;
1054 /// Holds all of the induction variables that we found in the loop.
1055 /// Notice that inductions don't need to start at zero and that induction
1056 /// variables can be pointers.
1057 InductionList Inductions;
1058 /// Holds the widest induction type encountered.
1061 /// Allowed outside users. This holds the reduction
1062 /// vars which can be accessed from outside the loop.
1063 SmallPtrSet<Value*, 4> AllowedExit;
1064 /// This set holds the variables which are known to be uniform after
1066 SmallPtrSet<Instruction*, 4> Uniforms;
1068 /// Can we assume the absence of NaNs.
1069 bool HasFunNoNaNAttr;
1071 /// Vectorization requirements that will go through late-evaluation.
1072 LoopVectorizationRequirements *Requirements;
1074 ValueToValueMap Strides;
1075 SmallPtrSet<Value *, 8> StrideSet;
1077 /// While vectorizing these instructions we have to generate a
1078 /// call to the appropriate masked intrinsic
1079 SmallPtrSet<const Instruction*, 8> MaskedOp;
1082 /// LoopVectorizationCostModel - estimates the expected speedups due to
1084 /// In many cases vectorization is not profitable. This can happen because of
1085 /// a number of reasons. In this class we mainly attempt to predict the
1086 /// expected speedup/slowdowns due to the supported instruction set. We use the
1087 /// TargetTransformInfo to query the different backends for the cost of
1088 /// different operations.
1089 class LoopVectorizationCostModel {
1091 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
1092 LoopVectorizationLegality *Legal,
1093 const TargetTransformInfo &TTI,
1094 const TargetLibraryInfo *TLI, AssumptionCache *AC,
1095 const Function *F, const LoopVectorizeHints *Hints)
1096 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI),
1097 TheFunction(F), Hints(Hints) {
1098 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
1101 /// Information about vectorization costs
1102 struct VectorizationFactor {
1103 unsigned Width; // Vector width with best cost
1104 unsigned Cost; // Cost of the loop with that width
1106 /// \return The most profitable vectorization factor and the cost of that VF.
1107 /// This method checks every power of two up to VF. If UserVF is not ZERO
1108 /// then this vectorization factor will be selected if vectorization is
1110 VectorizationFactor selectVectorizationFactor(bool OptForSize);
1112 /// \return The size (in bits) of the widest type in the code that
1113 /// needs to be vectorized. We ignore values that remain scalar such as
1114 /// 64 bit loop indices.
1115 unsigned getWidestType();
1117 /// \return The desired interleave count.
1118 /// If interleave count has been specified by metadata it will be returned.
1119 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1120 /// are the selected vectorization factor and the cost of the selected VF.
1121 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1124 /// \return The most profitable unroll factor.
1125 /// This method finds the best unroll-factor based on register pressure and
1126 /// other parameters. VF and LoopCost are the selected vectorization factor
1127 /// and the cost of the selected VF.
1128 unsigned computeInterleaveCount(bool OptForSize, unsigned VF,
1131 /// \brief A struct that represents some properties of the register usage
1133 struct RegisterUsage {
1134 /// Holds the number of loop invariant values that are used in the loop.
1135 unsigned LoopInvariantRegs;
1136 /// Holds the maximum number of concurrent live intervals in the loop.
1137 unsigned MaxLocalUsers;
1138 /// Holds the number of instructions in the loop.
1139 unsigned NumInstructions;
1142 /// \return information about the register usage of the loop.
1143 RegisterUsage calculateRegisterUsage();
1146 /// Returns the expected execution cost. The unit of the cost does
1147 /// not matter because we use the 'cost' units to compare different
1148 /// vector widths. The cost that is returned is *not* normalized by
1149 /// the factor width.
1150 unsigned expectedCost(unsigned VF);
1152 /// Returns the execution time cost of an instruction for a given vector
1153 /// width. Vector width of one means scalar.
1154 unsigned getInstructionCost(Instruction *I, unsigned VF);
1156 /// Returns whether the instruction is a load or store and will be a emitted
1157 /// as a vector operation.
1158 bool isConsecutiveLoadOrStore(Instruction *I);
1160 /// Report an analysis message to assist the user in diagnosing loops that are
1161 /// not vectorized. These are handled as LoopAccessReport rather than
1162 /// VectorizationReport because the << operator of VectorizationReport returns
1163 /// LoopAccessReport.
1164 void emitAnalysis(const LoopAccessReport &Message) {
1165 LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, LV_NAME);
1168 /// Values used only by @llvm.assume calls.
1169 SmallPtrSet<const Value *, 32> EphValues;
1171 /// The loop that we evaluate.
1174 ScalarEvolution *SE;
1175 /// Loop Info analysis.
1177 /// Vectorization legality.
1178 LoopVectorizationLegality *Legal;
1179 /// Vector target information.
1180 const TargetTransformInfo &TTI;
1181 /// Target Library Info.
1182 const TargetLibraryInfo *TLI;
1183 const Function *TheFunction;
1184 // Loop Vectorize Hint.
1185 const LoopVectorizeHints *Hints;
1188 /// Utility class for getting and setting loop vectorizer hints in the form
1189 /// of loop metadata.
1190 /// This class keeps a number of loop annotations locally (as member variables)
1191 /// and can, upon request, write them back as metadata on the loop. It will
1192 /// initially scan the loop for existing metadata, and will update the local
1193 /// values based on information in the loop.
1194 /// We cannot write all values to metadata, as the mere presence of some info,
1195 /// for example 'force', means a decision has been made. So, we need to be
1196 /// careful NOT to add them if the user hasn't specifically asked so.
1197 class LoopVectorizeHints {
1204 /// Hint - associates name and validation with the hint value.
1207 unsigned Value; // This may have to change for non-numeric values.
1210 Hint(const char * Name, unsigned Value, HintKind Kind)
1211 : Name(Name), Value(Value), Kind(Kind) { }
1213 bool validate(unsigned Val) {
1216 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
1218 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1226 /// Vectorization width.
1228 /// Vectorization interleave factor.
1230 /// Vectorization forced
1233 /// Return the loop metadata prefix.
1234 static StringRef Prefix() { return "llvm.loop."; }
1238 FK_Undefined = -1, ///< Not selected.
1239 FK_Disabled = 0, ///< Forcing disabled.
1240 FK_Enabled = 1, ///< Forcing enabled.
1243 LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1244 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
1246 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1247 Force("vectorize.enable", FK_Undefined, HK_FORCE),
1249 // Populate values with existing loop metadata.
1250 getHintsFromMetadata();
1252 // force-vector-interleave overrides DisableInterleaving.
1253 if (VectorizerParams::isInterleaveForced())
1254 Interleave.Value = VectorizerParams::VectorizationInterleave;
1256 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1257 << "LV: Interleaving disabled by the pass manager\n");
1260 /// Mark the loop L as already vectorized by setting the width to 1.
1261 void setAlreadyVectorized() {
1262 Width.Value = Interleave.Value = 1;
1263 Hint Hints[] = {Width, Interleave};
1264 writeHintsToMetadata(Hints);
1267 bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
1268 if (getForce() == LoopVectorizeHints::FK_Disabled) {
1269 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1270 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1271 L->getStartLoc(), emitRemark());
1275 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
1276 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1277 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1278 L->getStartLoc(), emitRemark());
1282 if (getWidth() == 1 && getInterleave() == 1) {
1283 // FIXME: Add a separate metadata to indicate when the loop has already
1284 // been vectorized instead of setting width and count to 1.
1285 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1286 // FIXME: Add interleave.disable metadata. This will allow
1287 // vectorize.disable to be used without disabling the pass and errors
1288 // to differentiate between disabled vectorization and a width of 1.
1289 emitOptimizationRemarkAnalysis(
1290 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1291 "loop not vectorized: vectorization and interleaving are explicitly "
1292 "disabled, or vectorize width and interleave count are both set to "
1300 /// Dumps all the hint information.
1301 std::string emitRemark() const {
1302 VectorizationReport R;
1303 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1304 R << "vectorization is explicitly disabled";
1306 R << "use -Rpass-analysis=loop-vectorize for more info";
1307 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1308 R << " (Force=true";
1309 if (Width.Value != 0)
1310 R << ", Vector Width=" << Width.Value;
1311 if (Interleave.Value != 0)
1312 R << ", Interleave Count=" << Interleave.Value;
1320 unsigned getWidth() const { return Width.Value; }
1321 unsigned getInterleave() const { return Interleave.Value; }
1322 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1325 /// Find hints specified in the loop metadata and update local values.
1326 void getHintsFromMetadata() {
1327 MDNode *LoopID = TheLoop->getLoopID();
1331 // First operand should refer to the loop id itself.
1332 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1333 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1335 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1336 const MDString *S = nullptr;
1337 SmallVector<Metadata *, 4> Args;
1339 // The expected hint is either a MDString or a MDNode with the first
1340 // operand a MDString.
1341 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1342 if (!MD || MD->getNumOperands() == 0)
1344 S = dyn_cast<MDString>(MD->getOperand(0));
1345 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1346 Args.push_back(MD->getOperand(i));
1348 S = dyn_cast<MDString>(LoopID->getOperand(i));
1349 assert(Args.size() == 0 && "too many arguments for MDString");
1355 // Check if the hint starts with the loop metadata prefix.
1356 StringRef Name = S->getString();
1357 if (Args.size() == 1)
1358 setHint(Name, Args[0]);
1362 /// Checks string hint with one operand and set value if valid.
1363 void setHint(StringRef Name, Metadata *Arg) {
1364 if (!Name.startswith(Prefix()))
1366 Name = Name.substr(Prefix().size(), StringRef::npos);
1368 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1370 unsigned Val = C->getZExtValue();
1372 Hint *Hints[] = {&Width, &Interleave, &Force};
1373 for (auto H : Hints) {
1374 if (Name == H->Name) {
1375 if (H->validate(Val))
1378 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1384 /// Create a new hint from name / value pair.
1385 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1386 LLVMContext &Context = TheLoop->getHeader()->getContext();
1387 Metadata *MDs[] = {MDString::get(Context, Name),
1388 ConstantAsMetadata::get(
1389 ConstantInt::get(Type::getInt32Ty(Context), V))};
1390 return MDNode::get(Context, MDs);
1393 /// Matches metadata with hint name.
1394 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1395 MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1399 for (auto H : HintTypes)
1400 if (Name->getString().endswith(H.Name))
1405 /// Sets current hints into loop metadata, keeping other values intact.
1406 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1407 if (HintTypes.size() == 0)
1410 // Reserve the first element to LoopID (see below).
1411 SmallVector<Metadata *, 4> MDs(1);
1412 // If the loop already has metadata, then ignore the existing operands.
1413 MDNode *LoopID = TheLoop->getLoopID();
1415 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1416 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1417 // If node in update list, ignore old value.
1418 if (!matchesHintMetadataName(Node, HintTypes))
1419 MDs.push_back(Node);
1423 // Now, add the missing hints.
1424 for (auto H : HintTypes)
1425 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1427 // Replace current metadata node with new one.
1428 LLVMContext &Context = TheLoop->getHeader()->getContext();
1429 MDNode *NewLoopID = MDNode::get(Context, MDs);
1430 // Set operand 0 to refer to the loop id itself.
1431 NewLoopID->replaceOperandWith(0, NewLoopID);
1433 TheLoop->setLoopID(NewLoopID);
1436 /// The loop these hints belong to.
1437 const Loop *TheLoop;
1440 static void emitMissedWarning(Function *F, Loop *L,
1441 const LoopVectorizeHints &LH) {
1442 emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1443 L->getStartLoc(), LH.emitRemark());
1445 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1446 if (LH.getWidth() != 1)
1447 emitLoopVectorizeWarning(
1448 F->getContext(), *F, L->getStartLoc(),
1449 "failed explicitly specified loop vectorization");
1450 else if (LH.getInterleave() != 1)
1451 emitLoopInterleaveWarning(
1452 F->getContext(), *F, L->getStartLoc(),
1453 "failed explicitly specified loop interleaving");
1457 /// \brief This holds vectorization requirements that must be verified late in
1458 /// the process. The requirements are set by legalize and costmodel. Once
1459 /// vectorization has been determined to be possible and profitable the
1460 /// requirements can be verified by looking for metadata or compiler options.
1461 /// For example, some loops require FP commutativity which is only allowed if
1462 /// vectorization is explicitly specified or if the fast-math compiler option
1463 /// has been provided.
1464 /// Late evaluation of these requirements allows helpful diagnostics to be
1465 /// composed that tells the user what need to be done to vectorize the loop. For
1466 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
1467 /// evaluation should be used only when diagnostics can generated that can be
1468 /// followed by a non-expert user.
1469 class LoopVectorizationRequirements {
1471 LoopVectorizationRequirements()
1472 : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr) {}
1474 void addUnsafeAlgebraInst(Instruction *I) {
1475 // First unsafe algebra instruction.
1476 if (!UnsafeAlgebraInst)
1477 UnsafeAlgebraInst = I;
1480 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
1482 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
1483 bool failed = false;
1485 if (UnsafeAlgebraInst &&
1486 Hints.getForce() == LoopVectorizeHints::FK_Undefined &&
1487 Hints.getWidth() == 0) {
1488 emitOptimizationRemarkAnalysisFPCommute(
1489 F->getContext(), DEBUG_TYPE, *F, UnsafeAlgebraInst->getDebugLoc(),
1490 VectorizationReport() << "vectorization requires changes in the "
1491 "order of operations, however IEEE 754 "
1492 "floating-point operations are not "
1497 if (NumRuntimePointerChecks >
1498 VectorizerParams::RuntimeMemoryCheckThreshold) {
1499 emitOptimizationRemarkAnalysisAliasing(
1500 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1501 VectorizationReport()
1502 << "cannot prove pointers refer to independent arrays in memory. "
1503 "The loop requires "
1504 << NumRuntimePointerChecks
1505 << " runtime independence checks to vectorize the loop, but that "
1506 "would exceed the limit of "
1507 << VectorizerParams::RuntimeMemoryCheckThreshold << " checks");
1508 DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1516 unsigned NumRuntimePointerChecks;
1517 Instruction *UnsafeAlgebraInst;
1520 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1522 return V.push_back(&L);
1524 for (Loop *InnerL : L)
1525 addInnerLoop(*InnerL, V);
1528 /// The LoopVectorize Pass.
1529 struct LoopVectorize : public FunctionPass {
1530 /// Pass identification, replacement for typeid
1533 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1535 DisableUnrolling(NoUnrolling),
1536 AlwaysVectorize(AlwaysVectorize) {
1537 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1540 ScalarEvolution *SE;
1542 TargetTransformInfo *TTI;
1544 BlockFrequencyInfo *BFI;
1545 TargetLibraryInfo *TLI;
1547 AssumptionCache *AC;
1548 LoopAccessAnalysis *LAA;
1549 bool DisableUnrolling;
1550 bool AlwaysVectorize;
1552 BlockFrequency ColdEntryFreq;
1554 bool runOnFunction(Function &F) override {
1555 SE = &getAnalysis<ScalarEvolution>();
1556 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1557 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1558 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1559 BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1560 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1561 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1562 AA = &getAnalysis<AliasAnalysis>();
1563 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1564 LAA = &getAnalysis<LoopAccessAnalysis>();
1566 // Compute some weights outside of the loop over the loops. Compute this
1567 // using a BranchProbability to re-use its scaling math.
1568 const BranchProbability ColdProb(1, 5); // 20%
1569 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1572 // 1. the target claims to have no vector registers, and
1573 // 2. interleaving won't help ILP.
1575 // The second condition is necessary because, even if the target has no
1576 // vector registers, loop vectorization may still enable scalar
1578 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
1581 // Build up a worklist of inner-loops to vectorize. This is necessary as
1582 // the act of vectorizing or partially unrolling a loop creates new loops
1583 // and can invalidate iterators across the loops.
1584 SmallVector<Loop *, 8> Worklist;
1587 addInnerLoop(*L, Worklist);
1589 LoopsAnalyzed += Worklist.size();
1591 // Now walk the identified inner loops.
1592 bool Changed = false;
1593 while (!Worklist.empty())
1594 Changed |= processLoop(Worklist.pop_back_val());
1596 // Process each loop nest in the function.
1600 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
1601 SmallVector<Metadata *, 4> MDs;
1602 // Reserve first location for self reference to the LoopID metadata node.
1603 MDs.push_back(nullptr);
1604 bool IsUnrollMetadata = false;
1605 MDNode *LoopID = L->getLoopID();
1607 // First find existing loop unrolling disable metadata.
1608 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1609 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1611 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1613 S && S->getString().startswith("llvm.loop.unroll.disable");
1615 MDs.push_back(LoopID->getOperand(i));
1619 if (!IsUnrollMetadata) {
1620 // Add runtime unroll disable metadata.
1621 LLVMContext &Context = L->getHeader()->getContext();
1622 SmallVector<Metadata *, 1> DisableOperands;
1623 DisableOperands.push_back(
1624 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
1625 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
1626 MDs.push_back(DisableNode);
1627 MDNode *NewLoopID = MDNode::get(Context, MDs);
1628 // Set operand 0 to refer to the loop id itself.
1629 NewLoopID->replaceOperandWith(0, NewLoopID);
1630 L->setLoopID(NewLoopID);
1634 bool processLoop(Loop *L) {
1635 assert(L->empty() && "Only process inner loops.");
1638 const std::string DebugLocStr = getDebugLocString(L);
1641 DEBUG(dbgs() << "\nLV: Checking a loop in \""
1642 << L->getHeader()->getParent()->getName() << "\" from "
1643 << DebugLocStr << "\n");
1645 LoopVectorizeHints Hints(L, DisableUnrolling);
1647 DEBUG(dbgs() << "LV: Loop hints:"
1649 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1651 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1653 : "?")) << " width=" << Hints.getWidth()
1654 << " unroll=" << Hints.getInterleave() << "\n");
1656 // Function containing loop
1657 Function *F = L->getHeader()->getParent();
1659 // Looking at the diagnostic output is the only way to determine if a loop
1660 // was vectorized (other than looking at the IR or machine code), so it
1661 // is important to generate an optimization remark for each loop. Most of
1662 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1663 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1664 // less verbose reporting vectorized loops and unvectorized loops that may
1665 // benefit from vectorization, respectively.
1667 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
1668 DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
1672 // Check the loop for a trip count threshold:
1673 // do not vectorize loops with a tiny trip count.
1674 const unsigned TC = SE->getSmallConstantTripCount(L);
1675 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1676 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1677 << "This loop is not worth vectorizing.");
1678 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1679 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1681 DEBUG(dbgs() << "\n");
1682 emitOptimizationRemarkAnalysis(
1683 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1684 "vectorization is not beneficial and is not explicitly forced");
1689 // Check if it is legal to vectorize the loop.
1690 LoopVectorizationRequirements Requirements;
1691 LoopVectorizationLegality LVL(L, SE, DT, TLI, AA, F, TTI, LAA,
1693 if (!LVL.canVectorize()) {
1694 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1695 emitMissedWarning(F, L, Hints);
1699 // Use the cost model.
1700 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, TLI, AC, F, &Hints);
1702 // Check the function attributes to find out if this function should be
1703 // optimized for size.
1704 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1705 // FIXME: Use Function::optForSize().
1706 F->hasFnAttribute(Attribute::OptimizeForSize);
1708 // Compute the weighted frequency of this loop being executed and see if it
1709 // is less than 20% of the function entry baseline frequency. Note that we
1710 // always have a canonical loop here because we think we *can* vectoriez.
1711 // FIXME: This is hidden behind a flag due to pervasive problems with
1712 // exactly what block frequency models.
1713 if (LoopVectorizeWithBlockFrequency) {
1714 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1715 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1716 LoopEntryFreq < ColdEntryFreq)
1720 // Check the function attributes to see if implicit floats are allowed.a
1721 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1722 // an integer loop and the vector instructions selected are purely integer
1723 // vector instructions?
1724 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1725 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1726 "attribute is used.\n");
1727 emitOptimizationRemarkAnalysis(
1728 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1729 "loop not vectorized due to NoImplicitFloat attribute");
1730 emitMissedWarning(F, L, Hints);
1734 // Select the optimal vectorization factor.
1735 const LoopVectorizationCostModel::VectorizationFactor VF =
1736 CM.selectVectorizationFactor(OptForSize);
1738 // Select the interleave count.
1739 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
1741 // Get user interleave count.
1742 unsigned UserIC = Hints.getInterleave();
1744 // Identify the diagnostic messages that should be produced.
1745 std::string VecDiagMsg, IntDiagMsg;
1746 bool VectorizeLoop = true, InterleaveLoop = true;
1748 if (Requirements.doesNotMeet(F, L, Hints)) {
1749 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
1751 emitMissedWarning(F, L, Hints);
1755 if (VF.Width == 1) {
1756 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1758 "the cost-model indicates that vectorization is not beneficial";
1759 VectorizeLoop = false;
1762 if (IC == 1 && UserIC <= 1) {
1763 // Tell the user interleaving is not beneficial.
1764 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
1766 "the cost-model indicates that interleaving is not beneficial";
1767 InterleaveLoop = false;
1770 " and is explicitly disabled or interleave count is set to 1";
1771 } else if (IC > 1 && UserIC == 1) {
1772 // Tell the user interleaving is beneficial, but it explicitly disabled.
1774 << "LV: Interleaving is beneficial but is explicitly disabled.");
1775 IntDiagMsg = "the cost-model indicates that interleaving is beneficial "
1776 "but is explicitly disabled or interleave count is set to 1";
1777 InterleaveLoop = false;
1780 // Override IC if user provided an interleave count.
1781 IC = UserIC > 0 ? UserIC : IC;
1783 // Emit diagnostic messages, if any.
1784 if (!VectorizeLoop && !InterleaveLoop) {
1785 // Do not vectorize or interleaving the loop.
1786 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1787 L->getStartLoc(), VecDiagMsg);
1788 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1789 L->getStartLoc(), IntDiagMsg);
1791 } else if (!VectorizeLoop && InterleaveLoop) {
1792 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1793 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1794 L->getStartLoc(), VecDiagMsg);
1795 } else if (VectorizeLoop && !InterleaveLoop) {
1796 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1797 << DebugLocStr << '\n');
1798 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1799 L->getStartLoc(), IntDiagMsg);
1800 } else if (VectorizeLoop && InterleaveLoop) {
1801 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1802 << DebugLocStr << '\n');
1803 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
1806 if (!VectorizeLoop) {
1807 assert(IC > 1 && "interleave count should not be 1 or 0");
1808 // If we decided that it is not legal to vectorize the loop then
1810 InnerLoopUnroller Unroller(L, SE, LI, DT, TLI, TTI, IC);
1811 Unroller.vectorize(&LVL);
1813 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1814 Twine("interleaved loop (interleaved count: ") +
1817 // If we decided that it is *legal* to vectorize the loop then do it.
1818 InnerLoopVectorizer LB(L, SE, LI, DT, TLI, TTI, VF.Width, IC);
1822 // Add metadata to disable runtime unrolling scalar loop when there's no
1823 // runtime check about strides and memory. Because at this situation,
1824 // scalar loop is rarely used not worthy to be unrolled.
1825 if (!LB.IsSafetyChecksAdded())
1826 AddRuntimeUnrollDisableMetaData(L);
1828 // Report the vectorization decision.
1829 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1830 Twine("vectorized loop (vectorization width: ") +
1831 Twine(VF.Width) + ", interleaved count: " +
1835 // Mark the loop as already vectorized to avoid vectorizing again.
1836 Hints.setAlreadyVectorized();
1838 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1842 void getAnalysisUsage(AnalysisUsage &AU) const override {
1843 AU.addRequired<AssumptionCacheTracker>();
1844 AU.addRequiredID(LoopSimplifyID);
1845 AU.addRequiredID(LCSSAID);
1846 AU.addRequired<BlockFrequencyInfoWrapperPass>();
1847 AU.addRequired<DominatorTreeWrapperPass>();
1848 AU.addRequired<LoopInfoWrapperPass>();
1849 AU.addRequired<ScalarEvolution>();
1850 AU.addRequired<TargetTransformInfoWrapperPass>();
1851 AU.addRequired<AliasAnalysis>();
1852 AU.addRequired<LoopAccessAnalysis>();
1853 AU.addPreserved<LoopInfoWrapperPass>();
1854 AU.addPreserved<DominatorTreeWrapperPass>();
1855 AU.addPreserved<AliasAnalysis>();
1860 } // end anonymous namespace
1862 //===----------------------------------------------------------------------===//
1863 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1864 // LoopVectorizationCostModel.
1865 //===----------------------------------------------------------------------===//
1867 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1868 // We need to place the broadcast of invariant variables outside the loop.
1869 Instruction *Instr = dyn_cast<Instruction>(V);
1871 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1872 Instr->getParent()) != LoopVectorBody.end());
1873 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1875 // Place the code for broadcasting invariant variables in the new preheader.
1876 IRBuilder<>::InsertPointGuard Guard(Builder);
1878 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1880 // Broadcast the scalar into all locations in the vector.
1881 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1886 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1888 assert(Val->getType()->isVectorTy() && "Must be a vector");
1889 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1890 "Elem must be an integer");
1891 assert(Step->getType() == Val->getType()->getScalarType() &&
1892 "Step has wrong type");
1893 // Create the types.
1894 Type *ITy = Val->getType()->getScalarType();
1895 VectorType *Ty = cast<VectorType>(Val->getType());
1896 int VLen = Ty->getNumElements();
1897 SmallVector<Constant*, 8> Indices;
1899 // Create a vector of consecutive numbers from zero to VF.
1900 for (int i = 0; i < VLen; ++i)
1901 Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1903 // Add the consecutive indices to the vector value.
1904 Constant *Cv = ConstantVector::get(Indices);
1905 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1906 Step = Builder.CreateVectorSplat(VLen, Step);
1907 assert(Step->getType() == Val->getType() && "Invalid step vec");
1908 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1909 // which can be found from the original scalar operations.
1910 Step = Builder.CreateMul(Cv, Step);
1911 return Builder.CreateAdd(Val, Step, "induction");
1914 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1915 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1916 // Make sure that the pointer does not point to structs.
1917 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1920 // If this value is a pointer induction variable we know it is consecutive.
1921 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1922 if (Phi && Inductions.count(Phi)) {
1923 InductionInfo II = Inductions[Phi];
1924 return II.getConsecutiveDirection();
1927 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1931 unsigned NumOperands = Gep->getNumOperands();
1932 Value *GpPtr = Gep->getPointerOperand();
1933 // If this GEP value is a consecutive pointer induction variable and all of
1934 // the indices are constant then we know it is consecutive. We can
1935 Phi = dyn_cast<PHINode>(GpPtr);
1936 if (Phi && Inductions.count(Phi)) {
1938 // Make sure that the pointer does not point to structs.
1939 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1940 if (GepPtrType->getElementType()->isAggregateType())
1943 // Make sure that all of the index operands are loop invariant.
1944 for (unsigned i = 1; i < NumOperands; ++i)
1945 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1948 InductionInfo II = Inductions[Phi];
1949 return II.getConsecutiveDirection();
1952 unsigned InductionOperand = getGEPInductionOperand(Gep);
1954 // Check that all of the gep indices are uniform except for our induction
1956 for (unsigned i = 0; i != NumOperands; ++i)
1957 if (i != InductionOperand &&
1958 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1961 // We can emit wide load/stores only if the last non-zero index is the
1962 // induction variable.
1963 const SCEV *Last = nullptr;
1964 if (!Strides.count(Gep))
1965 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1967 // Because of the multiplication by a stride we can have a s/zext cast.
1968 // We are going to replace this stride by 1 so the cast is safe to ignore.
1970 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1971 // %0 = trunc i64 %indvars.iv to i32
1972 // %mul = mul i32 %0, %Stride1
1973 // %idxprom = zext i32 %mul to i64 << Safe cast.
1974 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1976 Last = replaceSymbolicStrideSCEV(SE, Strides,
1977 Gep->getOperand(InductionOperand), Gep);
1978 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1980 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1984 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1985 const SCEV *Step = AR->getStepRecurrence(*SE);
1987 // The memory is consecutive because the last index is consecutive
1988 // and all other indices are loop invariant.
1991 if (Step->isAllOnesValue())
1998 bool LoopVectorizationLegality::isUniform(Value *V) {
1999 return LAI->isUniform(V);
2002 InnerLoopVectorizer::VectorParts&
2003 InnerLoopVectorizer::getVectorValue(Value *V) {
2004 assert(V != Induction && "The new induction variable should not be used.");
2005 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2007 // If we have a stride that is replaced by one, do it here.
2008 if (Legal->hasStride(V))
2009 V = ConstantInt::get(V->getType(), 1);
2011 // If we have this scalar in the map, return it.
2012 if (WidenMap.has(V))
2013 return WidenMap.get(V);
2015 // If this scalar is unknown, assume that it is a constant or that it is
2016 // loop invariant. Broadcast V and save the value for future uses.
2017 Value *B = getBroadcastInstrs(V);
2018 return WidenMap.splat(V, B);
2021 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2022 assert(Vec->getType()->isVectorTy() && "Invalid type");
2023 SmallVector<Constant*, 8> ShuffleMask;
2024 for (unsigned i = 0; i < VF; ++i)
2025 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2027 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2028 ConstantVector::get(ShuffleMask),
2032 // Get a mask to interleave \p NumVec vectors into a wide vector.
2033 // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
2034 // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
2035 // <0, 4, 1, 5, 2, 6, 3, 7>
2036 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
2038 SmallVector<Constant *, 16> Mask;
2039 for (unsigned i = 0; i < VF; i++)
2040 for (unsigned j = 0; j < NumVec; j++)
2041 Mask.push_back(Builder.getInt32(j * VF + i));
2043 return ConstantVector::get(Mask);
2046 // Get the strided mask starting from index \p Start.
2047 // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)>
2048 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
2049 unsigned Stride, unsigned VF) {
2050 SmallVector<Constant *, 16> Mask;
2051 for (unsigned i = 0; i < VF; i++)
2052 Mask.push_back(Builder.getInt32(Start + i * Stride));
2054 return ConstantVector::get(Mask);
2057 // Get a mask of two parts: The first part consists of sequential integers
2058 // starting from 0, The second part consists of UNDEFs.
2059 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
2060 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
2061 unsigned NumUndef) {
2062 SmallVector<Constant *, 16> Mask;
2063 for (unsigned i = 0; i < NumInt; i++)
2064 Mask.push_back(Builder.getInt32(i));
2066 Constant *Undef = UndefValue::get(Builder.getInt32Ty());
2067 for (unsigned i = 0; i < NumUndef; i++)
2068 Mask.push_back(Undef);
2070 return ConstantVector::get(Mask);
2073 // Concatenate two vectors with the same element type. The 2nd vector should
2074 // not have more elements than the 1st vector. If the 2nd vector has less
2075 // elements, extend it with UNDEFs.
2076 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
2078 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
2079 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
2080 assert(VecTy1 && VecTy2 &&
2081 VecTy1->getScalarType() == VecTy2->getScalarType() &&
2082 "Expect two vectors with the same element type");
2084 unsigned NumElts1 = VecTy1->getNumElements();
2085 unsigned NumElts2 = VecTy2->getNumElements();
2086 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
2088 if (NumElts1 > NumElts2) {
2089 // Extend with UNDEFs.
2091 getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
2092 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
2095 Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
2096 return Builder.CreateShuffleVector(V1, V2, Mask);
2099 // Concatenate vectors in the given list. All vectors have the same type.
2100 static Value *ConcatenateVectors(IRBuilder<> &Builder,
2101 ArrayRef<Value *> InputList) {
2102 unsigned NumVec = InputList.size();
2103 assert(NumVec > 1 && "Should be at least two vectors");
2105 SmallVector<Value *, 8> ResList;
2106 ResList.append(InputList.begin(), InputList.end());
2108 SmallVector<Value *, 8> TmpList;
2109 for (unsigned i = 0; i < NumVec - 1; i += 2) {
2110 Value *V0 = ResList[i], *V1 = ResList[i + 1];
2111 assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
2112 "Only the last vector may have a different type");
2114 TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
2117 // Push the last vector if the total number of vectors is odd.
2118 if (NumVec % 2 != 0)
2119 TmpList.push_back(ResList[NumVec - 1]);
2122 NumVec = ResList.size();
2123 } while (NumVec > 1);
2128 // Try to vectorize the interleave group that \p Instr belongs to.
2130 // E.g. Translate following interleaved load group (factor = 3):
2131 // for (i = 0; i < N; i+=3) {
2132 // R = Pic[i]; // Member of index 0
2133 // G = Pic[i+1]; // Member of index 1
2134 // B = Pic[i+2]; // Member of index 2
2135 // ... // do something to R, G, B
2138 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2139 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2140 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2141 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2143 // Or translate following interleaved store group (factor = 3):
2144 // for (i = 0; i < N; i+=3) {
2145 // ... do something to R, G, B
2146 // Pic[i] = R; // Member of index 0
2147 // Pic[i+1] = G; // Member of index 1
2148 // Pic[i+2] = B; // Member of index 2
2151 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2152 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2153 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2154 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2155 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2156 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2157 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2158 assert(Group && "Fail to get an interleaved access group.");
2160 // Skip if current instruction is not the insert position.
2161 if (Instr != Group->getInsertPos())
2164 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2165 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2166 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2168 // Prepare for the vector type of the interleaved load/store.
2169 Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2170 unsigned InterleaveFactor = Group->getFactor();
2171 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2172 Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
2174 // Prepare for the new pointers.
2175 setDebugLocFromInst(Builder, Ptr);
2176 VectorParts &PtrParts = getVectorValue(Ptr);
2177 SmallVector<Value *, 2> NewPtrs;
2178 unsigned Index = Group->getIndex(Instr);
2179 for (unsigned Part = 0; Part < UF; Part++) {
2180 // Extract the pointer for current instruction from the pointer vector. A
2181 // reverse access uses the pointer in the last lane.
2182 Value *NewPtr = Builder.CreateExtractElement(
2184 Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
2186 // Notice current instruction could be any index. Need to adjust the address
2187 // to the member of index 0.
2189 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2190 // b = A[i]; // Member of index 0
2191 // Current pointer is pointed to A[i+1], adjust it to A[i].
2193 // E.g. A[i+1] = a; // Member of index 1
2194 // A[i] = b; // Member of index 0
2195 // A[i+2] = c; // Member of index 2 (Current instruction)
2196 // Current pointer is pointed to A[i+2], adjust it to A[i].
2197 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2199 // Cast to the vector pointer type.
2200 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2203 setDebugLocFromInst(Builder, Instr);
2204 Value *UndefVec = UndefValue::get(VecTy);
2206 // Vectorize the interleaved load group.
2208 for (unsigned Part = 0; Part < UF; Part++) {
2209 Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
2210 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2212 for (unsigned i = 0; i < InterleaveFactor; i++) {
2213 Instruction *Member = Group->getMember(i);
2215 // Skip the gaps in the group.
2219 Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
2220 Value *StridedVec = Builder.CreateShuffleVector(
2221 NewLoadInstr, UndefVec, StrideMask, "strided.vec");
2223 // If this member has different type, cast the result type.
2224 if (Member->getType() != ScalarTy) {
2225 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2226 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2229 VectorParts &Entry = WidenMap.get(Member);
2231 Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2234 propagateMetadata(NewLoadInstr, Instr);
2239 // The sub vector type for current instruction.
2240 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2242 // Vectorize the interleaved store group.
2243 for (unsigned Part = 0; Part < UF; Part++) {
2244 // Collect the stored vector from each member.
2245 SmallVector<Value *, 4> StoredVecs;
2246 for (unsigned i = 0; i < InterleaveFactor; i++) {
2247 // Interleaved store group doesn't allow a gap, so each index has a member
2248 Instruction *Member = Group->getMember(i);
2249 assert(Member && "Fail to get a member from an interleaved store group");
2252 getVectorValue(dyn_cast<StoreInst>(Member)->getValueOperand())[Part];
2253 if (Group->isReverse())
2254 StoredVec = reverseVector(StoredVec);
2256 // If this member has different type, cast it to an unified type.
2257 if (StoredVec->getType() != SubVT)
2258 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2260 StoredVecs.push_back(StoredVec);
2263 // Concatenate all vectors into a wide vector.
2264 Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
2266 // Interleave the elements in the wide vector.
2267 Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
2268 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2271 Instruction *NewStoreInstr =
2272 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2273 propagateMetadata(NewStoreInstr, Instr);
2277 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2278 // Attempt to issue a wide load.
2279 LoadInst *LI = dyn_cast<LoadInst>(Instr);
2280 StoreInst *SI = dyn_cast<StoreInst>(Instr);
2282 assert((LI || SI) && "Invalid Load/Store instruction");
2284 // Try to vectorize the interleave group if this access is interleaved.
2285 if (Legal->isAccessInterleaved(Instr))
2286 return vectorizeInterleaveGroup(Instr);
2288 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
2289 Type *DataTy = VectorType::get(ScalarDataTy, VF);
2290 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
2291 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
2292 // An alignment of 0 means target abi alignment. We need to use the scalar's
2293 // target abi alignment in such a case.
2294 const DataLayout &DL = Instr->getModule()->getDataLayout();
2296 Alignment = DL.getABITypeAlignment(ScalarDataTy);
2297 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2298 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
2299 unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
2301 if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
2302 !Legal->isMaskRequired(SI))
2303 return scalarizeInstruction(Instr, true);
2305 if (ScalarAllocatedSize != VectorElementSize)
2306 return scalarizeInstruction(Instr);
2308 // If the pointer is loop invariant or if it is non-consecutive,
2309 // scalarize the load.
2310 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2311 bool Reverse = ConsecutiveStride < 0;
2312 bool UniformLoad = LI && Legal->isUniform(Ptr);
2313 if (!ConsecutiveStride || UniformLoad)
2314 return scalarizeInstruction(Instr);
2316 Constant *Zero = Builder.getInt32(0);
2317 VectorParts &Entry = WidenMap.get(Instr);
2319 // Handle consecutive loads/stores.
2320 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
2321 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
2322 setDebugLocFromInst(Builder, Gep);
2323 Value *PtrOperand = Gep->getPointerOperand();
2324 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
2325 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
2327 // Create the new GEP with the new induction variable.
2328 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2329 Gep2->setOperand(0, FirstBasePtr);
2330 Gep2->setName("gep.indvar.base");
2331 Ptr = Builder.Insert(Gep2);
2333 setDebugLocFromInst(Builder, Gep);
2334 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
2335 OrigLoop) && "Base ptr must be invariant");
2337 // The last index does not have to be the induction. It can be
2338 // consecutive and be a function of the index. For example A[I+1];
2339 unsigned NumOperands = Gep->getNumOperands();
2340 unsigned InductionOperand = getGEPInductionOperand(Gep);
2341 // Create the new GEP with the new induction variable.
2342 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
2344 for (unsigned i = 0; i < NumOperands; ++i) {
2345 Value *GepOperand = Gep->getOperand(i);
2346 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
2348 // Update last index or loop invariant instruction anchored in loop.
2349 if (i == InductionOperand ||
2350 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
2351 assert((i == InductionOperand ||
2352 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
2353 "Must be last index or loop invariant");
2355 VectorParts &GEPParts = getVectorValue(GepOperand);
2356 Value *Index = GEPParts[0];
2357 Index = Builder.CreateExtractElement(Index, Zero);
2358 Gep2->setOperand(i, Index);
2359 Gep2->setName("gep.indvar.idx");
2362 Ptr = Builder.Insert(Gep2);
2364 // Use the induction element ptr.
2365 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
2366 setDebugLocFromInst(Builder, Ptr);
2367 VectorParts &PtrVal = getVectorValue(Ptr);
2368 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
2371 VectorParts Mask = createBlockInMask(Instr->getParent());
2374 assert(!Legal->isUniform(SI->getPointerOperand()) &&
2375 "We do not allow storing to uniform addresses");
2376 setDebugLocFromInst(Builder, SI);
2377 // We don't want to update the value in the map as it might be used in
2378 // another expression. So don't use a reference type for "StoredVal".
2379 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
2381 for (unsigned Part = 0; Part < UF; ++Part) {
2382 // Calculate the pointer for the specific unroll-part.
2384 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2387 // If we store to reverse consecutive memory locations then we need
2388 // to reverse the order of elements in the stored value.
2389 StoredVal[Part] = reverseVector(StoredVal[Part]);
2390 // If the address is consecutive but reversed, then the
2391 // wide store needs to start at the last vector element.
2392 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2393 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2394 Mask[Part] = reverseVector(Mask[Part]);
2397 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2398 DataTy->getPointerTo(AddressSpace));
2401 if (Legal->isMaskRequired(SI))
2402 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
2405 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
2406 propagateMetadata(NewSI, SI);
2412 assert(LI && "Must have a load instruction");
2413 setDebugLocFromInst(Builder, LI);
2414 for (unsigned Part = 0; Part < UF; ++Part) {
2415 // Calculate the pointer for the specific unroll-part.
2417 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
2420 // If the address is consecutive but reversed, then the
2421 // wide load needs to start at the last vector element.
2422 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
2423 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
2424 Mask[Part] = reverseVector(Mask[Part]);
2428 Value *VecPtr = Builder.CreateBitCast(PartPtr,
2429 DataTy->getPointerTo(AddressSpace));
2430 if (Legal->isMaskRequired(LI))
2431 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
2432 UndefValue::get(DataTy),
2433 "wide.masked.load");
2435 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
2436 propagateMetadata(NewLI, LI);
2437 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
2441 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
2442 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2443 // Holds vector parameters or scalars, in case of uniform vals.
2444 SmallVector<VectorParts, 4> Params;
2446 setDebugLocFromInst(Builder, Instr);
2448 // Find all of the vectorized parameters.
2449 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2450 Value *SrcOp = Instr->getOperand(op);
2452 // If we are accessing the old induction variable, use the new one.
2453 if (SrcOp == OldInduction) {
2454 Params.push_back(getVectorValue(SrcOp));
2458 // Try using previously calculated values.
2459 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
2461 // If the src is an instruction that appeared earlier in the basic block
2462 // then it should already be vectorized.
2463 if (SrcInst && OrigLoop->contains(SrcInst)) {
2464 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
2465 // The parameter is a vector value from earlier.
2466 Params.push_back(WidenMap.get(SrcInst));
2468 // The parameter is a scalar from outside the loop. Maybe even a constant.
2469 VectorParts Scalars;
2470 Scalars.append(UF, SrcOp);
2471 Params.push_back(Scalars);
2475 assert(Params.size() == Instr->getNumOperands() &&
2476 "Invalid number of operands");
2478 // Does this instruction return a value ?
2479 bool IsVoidRetTy = Instr->getType()->isVoidTy();
2481 Value *UndefVec = IsVoidRetTy ? nullptr :
2482 UndefValue::get(VectorType::get(Instr->getType(), VF));
2483 // Create a new entry in the WidenMap and initialize it to Undef or Null.
2484 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
2486 Instruction *InsertPt = Builder.GetInsertPoint();
2487 BasicBlock *IfBlock = Builder.GetInsertBlock();
2488 BasicBlock *CondBlock = nullptr;
2491 Loop *VectorLp = nullptr;
2492 if (IfPredicateStore) {
2493 assert(Instr->getParent()->getSinglePredecessor() &&
2494 "Only support single predecessor blocks");
2495 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
2496 Instr->getParent());
2497 VectorLp = LI->getLoopFor(IfBlock);
2498 assert(VectorLp && "Must have a loop for this block");
2501 // For each vector unroll 'part':
2502 for (unsigned Part = 0; Part < UF; ++Part) {
2503 // For each scalar that we create:
2504 for (unsigned Width = 0; Width < VF; ++Width) {
2507 Value *Cmp = nullptr;
2508 if (IfPredicateStore) {
2509 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
2510 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
2511 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2512 LoopVectorBody.push_back(CondBlock);
2513 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
2514 // Update Builder with newly created basic block.
2515 Builder.SetInsertPoint(InsertPt);
2518 Instruction *Cloned = Instr->clone();
2520 Cloned->setName(Instr->getName() + ".cloned");
2521 // Replace the operands of the cloned instructions with extracted scalars.
2522 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2523 Value *Op = Params[op][Part];
2524 // Param is a vector. Need to extract the right lane.
2525 if (Op->getType()->isVectorTy())
2526 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
2527 Cloned->setOperand(op, Op);
2530 // Place the cloned scalar in the new loop.
2531 Builder.Insert(Cloned);
2533 // If the original scalar returns a value we need to place it in a vector
2534 // so that future users will be able to use it.
2536 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
2537 Builder.getInt32(Width));
2539 if (IfPredicateStore) {
2540 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2541 LoopVectorBody.push_back(NewIfBlock);
2542 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
2543 Builder.SetInsertPoint(InsertPt);
2544 ReplaceInstWithInst(IfBlock->getTerminator(),
2545 BranchInst::Create(CondBlock, NewIfBlock, Cmp));
2546 IfBlock = NewIfBlock;
2552 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2556 if (Instruction *I = dyn_cast<Instruction>(V))
2557 return I->getParent() == Loc->getParent() ? I : nullptr;
2561 std::pair<Instruction *, Instruction *>
2562 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
2563 Instruction *tnullptr = nullptr;
2564 if (!Legal->mustCheckStrides())
2565 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2567 IRBuilder<> ChkBuilder(Loc);
2570 Value *Check = nullptr;
2571 Instruction *FirstInst = nullptr;
2572 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
2573 SE = Legal->strides_end();
2575 Value *Ptr = stripIntegerCast(*SI);
2576 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2578 // Store the first instruction we create.
2579 FirstInst = getFirstInst(FirstInst, C, Loc);
2581 Check = ChkBuilder.CreateOr(Check, C);
2586 // We have to do this trickery because the IRBuilder might fold the check to a
2587 // constant expression in which case there is no Instruction anchored in a
2589 LLVMContext &Ctx = Loc->getContext();
2590 Instruction *TheCheck =
2591 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2592 ChkBuilder.Insert(TheCheck, "stride.not.one");
2593 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2595 return std::make_pair(FirstInst, TheCheck);
2598 void InnerLoopVectorizer::createEmptyLoop() {
2600 In this function we generate a new loop. The new loop will contain
2601 the vectorized instructions while the old loop will continue to run the
2604 [ ] <-- Back-edge taken count overflow check.
2607 | [ ] <-- vector loop bypass (may consist of multiple blocks).
2610 || [ ] <-- vector pre header.
2614 || [ ]_| <-- vector loop.
2617 | >[ ] <--- middle-block.
2620 -|- >[ ] <--- new preheader.
2624 | [ ]_| <-- old scalar loop to handle remainder.
2627 >[ ] <-- exit block.
2631 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2632 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2633 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2634 assert(VectorPH && "Invalid loop structure");
2635 assert(ExitBlock && "Must have an exit block");
2637 // Some loops have a single integer induction variable, while other loops
2638 // don't. One example is c++ iterators that often have multiple pointer
2639 // induction variables. In the code below we also support a case where we
2640 // don't have a single induction variable.
2641 OldInduction = Legal->getInduction();
2642 Type *IdxTy = Legal->getWidestInductionType();
2644 // Find the loop boundaries.
2645 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2646 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2648 // The exit count might have the type of i64 while the phi is i32. This can
2649 // happen if we have an induction variable that is sign extended before the
2650 // compare. The only way that we get a backedge taken count is that the
2651 // induction variable was signed and as such will not overflow. In such a case
2652 // truncation is legal.
2653 if (ExitCount->getType()->getPrimitiveSizeInBits() >
2654 IdxTy->getPrimitiveSizeInBits())
2655 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2657 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2658 // Get the total trip count from the count by adding 1.
2659 ExitCount = SE->getAddExpr(BackedgeTakeCount,
2660 SE->getConstant(BackedgeTakeCount->getType(), 1));
2662 const DataLayout &DL = OldBasicBlock->getModule()->getDataLayout();
2664 // Expand the trip count and place the new instructions in the preheader.
2665 // Notice that the pre-header does not change, only the loop body.
2666 SCEVExpander Exp(*SE, DL, "induction");
2668 // We need to test whether the backedge-taken count is uint##_max. Adding one
2669 // to it will cause overflow and an incorrect loop trip count in the vector
2670 // body. In case of overflow we want to directly jump to the scalar remainder
2672 Value *BackedgeCount =
2673 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2674 VectorPH->getTerminator());
2675 if (BackedgeCount->getType()->isPointerTy())
2676 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2677 "backedge.ptrcnt.to.int",
2678 VectorPH->getTerminator());
2679 Instruction *CheckBCOverflow =
2680 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2681 Constant::getAllOnesValue(BackedgeCount->getType()),
2682 "backedge.overflow", VectorPH->getTerminator());
2684 // The loop index does not have to start at Zero. Find the original start
2685 // value from the induction PHI node. If we don't have an induction variable
2686 // then we know that it starts at zero.
2687 Builder.SetInsertPoint(VectorPH->getTerminator());
2688 Value *StartIdx = ExtendedIdx =
2690 ? Builder.CreateZExt(OldInduction->getIncomingValueForBlock(VectorPH),
2692 : ConstantInt::get(IdxTy, 0);
2694 // Count holds the overall loop count (N).
2695 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2696 VectorPH->getTerminator());
2698 LoopBypassBlocks.push_back(VectorPH);
2700 // Split the single block loop into the two loop structure described above.
2701 BasicBlock *VecBody =
2702 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2703 BasicBlock *MiddleBlock =
2704 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2705 BasicBlock *ScalarPH =
2706 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2708 // Create and register the new vector loop.
2709 Loop* Lp = new Loop();
2710 Loop *ParentLoop = OrigLoop->getParentLoop();
2712 // Insert the new loop into the loop nest and register the new basic blocks
2713 // before calling any utilities such as SCEV that require valid LoopInfo.
2715 ParentLoop->addChildLoop(Lp);
2716 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2717 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2719 LI->addTopLevelLoop(Lp);
2721 Lp->addBasicBlockToLoop(VecBody, *LI);
2723 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2725 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2727 // Generate the induction variable.
2728 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2729 Induction = Builder.CreatePHI(IdxTy, 2, "index");
2730 // The loop step is equal to the vectorization factor (num of SIMD elements)
2731 // times the unroll factor (num of SIMD instructions).
2732 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2734 // Generate code to check that the loop's trip count that we computed by
2735 // adding one to the backedge-taken count will not overflow.
2736 BasicBlock *NewVectorPH =
2737 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "overflow.checked");
2739 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2740 ReplaceInstWithInst(
2741 VectorPH->getTerminator(),
2742 BranchInst::Create(ScalarPH, NewVectorPH, CheckBCOverflow));
2743 VectorPH = NewVectorPH;
2745 // This is the IR builder that we use to add all of the logic for bypassing
2746 // the new vector loop.
2747 IRBuilder<> BypassBuilder(VectorPH->getTerminator());
2748 setDebugLocFromInst(BypassBuilder,
2749 getDebugLocFromInstOrOperands(OldInduction));
2751 // We may need to extend the index in case there is a type mismatch.
2752 // We know that the count starts at zero and does not overflow.
2753 if (Count->getType() != IdxTy) {
2754 // The exit count can be of pointer type. Convert it to the correct
2756 if (ExitCount->getType()->isPointerTy())
2757 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2759 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2762 // Add the start index to the loop count to get the new end index.
2763 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2765 // Now we need to generate the expression for N - (N % VF), which is
2766 // the part that the vectorized body will execute.
2767 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2768 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2769 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2770 "end.idx.rnd.down");
2772 // Now, compare the new count to zero. If it is zero skip the vector loop and
2773 // jump to the scalar loop.
2775 BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2777 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.ph");
2779 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2780 LoopBypassBlocks.push_back(VectorPH);
2781 ReplaceInstWithInst(VectorPH->getTerminator(),
2782 BranchInst::Create(MiddleBlock, NewVectorPH, Cmp));
2783 VectorPH = NewVectorPH;
2785 // Generate the code to check that the strides we assumed to be one are really
2786 // one. We want the new basic block to start at the first instruction in a
2787 // sequence of instructions that form a check.
2788 Instruction *StrideCheck;
2789 Instruction *FirstCheckInst;
2790 std::tie(FirstCheckInst, StrideCheck) =
2791 addStrideCheck(VectorPH->getTerminator());
2793 AddedSafetyChecks = true;
2794 // Create a new block containing the stride check.
2795 VectorPH->setName("vector.stridecheck");
2797 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.ph");
2799 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2800 LoopBypassBlocks.push_back(VectorPH);
2802 // Replace the branch into the memory check block with a conditional branch
2803 // for the "few elements case".
2804 ReplaceInstWithInst(
2805 VectorPH->getTerminator(),
2806 BranchInst::Create(MiddleBlock, NewVectorPH, StrideCheck));
2808 VectorPH = NewVectorPH;
2811 // Generate the code that checks in runtime if arrays overlap. We put the
2812 // checks into a separate block to make the more common case of few elements
2814 Instruction *MemRuntimeCheck;
2815 std::tie(FirstCheckInst, MemRuntimeCheck) =
2816 Legal->getLAI()->addRuntimeChecks(VectorPH->getTerminator());
2817 if (MemRuntimeCheck) {
2818 AddedSafetyChecks = true;
2819 // Create a new block containing the memory check.
2820 VectorPH->setName("vector.memcheck");
2822 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.ph");
2824 ParentLoop->addBasicBlockToLoop(NewVectorPH, *LI);
2825 LoopBypassBlocks.push_back(VectorPH);
2827 // Replace the branch into the memory check block with a conditional branch
2828 // for the "few elements case".
2829 ReplaceInstWithInst(
2830 VectorPH->getTerminator(),
2831 BranchInst::Create(MiddleBlock, NewVectorPH, MemRuntimeCheck));
2833 VectorPH = NewVectorPH;
2836 // We are going to resume the execution of the scalar loop.
2837 // Go over all of the induction variables that we found and fix the
2838 // PHIs that are left in the scalar version of the loop.
2839 // The starting values of PHI nodes depend on the counter of the last
2840 // iteration in the vectorized loop.
2841 // If we come from a bypass edge then we need to start from the original
2844 // This variable saves the new starting index for the scalar loop.
2845 PHINode *ResumeIndex = nullptr;
2846 LoopVectorizationLegality::InductionList::iterator I, E;
2847 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2848 // Set builder to point to last bypass block.
2849 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2850 for (I = List->begin(), E = List->end(); I != E; ++I) {
2851 PHINode *OrigPhi = I->first;
2852 LoopVectorizationLegality::InductionInfo II = I->second;
2854 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2855 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2856 MiddleBlock->getTerminator());
2857 // We might have extended the type of the induction variable but we need a
2858 // truncated version for the scalar loop.
2859 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2860 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2861 MiddleBlock->getTerminator()) : nullptr;
2863 // Create phi nodes to merge from the backedge-taken check block.
2864 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2865 ScalarPH->getTerminator());
2866 BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2868 PHINode *BCTruncResumeVal = nullptr;
2869 if (OrigPhi == OldInduction) {
2871 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2872 ScalarPH->getTerminator());
2873 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2876 Value *EndValue = nullptr;
2878 case LoopVectorizationLegality::IK_NoInduction:
2879 llvm_unreachable("Unknown induction");
2880 case LoopVectorizationLegality::IK_IntInduction: {
2881 // Handle the integer induction counter.
2882 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2884 // We have the canonical induction variable.
2885 if (OrigPhi == OldInduction) {
2886 // Create a truncated version of the resume value for the scalar loop,
2887 // we might have promoted the type to a larger width.
2889 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2890 // The new PHI merges the original incoming value, in case of a bypass,
2891 // or the value at the end of the vectorized loop.
2892 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2893 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2894 TruncResumeVal->addIncoming(EndValue, VecBody);
2896 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2898 // We know what the end value is.
2899 EndValue = IdxEndRoundDown;
2900 // We also know which PHI node holds it.
2901 ResumeIndex = ResumeVal;
2905 // Not the canonical induction variable - add the vector loop count to the
2907 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2908 II.StartValue->getType(),
2910 EndValue = II.transform(BypassBuilder, CRD);
2911 EndValue->setName("ind.end");
2914 case LoopVectorizationLegality::IK_PtrInduction: {
2915 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2916 II.StepValue->getType(),
2918 EndValue = II.transform(BypassBuilder, CRD);
2919 EndValue->setName("ptr.ind.end");
2924 // The new PHI merges the original incoming value, in case of a bypass,
2925 // or the value at the end of the vectorized loop.
2926 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2927 if (OrigPhi == OldInduction)
2928 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2930 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2932 ResumeVal->addIncoming(EndValue, VecBody);
2934 // Fix the scalar body counter (PHI node).
2935 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2937 // The old induction's phi node in the scalar body needs the truncated
2939 if (OrigPhi == OldInduction) {
2940 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2941 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2943 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2944 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2948 // If we are generating a new induction variable then we also need to
2949 // generate the code that calculates the exit value. This value is not
2950 // simply the end of the counter because we may skip the vectorized body
2951 // in case of a runtime check.
2953 assert(!ResumeIndex && "Unexpected resume value found");
2954 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2955 MiddleBlock->getTerminator());
2956 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2957 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2958 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2961 // Make sure that we found the index where scalar loop needs to continue.
2962 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2963 "Invalid resume Index");
2965 // Add a check in the middle block to see if we have completed
2966 // all of the iterations in the first vector loop.
2967 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2968 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2969 ResumeIndex, "cmp.n",
2970 MiddleBlock->getTerminator());
2971 ReplaceInstWithInst(MiddleBlock->getTerminator(),
2972 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
2974 // Create i+1 and fill the PHINode.
2975 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2976 Induction->addIncoming(StartIdx, VectorPH);
2977 Induction->addIncoming(NextIdx, VecBody);
2978 // Create the compare.
2979 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2980 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2982 // Now we have two terminators. Remove the old one from the block.
2983 VecBody->getTerminator()->eraseFromParent();
2985 // Get ready to start creating new instructions into the vectorized body.
2986 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2989 LoopVectorPreHeader = VectorPH;
2990 LoopScalarPreHeader = ScalarPH;
2991 LoopMiddleBlock = MiddleBlock;
2992 LoopExitBlock = ExitBlock;
2993 LoopVectorBody.push_back(VecBody);
2994 LoopScalarBody = OldBasicBlock;
2996 LoopVectorizeHints Hints(Lp, true);
2997 Hints.setAlreadyVectorized();
3001 struct CSEDenseMapInfo {
3002 static bool canHandle(Instruction *I) {
3003 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3004 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3006 static inline Instruction *getEmptyKey() {
3007 return DenseMapInfo<Instruction *>::getEmptyKey();
3009 static inline Instruction *getTombstoneKey() {
3010 return DenseMapInfo<Instruction *>::getTombstoneKey();
3012 static unsigned getHashValue(Instruction *I) {
3013 assert(canHandle(I) && "Unknown instruction!");
3014 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3015 I->value_op_end()));
3017 static bool isEqual(Instruction *LHS, Instruction *RHS) {
3018 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3019 LHS == getTombstoneKey() || RHS == getTombstoneKey())
3021 return LHS->isIdenticalTo(RHS);
3026 /// \brief Check whether this block is a predicated block.
3027 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
3028 /// = ...; " blocks. We start with one vectorized basic block. For every
3029 /// conditional block we split this vectorized block. Therefore, every second
3030 /// block will be a predicated one.
3031 static bool isPredicatedBlock(unsigned BlockNum) {
3032 return BlockNum % 2;
3035 ///\brief Perform cse of induction variable instructions.
3036 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
3037 // Perform simple cse.
3038 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3039 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
3040 BasicBlock *BB = BBs[i];
3041 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3042 Instruction *In = I++;
3044 if (!CSEDenseMapInfo::canHandle(In))
3047 // Check if we can replace this instruction with any of the
3048 // visited instructions.
3049 if (Instruction *V = CSEMap.lookup(In)) {
3050 In->replaceAllUsesWith(V);
3051 In->eraseFromParent();
3054 // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
3055 // ...;" blocks for predicated stores. Every second block is a predicated
3057 if (isPredicatedBlock(i))
3065 /// \brief Adds a 'fast' flag to floating point operations.
3066 static Value *addFastMathFlag(Value *V) {
3067 if (isa<FPMathOperator>(V)){
3068 FastMathFlags Flags;
3069 Flags.setUnsafeAlgebra();
3070 cast<Instruction>(V)->setFastMathFlags(Flags);
3075 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
3076 /// the result needs to be inserted and/or extracted from vectors.
3077 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
3078 const TargetTransformInfo &TTI) {
3082 assert(Ty->isVectorTy() && "Can only scalarize vectors");
3085 for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
3087 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
3089 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
3095 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3096 // Return the cost of the instruction, including scalarization overhead if it's
3097 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3098 // i.e. either vector version isn't available, or is too expensive.
3099 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3100 const TargetTransformInfo &TTI,
3101 const TargetLibraryInfo *TLI,
3102 bool &NeedToScalarize) {
3103 Function *F = CI->getCalledFunction();
3104 StringRef FnName = CI->getCalledFunction()->getName();
3105 Type *ScalarRetTy = CI->getType();
3106 SmallVector<Type *, 4> Tys, ScalarTys;
3107 for (auto &ArgOp : CI->arg_operands())
3108 ScalarTys.push_back(ArgOp->getType());
3110 // Estimate cost of scalarized vector call. The source operands are assumed
3111 // to be vectors, so we need to extract individual elements from there,
3112 // execute VF scalar calls, and then gather the result into the vector return
3114 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3116 return ScalarCallCost;
3118 // Compute corresponding vector type for return value and arguments.
3119 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3120 for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
3121 Tys.push_back(ToVectorTy(ScalarTys[i], VF));
3123 // Compute costs of unpacking argument values for the scalar calls and
3124 // packing the return values to a vector.
3125 unsigned ScalarizationCost =
3126 getScalarizationOverhead(RetTy, true, false, TTI);
3127 for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
3128 ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
3130 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3132 // If we can't emit a vector call for this function, then the currently found
3133 // cost is the cost we need to return.
3134 NeedToScalarize = true;
3135 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3138 // If the corresponding vector cost is cheaper, return its cost.
3139 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3140 if (VectorCallCost < Cost) {
3141 NeedToScalarize = false;
3142 return VectorCallCost;
3147 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3148 // factor VF. Return the cost of the instruction, including scalarization
3149 // overhead if it's needed.
3150 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3151 const TargetTransformInfo &TTI,
3152 const TargetLibraryInfo *TLI) {
3153 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3154 assert(ID && "Expected intrinsic call!");
3156 Type *RetTy = ToVectorTy(CI->getType(), VF);
3157 SmallVector<Type *, 4> Tys;
3158 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3159 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3161 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3164 void InnerLoopVectorizer::vectorizeLoop() {
3165 //===------------------------------------------------===//
3167 // Notice: any optimization or new instruction that go
3168 // into the code below should be also be implemented in
3171 //===------------------------------------------------===//
3172 Constant *Zero = Builder.getInt32(0);
3174 // In order to support reduction variables we need to be able to vectorize
3175 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
3176 // stages. First, we create a new vector PHI node with no incoming edges.
3177 // We use this value when we vectorize all of the instructions that use the
3178 // PHI. Next, after all of the instructions in the block are complete we
3179 // add the new incoming edges to the PHI. At this point all of the
3180 // instructions in the basic block are vectorized, so we can use them to
3181 // construct the PHI.
3182 PhiVector RdxPHIsToFix;
3184 // Scan the loop in a topological order to ensure that defs are vectorized
3186 LoopBlocksDFS DFS(OrigLoop);
3189 // Vectorize all of the blocks in the original loop.
3190 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3191 be = DFS.endRPO(); bb != be; ++bb)
3192 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
3194 // At this point every instruction in the original loop is widened to
3195 // a vector form. We are almost done. Now, we need to fix the PHI nodes
3196 // that we vectorized. The PHI nodes are currently empty because we did
3197 // not want to introduce cycles. Notice that the remaining PHI nodes
3198 // that we need to fix are reduction variables.
3200 // Create the 'reduced' values for each of the induction vars.
3201 // The reduced values are the vector values that we scalarize and combine
3202 // after the loop is finished.
3203 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
3205 PHINode *RdxPhi = *it;
3206 assert(RdxPhi && "Unable to recover vectorized PHI");
3208 // Find the reduction variable descriptor.
3209 assert(Legal->getReductionVars()->count(RdxPhi) &&
3210 "Unable to find the reduction variable");
3211 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[RdxPhi];
3213 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3214 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3215 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3216 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3217 RdxDesc.getMinMaxRecurrenceKind();
3218 setDebugLocFromInst(Builder, ReductionStartValue);
3220 // We need to generate a reduction vector from the incoming scalar.
3221 // To do so, we need to generate the 'identity' vector and override
3222 // one of the elements with the incoming scalar reduction. We need
3223 // to do it in the vector-loop preheader.
3224 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
3226 // This is the vector-clone of the value that leaves the loop.
3227 VectorParts &VectorExit = getVectorValue(LoopExitInst);
3228 Type *VecTy = VectorExit[0]->getType();
3230 // Find the reduction identity variable. Zero for addition, or, xor,
3231 // one for multiplication, -1 for And.
3234 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3235 RK == RecurrenceDescriptor::RK_FloatMinMax) {
3236 // MinMax reduction have the start value as their identify.
3238 VectorStart = Identity = ReductionStartValue;
3240 VectorStart = Identity =
3241 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3244 // Handle other reduction kinds:
3245 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3246 RK, VecTy->getScalarType());
3249 // This vector is the Identity vector where the first element is the
3250 // incoming scalar reduction.
3251 VectorStart = ReductionStartValue;
3253 Identity = ConstantVector::getSplat(VF, Iden);
3255 // This vector is the Identity vector where the first element is the
3256 // incoming scalar reduction.
3258 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3262 // Fix the vector-loop phi.
3264 // Reductions do not have to start at zero. They can start with
3265 // any loop invariant values.
3266 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
3267 BasicBlock *Latch = OrigLoop->getLoopLatch();
3268 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
3269 VectorParts &Val = getVectorValue(LoopVal);
3270 for (unsigned part = 0; part < UF; ++part) {
3271 // Make sure to add the reduction stat value only to the
3272 // first unroll part.
3273 Value *StartVal = (part == 0) ? VectorStart : Identity;
3274 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
3275 LoopVectorPreHeader);
3276 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
3277 LoopVectorBody.back());
3280 // Before each round, move the insertion point right between
3281 // the PHIs and the values we are going to write.
3282 // This allows us to write both PHINodes and the extractelement
3284 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
3286 VectorParts RdxParts;
3287 setDebugLocFromInst(Builder, LoopExitInst);
3288 for (unsigned part = 0; part < UF; ++part) {
3289 // This PHINode contains the vectorized reduction variable, or
3290 // the initial value vector, if we bypass the vector loop.
3291 VectorParts &RdxExitVal = getVectorValue(LoopExitInst);
3292 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
3293 Value *StartVal = (part == 0) ? VectorStart : Identity;
3294 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3295 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
3296 NewPhi->addIncoming(RdxExitVal[part],
3297 LoopVectorBody.back());
3298 RdxParts.push_back(NewPhi);
3301 // Reduce all of the unrolled parts into a single vector.
3302 Value *ReducedPartRdx = RdxParts[0];
3303 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3304 setDebugLocFromInst(Builder, ReducedPartRdx);
3305 for (unsigned part = 1; part < UF; ++part) {
3306 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3307 // Floating point operations had to be 'fast' to enable the reduction.
3308 ReducedPartRdx = addFastMathFlag(
3309 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
3310 ReducedPartRdx, "bin.rdx"));
3312 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3313 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
3317 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3318 // and vector ops, reducing the set of values being computed by half each
3320 assert(isPowerOf2_32(VF) &&
3321 "Reduction emission only supported for pow2 vectors!");
3322 Value *TmpVec = ReducedPartRdx;
3323 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
3324 for (unsigned i = VF; i != 1; i >>= 1) {
3325 // Move the upper half of the vector to the lower half.
3326 for (unsigned j = 0; j != i/2; ++j)
3327 ShuffleMask[j] = Builder.getInt32(i/2 + j);
3329 // Fill the rest of the mask with undef.
3330 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
3331 UndefValue::get(Builder.getInt32Ty()));
3334 Builder.CreateShuffleVector(TmpVec,
3335 UndefValue::get(TmpVec->getType()),
3336 ConstantVector::get(ShuffleMask),
3339 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3340 // Floating point operations had to be 'fast' to enable the reduction.
3341 TmpVec = addFastMathFlag(Builder.CreateBinOp(
3342 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
3344 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
3348 // The result is in the first element of the vector.
3349 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
3350 Builder.getInt32(0));
3353 // Create a phi node that merges control-flow from the backedge-taken check
3354 // block and the middle block.
3355 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
3356 LoopScalarPreHeader->getTerminator());
3357 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[0]);
3358 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3360 // Now, we need to fix the users of the reduction variable
3361 // inside and outside of the scalar remainder loop.
3362 // We know that the loop is in LCSSA form. We need to update the
3363 // PHI nodes in the exit blocks.
3364 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3365 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3366 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3367 if (!LCSSAPhi) break;
3369 // All PHINodes need to have a single entry edge, or two if
3370 // we already fixed them.
3371 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3373 // We found our reduction value exit-PHI. Update it with the
3374 // incoming bypass edge.
3375 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
3376 // Add an edge coming from the bypass.
3377 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3380 }// end of the LCSSA phi scan.
3382 // Fix the scalar loop reduction variable with the incoming reduction sum
3383 // from the vector body and from the backedge value.
3384 int IncomingEdgeBlockIdx =
3385 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
3386 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3387 // Pick the other block.
3388 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3389 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3390 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3391 }// end of for each redux variable.
3395 // Remove redundant induction instructions.
3396 cse(LoopVectorBody);
3399 void InnerLoopVectorizer::fixLCSSAPHIs() {
3400 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3401 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3402 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3403 if (!LCSSAPhi) break;
3404 if (LCSSAPhi->getNumIncomingValues() == 1)
3405 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
3410 InnerLoopVectorizer::VectorParts
3411 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3412 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3415 // Look for cached value.
3416 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
3417 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3418 if (ECEntryIt != MaskCache.end())
3419 return ECEntryIt->second;
3421 VectorParts SrcMask = createBlockInMask(Src);
3423 // The terminator has to be a branch inst!
3424 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3425 assert(BI && "Unexpected terminator found");
3427 if (BI->isConditional()) {
3428 VectorParts EdgeMask = getVectorValue(BI->getCondition());
3430 if (BI->getSuccessor(0) != Dst)
3431 for (unsigned part = 0; part < UF; ++part)
3432 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3434 for (unsigned part = 0; part < UF; ++part)
3435 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3437 MaskCache[Edge] = EdgeMask;
3441 MaskCache[Edge] = SrcMask;
3445 InnerLoopVectorizer::VectorParts
3446 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3447 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3449 // Loop incoming mask is all-one.
3450 if (OrigLoop->getHeader() == BB) {
3451 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3452 return getVectorValue(C);
3455 // This is the block mask. We OR all incoming edges, and with zero.
3456 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3457 VectorParts BlockMask = getVectorValue(Zero);
3460 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3461 VectorParts EM = createEdgeMask(*it, BB);
3462 for (unsigned part = 0; part < UF; ++part)
3463 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3469 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3470 InnerLoopVectorizer::VectorParts &Entry,
3471 unsigned UF, unsigned VF, PhiVector *PV) {
3472 PHINode* P = cast<PHINode>(PN);
3473 // Handle reduction variables:
3474 if (Legal->getReductionVars()->count(P)) {
3475 for (unsigned part = 0; part < UF; ++part) {
3476 // This is phase one of vectorizing PHIs.
3477 Type *VecTy = (VF == 1) ? PN->getType() :
3478 VectorType::get(PN->getType(), VF);
3479 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
3480 LoopVectorBody.back()-> getFirstInsertionPt());
3486 setDebugLocFromInst(Builder, P);
3487 // Check for PHI nodes that are lowered to vector selects.
3488 if (P->getParent() != OrigLoop->getHeader()) {
3489 // We know that all PHIs in non-header blocks are converted into
3490 // selects, so we don't have to worry about the insertion order and we
3491 // can just use the builder.
3492 // At this point we generate the predication tree. There may be
3493 // duplications since this is a simple recursive scan, but future
3494 // optimizations will clean it up.
3496 unsigned NumIncoming = P->getNumIncomingValues();
3498 // Generate a sequence of selects of the form:
3499 // SELECT(Mask3, In3,
3500 // SELECT(Mask2, In2,
3502 for (unsigned In = 0; In < NumIncoming; In++) {
3503 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3505 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3507 for (unsigned part = 0; part < UF; ++part) {
3508 // We might have single edge PHIs (blocks) - use an identity
3509 // 'select' for the first PHI operand.
3511 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3514 // Select between the current value and the previous incoming edge
3515 // based on the incoming mask.
3516 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3517 Entry[part], "predphi");
3523 // This PHINode must be an induction variable.
3524 // Make sure that we know about it.
3525 assert(Legal->getInductionVars()->count(P) &&
3526 "Not an induction variable");
3528 LoopVectorizationLegality::InductionInfo II =
3529 Legal->getInductionVars()->lookup(P);
3531 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3532 // which can be found from the original scalar operations.
3534 case LoopVectorizationLegality::IK_NoInduction:
3535 llvm_unreachable("Unknown induction");
3536 case LoopVectorizationLegality::IK_IntInduction: {
3537 assert(P->getType() == II.StartValue->getType() && "Types must match");
3538 Type *PhiTy = P->getType();
3540 if (P == OldInduction) {
3541 // Handle the canonical induction variable. We might have had to
3543 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
3545 // Handle other induction variables that are now based on the
3547 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
3549 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
3550 Broadcasted = II.transform(Builder, NormalizedIdx);
3551 Broadcasted->setName("offset.idx");
3553 Broadcasted = getBroadcastInstrs(Broadcasted);
3554 // After broadcasting the induction variable we need to make the vector
3555 // consecutive by adding 0, 1, 2, etc.
3556 for (unsigned part = 0; part < UF; ++part)
3557 Entry[part] = getStepVector(Broadcasted, VF * part, II.StepValue);
3560 case LoopVectorizationLegality::IK_PtrInduction:
3561 // Handle the pointer induction variable case.
3562 assert(P->getType()->isPointerTy() && "Unexpected type.");
3563 // This is the normalized GEP that starts counting at zero.
3564 Value *NormalizedIdx =
3565 Builder.CreateSub(Induction, ExtendedIdx, "normalized.idx");
3567 Builder.CreateSExtOrTrunc(NormalizedIdx, II.StepValue->getType());
3568 // This is the vector of results. Notice that we don't generate
3569 // vector geps because scalar geps result in better code.
3570 for (unsigned part = 0; part < UF; ++part) {
3572 int EltIndex = part;
3573 Constant *Idx = ConstantInt::get(NormalizedIdx->getType(), EltIndex);
3574 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3575 Value *SclrGep = II.transform(Builder, GlobalIdx);
3576 SclrGep->setName("next.gep");
3577 Entry[part] = SclrGep;
3581 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3582 for (unsigned int i = 0; i < VF; ++i) {
3583 int EltIndex = i + part * VF;
3584 Constant *Idx = ConstantInt::get(NormalizedIdx->getType(), EltIndex);
3585 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3586 Value *SclrGep = II.transform(Builder, GlobalIdx);
3587 SclrGep->setName("next.gep");
3588 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3589 Builder.getInt32(i),
3592 Entry[part] = VecVal;
3598 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3599 // For each instruction in the old loop.
3600 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3601 VectorParts &Entry = WidenMap.get(it);
3602 switch (it->getOpcode()) {
3603 case Instruction::Br:
3604 // Nothing to do for PHIs and BR, since we already took care of the
3605 // loop control flow instructions.
3607 case Instruction::PHI: {
3608 // Vectorize PHINodes.
3609 widenPHIInstruction(it, Entry, UF, VF, PV);
3613 case Instruction::Add:
3614 case Instruction::FAdd:
3615 case Instruction::Sub:
3616 case Instruction::FSub:
3617 case Instruction::Mul:
3618 case Instruction::FMul:
3619 case Instruction::UDiv:
3620 case Instruction::SDiv:
3621 case Instruction::FDiv:
3622 case Instruction::URem:
3623 case Instruction::SRem:
3624 case Instruction::FRem:
3625 case Instruction::Shl:
3626 case Instruction::LShr:
3627 case Instruction::AShr:
3628 case Instruction::And:
3629 case Instruction::Or:
3630 case Instruction::Xor: {
3631 // Just widen binops.
3632 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3633 setDebugLocFromInst(Builder, BinOp);
3634 VectorParts &A = getVectorValue(it->getOperand(0));
3635 VectorParts &B = getVectorValue(it->getOperand(1));
3637 // Use this vector value for all users of the original instruction.
3638 for (unsigned Part = 0; Part < UF; ++Part) {
3639 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3641 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3642 VecOp->copyIRFlags(BinOp);
3647 propagateMetadata(Entry, it);
3650 case Instruction::Select: {
3652 // If the selector is loop invariant we can create a select
3653 // instruction with a scalar condition. Otherwise, use vector-select.
3654 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3656 setDebugLocFromInst(Builder, it);
3658 // The condition can be loop invariant but still defined inside the
3659 // loop. This means that we can't just use the original 'cond' value.
3660 // We have to take the 'vectorized' value and pick the first lane.
3661 // Instcombine will make this a no-op.
3662 VectorParts &Cond = getVectorValue(it->getOperand(0));
3663 VectorParts &Op0 = getVectorValue(it->getOperand(1));
3664 VectorParts &Op1 = getVectorValue(it->getOperand(2));
3666 Value *ScalarCond = (VF == 1) ? Cond[0] :
3667 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3669 for (unsigned Part = 0; Part < UF; ++Part) {
3670 Entry[Part] = Builder.CreateSelect(
3671 InvariantCond ? ScalarCond : Cond[Part],
3676 propagateMetadata(Entry, it);
3680 case Instruction::ICmp:
3681 case Instruction::FCmp: {
3682 // Widen compares. Generate vector compares.
3683 bool FCmp = (it->getOpcode() == Instruction::FCmp);
3684 CmpInst *Cmp = dyn_cast<CmpInst>(it);
3685 setDebugLocFromInst(Builder, it);
3686 VectorParts &A = getVectorValue(it->getOperand(0));
3687 VectorParts &B = getVectorValue(it->getOperand(1));
3688 for (unsigned Part = 0; Part < UF; ++Part) {
3691 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3693 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3697 propagateMetadata(Entry, it);
3701 case Instruction::Store:
3702 case Instruction::Load:
3703 vectorizeMemoryInstruction(it);
3705 case Instruction::ZExt:
3706 case Instruction::SExt:
3707 case Instruction::FPToUI:
3708 case Instruction::FPToSI:
3709 case Instruction::FPExt:
3710 case Instruction::PtrToInt:
3711 case Instruction::IntToPtr:
3712 case Instruction::SIToFP:
3713 case Instruction::UIToFP:
3714 case Instruction::Trunc:
3715 case Instruction::FPTrunc:
3716 case Instruction::BitCast: {
3717 CastInst *CI = dyn_cast<CastInst>(it);
3718 setDebugLocFromInst(Builder, it);
3719 /// Optimize the special case where the source is the induction
3720 /// variable. Notice that we can only optimize the 'trunc' case
3721 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3722 /// c. other casts depend on pointer size.
3723 if (CI->getOperand(0) == OldInduction &&
3724 it->getOpcode() == Instruction::Trunc) {
3725 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3727 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3728 LoopVectorizationLegality::InductionInfo II =
3729 Legal->getInductionVars()->lookup(OldInduction);
3731 ConstantInt::getSigned(CI->getType(), II.StepValue->getSExtValue());
3732 for (unsigned Part = 0; Part < UF; ++Part)
3733 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3734 propagateMetadata(Entry, it);
3737 /// Vectorize casts.
3738 Type *DestTy = (VF == 1) ? CI->getType() :
3739 VectorType::get(CI->getType(), VF);
3741 VectorParts &A = getVectorValue(it->getOperand(0));
3742 for (unsigned Part = 0; Part < UF; ++Part)
3743 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3744 propagateMetadata(Entry, it);
3748 case Instruction::Call: {
3749 // Ignore dbg intrinsics.
3750 if (isa<DbgInfoIntrinsic>(it))
3752 setDebugLocFromInst(Builder, it);
3754 Module *M = BB->getParent()->getParent();
3755 CallInst *CI = cast<CallInst>(it);
3757 StringRef FnName = CI->getCalledFunction()->getName();
3758 Function *F = CI->getCalledFunction();
3759 Type *RetTy = ToVectorTy(CI->getType(), VF);
3760 SmallVector<Type *, 4> Tys;
3761 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3762 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3764 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3766 (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
3767 ID == Intrinsic::lifetime_start)) {
3768 scalarizeInstruction(it);
3771 // The flag shows whether we use Intrinsic or a usual Call for vectorized
3772 // version of the instruction.
3773 // Is it beneficial to perform intrinsic call compared to lib call?
3774 bool NeedToScalarize;
3775 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
3776 bool UseVectorIntrinsic =
3777 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
3778 if (!UseVectorIntrinsic && NeedToScalarize) {
3779 scalarizeInstruction(it);
3783 for (unsigned Part = 0; Part < UF; ++Part) {
3784 SmallVector<Value *, 4> Args;
3785 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3786 Value *Arg = CI->getArgOperand(i);
3787 // Some intrinsics have a scalar argument - don't replace it with a
3789 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
3790 VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
3791 Arg = VectorArg[Part];
3793 Args.push_back(Arg);
3797 if (UseVectorIntrinsic) {
3798 // Use vector version of the intrinsic.
3799 Type *TysForDecl[] = {CI->getType()};
3801 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3802 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
3804 // Use vector version of the library call.
3805 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
3806 assert(!VFnName.empty() && "Vector function name is empty.");
3807 VectorF = M->getFunction(VFnName);
3809 // Generate a declaration
3810 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
3812 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
3813 VectorF->copyAttributesFrom(F);
3816 assert(VectorF && "Can't create vector function.");
3817 Entry[Part] = Builder.CreateCall(VectorF, Args);
3820 propagateMetadata(Entry, it);
3825 // All other instructions are unsupported. Scalarize them.
3826 scalarizeInstruction(it);
3829 }// end of for_each instr.
3832 void InnerLoopVectorizer::updateAnalysis() {
3833 // Forget the original basic block.
3834 SE->forgetLoop(OrigLoop);
3836 // Update the dominator tree information.
3837 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3838 "Entry does not dominate exit.");
3840 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3841 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3842 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3844 // Due to if predication of stores we might create a sequence of "if(pred)
3845 // a[i] = ...; " blocks.
3846 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3848 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3849 else if (isPredicatedBlock(i)) {
3850 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3852 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3856 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3857 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3858 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3859 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3861 DEBUG(DT->verifyDomTree());
3864 /// \brief Check whether it is safe to if-convert this phi node.
3866 /// Phi nodes with constant expressions that can trap are not safe to if
3868 static bool canIfConvertPHINodes(BasicBlock *BB) {
3869 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3870 PHINode *Phi = dyn_cast<PHINode>(I);
3873 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3874 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3881 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3882 if (!EnableIfConversion) {
3883 emitAnalysis(VectorizationReport() << "if-conversion is disabled");
3887 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3889 // A list of pointers that we can safely read and write to.
3890 SmallPtrSet<Value *, 8> SafePointes;
3892 // Collect safe addresses.
3893 for (Loop::block_iterator BI = TheLoop->block_begin(),
3894 BE = TheLoop->block_end(); BI != BE; ++BI) {
3895 BasicBlock *BB = *BI;
3897 if (blockNeedsPredication(BB))
3900 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3901 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3902 SafePointes.insert(LI->getPointerOperand());
3903 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3904 SafePointes.insert(SI->getPointerOperand());
3908 // Collect the blocks that need predication.
3909 BasicBlock *Header = TheLoop->getHeader();
3910 for (Loop::block_iterator BI = TheLoop->block_begin(),
3911 BE = TheLoop->block_end(); BI != BE; ++BI) {
3912 BasicBlock *BB = *BI;
3914 // We don't support switch statements inside loops.
3915 if (!isa<BranchInst>(BB->getTerminator())) {
3916 emitAnalysis(VectorizationReport(BB->getTerminator())
3917 << "loop contains a switch statement");
3921 // We must be able to predicate all blocks that need to be predicated.
3922 if (blockNeedsPredication(BB)) {
3923 if (!blockCanBePredicated(BB, SafePointes)) {
3924 emitAnalysis(VectorizationReport(BB->getTerminator())
3925 << "control flow cannot be substituted for a select");
3928 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3929 emitAnalysis(VectorizationReport(BB->getTerminator())
3930 << "control flow cannot be substituted for a select");
3935 // We can if-convert this loop.
3939 bool LoopVectorizationLegality::canVectorize() {
3940 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3941 // be canonicalized.
3942 if (!TheLoop->getLoopPreheader()) {
3944 VectorizationReport() <<
3945 "loop control flow is not understood by vectorizer");
3949 // We can only vectorize innermost loops.
3950 if (!TheLoop->empty()) {
3951 emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
3955 // We must have a single backedge.
3956 if (TheLoop->getNumBackEdges() != 1) {
3958 VectorizationReport() <<
3959 "loop control flow is not understood by vectorizer");
3963 // We must have a single exiting block.
3964 if (!TheLoop->getExitingBlock()) {
3966 VectorizationReport() <<
3967 "loop control flow is not understood by vectorizer");
3971 // We only handle bottom-tested loops, i.e. loop in which the condition is
3972 // checked at the end of each iteration. With that we can assume that all
3973 // instructions in the loop are executed the same number of times.
3974 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3976 VectorizationReport() <<
3977 "loop control flow is not understood by vectorizer");
3981 // We need to have a loop header.
3982 DEBUG(dbgs() << "LV: Found a loop: " <<
3983 TheLoop->getHeader()->getName() << '\n');
3985 // Check if we can if-convert non-single-bb loops.
3986 unsigned NumBlocks = TheLoop->getNumBlocks();
3987 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3988 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3992 // ScalarEvolution needs to be able to find the exit count.
3993 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3994 if (ExitCount == SE->getCouldNotCompute()) {
3995 emitAnalysis(VectorizationReport() <<
3996 "could not determine number of loop iterations");
3997 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
4001 // Check if we can vectorize the instructions and CFG in this loop.
4002 if (!canVectorizeInstrs()) {
4003 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
4007 // Go over each instruction and look at memory deps.
4008 if (!canVectorizeMemory()) {
4009 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
4013 // Collect all of the variables that remain uniform after vectorization.
4014 collectLoopUniforms();
4016 DEBUG(dbgs() << "LV: We can vectorize this loop"
4017 << (LAI->getRuntimePointerChecking()->Need
4018 ? " (with a runtime bound check)"
4022 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
4024 // If an override option has been passed in for interleaved accesses, use it.
4025 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
4026 UseInterleaved = EnableInterleavedMemAccesses;
4028 // Analyze interleaved memory accesses.
4030 InterleaveInfo.analyzeInterleaving(Strides);
4032 // Okay! We can vectorize. At this point we don't have any other mem analysis
4033 // which may limit our maximum vectorization factor, so just return true with
4038 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
4039 if (Ty->isPointerTy())
4040 return DL.getIntPtrType(Ty);
4042 // It is possible that char's or short's overflow when we ask for the loop's
4043 // trip count, work around this by changing the type size.
4044 if (Ty->getScalarSizeInBits() < 32)
4045 return Type::getInt32Ty(Ty->getContext());
4050 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4051 Ty0 = convertPointerToIntegerType(DL, Ty0);
4052 Ty1 = convertPointerToIntegerType(DL, Ty1);
4053 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4058 /// \brief Check that the instruction has outside loop users and is not an
4059 /// identified reduction variable.
4060 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
4061 SmallPtrSetImpl<Value *> &Reductions) {
4062 // Reduction instructions are allowed to have exit users. All other
4063 // instructions must not have external users.
4064 if (!Reductions.count(Inst))
4065 //Check that all of the users of the loop are inside the BB.
4066 for (User *U : Inst->users()) {
4067 Instruction *UI = cast<Instruction>(U);
4068 // This user may be a reduction exit value.
4069 if (!TheLoop->contains(UI)) {
4070 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
4077 bool LoopVectorizationLegality::canVectorizeInstrs() {
4078 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
4079 BasicBlock *Header = TheLoop->getHeader();
4081 // Look for the attribute signaling the absence of NaNs.
4082 Function &F = *Header->getParent();
4083 const DataLayout &DL = F.getParent()->getDataLayout();
4084 if (F.hasFnAttribute("no-nans-fp-math"))
4086 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
4088 // For each block in the loop.
4089 for (Loop::block_iterator bb = TheLoop->block_begin(),
4090 be = TheLoop->block_end(); bb != be; ++bb) {
4092 // Scan the instructions in the block and look for hazards.
4093 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4096 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
4097 Type *PhiTy = Phi->getType();
4098 // Check that this PHI type is allowed.
4099 if (!PhiTy->isIntegerTy() &&
4100 !PhiTy->isFloatingPointTy() &&
4101 !PhiTy->isPointerTy()) {
4102 emitAnalysis(VectorizationReport(it)
4103 << "loop control flow is not understood by vectorizer");
4104 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
4108 // If this PHINode is not in the header block, then we know that we
4109 // can convert it to select during if-conversion. No need to check if
4110 // the PHIs in this block are induction or reduction variables.
4111 if (*bb != Header) {
4112 // Check that this instruction has no outside users or is an
4113 // identified reduction value with an outside user.
4114 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
4116 emitAnalysis(VectorizationReport(it) <<
4117 "value could not be identified as "
4118 "an induction or reduction variable");
4122 // We only allow if-converted PHIs with exactly two incoming values.
4123 if (Phi->getNumIncomingValues() != 2) {
4124 emitAnalysis(VectorizationReport(it)
4125 << "control flow not understood by vectorizer");
4126 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
4130 // This is the value coming from the preheader.
4131 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
4132 ConstantInt *StepValue = nullptr;
4133 // Check if this is an induction variable.
4134 InductionKind IK = isInductionVariable(Phi, StepValue);
4136 if (IK_NoInduction != IK) {
4137 // Get the widest type.
4139 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
4141 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
4143 // Int inductions are special because we only allow one IV.
4144 if (IK == IK_IntInduction && StepValue->isOne()) {
4145 // Use the phi node with the widest type as induction. Use the last
4146 // one if there are multiple (no good reason for doing this other
4147 // than it is expedient).
4148 if (!Induction || PhiTy == WidestIndTy)
4152 DEBUG(dbgs() << "LV: Found an induction variable.\n");
4153 Inductions[Phi] = InductionInfo(StartValue, IK, StepValue);
4155 // Until we explicitly handle the case of an induction variable with
4156 // an outside loop user we have to give up vectorizing this loop.
4157 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4158 emitAnalysis(VectorizationReport(it) <<
4159 "use of induction value outside of the "
4160 "loop is not handled by vectorizer");
4167 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop,
4169 if (Reductions[Phi].hasUnsafeAlgebra())
4170 Requirements->addUnsafeAlgebraInst(
4171 Reductions[Phi].getUnsafeAlgebraInst());
4172 AllowedExit.insert(Reductions[Phi].getLoopExitInstr());
4176 emitAnalysis(VectorizationReport(it) <<
4177 "value that could not be identified as "
4178 "reduction is used outside the loop");
4179 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
4181 }// end of PHI handling
4183 // We handle calls that:
4184 // * Are debug info intrinsics.
4185 // * Have a mapping to an IR intrinsic.
4186 // * Have a vector version available.
4187 CallInst *CI = dyn_cast<CallInst>(it);
4188 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI) &&
4189 !(CI->getCalledFunction() && TLI &&
4190 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
4191 emitAnalysis(VectorizationReport(it) <<
4192 "call instruction cannot be vectorized");
4193 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
4197 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
4198 // second argument is the same (i.e. loop invariant)
4200 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
4201 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
4202 emitAnalysis(VectorizationReport(it)
4203 << "intrinsic instruction cannot be vectorized");
4204 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
4209 // Check that the instruction return type is vectorizable.
4210 // Also, we can't vectorize extractelement instructions.
4211 if ((!VectorType::isValidElementType(it->getType()) &&
4212 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
4213 emitAnalysis(VectorizationReport(it)
4214 << "instruction return type cannot be vectorized");
4215 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
4219 // Check that the stored type is vectorizable.
4220 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
4221 Type *T = ST->getValueOperand()->getType();
4222 if (!VectorType::isValidElementType(T)) {
4223 emitAnalysis(VectorizationReport(ST) <<
4224 "store instruction cannot be vectorized");
4227 if (EnableMemAccessVersioning)
4228 collectStridedAccess(ST);
4231 if (EnableMemAccessVersioning)
4232 if (LoadInst *LI = dyn_cast<LoadInst>(it))
4233 collectStridedAccess(LI);
4235 // Reduction instructions are allowed to have exit users.
4236 // All other instructions must not have external users.
4237 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
4238 emitAnalysis(VectorizationReport(it) <<
4239 "value cannot be used outside the loop");
4248 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
4249 if (Inductions.empty()) {
4250 emitAnalysis(VectorizationReport()
4251 << "loop induction variable could not be identified");
4259 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
4260 Value *Ptr = nullptr;
4261 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
4262 Ptr = LI->getPointerOperand();
4263 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
4264 Ptr = SI->getPointerOperand();
4268 Value *Stride = getStrideFromPointer(Ptr, SE, TheLoop);
4272 DEBUG(dbgs() << "LV: Found a strided access that we can version");
4273 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
4274 Strides[Ptr] = Stride;
4275 StrideSet.insert(Stride);
4278 void LoopVectorizationLegality::collectLoopUniforms() {
4279 // We now know that the loop is vectorizable!
4280 // Collect variables that will remain uniform after vectorization.
4281 std::vector<Value*> Worklist;
4282 BasicBlock *Latch = TheLoop->getLoopLatch();
4284 // Start with the conditional branch and walk up the block.
4285 Worklist.push_back(Latch->getTerminator()->getOperand(0));
4287 // Also add all consecutive pointer values; these values will be uniform
4288 // after vectorization (and subsequent cleanup) and, until revectorization is
4289 // supported, all dependencies must also be uniform.
4290 for (Loop::block_iterator B = TheLoop->block_begin(),
4291 BE = TheLoop->block_end(); B != BE; ++B)
4292 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
4294 if (I->getType()->isPointerTy() && isConsecutivePtr(I))
4295 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4297 while (!Worklist.empty()) {
4298 Instruction *I = dyn_cast<Instruction>(Worklist.back());
4299 Worklist.pop_back();
4301 // Look at instructions inside this loop.
4302 // Stop when reaching PHI nodes.
4303 // TODO: we need to follow values all over the loop, not only in this block.
4304 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
4307 // This is a known uniform.
4310 // Insert all operands.
4311 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4315 bool LoopVectorizationLegality::canVectorizeMemory() {
4316 LAI = &LAA->getInfo(TheLoop, Strides);
4317 auto &OptionalReport = LAI->getReport();
4319 emitAnalysis(VectorizationReport(*OptionalReport));
4320 if (!LAI->canVectorizeMemory())
4323 if (LAI->hasStoreToLoopInvariantAddress()) {
4325 VectorizationReport()
4326 << "write to a loop invariant address could not be vectorized");
4327 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4331 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
4336 LoopVectorizationLegality::InductionKind
4337 LoopVectorizationLegality::isInductionVariable(PHINode *Phi,
4338 ConstantInt *&StepValue) {
4339 if (!isInductionPHI(Phi, SE, StepValue))
4340 return IK_NoInduction;
4342 Type *PhiTy = Phi->getType();
4343 // Found an Integer induction variable.
4344 if (PhiTy->isIntegerTy())
4345 return IK_IntInduction;
4346 // Found an Pointer induction variable.
4347 return IK_PtrInduction;
4350 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4351 Value *In0 = const_cast<Value*>(V);
4352 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4356 return Inductions.count(PN);
4359 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4360 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4363 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4364 SmallPtrSetImpl<Value *> &SafePtrs) {
4366 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4367 // Check that we don't have a constant expression that can trap as operand.
4368 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4370 if (Constant *C = dyn_cast<Constant>(*OI))
4374 // We might be able to hoist the load.
4375 if (it->mayReadFromMemory()) {
4376 LoadInst *LI = dyn_cast<LoadInst>(it);
4379 if (!SafePtrs.count(LI->getPointerOperand())) {
4380 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
4381 MaskedOp.insert(LI);
4388 // We don't predicate stores at the moment.
4389 if (it->mayWriteToMemory()) {
4390 StoreInst *SI = dyn_cast<StoreInst>(it);
4391 // We only support predication of stores in basic blocks with one
4396 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
4397 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
4399 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
4400 !isSinglePredecessor) {
4401 // Build a masked store if it is legal for the target, otherwise scalarize
4403 bool isLegalMaskedOp =
4404 isLegalMaskedStore(SI->getValueOperand()->getType(),
4405 SI->getPointerOperand());
4406 if (isLegalMaskedOp) {
4408 MaskedOp.insert(SI);
4417 // The instructions below can trap.
4418 switch (it->getOpcode()) {
4420 case Instruction::UDiv:
4421 case Instruction::SDiv:
4422 case Instruction::URem:
4423 case Instruction::SRem:
4431 void InterleavedAccessInfo::collectConstStridedAccesses(
4432 MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
4433 const ValueToValueMap &Strides) {
4434 // Holds load/store instructions in program order.
4435 SmallVector<Instruction *, 16> AccessList;
4437 for (auto *BB : TheLoop->getBlocks()) {
4438 bool IsPred = LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
4440 for (auto &I : *BB) {
4441 if (!isa<LoadInst>(&I) && !isa<StoreInst>(&I))
4443 // FIXME: Currently we can't handle mixed accesses and predicated accesses
4447 AccessList.push_back(&I);
4451 if (AccessList.empty())
4454 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
4455 for (auto I : AccessList) {
4456 LoadInst *LI = dyn_cast<LoadInst>(I);
4457 StoreInst *SI = dyn_cast<StoreInst>(I);
4459 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
4460 int Stride = isStridedPtr(SE, Ptr, TheLoop, Strides);
4462 // The factor of the corresponding interleave group.
4463 unsigned Factor = std::abs(Stride);
4465 // Ignore the access if the factor is too small or too large.
4466 if (Factor < 2 || Factor > MaxInterleaveGroupFactor)
4469 const SCEV *Scev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
4470 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4471 unsigned Size = DL.getTypeAllocSize(PtrTy->getElementType());
4473 // An alignment of 0 means target ABI alignment.
4474 unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
4476 Align = DL.getABITypeAlignment(PtrTy->getElementType());
4478 StrideAccesses[I] = StrideDescriptor(Stride, Scev, Size, Align);
4482 // Analyze interleaved accesses and collect them into interleave groups.
4484 // Notice that the vectorization on interleaved groups will change instruction
4485 // orders and may break dependences. But the memory dependence check guarantees
4486 // that there is no overlap between two pointers of different strides, element
4487 // sizes or underlying bases.
4489 // For pointers sharing the same stride, element size and underlying base, no
4490 // need to worry about Read-After-Write dependences and Write-After-Read
4493 // E.g. The RAW dependence: A[i] = a;
4495 // This won't exist as it is a store-load forwarding conflict, which has
4496 // already been checked and forbidden in the dependence check.
4498 // E.g. The WAR dependence: a = A[i]; // (1)
4500 // The store group of (2) is always inserted at or below (2), and the load group
4501 // of (1) is always inserted at or above (1). The dependence is safe.
4502 void InterleavedAccessInfo::analyzeInterleaving(
4503 const ValueToValueMap &Strides) {
4504 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
4506 // Holds all the stride accesses.
4507 MapVector<Instruction *, StrideDescriptor> StrideAccesses;
4508 collectConstStridedAccesses(StrideAccesses, Strides);
4510 if (StrideAccesses.empty())
4513 // Holds all interleaved store groups temporarily.
4514 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
4516 // Search the load-load/write-write pair B-A in bottom-up order and try to
4517 // insert B into the interleave group of A according to 3 rules:
4518 // 1. A and B have the same stride.
4519 // 2. A and B have the same memory object size.
4520 // 3. B belongs to the group according to the distance.
4522 // The bottom-up order can avoid breaking the Write-After-Write dependences
4523 // between two pointers of the same base.
4524 // E.g. A[i] = a; (1)
4527 // We form the group (2)+(3) in front, so (1) has to form groups with accesses
4528 // above (1), which guarantees that (1) is always above (2).
4529 for (auto I = StrideAccesses.rbegin(), E = StrideAccesses.rend(); I != E;
4531 Instruction *A = I->first;
4532 StrideDescriptor DesA = I->second;
4534 InterleaveGroup *Group = getInterleaveGroup(A);
4536 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
4537 Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
4540 if (A->mayWriteToMemory())
4541 StoreGroups.insert(Group);
4543 for (auto II = std::next(I); II != E; ++II) {
4544 Instruction *B = II->first;
4545 StrideDescriptor DesB = II->second;
4547 // Ignore if B is already in a group or B is a different memory operation.
4548 if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
4551 // Check the rule 1 and 2.
4552 if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
4555 // Calculate the distance and prepare for the rule 3.
4556 const SCEVConstant *DistToA =
4557 dyn_cast<SCEVConstant>(SE->getMinusSCEV(DesB.Scev, DesA.Scev));
4561 int DistanceToA = DistToA->getValue()->getValue().getSExtValue();
4563 // Skip if the distance is not multiple of size as they are not in the
4565 if (DistanceToA % static_cast<int>(DesA.Size))
4568 // The index of B is the index of A plus the related index to A.
4570 Group->getIndex(A) + DistanceToA / static_cast<int>(DesA.Size);
4572 // Try to insert B into the group.
4573 if (Group->insertMember(B, IndexB, DesB.Align)) {
4574 DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
4575 << " into the interleave group with" << *A << '\n');
4576 InterleaveGroupMap[B] = Group;
4578 // Set the first load in program order as the insert position.
4579 if (B->mayReadFromMemory())
4580 Group->setInsertPos(B);
4582 } // Iteration on instruction B
4583 } // Iteration on instruction A
4585 // Remove interleaved store groups with gaps.
4586 for (InterleaveGroup *Group : StoreGroups)
4587 if (Group->getNumMembers() != Group->getFactor())
4588 releaseGroup(Group);
4591 LoopVectorizationCostModel::VectorizationFactor
4592 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
4593 // Width 1 means no vectorize
4594 VectorizationFactor Factor = { 1U, 0U };
4595 if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
4596 emitAnalysis(VectorizationReport() <<
4597 "runtime pointer checks needed. Enable vectorization of this "
4598 "loop with '#pragma clang loop vectorize(enable)' when "
4599 "compiling with -Os");
4600 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4604 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
4605 emitAnalysis(VectorizationReport() <<
4606 "store that is conditionally executed prevents vectorization");
4607 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
4611 // Find the trip count.
4612 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4613 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4615 unsigned WidestType = getWidestType();
4616 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4617 unsigned MaxSafeDepDist = -1U;
4618 if (Legal->getMaxSafeDepDistBytes() != -1U)
4619 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4620 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4621 WidestRegister : MaxSafeDepDist);
4622 unsigned MaxVectorSize = WidestRegister / WidestType;
4623 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4624 DEBUG(dbgs() << "LV: The Widest register is: "
4625 << WidestRegister << " bits.\n");
4627 if (MaxVectorSize == 0) {
4628 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4632 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
4633 " into one vector!");
4635 unsigned VF = MaxVectorSize;
4637 // If we optimize the program for size, avoid creating the tail loop.
4639 // If we are unable to calculate the trip count then don't try to vectorize.
4642 (VectorizationReport() <<
4643 "unable to calculate the loop count due to complex control flow");
4644 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4648 // Find the maximum SIMD width that can fit within the trip count.
4649 VF = TC % MaxVectorSize;
4654 // If the trip count that we found modulo the vectorization factor is not
4655 // zero then we require a tail.
4656 emitAnalysis(VectorizationReport() <<
4657 "cannot optimize for size and vectorize at the "
4658 "same time. Enable vectorization of this loop "
4659 "with '#pragma clang loop vectorize(enable)' "
4660 "when compiling with -Os");
4661 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4666 int UserVF = Hints->getWidth();
4668 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4669 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4671 Factor.Width = UserVF;
4675 float Cost = expectedCost(1);
4677 const float ScalarCost = Cost;
4680 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
4682 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
4683 // Ignore scalar width, because the user explicitly wants vectorization.
4684 if (ForceVectorization && VF > 1) {
4686 Cost = expectedCost(Width) / (float)Width;
4689 for (unsigned i=2; i <= VF; i*=2) {
4690 // Notice that the vector loop needs to be executed less times, so
4691 // we need to divide the cost of the vector loops by the width of
4692 // the vector elements.
4693 float VectorCost = expectedCost(i) / (float)i;
4694 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4695 (int)VectorCost << ".\n");
4696 if (VectorCost < Cost) {
4702 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
4703 << "LV: Vectorization seems to be not beneficial, "
4704 << "but was forced by a user.\n");
4705 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
4706 Factor.Width = Width;
4707 Factor.Cost = Width * Cost;
4711 unsigned LoopVectorizationCostModel::getWidestType() {
4712 unsigned MaxWidth = 8;
4713 const DataLayout &DL = TheFunction->getParent()->getDataLayout();
4716 for (Loop::block_iterator bb = TheLoop->block_begin(),
4717 be = TheLoop->block_end(); bb != be; ++bb) {
4718 BasicBlock *BB = *bb;
4720 // For each instruction in the loop.
4721 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4722 Type *T = it->getType();
4724 // Ignore ephemeral values.
4725 if (EphValues.count(it))
4728 // Only examine Loads, Stores and PHINodes.
4729 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4732 // Examine PHI nodes that are reduction variables.
4733 if (PHINode *PN = dyn_cast<PHINode>(it))
4734 if (!Legal->getReductionVars()->count(PN))
4737 // Examine the stored values.
4738 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4739 T = ST->getValueOperand()->getType();
4741 // Ignore loaded pointer types and stored pointer types that are not
4742 // consecutive. However, we do want to take consecutive stores/loads of
4743 // pointer vectors into account.
4744 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4747 MaxWidth = std::max(MaxWidth,
4748 (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
4755 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
4757 unsigned LoopCost) {
4759 // -- The interleave heuristics --
4760 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4761 // There are many micro-architectural considerations that we can't predict
4762 // at this level. For example, frontend pressure (on decode or fetch) due to
4763 // code size, or the number and capabilities of the execution ports.
4765 // We use the following heuristics to select the interleave count:
4766 // 1. If the code has reductions, then we interleave to break the cross
4767 // iteration dependency.
4768 // 2. If the loop is really small, then we interleave to reduce the loop
4770 // 3. We don't interleave if we think that we will spill registers to memory
4771 // due to the increased register pressure.
4773 // When we optimize for size, we don't interleave.
4777 // We used the distance for the interleave count.
4778 if (Legal->getMaxSafeDepDistBytes() != -1U)
4781 // Do not interleave loops with a relatively small trip count.
4782 unsigned TC = SE->getSmallConstantTripCount(TheLoop);
4783 if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
4786 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
4787 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
4791 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4792 TargetNumRegisters = ForceTargetNumScalarRegs;
4794 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4795 TargetNumRegisters = ForceTargetNumVectorRegs;
4798 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4799 // We divide by these constants so assume that we have at least one
4800 // instruction that uses at least one register.
4801 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4802 R.NumInstructions = std::max(R.NumInstructions, 1U);
4804 // We calculate the interleave count using the following formula.
4805 // Subtract the number of loop invariants from the number of available
4806 // registers. These registers are used by all of the interleaved instances.
4807 // Next, divide the remaining registers by the number of registers that is
4808 // required by the loop, in order to estimate how many parallel instances
4809 // fit without causing spills. All of this is rounded down if necessary to be
4810 // a power of two. We want power of two interleave count to simplify any
4811 // addressing operations or alignment considerations.
4812 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
4815 // Don't count the induction variable as interleaved.
4816 if (EnableIndVarRegisterHeur)
4817 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
4818 std::max(1U, (R.MaxLocalUsers - 1)));
4820 // Clamp the interleave ranges to reasonable counts.
4821 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4823 // Check if the user has overridden the max.
4825 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4826 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4828 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4829 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4832 // If we did not calculate the cost for VF (because the user selected the VF)
4833 // then we calculate the cost of VF here.
4835 LoopCost = expectedCost(VF);
4837 // Clamp the calculated IC to be between the 1 and the max interleave count
4838 // that the target allows.
4839 if (IC > MaxInterleaveCount)
4840 IC = MaxInterleaveCount;
4844 // Interleave if we vectorized this loop and there is a reduction that could
4845 // benefit from interleaving.
4846 if (VF > 1 && Legal->getReductionVars()->size()) {
4847 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
4851 // Note that if we've already vectorized the loop we will have done the
4852 // runtime check and so interleaving won't require further checks.
4853 bool InterleavingRequiresRuntimePointerCheck =
4854 (VF == 1 && Legal->getRuntimePointerChecking()->Need);
4856 // We want to interleave small loops in order to reduce the loop overhead and
4857 // potentially expose ILP opportunities.
4858 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4859 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
4860 // We assume that the cost overhead is 1 and we use the cost model
4861 // to estimate the cost of the loop and interleave until the cost of the
4862 // loop overhead is about 5% of the cost of the loop.
4864 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
4866 // Interleave until store/load ports (estimated by max interleave count) are
4868 unsigned NumStores = Legal->getNumStores();
4869 unsigned NumLoads = Legal->getNumLoads();
4870 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
4871 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
4873 // If we have a scalar reduction (vector reductions are already dealt with
4874 // by this point), we can increase the critical path length if the loop
4875 // we're interleaving is inside another loop. Limit, by default to 2, so the
4876 // critical path only gets increased by one reduction operation.
4877 if (Legal->getReductionVars()->size() &&
4878 TheLoop->getLoopDepth() > 1) {
4879 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
4880 SmallIC = std::min(SmallIC, F);
4881 StoresIC = std::min(StoresIC, F);
4882 LoadsIC = std::min(LoadsIC, F);
4885 if (EnableLoadStoreRuntimeInterleave &&
4886 std::max(StoresIC, LoadsIC) > SmallIC) {
4887 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
4888 return std::max(StoresIC, LoadsIC);
4891 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
4895 // Interleave if this is a large loop (small loops are already dealt with by
4897 // point) that could benefit from interleaving.
4898 bool HasReductions = (Legal->getReductionVars()->size() > 0);
4899 if (TTI.enableAggressiveInterleaving(HasReductions)) {
4900 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4904 DEBUG(dbgs() << "LV: Not Interleaving.\n");
4908 LoopVectorizationCostModel::RegisterUsage
4909 LoopVectorizationCostModel::calculateRegisterUsage() {
4910 // This function calculates the register usage by measuring the highest number
4911 // of values that are alive at a single location. Obviously, this is a very
4912 // rough estimation. We scan the loop in a topological order in order and
4913 // assign a number to each instruction. We use RPO to ensure that defs are
4914 // met before their users. We assume that each instruction that has in-loop
4915 // users starts an interval. We record every time that an in-loop value is
4916 // used, so we have a list of the first and last occurrences of each
4917 // instruction. Next, we transpose this data structure into a multi map that
4918 // holds the list of intervals that *end* at a specific location. This multi
4919 // map allows us to perform a linear search. We scan the instructions linearly
4920 // and record each time that a new interval starts, by placing it in a set.
4921 // If we find this value in the multi-map then we remove it from the set.
4922 // The max register usage is the maximum size of the set.
4923 // We also search for instructions that are defined outside the loop, but are
4924 // used inside the loop. We need this number separately from the max-interval
4925 // usage number because when we unroll, loop-invariant values do not take
4927 LoopBlocksDFS DFS(TheLoop);
4931 R.NumInstructions = 0;
4933 // Each 'key' in the map opens a new interval. The values
4934 // of the map are the index of the 'last seen' usage of the
4935 // instruction that is the key.
4936 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4937 // Maps instruction to its index.
4938 DenseMap<unsigned, Instruction*> IdxToInstr;
4939 // Marks the end of each interval.
4940 IntervalMap EndPoint;
4941 // Saves the list of instruction indices that are used in the loop.
4942 SmallSet<Instruction*, 8> Ends;
4943 // Saves the list of values that are used in the loop but are
4944 // defined outside the loop, such as arguments and constants.
4945 SmallPtrSet<Value*, 8> LoopInvariants;
4948 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4949 be = DFS.endRPO(); bb != be; ++bb) {
4950 R.NumInstructions += (*bb)->size();
4951 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4953 Instruction *I = it;
4954 IdxToInstr[Index++] = I;
4956 // Save the end location of each USE.
4957 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4958 Value *U = I->getOperand(i);
4959 Instruction *Instr = dyn_cast<Instruction>(U);
4961 // Ignore non-instruction values such as arguments, constants, etc.
4962 if (!Instr) continue;
4964 // If this instruction is outside the loop then record it and continue.
4965 if (!TheLoop->contains(Instr)) {
4966 LoopInvariants.insert(Instr);
4970 // Overwrite previous end points.
4971 EndPoint[Instr] = Index;
4977 // Saves the list of intervals that end with the index in 'key'.
4978 typedef SmallVector<Instruction*, 2> InstrList;
4979 DenseMap<unsigned, InstrList> TransposeEnds;
4981 // Transpose the EndPoints to a list of values that end at each index.
4982 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4984 TransposeEnds[it->second].push_back(it->first);
4986 SmallSet<Instruction*, 8> OpenIntervals;
4987 unsigned MaxUsage = 0;
4990 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4991 for (unsigned int i = 0; i < Index; ++i) {
4992 Instruction *I = IdxToInstr[i];
4993 // Ignore instructions that are never used within the loop.
4994 if (!Ends.count(I)) continue;
4996 // Ignore ephemeral values.
4997 if (EphValues.count(I))
5000 // Remove all of the instructions that end at this location.
5001 InstrList &List = TransposeEnds[i];
5002 for (unsigned int j=0, e = List.size(); j < e; ++j)
5003 OpenIntervals.erase(List[j]);
5005 // Count the number of live interals.
5006 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5008 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5009 OpenIntervals.size() << '\n');
5011 // Add the current instruction to the list of open intervals.
5012 OpenIntervals.insert(I);
5015 unsigned Invariant = LoopInvariants.size();
5016 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5017 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5018 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5020 R.LoopInvariantRegs = Invariant;
5021 R.MaxLocalUsers = MaxUsage;
5025 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5029 for (Loop::block_iterator bb = TheLoop->block_begin(),
5030 be = TheLoop->block_end(); bb != be; ++bb) {
5031 unsigned BlockCost = 0;
5032 BasicBlock *BB = *bb;
5034 // For each instruction in the old loop.
5035 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5036 // Skip dbg intrinsics.
5037 if (isa<DbgInfoIntrinsic>(it))
5040 // Ignore ephemeral values.
5041 if (EphValues.count(it))
5044 unsigned C = getInstructionCost(it, VF);
5046 // Check if we should override the cost.
5047 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5048 C = ForceTargetInstructionCost;
5051 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5052 VF << " For instruction: " << *it << '\n');
5055 // We assume that if-converted blocks have a 50% chance of being executed.
5056 // When the code is scalar then some of the blocks are avoided due to CF.
5057 // When the code is vectorized we execute all code paths.
5058 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5067 /// \brief Check whether the address computation for a non-consecutive memory
5068 /// access looks like an unlikely candidate for being merged into the indexing
5071 /// We look for a GEP which has one index that is an induction variable and all
5072 /// other indices are loop invariant. If the stride of this access is also
5073 /// within a small bound we decide that this address computation can likely be
5074 /// merged into the addressing mode.
5075 /// In all other cases, we identify the address computation as complex.
5076 static bool isLikelyComplexAddressComputation(Value *Ptr,
5077 LoopVectorizationLegality *Legal,
5078 ScalarEvolution *SE,
5079 const Loop *TheLoop) {
5080 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5084 // We are looking for a gep with all loop invariant indices except for one
5085 // which should be an induction variable.
5086 unsigned NumOperands = Gep->getNumOperands();
5087 for (unsigned i = 1; i < NumOperands; ++i) {
5088 Value *Opd = Gep->getOperand(i);
5089 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5090 !Legal->isInductionVariable(Opd))
5094 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5095 // can likely be merged into the address computation.
5096 unsigned MaxMergeDistance = 64;
5098 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5102 // Check the step is constant.
5103 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5104 // Calculate the pointer stride and check if it is consecutive.
5105 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5109 const APInt &APStepVal = C->getValue()->getValue();
5111 // Huge step value - give up.
5112 if (APStepVal.getBitWidth() > 64)
5115 int64_t StepVal = APStepVal.getSExtValue();
5117 return StepVal > MaxMergeDistance;
5120 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5121 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5127 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5128 // If we know that this instruction will remain uniform, check the cost of
5129 // the scalar version.
5130 if (Legal->isUniformAfterVectorization(I))
5133 Type *RetTy = I->getType();
5134 Type *VectorTy = ToVectorTy(RetTy, VF);
5136 // TODO: We need to estimate the cost of intrinsic calls.
5137 switch (I->getOpcode()) {
5138 case Instruction::GetElementPtr:
5139 // We mark this instruction as zero-cost because the cost of GEPs in
5140 // vectorized code depends on whether the corresponding memory instruction
5141 // is scalarized or not. Therefore, we handle GEPs with the memory
5142 // instruction cost.
5144 case Instruction::Br: {
5145 return TTI.getCFInstrCost(I->getOpcode());
5147 case Instruction::PHI:
5148 //TODO: IF-converted IFs become selects.
5150 case Instruction::Add:
5151 case Instruction::FAdd:
5152 case Instruction::Sub:
5153 case Instruction::FSub:
5154 case Instruction::Mul:
5155 case Instruction::FMul:
5156 case Instruction::UDiv:
5157 case Instruction::SDiv:
5158 case Instruction::FDiv:
5159 case Instruction::URem:
5160 case Instruction::SRem:
5161 case Instruction::FRem:
5162 case Instruction::Shl:
5163 case Instruction::LShr:
5164 case Instruction::AShr:
5165 case Instruction::And:
5166 case Instruction::Or:
5167 case Instruction::Xor: {
5168 // Since we will replace the stride by 1 the multiplication should go away.
5169 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5171 // Certain instructions can be cheaper to vectorize if they have a constant
5172 // second vector operand. One example of this are shifts on x86.
5173 TargetTransformInfo::OperandValueKind Op1VK =
5174 TargetTransformInfo::OK_AnyValue;
5175 TargetTransformInfo::OperandValueKind Op2VK =
5176 TargetTransformInfo::OK_AnyValue;
5177 TargetTransformInfo::OperandValueProperties Op1VP =
5178 TargetTransformInfo::OP_None;
5179 TargetTransformInfo::OperandValueProperties Op2VP =
5180 TargetTransformInfo::OP_None;
5181 Value *Op2 = I->getOperand(1);
5183 // Check for a splat of a constant or for a non uniform vector of constants.
5184 if (isa<ConstantInt>(Op2)) {
5185 ConstantInt *CInt = cast<ConstantInt>(Op2);
5186 if (CInt && CInt->getValue().isPowerOf2())
5187 Op2VP = TargetTransformInfo::OP_PowerOf2;
5188 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5189 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
5190 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5191 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
5193 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
5194 if (CInt && CInt->getValue().isPowerOf2())
5195 Op2VP = TargetTransformInfo::OP_PowerOf2;
5196 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5200 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
5203 case Instruction::Select: {
5204 SelectInst *SI = cast<SelectInst>(I);
5205 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5206 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5207 Type *CondTy = SI->getCondition()->getType();
5209 CondTy = VectorType::get(CondTy, VF);
5211 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5213 case Instruction::ICmp:
5214 case Instruction::FCmp: {
5215 Type *ValTy = I->getOperand(0)->getType();
5216 VectorTy = ToVectorTy(ValTy, VF);
5217 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5219 case Instruction::Store:
5220 case Instruction::Load: {
5221 StoreInst *SI = dyn_cast<StoreInst>(I);
5222 LoadInst *LI = dyn_cast<LoadInst>(I);
5223 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5225 VectorTy = ToVectorTy(ValTy, VF);
5227 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5228 unsigned AS = SI ? SI->getPointerAddressSpace() :
5229 LI->getPointerAddressSpace();
5230 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5231 // We add the cost of address computation here instead of with the gep
5232 // instruction because only here we know whether the operation is
5235 return TTI.getAddressComputationCost(VectorTy) +
5236 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5238 // For an interleaved access, calculate the total cost of the whole
5239 // interleave group.
5240 if (Legal->isAccessInterleaved(I)) {
5241 auto Group = Legal->getInterleavedAccessGroup(I);
5242 assert(Group && "Fail to get an interleaved access group.");
5244 // Only calculate the cost once at the insert position.
5245 if (Group->getInsertPos() != I)
5248 unsigned InterleaveFactor = Group->getFactor();
5250 VectorType::get(VectorTy->getVectorElementType(),
5251 VectorTy->getVectorNumElements() * InterleaveFactor);
5253 // Holds the indices of existing members in an interleaved load group.
5254 // An interleaved store group doesn't need this as it dones't allow gaps.
5255 SmallVector<unsigned, 4> Indices;
5257 for (unsigned i = 0; i < InterleaveFactor; i++)
5258 if (Group->getMember(i))
5259 Indices.push_back(i);
5262 // Calculate the cost of the whole interleaved group.
5263 unsigned Cost = TTI.getInterleavedMemoryOpCost(
5264 I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5265 Group->getAlignment(), AS);
5267 if (Group->isReverse())
5269 Group->getNumMembers() *
5270 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
5272 // FIXME: The interleaved load group with a huge gap could be even more
5273 // expensive than scalar operations. Then we could ignore such group and
5274 // use scalar operations instead.
5278 // Scalarized loads/stores.
5279 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5280 bool Reverse = ConsecutiveStride < 0;
5281 const DataLayout &DL = I->getModule()->getDataLayout();
5282 unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
5283 unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
5284 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5285 bool IsComplexComputation =
5286 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5288 // The cost of extracting from the value vector and pointer vector.
5289 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5290 for (unsigned i = 0; i < VF; ++i) {
5291 // The cost of extracting the pointer operand.
5292 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5293 // In case of STORE, the cost of ExtractElement from the vector.
5294 // In case of LOAD, the cost of InsertElement into the returned
5296 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5297 Instruction::InsertElement,
5301 // The cost of the scalar loads/stores.
5302 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5303 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5308 // Wide load/stores.
5309 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5310 if (Legal->isMaskRequired(I))
5311 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
5314 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5317 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5321 case Instruction::ZExt:
5322 case Instruction::SExt:
5323 case Instruction::FPToUI:
5324 case Instruction::FPToSI:
5325 case Instruction::FPExt:
5326 case Instruction::PtrToInt:
5327 case Instruction::IntToPtr:
5328 case Instruction::SIToFP:
5329 case Instruction::UIToFP:
5330 case Instruction::Trunc:
5331 case Instruction::FPTrunc:
5332 case Instruction::BitCast: {
5333 // We optimize the truncation of induction variable.
5334 // The cost of these is the same as the scalar operation.
5335 if (I->getOpcode() == Instruction::Trunc &&
5336 Legal->isInductionVariable(I->getOperand(0)))
5337 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5338 I->getOperand(0)->getType());
5340 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5341 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5343 case Instruction::Call: {
5344 bool NeedToScalarize;
5345 CallInst *CI = cast<CallInst>(I);
5346 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
5347 if (getIntrinsicIDForCall(CI, TLI))
5348 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
5352 // We are scalarizing the instruction. Return the cost of the scalar
5353 // instruction, plus the cost of insert and extract into vector
5354 // elements, times the vector width.
5357 if (!RetTy->isVoidTy() && VF != 1) {
5358 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5360 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5363 // The cost of inserting the results plus extracting each one of the
5365 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5368 // The cost of executing VF copies of the scalar instruction. This opcode
5369 // is unknown. Assume that it is the same as 'mul'.
5370 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5376 char LoopVectorize::ID = 0;
5377 static const char lv_name[] = "Loop Vectorization";
5378 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5379 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5380 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
5381 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5382 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
5383 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5384 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5385 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5386 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5387 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5388 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
5389 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5392 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5393 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5397 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5398 // Check for a store.
5399 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5400 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5402 // Check for a load.
5403 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5404 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5410 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
5411 bool IfPredicateStore) {
5412 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5413 // Holds vector parameters or scalars, in case of uniform vals.
5414 SmallVector<VectorParts, 4> Params;
5416 setDebugLocFromInst(Builder, Instr);
5418 // Find all of the vectorized parameters.
5419 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5420 Value *SrcOp = Instr->getOperand(op);
5422 // If we are accessing the old induction variable, use the new one.
5423 if (SrcOp == OldInduction) {
5424 Params.push_back(getVectorValue(SrcOp));
5428 // Try using previously calculated values.
5429 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5431 // If the src is an instruction that appeared earlier in the basic block
5432 // then it should already be vectorized.
5433 if (SrcInst && OrigLoop->contains(SrcInst)) {
5434 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5435 // The parameter is a vector value from earlier.
5436 Params.push_back(WidenMap.get(SrcInst));
5438 // The parameter is a scalar from outside the loop. Maybe even a constant.
5439 VectorParts Scalars;
5440 Scalars.append(UF, SrcOp);
5441 Params.push_back(Scalars);
5445 assert(Params.size() == Instr->getNumOperands() &&
5446 "Invalid number of operands");
5448 // Does this instruction return a value ?
5449 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5451 Value *UndefVec = IsVoidRetTy ? nullptr :
5452 UndefValue::get(Instr->getType());
5453 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5454 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5456 Instruction *InsertPt = Builder.GetInsertPoint();
5457 BasicBlock *IfBlock = Builder.GetInsertBlock();
5458 BasicBlock *CondBlock = nullptr;
5461 Loop *VectorLp = nullptr;
5462 if (IfPredicateStore) {
5463 assert(Instr->getParent()->getSinglePredecessor() &&
5464 "Only support single predecessor blocks");
5465 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
5466 Instr->getParent());
5467 VectorLp = LI->getLoopFor(IfBlock);
5468 assert(VectorLp && "Must have a loop for this block");
5471 // For each vector unroll 'part':
5472 for (unsigned Part = 0; Part < UF; ++Part) {
5473 // For each scalar that we create:
5475 // Start an "if (pred) a[i] = ..." block.
5476 Value *Cmp = nullptr;
5477 if (IfPredicateStore) {
5478 if (Cond[Part]->getType()->isVectorTy())
5480 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
5481 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
5482 ConstantInt::get(Cond[Part]->getType(), 1));
5483 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
5484 LoopVectorBody.push_back(CondBlock);
5485 VectorLp->addBasicBlockToLoop(CondBlock, *LI);
5486 // Update Builder with newly created basic block.
5487 Builder.SetInsertPoint(InsertPt);
5490 Instruction *Cloned = Instr->clone();
5492 Cloned->setName(Instr->getName() + ".cloned");
5493 // Replace the operands of the cloned instructions with extracted scalars.
5494 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5495 Value *Op = Params[op][Part];
5496 Cloned->setOperand(op, Op);
5499 // Place the cloned scalar in the new loop.
5500 Builder.Insert(Cloned);
5502 // If the original scalar returns a value we need to place it in a vector
5503 // so that future users will be able to use it.
5505 VecResults[Part] = Cloned;
5508 if (IfPredicateStore) {
5509 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
5510 LoopVectorBody.push_back(NewIfBlock);
5511 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
5512 Builder.SetInsertPoint(InsertPt);
5513 ReplaceInstWithInst(IfBlock->getTerminator(),
5514 BranchInst::Create(CondBlock, NewIfBlock, Cmp));
5515 IfBlock = NewIfBlock;
5520 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5521 StoreInst *SI = dyn_cast<StoreInst>(Instr);
5522 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
5524 return scalarizeInstruction(Instr, IfPredicateStore);
5527 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5531 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5535 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
5536 // When unrolling and the VF is 1, we only need to add a simple scalar.
5537 Type *ITy = Val->getType();
5538 assert(!ITy->isVectorTy() && "Val must be a scalar");
5539 Constant *C = ConstantInt::get(ITy, StartIdx);
5540 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");