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. Legalization of the IR is done
12 // in the codegen. However, the vectorizes uses (will use) the codegen
13 // interfaces to generate IR that is likely to result in an optimal binary.
15 // The loop vectorizer combines consecutive loop iteration into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A unit that checks for the legality
22 // of the vectorization.
23 // 3. InnerLoopVectorizer - A unit that performs the actual
24 // widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 // of vectorization. It decides on the optimal vector width, which
27 // can be one, if vectorization is not profitable.
29 //===----------------------------------------------------------------------===//
31 // The reduction-variable vectorization is based on the paper:
32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
37 // Other ideas/concepts are from:
38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
41 // Vectorizing Compilers.
43 //===----------------------------------------------------------------------===//
45 #define LV_NAME "loop-vectorize"
46 #define DEBUG_TYPE LV_NAME
48 #include "llvm/Transforms/Vectorize.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/MapVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/AliasSetTracker.h"
57 #include "llvm/Analysis/Dominators.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/LoopIterator.h"
60 #include "llvm/Analysis/LoopPass.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/ScalarEvolutionExpander.h"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Analysis/TargetTransformInfo.h"
65 #include "llvm/Analysis/ValueTracking.h"
66 #include "llvm/Analysis/Verifier.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/Instructions.h"
73 #include "llvm/IR/IntrinsicInst.h"
74 #include "llvm/IR/LLVMContext.h"
75 #include "llvm/IR/Module.h"
76 #include "llvm/IR/Type.h"
77 #include "llvm/IR/Value.h"
78 #include "llvm/Pass.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/Transforms/Scalar.h"
83 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
84 #include "llvm/Transforms/Utils/Local.h"
90 static cl::opt<unsigned>
91 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
92 cl::desc("Sets the SIMD width. Zero is autoselect."));
94 static cl::opt<unsigned>
95 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
96 cl::desc("Sets the vectorization unroll count. "
97 "Zero is autoselect."));
100 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
101 cl::desc("Enable if-conversion during vectorization."));
103 /// We don't vectorize loops with a known constant trip count below this number.
104 static const unsigned TinyTripCountVectorThreshold = 16;
106 /// We don't unroll loops with a known constant trip count below this number.
107 static const unsigned TinyTripCountUnrollThreshold = 128;
109 /// We don't unroll loops that are larget than this threshold.
110 static const unsigned MaxLoopSizeThreshold = 32;
112 /// When performing a runtime memory check, do not check more than this
113 /// number of pointers. Notice that the check is quadratic!
114 static const unsigned RuntimeMemoryCheckThreshold = 4;
118 // Forward declarations.
119 class LoopVectorizationLegality;
120 class LoopVectorizationCostModel;
122 /// InnerLoopVectorizer vectorizes loops which contain only one basic
123 /// block to a specified vectorization factor (VF).
124 /// This class performs the widening of scalars into vectors, or multiple
125 /// scalars. This class also implements the following features:
126 /// * It inserts an epilogue loop for handling loops that don't have iteration
127 /// counts that are known to be a multiple of the vectorization factor.
128 /// * It handles the code generation for reduction variables.
129 /// * Scalarization (implementation using scalars) of un-vectorizable
131 /// InnerLoopVectorizer does not perform any vectorization-legality
132 /// checks, and relies on the caller to check for the different legality
133 /// aspects. The InnerLoopVectorizer relies on the
134 /// LoopVectorizationLegality class to provide information about the induction
135 /// and reduction variables that were found to a given vectorization factor.
136 class InnerLoopVectorizer {
138 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
139 DominatorTree *DT, DataLayout *DL, unsigned VecWidth,
140 unsigned UnrollFactor)
141 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), VF(VecWidth),
142 UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
143 OldInduction(0), WidenMap(UnrollFactor) {}
145 // Perform the actual loop widening (vectorization).
146 void vectorize(LoopVectorizationLegality *Legal) {
147 // Create a new empty loop. Unlink the old loop and connect the new one.
148 createEmptyLoop(Legal);
149 // Widen each instruction in the old loop to a new one in the new loop.
150 // Use the Legality module to find the induction and reduction variables.
151 vectorizeLoop(Legal);
152 // Register the new loop and update the analysis passes.
157 /// A small list of PHINodes.
158 typedef SmallVector<PHINode*, 4> PhiVector;
159 /// When we unroll loops we have multiple vector values for each scalar.
160 /// This data structure holds the unrolled and vectorized values that
161 /// originated from one scalar instruction.
162 typedef SmallVector<Value*, 2> VectorParts;
164 /// Add code that checks at runtime if the accessed arrays overlap.
165 /// Returns the comparator value or NULL if no check is needed.
166 Value *addRuntimeCheck(LoopVectorizationLegality *Legal,
168 /// Create an empty loop, based on the loop ranges of the old loop.
169 void createEmptyLoop(LoopVectorizationLegality *Legal);
170 /// Copy and widen the instructions from the old loop.
171 void vectorizeLoop(LoopVectorizationLegality *Legal);
173 /// A helper function that computes the predicate of the block BB, assuming
174 /// that the header block of the loop is set to True. It returns the *entry*
175 /// mask for the block BB.
176 VectorParts createBlockInMask(BasicBlock *BB);
177 /// A helper function that computes the predicate of the edge between SRC
179 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
181 /// A helper function to vectorize a single BB within the innermost loop.
182 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
185 /// Insert the new loop to the loop hierarchy and pass manager
186 /// and update the analysis passes.
187 void updateAnalysis();
189 /// This instruction is un-vectorizable. Implement it as a sequence
191 void scalarizeInstruction(Instruction *Instr);
193 /// Create a broadcast instruction. This method generates a broadcast
194 /// instruction (shuffle) for loop invariant values and for the induction
195 /// value. If this is the induction variable then we extend it to N, N+1, ...
196 /// this is needed because each iteration in the loop corresponds to a SIMD
198 Value *getBroadcastInstrs(Value *V);
200 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
201 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
202 /// The sequence starts at StartIndex.
203 Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate);
205 /// When we go over instructions in the basic block we rely on previous
206 /// values within the current basic block or on loop invariant values.
207 /// When we widen (vectorize) values we place them in the map. If the values
208 /// are not within the map, they have to be loop invariant, so we simply
209 /// broadcast them into a vector.
210 VectorParts &getVectorValue(Value *V);
212 /// Generate a shuffle sequence that will reverse the vector Vec.
213 Value *reverseVector(Value *Vec);
215 /// This is a helper class that holds the vectorizer state. It maps scalar
216 /// instructions to vector instructions. When the code is 'unrolled' then
217 /// then a single scalar value is mapped to multiple vector parts. The parts
218 /// are stored in the VectorPart type.
220 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
222 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
224 /// \return True if 'Key' is saved in the Value Map.
225 bool has(Value *Key) { return MapStoreage.count(Key); }
227 /// Initializes a new entry in the map. Sets all of the vector parts to the
228 /// save value in 'Val'.
229 /// \return A reference to a vector with splat values.
230 VectorParts &splat(Value *Key, Value *Val) {
231 MapStoreage[Key].clear();
232 MapStoreage[Key].append(UF, Val);
233 return MapStoreage[Key];
236 ///\return A reference to the value that is stored at 'Key'.
237 VectorParts &get(Value *Key) {
239 MapStoreage[Key].resize(UF);
240 return MapStoreage[Key];
243 /// The unroll factor. Each entry in the map stores this number of vector
247 /// Map storage. We use std::map and not DenseMap because insertions to a
248 /// dense map invalidates its iterators.
249 std::map<Value*, VectorParts> MapStoreage;
252 /// The original loop.
254 /// Scev analysis to use.
262 /// The vectorization SIMD factor to use. Each vector will have this many
265 /// The vectorization unroll factor to use. Each scalar is vectorized to this
266 /// many different vector instructions.
269 /// The builder that we use
272 // --- Vectorization state ---
274 /// The vector-loop preheader.
275 BasicBlock *LoopVectorPreHeader;
276 /// The scalar-loop preheader.
277 BasicBlock *LoopScalarPreHeader;
278 /// Middle Block between the vector and the scalar.
279 BasicBlock *LoopMiddleBlock;
280 ///The ExitBlock of the scalar loop.
281 BasicBlock *LoopExitBlock;
282 ///The vector loop body.
283 BasicBlock *LoopVectorBody;
284 ///The scalar loop body.
285 BasicBlock *LoopScalarBody;
286 ///The first bypass block.
287 BasicBlock *LoopBypassBlock;
289 /// The new Induction variable which was added to the new block.
291 /// The induction variable of the old basic block.
292 PHINode *OldInduction;
293 /// Maps scalars to widened vectors.
297 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
298 /// to what vectorization factor.
299 /// This class does not look at the profitability of vectorization, only the
300 /// legality. This class has two main kinds of checks:
301 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
302 /// will change the order of memory accesses in a way that will change the
303 /// correctness of the program.
304 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
305 /// checks for a number of different conditions, such as the availability of a
306 /// single induction variable, that all types are supported and vectorize-able,
307 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
308 /// This class is also used by InnerLoopVectorizer for identifying
309 /// induction variable and the different reduction variables.
310 class LoopVectorizationLegality {
312 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
314 : TheLoop(L), SE(SE), DL(DL), DT(DT), Induction(0) {}
316 /// This enum represents the kinds of reductions that we support.
318 RK_NoReduction, ///< Not a reduction.
319 RK_IntegerAdd, ///< Sum of integers.
320 RK_IntegerMult, ///< Product of integers.
321 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
322 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
323 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
324 RK_FloatAdd, ///< Sum of floats.
325 RK_FloatMult ///< Product of floats.
328 /// This enum represents the kinds of inductions that we support.
330 IK_NoInduction, ///< Not an induction variable.
331 IK_IntInduction, ///< Integer induction variable. Step = 1.
332 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
333 IK_PtrInduction ///< Pointer induction variable. Step = sizeof(elem).
336 /// This POD struct holds information about reduction variables.
337 struct ReductionDescriptor {
338 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
339 Kind(RK_NoReduction) {}
341 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K)
342 : StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
344 // The starting value of the reduction.
345 // It does not have to be zero!
347 // The instruction who's value is used outside the loop.
348 Instruction *LoopExitInstr;
349 // The kind of the reduction.
353 // This POD struct holds information about the memory runtime legality
354 // check that a group of pointers do not overlap.
355 struct RuntimePointerCheck {
356 RuntimePointerCheck() : Need(false) {}
358 /// Reset the state of the pointer runtime information.
366 /// Insert a pointer and calculate the start and end SCEVs.
367 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
369 /// This flag indicates if we need to add the runtime check.
371 /// Holds the pointers that we need to check.
372 SmallVector<Value*, 2> Pointers;
373 /// Holds the pointer value at the beginning of the loop.
374 SmallVector<const SCEV*, 2> Starts;
375 /// Holds the pointer value at the end of the loop.
376 SmallVector<const SCEV*, 2> Ends;
379 /// A POD for saving information about induction variables.
380 struct InductionInfo {
381 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
382 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
389 /// ReductionList contains the reduction descriptors for all
390 /// of the reductions that were found in the loop.
391 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
393 /// InductionList saves induction variables and maps them to the
394 /// induction descriptor.
395 typedef MapVector<PHINode*, InductionInfo> InductionList;
397 /// Returns true if it is legal to vectorize this loop.
398 /// This does not mean that it is profitable to vectorize this
399 /// loop, only that it is legal to do so.
402 /// Returns the Induction variable.
403 PHINode *getInduction() { return Induction; }
405 /// Returns the reduction variables found in the loop.
406 ReductionList *getReductionVars() { return &Reductions; }
408 /// Returns the induction variables found in the loop.
409 InductionList *getInductionVars() { return &Inductions; }
411 /// Returns True if V is an induction variable in this loop.
412 bool isInductionVariable(const Value *V);
414 /// Return true if the block BB needs to be predicated in order for the loop
415 /// to be vectorized.
416 bool blockNeedsPredication(BasicBlock *BB);
418 /// Check if this pointer is consecutive when vectorizing. This happens
419 /// when the last index of the GEP is the induction variable, or that the
420 /// pointer itself is an induction variable.
421 /// This check allows us to vectorize A[idx] into a wide load/store.
423 /// 0 - Stride is unknown or non consecutive.
424 /// 1 - Address is consecutive.
425 /// -1 - Address is consecutive, and decreasing.
426 int isConsecutivePtr(Value *Ptr);
428 /// Returns true if the value V is uniform within the loop.
429 bool isUniform(Value *V);
431 /// Returns true if this instruction will remain scalar after vectorization.
432 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
434 /// Returns the information that we collected about runtime memory check.
435 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
437 /// Check if a single basic block loop is vectorizable.
438 /// At this point we know that this is a loop with a constant trip count
439 /// and we only need to check individual instructions.
440 bool canVectorizeInstrs();
442 /// When we vectorize loops we may change the order in which
443 /// we read and write from memory. This method checks if it is
444 /// legal to vectorize the code, considering only memory constrains.
445 /// Returns true if the loop is vectorizable
446 bool canVectorizeMemory();
448 /// Return true if we can vectorize this loop using the IF-conversion
450 bool canVectorizeWithIfConvert();
452 /// Collect the variables that need to stay uniform after vectorization.
453 void collectLoopUniforms();
455 /// Return true if all of the instructions in the block can be speculatively
457 bool blockCanBePredicated(BasicBlock *BB);
459 /// Returns True, if 'Phi' is the kind of reduction variable for type
460 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
461 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
462 /// Returns true if the instruction I can be a reduction variable of type
464 bool isReductionInstr(Instruction *I, ReductionKind Kind);
465 /// Returns the induction kind of Phi. This function may return NoInduction
466 /// if the PHI is not an induction variable.
467 InductionKind isInductionVariable(PHINode *Phi);
468 /// Return true if can compute the address bounds of Ptr within the loop.
469 bool hasComputableBounds(Value *Ptr);
471 /// The loop that we evaluate.
475 /// DataLayout analysis.
480 // --- vectorization state --- //
482 /// Holds the integer induction variable. This is the counter of the
485 /// Holds the reduction variables.
486 ReductionList Reductions;
487 /// Holds all of the induction variables that we found in the loop.
488 /// Notice that inductions don't need to start at zero and that induction
489 /// variables can be pointers.
490 InductionList Inductions;
492 /// Allowed outside users. This holds the reduction
493 /// vars which can be accessed from outside the loop.
494 SmallPtrSet<Value*, 4> AllowedExit;
495 /// This set holds the variables which are known to be uniform after
497 SmallPtrSet<Instruction*, 4> Uniforms;
498 /// We need to check that all of the pointers in this list are disjoint
500 RuntimePointerCheck PtrRtCheck;
503 /// LoopVectorizationCostModel - estimates the expected speedups due to
505 /// In many cases vectorization is not profitable. This can happen because of
506 /// a number of reasons. In this class we mainly attempt to predict the
507 /// expected speedup/slowdowns due to the supported instruction set. We use the
508 /// TargetTransformInfo to query the different backends for the cost of
509 /// different operations.
510 class LoopVectorizationCostModel {
512 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
513 LoopVectorizationLegality *Legal,
514 const TargetTransformInfo &TTI)
515 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI) {}
517 /// \return The most profitable vectorization factor.
518 /// This method checks every power of two up to VF. If UserVF is not ZERO
519 /// then this vectorization factor will be selected if vectorization is
521 unsigned selectVectorizationFactor(bool OptForSize, unsigned UserVF);
523 /// \returns The size (in bits) of the widest type in the code that
524 /// needs to be vectorized. We ignore values that remain scalar such as
525 /// 64 bit loop indices.
526 unsigned getWidestType();
528 /// \return The most profitable unroll factor.
529 /// If UserUF is non-zero then this method finds the best unroll-factor
530 /// based on register pressure and other parameters.
531 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF);
533 /// \brief A struct that represents some properties of the register usage
535 struct RegisterUsage {
536 /// Holds the number of loop invariant values that are used in the loop.
537 unsigned LoopInvariantRegs;
538 /// Holds the maximum number of concurrent live intervals in the loop.
539 unsigned MaxLocalUsers;
540 /// Holds the number of instructions in the loop.
541 unsigned NumInstructions;
544 /// \return information about the register usage of the loop.
545 RegisterUsage calculateRegisterUsage();
548 /// Returns the expected execution cost. The unit of the cost does
549 /// not matter because we use the 'cost' units to compare different
550 /// vector widths. The cost that is returned is *not* normalized by
551 /// the factor width.
552 unsigned expectedCost(unsigned VF);
554 /// Returns the execution time cost of an instruction for a given vector
555 /// width. Vector width of one means scalar.
556 unsigned getInstructionCost(Instruction *I, unsigned VF);
558 /// A helper function for converting Scalar types to vector types.
559 /// If the incoming type is void, we return void. If the VF is 1, we return
561 static Type* ToVectorTy(Type *Scalar, unsigned VF);
563 /// The loop that we evaluate.
567 /// Loop Info analysis.
569 /// Vectorization legality.
570 LoopVectorizationLegality *Legal;
571 /// Vector target information.
572 const TargetTransformInfo &TTI;
575 /// The LoopVectorize Pass.
576 struct LoopVectorize : public LoopPass {
577 /// Pass identification, replacement for typeid
580 explicit LoopVectorize() : LoopPass(ID) {
581 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
587 TargetTransformInfo *TTI;
590 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
591 // We only vectorize innermost loops.
595 SE = &getAnalysis<ScalarEvolution>();
596 DL = getAnalysisIfAvailable<DataLayout>();
597 LI = &getAnalysis<LoopInfo>();
598 TTI = &getAnalysis<TargetTransformInfo>();
599 DT = &getAnalysis<DominatorTree>();
601 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
602 L->getHeader()->getParent()->getName() << "\"\n");
604 // Check if it is legal to vectorize the loop.
605 LoopVectorizationLegality LVL(L, SE, DL, DT);
606 if (!LVL.canVectorize()) {
607 DEBUG(dbgs() << "LV: Not vectorizing.\n");
611 // Use the cost model.
612 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI);
614 // Check the function attribues to find out if this function should be
615 // optimized for size.
616 Function *F = L->getHeader()->getParent();
617 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
618 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
619 unsigned FnIndex = AttributeSet::FunctionIndex;
620 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
621 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
624 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
625 "attribute is used.\n");
629 unsigned VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
630 unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll);
633 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
637 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
638 F->getParent()->getModuleIdentifier()<<"\n");
639 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
641 // If we decided that it is *legal* to vectorizer the loop then do it.
642 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF, UF);
645 DEBUG(verifyFunction(*L->getHeader()->getParent()));
649 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
650 LoopPass::getAnalysisUsage(AU);
651 AU.addRequiredID(LoopSimplifyID);
652 AU.addRequiredID(LCSSAID);
653 AU.addRequired<DominatorTree>();
654 AU.addRequired<LoopInfo>();
655 AU.addRequired<ScalarEvolution>();
656 AU.addRequired<TargetTransformInfo>();
657 AU.addPreserved<LoopInfo>();
658 AU.addPreserved<DominatorTree>();
663 } // end anonymous namespace
665 //===----------------------------------------------------------------------===//
666 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
667 // LoopVectorizationCostModel.
668 //===----------------------------------------------------------------------===//
671 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
672 Loop *Lp, Value *Ptr) {
673 const SCEV *Sc = SE->getSCEV(Ptr);
674 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
675 assert(AR && "Invalid addrec expression");
676 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
677 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
678 Pointers.push_back(Ptr);
679 Starts.push_back(AR->getStart());
680 Ends.push_back(ScEnd);
683 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
684 // Save the current insertion location.
685 Instruction *Loc = Builder.GetInsertPoint();
687 // We need to place the broadcast of invariant variables outside the loop.
688 Instruction *Instr = dyn_cast<Instruction>(V);
689 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
690 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
692 // Place the code for broadcasting invariant variables in the new preheader.
694 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
696 // Broadcast the scalar into all locations in the vector.
697 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
699 // Restore the builder insertion point.
701 Builder.SetInsertPoint(Loc);
706 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
708 assert(Val->getType()->isVectorTy() && "Must be a vector");
709 assert(Val->getType()->getScalarType()->isIntegerTy() &&
710 "Elem must be an integer");
712 Type *ITy = Val->getType()->getScalarType();
713 VectorType *Ty = cast<VectorType>(Val->getType());
714 int VLen = Ty->getNumElements();
715 SmallVector<Constant*, 8> Indices;
717 // Create a vector of consecutive numbers from zero to VF.
718 for (int i = 0; i < VLen; ++i) {
719 int Idx = Negate ? (-i): i;
720 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
723 // Add the consecutive indices to the vector value.
724 Constant *Cv = ConstantVector::get(Indices);
725 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
726 return Builder.CreateAdd(Val, Cv, "induction");
729 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
730 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
732 // If this value is a pointer induction variable we know it is consecutive.
733 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
734 if (Phi && Inductions.count(Phi)) {
735 InductionInfo II = Inductions[Phi];
736 if (IK_PtrInduction == II.IK)
740 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
744 unsigned NumOperands = Gep->getNumOperands();
745 Value *LastIndex = Gep->getOperand(NumOperands - 1);
747 // Check that all of the gep indices are uniform except for the last.
748 for (unsigned i = 0; i < NumOperands - 1; ++i)
749 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
752 // We can emit wide load/stores only if the last index is the induction
754 const SCEV *Last = SE->getSCEV(LastIndex);
755 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
756 const SCEV *Step = AR->getStepRecurrence(*SE);
758 // The memory is consecutive because the last index is consecutive
759 // and all other indices are loop invariant.
762 if (Step->isAllOnesValue())
769 bool LoopVectorizationLegality::isUniform(Value *V) {
770 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
773 InnerLoopVectorizer::VectorParts&
774 InnerLoopVectorizer::getVectorValue(Value *V) {
775 assert(V != Induction && "The new induction variable should not be used.");
776 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
778 // If we have this scalar in the map, return it.
780 return WidenMap.get(V);
782 // If this scalar is unknown, assume that it is a constant or that it is
783 // loop invariant. Broadcast V and save the value for future uses.
784 Value *B = getBroadcastInstrs(V);
785 WidenMap.splat(V, B);
786 return WidenMap.get(V);
789 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
790 assert(Vec->getType()->isVectorTy() && "Invalid type");
791 SmallVector<Constant*, 8> ShuffleMask;
792 for (unsigned i = 0; i < VF; ++i)
793 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
795 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
796 ConstantVector::get(ShuffleMask),
800 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
801 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
802 // Holds vector parameters or scalars, in case of uniform vals.
803 SmallVector<VectorParts, 4> Params;
805 // Find all of the vectorized parameters.
806 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
807 Value *SrcOp = Instr->getOperand(op);
809 // If we are accessing the old induction variable, use the new one.
810 if (SrcOp == OldInduction) {
811 Params.push_back(getVectorValue(SrcOp));
815 // Try using previously calculated values.
816 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
818 // If the src is an instruction that appeared earlier in the basic block
819 // then it should already be vectorized.
820 if (SrcInst && OrigLoop->contains(SrcInst)) {
821 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
822 // The parameter is a vector value from earlier.
823 Params.push_back(WidenMap.get(SrcInst));
825 // The parameter is a scalar from outside the loop. Maybe even a constant.
827 Scalars.append(UF, SrcOp);
828 Params.push_back(Scalars);
832 assert(Params.size() == Instr->getNumOperands() &&
833 "Invalid number of operands");
835 // Does this instruction return a value ?
836 bool IsVoidRetTy = Instr->getType()->isVoidTy();
838 Value *UndefVec = IsVoidRetTy ? 0 :
839 UndefValue::get(VectorType::get(Instr->getType(), VF));
840 // Create a new entry in the WidenMap and initialize it to Undef or Null.
841 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
843 // For each scalar that we create:
844 for (unsigned Width = 0; Width < VF; ++Width) {
845 // For each vector unroll 'part':
846 for (unsigned Part = 0; Part < UF; ++Part) {
847 Instruction *Cloned = Instr->clone();
849 Cloned->setName(Instr->getName() + ".cloned");
850 // Replace the operands of the cloned instrucions with extracted scalars.
851 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
852 Value *Op = Params[op][Part];
853 // Param is a vector. Need to extract the right lane.
854 if (Op->getType()->isVectorTy())
855 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
856 Cloned->setOperand(op, Op);
859 // Place the cloned scalar in the new loop.
860 Builder.Insert(Cloned);
862 // If the original scalar returns a value we need to place it in a vector
863 // so that future users will be able to use it.
865 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
866 Builder.getInt32(Width));
872 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
874 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
875 Legal->getRuntimePointerCheck();
877 if (!PtrRtCheck->Need)
880 Value *MemoryRuntimeCheck = 0;
881 unsigned NumPointers = PtrRtCheck->Pointers.size();
882 SmallVector<Value* , 2> Starts;
883 SmallVector<Value* , 2> Ends;
885 SCEVExpander Exp(*SE, "induction");
887 // Use this type for pointer arithmetic.
888 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
890 for (unsigned i = 0; i < NumPointers; ++i) {
891 Value *Ptr = PtrRtCheck->Pointers[i];
892 const SCEV *Sc = SE->getSCEV(Ptr);
894 if (SE->isLoopInvariant(Sc, OrigLoop)) {
895 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
897 Starts.push_back(Ptr);
900 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
902 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
903 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
904 Starts.push_back(Start);
909 for (unsigned i = 0; i < NumPointers; ++i) {
910 for (unsigned j = i+1; j < NumPointers; ++j) {
911 Instruction::CastOps Op = Instruction::BitCast;
912 Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
913 Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
914 Value *End0 = CastInst::Create(Op, Ends[i], PtrArithTy, "bc", Loc);
915 Value *End1 = CastInst::Create(Op, Ends[j], PtrArithTy, "bc", Loc);
917 Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
918 Start0, End1, "bound0", Loc);
919 Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
920 Start1, End0, "bound1", Loc);
921 Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
922 "found.conflict", Loc);
923 if (MemoryRuntimeCheck)
924 MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
927 "conflict.rdx", Loc);
929 MemoryRuntimeCheck = IsConflict;
934 return MemoryRuntimeCheck;
938 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
940 In this function we generate a new loop. The new loop will contain
941 the vectorized instructions while the old loop will continue to run the
944 [ ] <-- vector loop bypass.
947 | [ ] <-- vector pre header.
951 | [ ]_| <-- vector loop.
954 >[ ] <--- middle-block.
957 | [ ] <--- new preheader.
961 | [ ]_| <-- old scalar loop to handle remainder.
968 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
969 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
970 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
971 assert(ExitBlock && "Must have an exit block");
973 // Some loops have a single integer induction variable, while other loops
974 // don't. One example is c++ iterators that often have multiple pointer
975 // induction variables. In the code below we also support a case where we
976 // don't have a single induction variable.
977 OldInduction = Legal->getInduction();
978 Type *IdxTy = OldInduction ? OldInduction->getType() :
979 DL->getIntPtrType(SE->getContext());
981 // Find the loop boundaries.
982 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
983 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
985 // Get the total trip count from the count by adding 1.
986 ExitCount = SE->getAddExpr(ExitCount,
987 SE->getConstant(ExitCount->getType(), 1));
989 // Expand the trip count and place the new instructions in the preheader.
990 // Notice that the pre-header does not change, only the loop body.
991 SCEVExpander Exp(*SE, "induction");
993 // Count holds the overall loop count (N).
994 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
995 BypassBlock->getTerminator());
997 // The loop index does not have to start at Zero. Find the original start
998 // value from the induction PHI node. If we don't have an induction variable
999 // then we know that it starts at zero.
1000 Value *StartIdx = OldInduction ?
1001 OldInduction->getIncomingValueForBlock(BypassBlock):
1002 ConstantInt::get(IdxTy, 0);
1004 assert(BypassBlock && "Invalid loop structure");
1006 // Generate the code that checks in runtime if arrays overlap.
1007 Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
1008 BypassBlock->getTerminator());
1010 // Split the single block loop into the two loop structure described above.
1011 BasicBlock *VectorPH =
1012 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1013 BasicBlock *VecBody =
1014 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1015 BasicBlock *MiddleBlock =
1016 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1017 BasicBlock *ScalarPH =
1018 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1020 // This is the location in which we add all of the logic for bypassing
1021 // the new vector loop.
1022 Instruction *Loc = BypassBlock->getTerminator();
1024 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1026 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1028 // Generate the induction variable.
1029 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1030 // The loop step is equal to the vectorization factor (num of SIMD elements)
1031 // times the unroll factor (num of SIMD instructions).
1032 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1034 // We may need to extend the index in case there is a type mismatch.
1035 // We know that the count starts at zero and does not overflow.
1036 unsigned IdxTyBW = IdxTy->getScalarSizeInBits();
1037 if (Count->getType() != IdxTy) {
1038 // The exit count can be of pointer type. Convert it to the correct
1040 if (ExitCount->getType()->isPointerTy())
1041 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
1042 else if (IdxTyBW < Count->getType()->getScalarSizeInBits())
1043 Count = CastInst::CreateTruncOrBitCast(Count, IdxTy, "tr.cnt", Loc);
1045 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
1048 // Add the start index to the loop count to get the new end index.
1049 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
1051 // Now we need to generate the expression for N - (N % VF), which is
1052 // the part that the vectorized body will execute.
1053 Value *R = BinaryOperator::CreateURem(Count, Step, "n.mod.vf", Loc);
1054 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
1055 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
1056 "end.idx.rnd.down", Loc);
1058 // Now, compare the new count to zero. If it is zero skip the vector loop and
1059 // jump to the scalar loop.
1060 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
1065 // If we are using memory runtime checks, include them in.
1066 if (MemoryRuntimeCheck)
1067 Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
1070 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
1071 // Remove the old terminator.
1072 Loc->eraseFromParent();
1074 // We are going to resume the execution of the scalar loop.
1075 // Go over all of the induction variables that we found and fix the
1076 // PHIs that are left in the scalar version of the loop.
1077 // The starting values of PHI nodes depend on the counter of the last
1078 // iteration in the vectorized loop.
1079 // If we come from a bypass edge then we need to start from the original
1082 // This variable saves the new starting index for the scalar loop.
1083 PHINode *ResumeIndex = 0;
1084 LoopVectorizationLegality::InductionList::iterator I, E;
1085 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1086 for (I = List->begin(), E = List->end(); I != E; ++I) {
1087 PHINode *OrigPhi = I->first;
1088 LoopVectorizationLegality::InductionInfo II = I->second;
1089 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1090 MiddleBlock->getTerminator());
1091 Value *EndValue = 0;
1093 case LoopVectorizationLegality::IK_NoInduction:
1094 llvm_unreachable("Unknown induction");
1095 case LoopVectorizationLegality::IK_IntInduction: {
1096 // Handle the integer induction counter:
1097 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1098 assert(OrigPhi == OldInduction && "Unknown integer PHI");
1099 // We know what the end value is.
1100 EndValue = IdxEndRoundDown;
1101 // We also know which PHI node holds it.
1102 ResumeIndex = ResumeVal;
1105 case LoopVectorizationLegality::IK_ReverseIntInduction: {
1106 // Convert the CountRoundDown variable to the PHI size.
1107 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1108 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1109 Value *CRD = CountRoundDown;
1110 if (CRDSize > IISize)
1111 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1112 II.StartValue->getType(),
1113 "tr.crd", BypassBlock->getTerminator());
1114 else if (CRDSize < IISize)
1115 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1116 II.StartValue->getType(),
1117 "sext.crd", BypassBlock->getTerminator());
1118 // Handle reverse integer induction counter:
1119 EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1120 BypassBlock->getTerminator());
1123 case LoopVectorizationLegality::IK_PtrInduction: {
1124 // For pointer induction variables, calculate the offset using
1126 EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
1128 BypassBlock->getTerminator());
1133 // The new PHI merges the original incoming value, in case of a bypass,
1134 // or the value at the end of the vectorized loop.
1135 ResumeVal->addIncoming(II.StartValue, BypassBlock);
1136 ResumeVal->addIncoming(EndValue, VecBody);
1138 // Fix the scalar body counter (PHI node).
1139 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1140 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1143 // If we are generating a new induction variable then we also need to
1144 // generate the code that calculates the exit value. This value is not
1145 // simply the end of the counter because we may skip the vectorized body
1146 // in case of a runtime check.
1148 assert(!ResumeIndex && "Unexpected resume value found");
1149 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1150 MiddleBlock->getTerminator());
1151 ResumeIndex->addIncoming(StartIdx, BypassBlock);
1152 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1155 // Make sure that we found the index where scalar loop needs to continue.
1156 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1157 "Invalid resume Index");
1159 // Add a check in the middle block to see if we have completed
1160 // all of the iterations in the first vector loop.
1161 // If (N - N%VF) == N, then we *don't* need to run the remainder.
1162 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1163 ResumeIndex, "cmp.n",
1164 MiddleBlock->getTerminator());
1166 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1167 // Remove the old terminator.
1168 MiddleBlock->getTerminator()->eraseFromParent();
1170 // Create i+1 and fill the PHINode.
1171 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1172 Induction->addIncoming(StartIdx, VectorPH);
1173 Induction->addIncoming(NextIdx, VecBody);
1174 // Create the compare.
1175 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1176 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1178 // Now we have two terminators. Remove the old one from the block.
1179 VecBody->getTerminator()->eraseFromParent();
1181 // Get ready to start creating new instructions into the vectorized body.
1182 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1184 // Create and register the new vector loop.
1185 Loop* Lp = new Loop();
1186 Loop *ParentLoop = OrigLoop->getParentLoop();
1188 // Insert the new loop into the loop nest and register the new basic blocks.
1190 ParentLoop->addChildLoop(Lp);
1191 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1192 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1193 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1195 LI->addTopLevelLoop(Lp);
1198 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1201 LoopVectorPreHeader = VectorPH;
1202 LoopScalarPreHeader = ScalarPH;
1203 LoopMiddleBlock = MiddleBlock;
1204 LoopExitBlock = ExitBlock;
1205 LoopVectorBody = VecBody;
1206 LoopScalarBody = OldBasicBlock;
1207 LoopBypassBlock = BypassBlock;
1210 /// This function returns the identity element (or neutral element) for
1211 /// the operation K.
1213 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) {
1215 case LoopVectorizationLegality:: RK_IntegerXor:
1216 case LoopVectorizationLegality:: RK_IntegerAdd:
1217 case LoopVectorizationLegality:: RK_IntegerOr:
1218 // Adding, Xoring, Oring zero to a number does not change it.
1219 return ConstantInt::get(Tp, 0);
1220 case LoopVectorizationLegality:: RK_IntegerMult:
1221 // Multiplying a number by 1 does not change it.
1222 return ConstantInt::get(Tp, 1);
1223 case LoopVectorizationLegality:: RK_IntegerAnd:
1224 // AND-ing a number with an all-1 value does not change it.
1225 return ConstantInt::get(Tp, -1, true);
1226 case LoopVectorizationLegality:: RK_FloatMult:
1227 // Multiplying a number by 1 does not change it.
1228 return ConstantFP::get(Tp, 1.0L);
1229 case LoopVectorizationLegality:: RK_FloatAdd:
1230 // Adding zero to a number does not change it.
1231 return ConstantFP::get(Tp, 0.0L);
1233 llvm_unreachable("Unknown reduction kind");
1238 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
1239 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
1242 switch (II->getIntrinsicID()) {
1243 case Intrinsic::sqrt:
1244 case Intrinsic::sin:
1245 case Intrinsic::cos:
1246 case Intrinsic::exp:
1247 case Intrinsic::exp2:
1248 case Intrinsic::log:
1249 case Intrinsic::log10:
1250 case Intrinsic::log2:
1251 case Intrinsic::fabs:
1252 case Intrinsic::floor:
1253 case Intrinsic::ceil:
1254 case Intrinsic::trunc:
1255 case Intrinsic::rint:
1256 case Intrinsic::nearbyint:
1257 case Intrinsic::pow:
1258 case Intrinsic::fma:
1259 case Intrinsic::fmuladd:
1267 /// This function translates the reduction kind to an LLVM binary operator.
1268 static Instruction::BinaryOps
1269 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1271 case LoopVectorizationLegality::RK_IntegerAdd:
1272 return Instruction::Add;
1273 case LoopVectorizationLegality::RK_IntegerMult:
1274 return Instruction::Mul;
1275 case LoopVectorizationLegality::RK_IntegerOr:
1276 return Instruction::Or;
1277 case LoopVectorizationLegality::RK_IntegerAnd:
1278 return Instruction::And;
1279 case LoopVectorizationLegality::RK_IntegerXor:
1280 return Instruction::Xor;
1281 case LoopVectorizationLegality::RK_FloatMult:
1282 return Instruction::FMul;
1283 case LoopVectorizationLegality::RK_FloatAdd:
1284 return Instruction::FAdd;
1286 llvm_unreachable("Unknown reduction operation");
1291 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1292 //===------------------------------------------------===//
1294 // Notice: any optimization or new instruction that go
1295 // into the code below should be also be implemented in
1298 //===------------------------------------------------===//
1299 BasicBlock &BB = *OrigLoop->getHeader();
1301 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
1303 // In order to support reduction variables we need to be able to vectorize
1304 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1305 // stages. First, we create a new vector PHI node with no incoming edges.
1306 // We use this value when we vectorize all of the instructions that use the
1307 // PHI. Next, after all of the instructions in the block are complete we
1308 // add the new incoming edges to the PHI. At this point all of the
1309 // instructions in the basic block are vectorized, so we can use them to
1310 // construct the PHI.
1311 PhiVector RdxPHIsToFix;
1313 // Scan the loop in a topological order to ensure that defs are vectorized
1315 LoopBlocksDFS DFS(OrigLoop);
1318 // Vectorize all of the blocks in the original loop.
1319 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1320 be = DFS.endRPO(); bb != be; ++bb)
1321 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1323 // At this point every instruction in the original loop is widened to
1324 // a vector form. We are almost done. Now, we need to fix the PHI nodes
1325 // that we vectorized. The PHI nodes are currently empty because we did
1326 // not want to introduce cycles. Notice that the remaining PHI nodes
1327 // that we need to fix are reduction variables.
1329 // Create the 'reduced' values for each of the induction vars.
1330 // The reduced values are the vector values that we scalarize and combine
1331 // after the loop is finished.
1332 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1334 PHINode *RdxPhi = *it;
1335 assert(RdxPhi && "Unable to recover vectorized PHI");
1337 // Find the reduction variable descriptor.
1338 assert(Legal->getReductionVars()->count(RdxPhi) &&
1339 "Unable to find the reduction variable");
1340 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1341 (*Legal->getReductionVars())[RdxPhi];
1343 // We need to generate a reduction vector from the incoming scalar.
1344 // To do so, we need to generate the 'identity' vector and overide
1345 // one of the elements with the incoming scalar reduction. We need
1346 // to do it in the vector-loop preheader.
1347 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
1349 // This is the vector-clone of the value that leaves the loop.
1350 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1351 Type *VecTy = VectorExit[0]->getType();
1353 // Find the reduction identity variable. Zero for addition, or, xor,
1354 // one for multiplication, -1 for And.
1355 Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType());
1356 Constant *Identity = ConstantVector::getSplat(VF, Iden);
1358 // This vector is the Identity vector where the first element is the
1359 // incoming scalar reduction.
1360 Value *VectorStart = Builder.CreateInsertElement(Identity,
1361 RdxDesc.StartValue, Zero);
1363 // Fix the vector-loop phi.
1364 // We created the induction variable so we know that the
1365 // preheader is the first entry.
1366 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1368 // Reductions do not have to start at zero. They can start with
1369 // any loop invariant values.
1370 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1371 BasicBlock *Latch = OrigLoop->getLoopLatch();
1372 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1373 VectorParts &Val = getVectorValue(LoopVal);
1374 for (unsigned part = 0; part < UF; ++part) {
1375 // Make sure to add the reduction stat value only to the
1376 // first unroll part.
1377 Value *StartVal = (part == 0) ? VectorStart : Identity;
1378 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1379 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1382 // Before each round, move the insertion point right between
1383 // the PHIs and the values we are going to write.
1384 // This allows us to write both PHINodes and the extractelement
1386 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1388 VectorParts RdxParts;
1389 for (unsigned part = 0; part < UF; ++part) {
1390 // This PHINode contains the vectorized reduction variable, or
1391 // the initial value vector, if we bypass the vector loop.
1392 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1393 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1394 Value *StartVal = (part == 0) ? VectorStart : Identity;
1395 NewPhi->addIncoming(StartVal, LoopBypassBlock);
1396 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1397 RdxParts.push_back(NewPhi);
1400 // Reduce all of the unrolled parts into a single vector.
1401 Value *ReducedPartRdx = RdxParts[0];
1402 for (unsigned part = 1; part < UF; ++part) {
1403 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1404 ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx,
1408 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1409 // and vector ops, reducing the set of values being computed by half each
1411 assert(isPowerOf2_32(VF) &&
1412 "Reduction emission only supported for pow2 vectors!");
1413 Value *TmpVec = ReducedPartRdx;
1414 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1415 for (unsigned i = VF; i != 1; i >>= 1) {
1416 // Move the upper half of the vector to the lower half.
1417 for (unsigned j = 0; j != i/2; ++j)
1418 ShuffleMask[j] = Builder.getInt32(i/2 + j);
1420 // Fill the rest of the mask with undef.
1421 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1422 UndefValue::get(Builder.getInt32Ty()));
1425 Builder.CreateShuffleVector(TmpVec,
1426 UndefValue::get(TmpVec->getType()),
1427 ConstantVector::get(ShuffleMask),
1430 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1431 TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx");
1434 // The result is in the first element of the vector.
1435 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1437 // Now, we need to fix the users of the reduction variable
1438 // inside and outside of the scalar remainder loop.
1439 // We know that the loop is in LCSSA form. We need to update the
1440 // PHI nodes in the exit blocks.
1441 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1442 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1443 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1444 if (!LCSSAPhi) continue;
1446 // All PHINodes need to have a single entry edge, or two if
1447 // we already fixed them.
1448 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1450 // We found our reduction value exit-PHI. Update it with the
1451 // incoming bypass edge.
1452 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1453 // Add an edge coming from the bypass.
1454 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1457 }// end of the LCSSA phi scan.
1459 // Fix the scalar loop reduction variable with the incoming reduction sum
1460 // from the vector body and from the backedge value.
1461 int IncomingEdgeBlockIdx =
1462 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1463 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1464 // Pick the other block.
1465 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1466 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1467 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1468 }// end of for each redux variable.
1470 // The Loop exit block may have single value PHI nodes where the incoming
1471 // value is 'undef'. While vectorizing we only handled real values that
1472 // were defined inside the loop. Here we handle the 'undef case'.
1474 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1475 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1476 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1477 if (!LCSSAPhi) continue;
1478 if (LCSSAPhi->getNumIncomingValues() == 1)
1479 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1484 InnerLoopVectorizer::VectorParts
1485 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1486 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1489 VectorParts SrcMask = createBlockInMask(Src);
1491 // The terminator has to be a branch inst!
1492 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1493 assert(BI && "Unexpected terminator found");
1495 if (BI->isConditional()) {
1496 VectorParts EdgeMask = getVectorValue(BI->getCondition());
1498 if (BI->getSuccessor(0) != Dst)
1499 for (unsigned part = 0; part < UF; ++part)
1500 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1502 for (unsigned part = 0; part < UF; ++part)
1503 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1510 InnerLoopVectorizer::VectorParts
1511 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1512 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1514 // Loop incoming mask is all-one.
1515 if (OrigLoop->getHeader() == BB) {
1516 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1517 return getVectorValue(C);
1520 // This is the block mask. We OR all incoming edges, and with zero.
1521 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1522 VectorParts BlockMask = getVectorValue(Zero);
1525 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1526 VectorParts EM = createEdgeMask(*it, BB);
1527 for (unsigned part = 0; part < UF; ++part)
1528 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1535 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1536 BasicBlock *BB, PhiVector *PV) {
1537 Constant *Zero = Builder.getInt32(0);
1539 // For each instruction in the old loop.
1540 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1541 VectorParts &Entry = WidenMap.get(it);
1542 switch (it->getOpcode()) {
1543 case Instruction::Br:
1544 // Nothing to do for PHIs and BR, since we already took care of the
1545 // loop control flow instructions.
1547 case Instruction::PHI:{
1548 PHINode* P = cast<PHINode>(it);
1549 // Handle reduction variables:
1550 if (Legal->getReductionVars()->count(P)) {
1551 for (unsigned part = 0; part < UF; ++part) {
1552 // This is phase one of vectorizing PHIs.
1553 Type *VecTy = VectorType::get(it->getType(), VF);
1554 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1555 LoopVectorBody-> getFirstInsertionPt());
1561 // Check for PHI nodes that are lowered to vector selects.
1562 if (P->getParent() != OrigLoop->getHeader()) {
1563 // We know that all PHIs in non header blocks are converted into
1564 // selects, so we don't have to worry about the insertion order and we
1565 // can just use the builder.
1567 // At this point we generate the predication tree. There may be
1568 // duplications since this is a simple recursive scan, but future
1569 // optimizations will clean it up.
1570 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1573 for (unsigned part = 0; part < UF; ++part) {
1574 VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1575 VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1576 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1582 // This PHINode must be an induction variable.
1583 // Make sure that we know about it.
1584 assert(Legal->getInductionVars()->count(P) &&
1585 "Not an induction variable");
1587 LoopVectorizationLegality::InductionInfo II =
1588 Legal->getInductionVars()->lookup(P);
1591 case LoopVectorizationLegality::IK_NoInduction:
1592 llvm_unreachable("Unknown induction");
1593 case LoopVectorizationLegality::IK_IntInduction: {
1594 assert(P == OldInduction && "Unexpected PHI");
1595 Value *Broadcasted = getBroadcastInstrs(Induction);
1596 // After broadcasting the induction variable we need to make the
1597 // vector consecutive by adding 0, 1, 2 ...
1598 for (unsigned part = 0; part < UF; ++part)
1599 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1602 case LoopVectorizationLegality::IK_ReverseIntInduction:
1603 case LoopVectorizationLegality::IK_PtrInduction:
1604 // Handle reverse integer and pointer inductions.
1605 Value *StartIdx = 0;
1606 // If we have a single integer induction variable then use it.
1607 // Otherwise, start counting at zero.
1609 LoopVectorizationLegality::InductionInfo OldII =
1610 Legal->getInductionVars()->lookup(OldInduction);
1611 StartIdx = OldII.StartValue;
1613 StartIdx = ConstantInt::get(Induction->getType(), 0);
1615 // This is the normalized GEP that starts counting at zero.
1616 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1619 // Handle the reverse integer induction variable case.
1620 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1621 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1622 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1624 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1627 // This is a new value so do not hoist it out.
1628 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1629 // After broadcasting the induction variable we need to make the
1630 // vector consecutive by adding ... -3, -2, -1, 0.
1631 for (unsigned part = 0; part < UF; ++part)
1632 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1636 // Handle the pointer induction variable case.
1637 assert(P->getType()->isPointerTy() && "Unexpected type.");
1639 // This is the vector of results. Notice that we don't generate
1640 // vector geps because scalar geps result in better code.
1641 for (unsigned part = 0; part < UF; ++part) {
1642 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1643 for (unsigned int i = 0; i < VF; ++i) {
1644 Constant *Idx = ConstantInt::get(Induction->getType(),
1646 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1648 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1650 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1651 Builder.getInt32(i),
1654 Entry[part] = VecVal;
1661 case Instruction::Add:
1662 case Instruction::FAdd:
1663 case Instruction::Sub:
1664 case Instruction::FSub:
1665 case Instruction::Mul:
1666 case Instruction::FMul:
1667 case Instruction::UDiv:
1668 case Instruction::SDiv:
1669 case Instruction::FDiv:
1670 case Instruction::URem:
1671 case Instruction::SRem:
1672 case Instruction::FRem:
1673 case Instruction::Shl:
1674 case Instruction::LShr:
1675 case Instruction::AShr:
1676 case Instruction::And:
1677 case Instruction::Or:
1678 case Instruction::Xor: {
1679 // Just widen binops.
1680 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1681 VectorParts &A = getVectorValue(it->getOperand(0));
1682 VectorParts &B = getVectorValue(it->getOperand(1));
1684 // Use this vector value for all users of the original instruction.
1685 for (unsigned Part = 0; Part < UF; ++Part) {
1686 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1688 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
1689 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
1690 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
1691 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1692 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1694 if (VecOp && isa<PossiblyExactOperator>(VecOp))
1695 VecOp->setIsExact(BinOp->isExact());
1701 case Instruction::Select: {
1703 // If the selector is loop invariant we can create a select
1704 // instruction with a scalar condition. Otherwise, use vector-select.
1705 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1708 // The condition can be loop invariant but still defined inside the
1709 // loop. This means that we can't just use the original 'cond' value.
1710 // We have to take the 'vectorized' value and pick the first lane.
1711 // Instcombine will make this a no-op.
1712 VectorParts &Cond = getVectorValue(it->getOperand(0));
1713 VectorParts &Op0 = getVectorValue(it->getOperand(1));
1714 VectorParts &Op1 = getVectorValue(it->getOperand(2));
1715 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1716 Builder.getInt32(0));
1717 for (unsigned Part = 0; Part < UF; ++Part) {
1718 Entry[Part] = Builder.CreateSelect(
1719 InvariantCond ? ScalarCond : Cond[Part],
1726 case Instruction::ICmp:
1727 case Instruction::FCmp: {
1728 // Widen compares. Generate vector compares.
1729 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1730 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1731 VectorParts &A = getVectorValue(it->getOperand(0));
1732 VectorParts &B = getVectorValue(it->getOperand(1));
1733 for (unsigned Part = 0; Part < UF; ++Part) {
1736 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1738 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1744 case Instruction::Store: {
1745 // Attempt to issue a wide store.
1746 StoreInst *SI = dyn_cast<StoreInst>(it);
1747 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1748 Value *Ptr = SI->getPointerOperand();
1749 unsigned Alignment = SI->getAlignment();
1751 assert(!Legal->isUniform(Ptr) &&
1752 "We do not allow storing to uniform addresses");
1755 int Stride = Legal->isConsecutivePtr(Ptr);
1756 bool Reverse = Stride < 0;
1758 scalarizeInstruction(it);
1762 // Handle consecutive stores.
1764 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1766 // The last index does not have to be the induction. It can be
1767 // consecutive and be a function of the index. For example A[I+1];
1768 unsigned NumOperands = Gep->getNumOperands();
1770 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1771 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1772 Value *LastIndex = GEPParts[0];
1773 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1775 // Create the new GEP with the new induction variable.
1776 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1777 Gep2->setOperand(NumOperands - 1, LastIndex);
1778 Ptr = Builder.Insert(Gep2);
1780 // Use the induction element ptr.
1781 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1782 VectorParts &PtrVal = getVectorValue(Ptr);
1783 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1786 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1787 for (unsigned Part = 0; Part < UF; ++Part) {
1788 // Calculate the pointer for the specific unroll-part.
1789 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1792 // If we store to reverse consecutive memory locations then we need
1793 // to reverse the order of elements in the stored value.
1794 StoredVal[Part] = reverseVector(StoredVal[Part]);
1795 // If the address is consecutive but reversed, then the
1796 // wide store needs to start at the last vector element.
1797 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1798 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1801 Value *VecPtr = Builder.CreateBitCast(PartPtr, StTy->getPointerTo());
1802 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1806 case Instruction::Load: {
1807 // Attempt to issue a wide load.
1808 LoadInst *LI = dyn_cast<LoadInst>(it);
1809 Type *RetTy = VectorType::get(LI->getType(), VF);
1810 Value *Ptr = LI->getPointerOperand();
1811 unsigned Alignment = LI->getAlignment();
1813 // If the pointer is loop invariant or if it is non consecutive,
1814 // scalarize the load.
1815 int Stride = Legal->isConsecutivePtr(Ptr);
1816 bool Reverse = Stride < 0;
1817 if (Legal->isUniform(Ptr) || Stride == 0) {
1818 scalarizeInstruction(it);
1822 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1824 // The last index does not have to be the induction. It can be
1825 // consecutive and be a function of the index. For example A[I+1];
1826 unsigned NumOperands = Gep->getNumOperands();
1828 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1829 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1830 Value *LastIndex = GEPParts[0];
1831 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1833 // Create the new GEP with the new induction variable.
1834 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1835 Gep2->setOperand(NumOperands - 1, LastIndex);
1836 Ptr = Builder.Insert(Gep2);
1838 // Use the induction element ptr.
1839 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1840 VectorParts &PtrVal = getVectorValue(Ptr);
1841 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1844 for (unsigned Part = 0; Part < UF; ++Part) {
1845 // Calculate the pointer for the specific unroll-part.
1846 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1849 // If the address is consecutive but reversed, then the
1850 // wide store needs to start at the last vector element.
1851 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1852 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1855 Value *VecPtr = Builder.CreateBitCast(PartPtr, RetTy->getPointerTo());
1856 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1857 cast<LoadInst>(LI)->setAlignment(Alignment);
1858 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1862 case Instruction::ZExt:
1863 case Instruction::SExt:
1864 case Instruction::FPToUI:
1865 case Instruction::FPToSI:
1866 case Instruction::FPExt:
1867 case Instruction::PtrToInt:
1868 case Instruction::IntToPtr:
1869 case Instruction::SIToFP:
1870 case Instruction::UIToFP:
1871 case Instruction::Trunc:
1872 case Instruction::FPTrunc:
1873 case Instruction::BitCast: {
1874 CastInst *CI = dyn_cast<CastInst>(it);
1875 /// Optimize the special case where the source is the induction
1876 /// variable. Notice that we can only optimize the 'trunc' case
1877 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1878 /// c. other casts depend on pointer size.
1879 if (CI->getOperand(0) == OldInduction &&
1880 it->getOpcode() == Instruction::Trunc) {
1881 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1883 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1884 for (unsigned Part = 0; Part < UF; ++Part)
1885 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1888 /// Vectorize casts.
1889 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1891 VectorParts &A = getVectorValue(it->getOperand(0));
1892 for (unsigned Part = 0; Part < UF; ++Part)
1893 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1897 case Instruction::Call: {
1898 assert(isTriviallyVectorizableIntrinsic(it));
1899 Module *M = BB->getParent()->getParent();
1900 IntrinsicInst *II = cast<IntrinsicInst>(it);
1901 Intrinsic::ID ID = II->getIntrinsicID();
1902 for (unsigned Part = 0; Part < UF; ++Part) {
1903 SmallVector<Value*, 4> Args;
1904 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
1905 VectorParts &Arg = getVectorValue(II->getArgOperand(i));
1906 Args.push_back(Arg[Part]);
1908 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1909 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1910 Entry[Part] = Builder.CreateCall(F, Args);
1916 // All other instructions are unsupported. Scalarize them.
1917 scalarizeInstruction(it);
1920 }// end of for_each instr.
1923 void InnerLoopVectorizer::updateAnalysis() {
1924 // Forget the original basic block.
1925 SE->forgetLoop(OrigLoop);
1927 // Update the dominator tree information.
1928 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1929 "Entry does not dominate exit.");
1931 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1932 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1933 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1934 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1935 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1936 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1938 DEBUG(DT->verifyAnalysis());
1941 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1942 if (!EnableIfConversion)
1945 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1946 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1948 // Collect the blocks that need predication.
1949 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1950 BasicBlock *BB = LoopBlocks[i];
1952 // We don't support switch statements inside loops.
1953 if (!isa<BranchInst>(BB->getTerminator()))
1956 // We must have at most two predecessors because we need to convert
1957 // all PHIs to selects.
1958 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1962 // We must be able to predicate all blocks that need to be predicated.
1963 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1967 // We can if-convert this loop.
1971 bool LoopVectorizationLegality::canVectorize() {
1972 assert(TheLoop->getLoopPreheader() && "No preheader!!");
1974 // We can only vectorize innermost loops.
1975 if (TheLoop->getSubLoopsVector().size())
1978 // We must have a single backedge.
1979 if (TheLoop->getNumBackEdges() != 1)
1982 // We must have a single exiting block.
1983 if (!TheLoop->getExitingBlock())
1986 unsigned NumBlocks = TheLoop->getNumBlocks();
1988 // Check if we can if-convert non single-bb loops.
1989 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1990 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1994 // We need to have a loop header.
1995 BasicBlock *Latch = TheLoop->getLoopLatch();
1996 DEBUG(dbgs() << "LV: Found a loop: " <<
1997 TheLoop->getHeader()->getName() << "\n");
1999 // ScalarEvolution needs to be able to find the exit count.
2000 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2001 if (ExitCount == SE->getCouldNotCompute()) {
2002 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2006 // Do not loop-vectorize loops with a tiny trip count.
2007 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2008 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2009 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2010 "This loop is not worth vectorizing.\n");
2014 // Check if we can vectorize the instructions and CFG in this loop.
2015 if (!canVectorizeInstrs()) {
2016 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2020 // Go over each instruction and look at memory deps.
2021 if (!canVectorizeMemory()) {
2022 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2026 // Collect all of the variables that remain uniform after vectorization.
2027 collectLoopUniforms();
2029 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2030 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2033 // Okay! We can vectorize. At this point we don't have any other mem analysis
2034 // which may limit our maximum vectorization factor, so just return true with
2039 bool LoopVectorizationLegality::canVectorizeInstrs() {
2040 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2041 BasicBlock *Header = TheLoop->getHeader();
2043 // For each block in the loop.
2044 for (Loop::block_iterator bb = TheLoop->block_begin(),
2045 be = TheLoop->block_end(); bb != be; ++bb) {
2047 // Scan the instructions in the block and look for hazards.
2048 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2051 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2052 // This should not happen because the loop should be normalized.
2053 if (Phi->getNumIncomingValues() != 2) {
2054 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2058 // Check that this PHI type is allowed.
2059 if (!Phi->getType()->isIntegerTy() &&
2060 !Phi->getType()->isFloatingPointTy() &&
2061 !Phi->getType()->isPointerTy()) {
2062 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2066 // If this PHINode is not in the header block, then we know that we
2067 // can convert it to select during if-conversion. No need to check if
2068 // the PHIs in this block are induction or reduction variables.
2072 // This is the value coming from the preheader.
2073 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2074 // Check if this is an induction variable.
2075 InductionKind IK = isInductionVariable(Phi);
2077 if (IK_NoInduction != IK) {
2078 // Int inductions are special because we only allow one IV.
2079 if (IK == IK_IntInduction) {
2081 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2087 DEBUG(dbgs() << "LV: Found an induction variable.\n");
2088 Inductions[Phi] = InductionInfo(StartValue, IK);
2092 if (AddReductionVar(Phi, RK_IntegerAdd)) {
2093 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2096 if (AddReductionVar(Phi, RK_IntegerMult)) {
2097 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2100 if (AddReductionVar(Phi, RK_IntegerOr)) {
2101 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2104 if (AddReductionVar(Phi, RK_IntegerAnd)) {
2105 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2108 if (AddReductionVar(Phi, RK_IntegerXor)) {
2109 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2112 if (AddReductionVar(Phi, RK_FloatMult)) {
2113 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2116 if (AddReductionVar(Phi, RK_FloatAdd)) {
2117 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2121 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2123 }// end of PHI handling
2125 // We still don't handle functions.
2126 CallInst *CI = dyn_cast<CallInst>(it);
2127 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
2128 DEBUG(dbgs() << "LV: Found a call site.\n");
2132 // Check that the instruction return type is vectorizable.
2133 if (!VectorType::isValidElementType(it->getType()) &&
2134 !it->getType()->isVoidTy()) {
2135 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2139 // Check that the stored type is vectorizable.
2140 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2141 Type *T = ST->getValueOperand()->getType();
2142 if (!VectorType::isValidElementType(T))
2146 // Reduction instructions are allowed to have exit users.
2147 // All other instructions must not have external users.
2148 if (!AllowedExit.count(it))
2149 //Check that all of the users of the loop are inside the BB.
2150 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2152 Instruction *U = cast<Instruction>(*I);
2153 // This user may be a reduction exit value.
2154 if (!TheLoop->contains(U)) {
2155 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2164 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2165 assert(getInductionVars()->size() && "No induction variables");
2171 void LoopVectorizationLegality::collectLoopUniforms() {
2172 // We now know that the loop is vectorizable!
2173 // Collect variables that will remain uniform after vectorization.
2174 std::vector<Value*> Worklist;
2175 BasicBlock *Latch = TheLoop->getLoopLatch();
2177 // Start with the conditional branch and walk up the block.
2178 Worklist.push_back(Latch->getTerminator()->getOperand(0));
2180 while (Worklist.size()) {
2181 Instruction *I = dyn_cast<Instruction>(Worklist.back());
2182 Worklist.pop_back();
2184 // Look at instructions inside this loop.
2185 // Stop when reaching PHI nodes.
2186 // TODO: we need to follow values all over the loop, not only in this block.
2187 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2190 // This is a known uniform.
2193 // Insert all operands.
2194 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2195 Worklist.push_back(I->getOperand(i));
2200 bool LoopVectorizationLegality::canVectorizeMemory() {
2201 typedef SmallVector<Value*, 16> ValueVector;
2202 typedef SmallPtrSet<Value*, 16> ValueSet;
2203 // Holds the Load and Store *instructions*.
2206 PtrRtCheck.Pointers.clear();
2207 PtrRtCheck.Need = false;
2210 for (Loop::block_iterator bb = TheLoop->block_begin(),
2211 be = TheLoop->block_end(); bb != be; ++bb) {
2213 // Scan the BB and collect legal loads and stores.
2214 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2217 // If this is a load, save it. If this instruction can read from memory
2218 // but is not a load, then we quit. Notice that we don't handle function
2219 // calls that read or write.
2220 if (it->mayReadFromMemory()) {
2221 LoadInst *Ld = dyn_cast<LoadInst>(it);
2222 if (!Ld) return false;
2223 if (!Ld->isSimple()) {
2224 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2227 Loads.push_back(Ld);
2231 // Save 'store' instructions. Abort if other instructions write to memory.
2232 if (it->mayWriteToMemory()) {
2233 StoreInst *St = dyn_cast<StoreInst>(it);
2234 if (!St) return false;
2235 if (!St->isSimple()) {
2236 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2239 Stores.push_back(St);
2244 // Now we have two lists that hold the loads and the stores.
2245 // Next, we find the pointers that they use.
2247 // Check if we see any stores. If there are no stores, then we don't
2248 // care if the pointers are *restrict*.
2249 if (!Stores.size()) {
2250 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2254 // Holds the read and read-write *pointers* that we find.
2256 ValueVector ReadWrites;
2258 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2259 // multiple times on the same object. If the ptr is accessed twice, once
2260 // for read and once for write, it will only appear once (on the write
2261 // list). This is okay, since we are going to check for conflicts between
2262 // writes and between reads and writes, but not between reads and reads.
2265 ValueVector::iterator I, IE;
2266 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2267 StoreInst *ST = cast<StoreInst>(*I);
2268 Value* Ptr = ST->getPointerOperand();
2270 if (isUniform(Ptr)) {
2271 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2275 // If we did *not* see this pointer before, insert it to
2276 // the read-write list. At this phase it is only a 'write' list.
2277 if (Seen.insert(Ptr))
2278 ReadWrites.push_back(Ptr);
2281 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2282 LoadInst *LD = cast<LoadInst>(*I);
2283 Value* Ptr = LD->getPointerOperand();
2284 // If we did *not* see this pointer before, insert it to the
2285 // read list. If we *did* see it before, then it is already in
2286 // the read-write list. This allows us to vectorize expressions
2287 // such as A[i] += x; Because the address of A[i] is a read-write
2288 // pointer. This only works if the index of A[i] is consecutive.
2289 // If the address of i is unknown (for example A[B[i]]) then we may
2290 // read a few words, modify, and write a few words, and some of the
2291 // words may be written to the same address.
2292 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2293 Reads.push_back(Ptr);
2296 // If we write (or read-write) to a single destination and there are no
2297 // other reads in this loop then is it safe to vectorize.
2298 if (ReadWrites.size() == 1 && Reads.size() == 0) {
2299 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2303 // Find pointers with computable bounds. We are going to use this information
2304 // to place a runtime bound check.
2305 bool CanDoRT = true;
2306 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
2307 if (hasComputableBounds(*I)) {
2308 PtrRtCheck.insert(SE, TheLoop, *I);
2309 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2314 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
2315 if (hasComputableBounds(*I)) {
2316 PtrRtCheck.insert(SE, TheLoop, *I);
2317 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2323 // Check that we did not collect too many pointers or found a
2324 // unsizeable pointer.
2325 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2331 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2334 bool NeedRTCheck = false;
2336 // Now that the pointers are in two lists (Reads and ReadWrites), we
2337 // can check that there are no conflicts between each of the writes and
2338 // between the writes to the reads.
2339 ValueSet WriteObjects;
2340 ValueVector TempObjects;
2342 // Check that the read-writes do not conflict with other read-write
2344 bool AllWritesIdentified = true;
2345 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
2346 GetUnderlyingObjects(*I, TempObjects, DL);
2347 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2349 if (!isIdentifiedObject(*it)) {
2350 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
2352 AllWritesIdentified = false;
2354 if (!WriteObjects.insert(*it)) {
2355 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2360 TempObjects.clear();
2363 /// Check that the reads don't conflict with the read-writes.
2364 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
2365 GetUnderlyingObjects(*I, TempObjects, DL);
2366 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2368 // If all of the writes are identified then we don't care if the read
2369 // pointer is identified or not.
2370 if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
2371 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
2374 if (WriteObjects.count(*it)) {
2375 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
2380 TempObjects.clear();
2383 PtrRtCheck.Need = NeedRTCheck;
2384 if (NeedRTCheck && !CanDoRT) {
2385 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2386 "the array bounds.\n");
2391 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2392 " need a runtime memory check.\n");
2396 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2397 ReductionKind Kind) {
2398 if (Phi->getNumIncomingValues() != 2)
2401 // Reduction variables are only found in the loop header block.
2402 if (Phi->getParent() != TheLoop->getHeader())
2405 // Obtain the reduction start value from the value that comes from the loop
2407 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2409 // ExitInstruction is the single value which is used outside the loop.
2410 // We only allow for a single reduction value to be used outside the loop.
2411 // This includes users of the reduction, variables (which form a cycle
2412 // which ends in the phi node).
2413 Instruction *ExitInstruction = 0;
2414 // Indicates that we found a binary operation in our scan.
2415 bool FoundBinOp = false;
2417 // Iter is our iterator. We start with the PHI node and scan for all of the
2418 // users of this instruction. All users must be instructions that can be
2419 // used as reduction variables (such as ADD). We may have a single
2420 // out-of-block user. The cycle must end with the original PHI.
2421 Instruction *Iter = Phi;
2423 // If the instruction has no users then this is a broken
2424 // chain and can't be a reduction variable.
2425 if (Iter->use_empty())
2428 // Did we find a user inside this loop already ?
2429 bool FoundInBlockUser = false;
2430 // Did we reach the initial PHI node already ?
2431 bool FoundStartPHI = false;
2433 // Is this a bin op ?
2434 FoundBinOp |= !isa<PHINode>(Iter);
2436 // For each of the *users* of iter.
2437 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2439 Instruction *U = cast<Instruction>(*it);
2440 // We already know that the PHI is a user.
2442 FoundStartPHI = true;
2446 // Check if we found the exit user.
2447 BasicBlock *Parent = U->getParent();
2448 if (!TheLoop->contains(Parent)) {
2449 // Exit if you find multiple outside users.
2450 if (ExitInstruction != 0)
2452 ExitInstruction = Iter;
2455 // We allow in-loop PHINodes which are not the original reduction PHI
2456 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2457 // structure) then don't skip this PHI.
2458 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2459 U->getParent() != TheLoop->getHeader() &&
2460 TheLoop->contains(U) &&
2461 Iter->getNumUses() > 1)
2464 // We can't have multiple inside users.
2465 if (FoundInBlockUser)
2467 FoundInBlockUser = true;
2469 // Any reduction instr must be of one of the allowed kinds.
2470 if (!isReductionInstr(U, Kind))
2473 // Reductions of instructions such as Div, and Sub is only
2474 // possible if the LHS is the reduction variable.
2475 if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter)
2481 // We found a reduction var if we have reached the original
2482 // phi node and we only have a single instruction with out-of-loop
2484 if (FoundStartPHI) {
2485 // This instruction is allowed to have out-of-loop users.
2486 AllowedExit.insert(ExitInstruction);
2488 // Save the description of this reduction variable.
2489 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2490 Reductions[Phi] = RD;
2491 // We've ended the cycle. This is a reduction variable if we have an
2492 // outside user and it has a binary op.
2493 return FoundBinOp && ExitInstruction;
2499 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2500 ReductionKind Kind) {
2501 bool FP = I->getType()->isFloatingPointTy();
2502 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2504 switch (I->getOpcode()) {
2507 case Instruction::PHI:
2508 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2512 case Instruction::Sub:
2513 case Instruction::Add:
2514 return Kind == RK_IntegerAdd;
2515 case Instruction::SDiv:
2516 case Instruction::UDiv:
2517 case Instruction::Mul:
2518 return Kind == RK_IntegerMult;
2519 case Instruction::And:
2520 return Kind == RK_IntegerAnd;
2521 case Instruction::Or:
2522 return Kind == RK_IntegerOr;
2523 case Instruction::Xor:
2524 return Kind == RK_IntegerXor;
2525 case Instruction::FMul:
2526 return Kind == RK_FloatMult && FastMath;
2527 case Instruction::FAdd:
2528 return Kind == RK_FloatAdd && FastMath;
2532 LoopVectorizationLegality::InductionKind
2533 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2534 Type *PhiTy = Phi->getType();
2535 // We only handle integer and pointer inductions variables.
2536 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2537 return IK_NoInduction;
2539 // Check that the PHI is consecutive and starts at zero.
2540 const SCEV *PhiScev = SE->getSCEV(Phi);
2541 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2543 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2544 return IK_NoInduction;
2546 const SCEV *Step = AR->getStepRecurrence(*SE);
2548 // Integer inductions need to have a stride of one.
2549 if (PhiTy->isIntegerTy()) {
2551 return IK_IntInduction;
2552 if (Step->isAllOnesValue())
2553 return IK_ReverseIntInduction;
2554 return IK_NoInduction;
2557 // Calculate the pointer stride and check if it is consecutive.
2558 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2560 return IK_NoInduction;
2562 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2563 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2564 if (C->getValue()->equalsInt(Size))
2565 return IK_PtrInduction;
2567 return IK_NoInduction;
2570 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2571 Value *In0 = const_cast<Value*>(V);
2572 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2576 return Inductions.count(PN);
2579 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
2580 assert(TheLoop->contains(BB) && "Unknown block used");
2582 // Blocks that do not dominate the latch need predication.
2583 BasicBlock* Latch = TheLoop->getLoopLatch();
2584 return !DT->dominates(BB, Latch);
2587 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2588 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2589 // We don't predicate loads/stores at the moment.
2590 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2593 // The instructions below can trap.
2594 switch (it->getOpcode()) {
2596 case Instruction::UDiv:
2597 case Instruction::SDiv:
2598 case Instruction::URem:
2599 case Instruction::SRem:
2607 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2608 const SCEV *PhiScev = SE->getSCEV(Ptr);
2609 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2613 return AR->isAffine();
2617 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2619 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2620 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2624 // Find the trip count.
2625 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2626 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2628 unsigned WidestType = getWidestType();
2629 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
2630 unsigned MaxVectorSize = WidestRegister / WidestType;
2631 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
2632 DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
2634 if (MaxVectorSize == 0) {
2635 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
2639 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
2640 " into one vector.");
2642 unsigned VF = MaxVectorSize;
2644 // If we optimize the program for size, avoid creating the tail loop.
2646 // If we are unable to calculate the trip count then don't try to vectorize.
2648 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2652 // Find the maximum SIMD width that can fit within the trip count.
2653 VF = TC % MaxVectorSize;
2658 // If the trip count that we found modulo the vectorization factor is not
2659 // zero then we require a tail.
2661 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2667 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2668 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2673 float Cost = expectedCost(1);
2675 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2676 for (unsigned i=2; i <= VF; i*=2) {
2677 // Notice that the vector loop needs to be executed less times, so
2678 // we need to divide the cost of the vector loops by the width of
2679 // the vector elements.
2680 float VectorCost = expectedCost(i) / (float)i;
2681 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2682 (int)VectorCost << ".\n");
2683 if (VectorCost < Cost) {
2689 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2693 unsigned LoopVectorizationCostModel::getWidestType() {
2694 unsigned MaxWidth = 8;
2697 for (Loop::block_iterator bb = TheLoop->block_begin(),
2698 be = TheLoop->block_end(); bb != be; ++bb) {
2699 BasicBlock *BB = *bb;
2701 // For each instruction in the loop.
2702 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2703 Type *T = it->getType();
2705 // Only examine Loads, Stores and PHINodes.
2706 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
2709 // Examine PHI nodes that are reduction variables.
2710 if (PHINode *PN = dyn_cast<PHINode>(it))
2711 if (!Legal->getReductionVars()->count(PN))
2714 // Examine the stored values.
2715 if (StoreInst *ST = dyn_cast<StoreInst>(it))
2716 T = ST->getValueOperand()->getType();
2718 // Ignore stored/loaded pointer types.
2719 if (T->isPointerTy())
2722 MaxWidth = std::max(MaxWidth, T->getScalarSizeInBits());
2730 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2732 // Use the user preference, unless 'auto' is selected.
2736 // When we optimize for size we don't unroll.
2740 // Do not unroll loops with a relatively small trip count.
2741 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
2742 TheLoop->getLoopLatch());
2743 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
2746 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
2747 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
2748 " vector registers\n");
2750 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
2751 // We divide by these constants so assume that we have at least one
2752 // instruction that uses at least one register.
2753 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
2754 R.NumInstructions = std::max(R.NumInstructions, 1U);
2756 // We calculate the unroll factor using the following formula.
2757 // Subtract the number of loop invariants from the number of available
2758 // registers. These registers are used by all of the unrolled instances.
2759 // Next, divide the remaining registers by the number of registers that is
2760 // required by the loop, in order to estimate how many parallel instances
2761 // fit without causing spills.
2762 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
2764 // We don't want to unroll the loops to the point where they do not fit into
2765 // the decoded cache. Assume that we only allow 32 IR instructions.
2766 UF = std::min(UF, (MaxLoopSizeThreshold / R.NumInstructions));
2768 // Clamp the unroll factor ranges to reasonable factors.
2769 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
2771 if (UF > MaxUnrollSize)
2779 LoopVectorizationCostModel::RegisterUsage
2780 LoopVectorizationCostModel::calculateRegisterUsage() {
2781 // This function calculates the register usage by measuring the highest number
2782 // of values that are alive at a single location. Obviously, this is a very
2783 // rough estimation. We scan the loop in a topological order in order and
2784 // assign a number to each instruction. We use RPO to ensure that defs are
2785 // met before their users. We assume that each instruction that has in-loop
2786 // users starts an interval. We record every time that an in-loop value is
2787 // used, so we have a list of the first and last occurrences of each
2788 // instruction. Next, we transpose this data structure into a multi map that
2789 // holds the list of intervals that *end* at a specific location. This multi
2790 // map allows us to perform a linear search. We scan the instructions linearly
2791 // and record each time that a new interval starts, by placing it in a set.
2792 // If we find this value in the multi-map then we remove it from the set.
2793 // The max register usage is the maximum size of the set.
2794 // We also search for instructions that are defined outside the loop, but are
2795 // used inside the loop. We need this number separately from the max-interval
2796 // usage number because when we unroll, loop-invariant values do not take
2798 LoopBlocksDFS DFS(TheLoop);
2802 R.NumInstructions = 0;
2804 // Each 'key' in the map opens a new interval. The values
2805 // of the map are the index of the 'last seen' usage of the
2806 // instruction that is the key.
2807 typedef DenseMap<Instruction*, unsigned> IntervalMap;
2808 // Maps instruction to its index.
2809 DenseMap<unsigned, Instruction*> IdxToInstr;
2810 // Marks the end of each interval.
2811 IntervalMap EndPoint;
2812 // Saves the list of instruction indices that are used in the loop.
2813 SmallSet<Instruction*, 8> Ends;
2814 // Saves the list of values that are used in the loop but are
2815 // defined outside the loop, such as arguments and constants.
2816 SmallPtrSet<Value*, 8> LoopInvariants;
2819 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2820 be = DFS.endRPO(); bb != be; ++bb) {
2821 R.NumInstructions += (*bb)->size();
2822 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2824 Instruction *I = it;
2825 IdxToInstr[Index++] = I;
2827 // Save the end location of each USE.
2828 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2829 Value *U = I->getOperand(i);
2830 Instruction *Instr = dyn_cast<Instruction>(U);
2832 // Ignore non-instruction values such as arguments, constants, etc.
2833 if (!Instr) continue;
2835 // If this instruction is outside the loop then record it and continue.
2836 if (!TheLoop->contains(Instr)) {
2837 LoopInvariants.insert(Instr);
2841 // Overwrite previous end points.
2842 EndPoint[Instr] = Index;
2848 // Saves the list of intervals that end with the index in 'key'.
2849 typedef SmallVector<Instruction*, 2> InstrList;
2850 DenseMap<unsigned, InstrList> TransposeEnds;
2852 // Transpose the EndPoints to a list of values that end at each index.
2853 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
2855 TransposeEnds[it->second].push_back(it->first);
2857 SmallSet<Instruction*, 8> OpenIntervals;
2858 unsigned MaxUsage = 0;
2861 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
2862 for (unsigned int i = 0; i < Index; ++i) {
2863 Instruction *I = IdxToInstr[i];
2864 // Ignore instructions that are never used within the loop.
2865 if (!Ends.count(I)) continue;
2867 // Remove all of the instructions that end at this location.
2868 InstrList &List = TransposeEnds[i];
2869 for (unsigned int j=0, e = List.size(); j < e; ++j)
2870 OpenIntervals.erase(List[j]);
2872 // Count the number of live interals.
2873 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
2875 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
2876 OpenIntervals.size() <<"\n");
2878 // Add the current instruction to the list of open intervals.
2879 OpenIntervals.insert(I);
2882 unsigned Invariant = LoopInvariants.size();
2883 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
2884 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
2885 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
2887 R.LoopInvariantRegs = Invariant;
2888 R.MaxLocalUsers = MaxUsage;
2892 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2896 for (Loop::block_iterator bb = TheLoop->block_begin(),
2897 be = TheLoop->block_end(); bb != be; ++bb) {
2898 unsigned BlockCost = 0;
2899 BasicBlock *BB = *bb;
2901 // For each instruction in the old loop.
2902 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2903 unsigned C = getInstructionCost(it, VF);
2905 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2906 VF << " For instruction: "<< *it << "\n");
2909 // We assume that if-converted blocks have a 50% chance of being executed.
2910 // When the code is scalar then some of the blocks are avoided due to CF.
2911 // When the code is vectorized we execute all code paths.
2912 if (Legal->blockNeedsPredication(*bb) && VF == 1)
2922 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2923 // If we know that this instruction will remain uniform, check the cost of
2924 // the scalar version.
2925 if (Legal->isUniformAfterVectorization(I))
2928 Type *RetTy = I->getType();
2929 Type *VectorTy = ToVectorTy(RetTy, VF);
2931 // TODO: We need to estimate the cost of intrinsic calls.
2932 switch (I->getOpcode()) {
2933 case Instruction::GetElementPtr:
2934 // We mark this instruction as zero-cost because scalar GEPs are usually
2935 // lowered to the intruction addressing mode. At the moment we don't
2936 // generate vector geps.
2938 case Instruction::Br: {
2939 return TTI.getCFInstrCost(I->getOpcode());
2941 case Instruction::PHI:
2942 //TODO: IF-converted IFs become selects.
2944 case Instruction::Add:
2945 case Instruction::FAdd:
2946 case Instruction::Sub:
2947 case Instruction::FSub:
2948 case Instruction::Mul:
2949 case Instruction::FMul:
2950 case Instruction::UDiv:
2951 case Instruction::SDiv:
2952 case Instruction::FDiv:
2953 case Instruction::URem:
2954 case Instruction::SRem:
2955 case Instruction::FRem:
2956 case Instruction::Shl:
2957 case Instruction::LShr:
2958 case Instruction::AShr:
2959 case Instruction::And:
2960 case Instruction::Or:
2961 case Instruction::Xor:
2962 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy);
2963 case Instruction::Select: {
2964 SelectInst *SI = cast<SelectInst>(I);
2965 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2966 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2967 Type *CondTy = SI->getCondition()->getType();
2969 CondTy = VectorType::get(CondTy, VF);
2971 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2973 case Instruction::ICmp:
2974 case Instruction::FCmp: {
2975 Type *ValTy = I->getOperand(0)->getType();
2976 VectorTy = ToVectorTy(ValTy, VF);
2977 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
2979 case Instruction::Store: {
2980 StoreInst *SI = cast<StoreInst>(I);
2981 Type *ValTy = SI->getValueOperand()->getType();
2982 VectorTy = ToVectorTy(ValTy, VF);
2985 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
2987 SI->getPointerAddressSpace());
2989 // Scalarized stores.
2990 int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
2991 bool Reverse = Stride < 0;
2995 // The cost of extracting from the value vector and pointer vector.
2996 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2997 for (unsigned i = 0; i < VF; ++i) {
2998 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
3000 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3003 // The cost of the scalar stores.
3004 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3006 SI->getPointerAddressSpace());
3011 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3013 SI->getPointerAddressSpace());
3015 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3019 case Instruction::Load: {
3020 LoadInst *LI = cast<LoadInst>(I);
3023 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
3024 LI->getPointerAddressSpace());
3026 // Scalarized loads.
3027 int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
3028 bool Reverse = Stride < 0;
3031 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3033 // The cost of extracting from the pointer vector.
3034 for (unsigned i = 0; i < VF; ++i)
3035 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3037 // The cost of inserting data to the result vector.
3038 for (unsigned i = 0; i < VF; ++i)
3039 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy, i);
3041 // The cost of the scalar stores.
3042 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), RetTy->getScalarType(),
3044 LI->getPointerAddressSpace());
3049 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3051 LI->getPointerAddressSpace());
3053 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
3056 case Instruction::ZExt:
3057 case Instruction::SExt:
3058 case Instruction::FPToUI:
3059 case Instruction::FPToSI:
3060 case Instruction::FPExt:
3061 case Instruction::PtrToInt:
3062 case Instruction::IntToPtr:
3063 case Instruction::SIToFP:
3064 case Instruction::UIToFP:
3065 case Instruction::Trunc:
3066 case Instruction::FPTrunc:
3067 case Instruction::BitCast: {
3068 // We optimize the truncation of induction variable.
3069 // The cost of these is the same as the scalar operation.
3070 if (I->getOpcode() == Instruction::Trunc &&
3071 Legal->isInductionVariable(I->getOperand(0)))
3072 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3073 I->getOperand(0)->getType());
3075 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3076 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3078 case Instruction::Call: {
3079 assert(isTriviallyVectorizableIntrinsic(I));
3080 IntrinsicInst *II = cast<IntrinsicInst>(I);
3081 Type *RetTy = ToVectorTy(II->getType(), VF);
3082 SmallVector<Type*, 4> Tys;
3083 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
3084 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
3085 return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
3088 // We are scalarizing the instruction. Return the cost of the scalar
3089 // instruction, plus the cost of insert and extract into vector
3090 // elements, times the vector width.
3093 if (!RetTy->isVoidTy() && VF != 1) {
3094 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3096 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3099 // The cost of inserting the results plus extracting each one of the
3101 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3104 // The cost of executing VF copies of the scalar instruction. This opcode
3105 // is unknown. Assume that it is the same as 'mul'.
3106 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3112 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3113 if (Scalar->isVoidTy() || VF == 1)
3115 return VectorType::get(Scalar, VF);
3118 char LoopVectorize::ID = 0;
3119 static const char lv_name[] = "Loop Vectorization";
3120 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3121 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3122 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3123 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3124 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3125 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3128 Pass *createLoopVectorizePass() {
3129 return new LoopVectorize();