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 if (Count->getType() != IdxTy) {
1037 // The exit count can be of pointer type. Convert it to the correct
1039 if (ExitCount->getType()->isPointerTy())
1040 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
1042 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
1045 // Add the start index to the loop count to get the new end index.
1046 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
1048 // Now we need to generate the expression for N - (N % VF), which is
1049 // the part that the vectorized body will execute.
1050 Value *R = BinaryOperator::CreateURem(Count, Step, "n.mod.vf", Loc);
1051 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
1052 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
1053 "end.idx.rnd.down", Loc);
1055 // Now, compare the new count to zero. If it is zero skip the vector loop and
1056 // jump to the scalar loop.
1057 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
1062 // If we are using memory runtime checks, include them in.
1063 if (MemoryRuntimeCheck)
1064 Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
1067 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
1068 // Remove the old terminator.
1069 Loc->eraseFromParent();
1071 // We are going to resume the execution of the scalar loop.
1072 // Go over all of the induction variables that we found and fix the
1073 // PHIs that are left in the scalar version of the loop.
1074 // The starting values of PHI nodes depend on the counter of the last
1075 // iteration in the vectorized loop.
1076 // If we come from a bypass edge then we need to start from the original
1079 // This variable saves the new starting index for the scalar loop.
1080 PHINode *ResumeIndex = 0;
1081 LoopVectorizationLegality::InductionList::iterator I, E;
1082 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1083 for (I = List->begin(), E = List->end(); I != E; ++I) {
1084 PHINode *OrigPhi = I->first;
1085 LoopVectorizationLegality::InductionInfo II = I->second;
1086 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1087 MiddleBlock->getTerminator());
1088 Value *EndValue = 0;
1090 case LoopVectorizationLegality::IK_NoInduction:
1091 llvm_unreachable("Unknown induction");
1092 case LoopVectorizationLegality::IK_IntInduction: {
1093 // Handle the integer induction counter:
1094 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1095 assert(OrigPhi == OldInduction && "Unknown integer PHI");
1096 // We know what the end value is.
1097 EndValue = IdxEndRoundDown;
1098 // We also know which PHI node holds it.
1099 ResumeIndex = ResumeVal;
1102 case LoopVectorizationLegality::IK_ReverseIntInduction: {
1103 // Convert the CountRoundDown variable to the PHI size.
1104 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1105 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1106 Value *CRD = CountRoundDown;
1107 if (CRDSize > IISize)
1108 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1109 II.StartValue->getType(),
1110 "tr.crd", BypassBlock->getTerminator());
1111 else if (CRDSize < IISize)
1112 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1113 II.StartValue->getType(),
1114 "sext.crd", BypassBlock->getTerminator());
1115 // Handle reverse integer induction counter:
1116 EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1117 BypassBlock->getTerminator());
1120 case LoopVectorizationLegality::IK_PtrInduction: {
1121 // For pointer induction variables, calculate the offset using
1123 EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
1125 BypassBlock->getTerminator());
1130 // The new PHI merges the original incoming value, in case of a bypass,
1131 // or the value at the end of the vectorized loop.
1132 ResumeVal->addIncoming(II.StartValue, BypassBlock);
1133 ResumeVal->addIncoming(EndValue, VecBody);
1135 // Fix the scalar body counter (PHI node).
1136 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1137 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1140 // If we are generating a new induction variable then we also need to
1141 // generate the code that calculates the exit value. This value is not
1142 // simply the end of the counter because we may skip the vectorized body
1143 // in case of a runtime check.
1145 assert(!ResumeIndex && "Unexpected resume value found");
1146 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1147 MiddleBlock->getTerminator());
1148 ResumeIndex->addIncoming(StartIdx, BypassBlock);
1149 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1152 // Make sure that we found the index where scalar loop needs to continue.
1153 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1154 "Invalid resume Index");
1156 // Add a check in the middle block to see if we have completed
1157 // all of the iterations in the first vector loop.
1158 // If (N - N%VF) == N, then we *don't* need to run the remainder.
1159 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1160 ResumeIndex, "cmp.n",
1161 MiddleBlock->getTerminator());
1163 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1164 // Remove the old terminator.
1165 MiddleBlock->getTerminator()->eraseFromParent();
1167 // Create i+1 and fill the PHINode.
1168 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1169 Induction->addIncoming(StartIdx, VectorPH);
1170 Induction->addIncoming(NextIdx, VecBody);
1171 // Create the compare.
1172 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1173 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1175 // Now we have two terminators. Remove the old one from the block.
1176 VecBody->getTerminator()->eraseFromParent();
1178 // Get ready to start creating new instructions into the vectorized body.
1179 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1181 // Create and register the new vector loop.
1182 Loop* Lp = new Loop();
1183 Loop *ParentLoop = OrigLoop->getParentLoop();
1185 // Insert the new loop into the loop nest and register the new basic blocks.
1187 ParentLoop->addChildLoop(Lp);
1188 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1189 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1190 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1192 LI->addTopLevelLoop(Lp);
1195 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1198 LoopVectorPreHeader = VectorPH;
1199 LoopScalarPreHeader = ScalarPH;
1200 LoopMiddleBlock = MiddleBlock;
1201 LoopExitBlock = ExitBlock;
1202 LoopVectorBody = VecBody;
1203 LoopScalarBody = OldBasicBlock;
1204 LoopBypassBlock = BypassBlock;
1207 /// This function returns the identity element (or neutral element) for
1208 /// the operation K.
1210 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) {
1212 case LoopVectorizationLegality:: RK_IntegerXor:
1213 case LoopVectorizationLegality:: RK_IntegerAdd:
1214 case LoopVectorizationLegality:: RK_IntegerOr:
1215 // Adding, Xoring, Oring zero to a number does not change it.
1216 return ConstantInt::get(Tp, 0);
1217 case LoopVectorizationLegality:: RK_IntegerMult:
1218 // Multiplying a number by 1 does not change it.
1219 return ConstantInt::get(Tp, 1);
1220 case LoopVectorizationLegality:: RK_IntegerAnd:
1221 // AND-ing a number with an all-1 value does not change it.
1222 return ConstantInt::get(Tp, -1, true);
1223 case LoopVectorizationLegality:: RK_FloatMult:
1224 // Multiplying a number by 1 does not change it.
1225 return ConstantFP::get(Tp, 1.0L);
1226 case LoopVectorizationLegality:: RK_FloatAdd:
1227 // Adding zero to a number does not change it.
1228 return ConstantFP::get(Tp, 0.0L);
1230 llvm_unreachable("Unknown reduction kind");
1235 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
1236 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
1239 switch (II->getIntrinsicID()) {
1240 case Intrinsic::sqrt:
1241 case Intrinsic::sin:
1242 case Intrinsic::cos:
1243 case Intrinsic::exp:
1244 case Intrinsic::exp2:
1245 case Intrinsic::log:
1246 case Intrinsic::log10:
1247 case Intrinsic::log2:
1248 case Intrinsic::fabs:
1249 case Intrinsic::floor:
1250 case Intrinsic::ceil:
1251 case Intrinsic::trunc:
1252 case Intrinsic::rint:
1253 case Intrinsic::nearbyint:
1254 case Intrinsic::pow:
1255 case Intrinsic::fma:
1256 case Intrinsic::fmuladd:
1264 /// This function translates the reduction kind to an LLVM binary operator.
1265 static Instruction::BinaryOps
1266 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1268 case LoopVectorizationLegality::RK_IntegerAdd:
1269 return Instruction::Add;
1270 case LoopVectorizationLegality::RK_IntegerMult:
1271 return Instruction::Mul;
1272 case LoopVectorizationLegality::RK_IntegerOr:
1273 return Instruction::Or;
1274 case LoopVectorizationLegality::RK_IntegerAnd:
1275 return Instruction::And;
1276 case LoopVectorizationLegality::RK_IntegerXor:
1277 return Instruction::Xor;
1278 case LoopVectorizationLegality::RK_FloatMult:
1279 return Instruction::FMul;
1280 case LoopVectorizationLegality::RK_FloatAdd:
1281 return Instruction::FAdd;
1283 llvm_unreachable("Unknown reduction operation");
1288 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1289 //===------------------------------------------------===//
1291 // Notice: any optimization or new instruction that go
1292 // into the code below should be also be implemented in
1295 //===------------------------------------------------===//
1296 BasicBlock &BB = *OrigLoop->getHeader();
1298 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
1300 // In order to support reduction variables we need to be able to vectorize
1301 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1302 // stages. First, we create a new vector PHI node with no incoming edges.
1303 // We use this value when we vectorize all of the instructions that use the
1304 // PHI. Next, after all of the instructions in the block are complete we
1305 // add the new incoming edges to the PHI. At this point all of the
1306 // instructions in the basic block are vectorized, so we can use them to
1307 // construct the PHI.
1308 PhiVector RdxPHIsToFix;
1310 // Scan the loop in a topological order to ensure that defs are vectorized
1312 LoopBlocksDFS DFS(OrigLoop);
1315 // Vectorize all of the blocks in the original loop.
1316 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1317 be = DFS.endRPO(); bb != be; ++bb)
1318 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1320 // At this point every instruction in the original loop is widened to
1321 // a vector form. We are almost done. Now, we need to fix the PHI nodes
1322 // that we vectorized. The PHI nodes are currently empty because we did
1323 // not want to introduce cycles. Notice that the remaining PHI nodes
1324 // that we need to fix are reduction variables.
1326 // Create the 'reduced' values for each of the induction vars.
1327 // The reduced values are the vector values that we scalarize and combine
1328 // after the loop is finished.
1329 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1331 PHINode *RdxPhi = *it;
1332 assert(RdxPhi && "Unable to recover vectorized PHI");
1334 // Find the reduction variable descriptor.
1335 assert(Legal->getReductionVars()->count(RdxPhi) &&
1336 "Unable to find the reduction variable");
1337 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1338 (*Legal->getReductionVars())[RdxPhi];
1340 // We need to generate a reduction vector from the incoming scalar.
1341 // To do so, we need to generate the 'identity' vector and overide
1342 // one of the elements with the incoming scalar reduction. We need
1343 // to do it in the vector-loop preheader.
1344 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
1346 // This is the vector-clone of the value that leaves the loop.
1347 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1348 Type *VecTy = VectorExit[0]->getType();
1350 // Find the reduction identity variable. Zero for addition, or, xor,
1351 // one for multiplication, -1 for And.
1352 Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType());
1353 Constant *Identity = ConstantVector::getSplat(VF, Iden);
1355 // This vector is the Identity vector where the first element is the
1356 // incoming scalar reduction.
1357 Value *VectorStart = Builder.CreateInsertElement(Identity,
1358 RdxDesc.StartValue, Zero);
1360 // Fix the vector-loop phi.
1361 // We created the induction variable so we know that the
1362 // preheader is the first entry.
1363 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1365 // Reductions do not have to start at zero. They can start with
1366 // any loop invariant values.
1367 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1368 BasicBlock *Latch = OrigLoop->getLoopLatch();
1369 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1370 VectorParts &Val = getVectorValue(LoopVal);
1371 for (unsigned part = 0; part < UF; ++part) {
1372 // Make sure to add the reduction stat value only to the
1373 // first unroll part.
1374 Value *StartVal = (part == 0) ? VectorStart : Identity;
1375 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1376 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1379 // Before each round, move the insertion point right between
1380 // the PHIs and the values we are going to write.
1381 // This allows us to write both PHINodes and the extractelement
1383 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1385 VectorParts RdxParts;
1386 for (unsigned part = 0; part < UF; ++part) {
1387 // This PHINode contains the vectorized reduction variable, or
1388 // the initial value vector, if we bypass the vector loop.
1389 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1390 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1391 Value *StartVal = (part == 0) ? VectorStart : Identity;
1392 NewPhi->addIncoming(StartVal, LoopBypassBlock);
1393 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1394 RdxParts.push_back(NewPhi);
1397 // Reduce all of the unrolled parts into a single vector.
1398 Value *ReducedPartRdx = RdxParts[0];
1399 for (unsigned part = 1; part < UF; ++part) {
1400 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1401 ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx,
1405 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1406 // and vector ops, reducing the set of values being computed by half each
1408 assert(isPowerOf2_32(VF) &&
1409 "Reduction emission only supported for pow2 vectors!");
1410 Value *TmpVec = ReducedPartRdx;
1411 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1412 for (unsigned i = VF; i != 1; i >>= 1) {
1413 // Move the upper half of the vector to the lower half.
1414 for (unsigned j = 0; j != i/2; ++j)
1415 ShuffleMask[j] = Builder.getInt32(i/2 + j);
1417 // Fill the rest of the mask with undef.
1418 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1419 UndefValue::get(Builder.getInt32Ty()));
1422 Builder.CreateShuffleVector(TmpVec,
1423 UndefValue::get(TmpVec->getType()),
1424 ConstantVector::get(ShuffleMask),
1427 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1428 TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx");
1431 // The result is in the first element of the vector.
1432 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1434 // Now, we need to fix the users of the reduction variable
1435 // inside and outside of the scalar remainder loop.
1436 // We know that the loop is in LCSSA form. We need to update the
1437 // PHI nodes in the exit blocks.
1438 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1439 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1440 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1441 if (!LCSSAPhi) continue;
1443 // All PHINodes need to have a single entry edge, or two if
1444 // we already fixed them.
1445 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1447 // We found our reduction value exit-PHI. Update it with the
1448 // incoming bypass edge.
1449 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1450 // Add an edge coming from the bypass.
1451 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1454 }// end of the LCSSA phi scan.
1456 // Fix the scalar loop reduction variable with the incoming reduction sum
1457 // from the vector body and from the backedge value.
1458 int IncomingEdgeBlockIdx =
1459 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1460 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1461 // Pick the other block.
1462 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1463 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1464 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1465 }// end of for each redux variable.
1467 // The Loop exit block may have single value PHI nodes where the incoming
1468 // value is 'undef'. While vectorizing we only handled real values that
1469 // were defined inside the loop. Here we handle the 'undef case'.
1471 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1472 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1473 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1474 if (!LCSSAPhi) continue;
1475 if (LCSSAPhi->getNumIncomingValues() == 1)
1476 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1481 InnerLoopVectorizer::VectorParts
1482 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1483 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1486 VectorParts SrcMask = createBlockInMask(Src);
1488 // The terminator has to be a branch inst!
1489 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1490 assert(BI && "Unexpected terminator found");
1492 if (BI->isConditional()) {
1493 VectorParts EdgeMask = getVectorValue(BI->getCondition());
1495 if (BI->getSuccessor(0) != Dst)
1496 for (unsigned part = 0; part < UF; ++part)
1497 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1499 for (unsigned part = 0; part < UF; ++part)
1500 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1507 InnerLoopVectorizer::VectorParts
1508 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1509 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1511 // Loop incoming mask is all-one.
1512 if (OrigLoop->getHeader() == BB) {
1513 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1514 return getVectorValue(C);
1517 // This is the block mask. We OR all incoming edges, and with zero.
1518 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1519 VectorParts BlockMask = getVectorValue(Zero);
1522 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1523 VectorParts EM = createEdgeMask(*it, BB);
1524 for (unsigned part = 0; part < UF; ++part)
1525 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1532 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1533 BasicBlock *BB, PhiVector *PV) {
1534 Constant *Zero = Builder.getInt32(0);
1536 // For each instruction in the old loop.
1537 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1538 VectorParts &Entry = WidenMap.get(it);
1539 switch (it->getOpcode()) {
1540 case Instruction::Br:
1541 // Nothing to do for PHIs and BR, since we already took care of the
1542 // loop control flow instructions.
1544 case Instruction::PHI:{
1545 PHINode* P = cast<PHINode>(it);
1546 // Handle reduction variables:
1547 if (Legal->getReductionVars()->count(P)) {
1548 for (unsigned part = 0; part < UF; ++part) {
1549 // This is phase one of vectorizing PHIs.
1550 Type *VecTy = VectorType::get(it->getType(), VF);
1551 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1552 LoopVectorBody-> getFirstInsertionPt());
1558 // Check for PHI nodes that are lowered to vector selects.
1559 if (P->getParent() != OrigLoop->getHeader()) {
1560 // We know that all PHIs in non header blocks are converted into
1561 // selects, so we don't have to worry about the insertion order and we
1562 // can just use the builder.
1564 // At this point we generate the predication tree. There may be
1565 // duplications since this is a simple recursive scan, but future
1566 // optimizations will clean it up.
1567 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1570 for (unsigned part = 0; part < UF; ++part) {
1571 VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1572 VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1573 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1579 // This PHINode must be an induction variable.
1580 // Make sure that we know about it.
1581 assert(Legal->getInductionVars()->count(P) &&
1582 "Not an induction variable");
1584 LoopVectorizationLegality::InductionInfo II =
1585 Legal->getInductionVars()->lookup(P);
1588 case LoopVectorizationLegality::IK_NoInduction:
1589 llvm_unreachable("Unknown induction");
1590 case LoopVectorizationLegality::IK_IntInduction: {
1591 assert(P == OldInduction && "Unexpected PHI");
1592 Value *Broadcasted = getBroadcastInstrs(Induction);
1593 // After broadcasting the induction variable we need to make the
1594 // vector consecutive by adding 0, 1, 2 ...
1595 for (unsigned part = 0; part < UF; ++part)
1596 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1599 case LoopVectorizationLegality::IK_ReverseIntInduction:
1600 case LoopVectorizationLegality::IK_PtrInduction:
1601 // Handle reverse integer and pointer inductions.
1602 Value *StartIdx = 0;
1603 // If we have a single integer induction variable then use it.
1604 // Otherwise, start counting at zero.
1606 LoopVectorizationLegality::InductionInfo OldII =
1607 Legal->getInductionVars()->lookup(OldInduction);
1608 StartIdx = OldII.StartValue;
1610 StartIdx = ConstantInt::get(Induction->getType(), 0);
1612 // This is the normalized GEP that starts counting at zero.
1613 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1616 // Handle the reverse integer induction variable case.
1617 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1618 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1619 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1621 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1624 // This is a new value so do not hoist it out.
1625 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1626 // After broadcasting the induction variable we need to make the
1627 // vector consecutive by adding ... -3, -2, -1, 0.
1628 for (unsigned part = 0; part < UF; ++part)
1629 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1633 // Handle the pointer induction variable case.
1634 assert(P->getType()->isPointerTy() && "Unexpected type.");
1636 // This is the vector of results. Notice that we don't generate
1637 // vector geps because scalar geps result in better code.
1638 for (unsigned part = 0; part < UF; ++part) {
1639 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1640 for (unsigned int i = 0; i < VF; ++i) {
1641 Constant *Idx = ConstantInt::get(Induction->getType(),
1643 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1645 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1647 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1648 Builder.getInt32(i),
1651 Entry[part] = VecVal;
1658 case Instruction::Add:
1659 case Instruction::FAdd:
1660 case Instruction::Sub:
1661 case Instruction::FSub:
1662 case Instruction::Mul:
1663 case Instruction::FMul:
1664 case Instruction::UDiv:
1665 case Instruction::SDiv:
1666 case Instruction::FDiv:
1667 case Instruction::URem:
1668 case Instruction::SRem:
1669 case Instruction::FRem:
1670 case Instruction::Shl:
1671 case Instruction::LShr:
1672 case Instruction::AShr:
1673 case Instruction::And:
1674 case Instruction::Or:
1675 case Instruction::Xor: {
1676 // Just widen binops.
1677 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1678 VectorParts &A = getVectorValue(it->getOperand(0));
1679 VectorParts &B = getVectorValue(it->getOperand(1));
1681 // Use this vector value for all users of the original instruction.
1682 for (unsigned Part = 0; Part < UF; ++Part) {
1683 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1685 // Update the NSW, NUW and Exact flags.
1686 BinaryOperator *VecOp = cast<BinaryOperator>(V);
1687 if (isa<OverflowingBinaryOperator>(BinOp)) {
1688 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1689 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1691 if (isa<PossiblyExactOperator>(VecOp))
1692 VecOp->setIsExact(BinOp->isExact());
1698 case Instruction::Select: {
1700 // If the selector is loop invariant we can create a select
1701 // instruction with a scalar condition. Otherwise, use vector-select.
1702 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1705 // The condition can be loop invariant but still defined inside the
1706 // loop. This means that we can't just use the original 'cond' value.
1707 // We have to take the 'vectorized' value and pick the first lane.
1708 // Instcombine will make this a no-op.
1709 VectorParts &Cond = getVectorValue(it->getOperand(0));
1710 VectorParts &Op0 = getVectorValue(it->getOperand(1));
1711 VectorParts &Op1 = getVectorValue(it->getOperand(2));
1712 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1713 Builder.getInt32(0));
1714 for (unsigned Part = 0; Part < UF; ++Part) {
1715 Entry[Part] = Builder.CreateSelect(
1716 InvariantCond ? ScalarCond : Cond[Part],
1723 case Instruction::ICmp:
1724 case Instruction::FCmp: {
1725 // Widen compares. Generate vector compares.
1726 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1727 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1728 VectorParts &A = getVectorValue(it->getOperand(0));
1729 VectorParts &B = getVectorValue(it->getOperand(1));
1730 for (unsigned Part = 0; Part < UF; ++Part) {
1733 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1735 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1741 case Instruction::Store: {
1742 // Attempt to issue a wide store.
1743 StoreInst *SI = dyn_cast<StoreInst>(it);
1744 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1745 Value *Ptr = SI->getPointerOperand();
1746 unsigned Alignment = SI->getAlignment();
1748 assert(!Legal->isUniform(Ptr) &&
1749 "We do not allow storing to uniform addresses");
1752 int Stride = Legal->isConsecutivePtr(Ptr);
1753 bool Reverse = Stride < 0;
1755 scalarizeInstruction(it);
1759 // Handle consecutive stores.
1761 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1763 // The last index does not have to be the induction. It can be
1764 // consecutive and be a function of the index. For example A[I+1];
1765 unsigned NumOperands = Gep->getNumOperands();
1767 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1768 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1769 Value *LastIndex = GEPParts[0];
1770 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1772 // Create the new GEP with the new induction variable.
1773 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1774 Gep2->setOperand(NumOperands - 1, LastIndex);
1775 Ptr = Builder.Insert(Gep2);
1777 // Use the induction element ptr.
1778 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1779 VectorParts &PtrVal = getVectorValue(Ptr);
1780 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1783 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1784 for (unsigned Part = 0; Part < UF; ++Part) {
1785 // Calculate the pointer for the specific unroll-part.
1786 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1789 // If we store to reverse consecutive memory locations then we need
1790 // to reverse the order of elements in the stored value.
1791 StoredVal[Part] = reverseVector(StoredVal[Part]);
1792 // If the address is consecutive but reversed, then the
1793 // wide store needs to start at the last vector element.
1794 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1795 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1798 Value *VecPtr = Builder.CreateBitCast(PartPtr, StTy->getPointerTo());
1799 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1803 case Instruction::Load: {
1804 // Attempt to issue a wide load.
1805 LoadInst *LI = dyn_cast<LoadInst>(it);
1806 Type *RetTy = VectorType::get(LI->getType(), VF);
1807 Value *Ptr = LI->getPointerOperand();
1808 unsigned Alignment = LI->getAlignment();
1810 // If the pointer is loop invariant or if it is non consecutive,
1811 // scalarize the load.
1812 int Stride = Legal->isConsecutivePtr(Ptr);
1813 bool Reverse = Stride < 0;
1814 if (Legal->isUniform(Ptr) || Stride == 0) {
1815 scalarizeInstruction(it);
1819 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1821 // The last index does not have to be the induction. It can be
1822 // consecutive and be a function of the index. For example A[I+1];
1823 unsigned NumOperands = Gep->getNumOperands();
1825 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1826 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1827 Value *LastIndex = GEPParts[0];
1828 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1830 // Create the new GEP with the new induction variable.
1831 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1832 Gep2->setOperand(NumOperands - 1, LastIndex);
1833 Ptr = Builder.Insert(Gep2);
1835 // Use the induction element ptr.
1836 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1837 VectorParts &PtrVal = getVectorValue(Ptr);
1838 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1841 for (unsigned Part = 0; Part < UF; ++Part) {
1842 // Calculate the pointer for the specific unroll-part.
1843 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1846 // If the address is consecutive but reversed, then the
1847 // wide store needs to start at the last vector element.
1848 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1849 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1852 Value *VecPtr = Builder.CreateBitCast(PartPtr, RetTy->getPointerTo());
1853 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1854 cast<LoadInst>(LI)->setAlignment(Alignment);
1855 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1859 case Instruction::ZExt:
1860 case Instruction::SExt:
1861 case Instruction::FPToUI:
1862 case Instruction::FPToSI:
1863 case Instruction::FPExt:
1864 case Instruction::PtrToInt:
1865 case Instruction::IntToPtr:
1866 case Instruction::SIToFP:
1867 case Instruction::UIToFP:
1868 case Instruction::Trunc:
1869 case Instruction::FPTrunc:
1870 case Instruction::BitCast: {
1871 CastInst *CI = dyn_cast<CastInst>(it);
1872 /// Optimize the special case where the source is the induction
1873 /// variable. Notice that we can only optimize the 'trunc' case
1874 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1875 /// c. other casts depend on pointer size.
1876 if (CI->getOperand(0) == OldInduction &&
1877 it->getOpcode() == Instruction::Trunc) {
1878 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1880 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1881 for (unsigned Part = 0; Part < UF; ++Part)
1882 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1885 /// Vectorize casts.
1886 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1888 VectorParts &A = getVectorValue(it->getOperand(0));
1889 for (unsigned Part = 0; Part < UF; ++Part)
1890 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1894 case Instruction::Call: {
1895 assert(isTriviallyVectorizableIntrinsic(it));
1896 Module *M = BB->getParent()->getParent();
1897 IntrinsicInst *II = cast<IntrinsicInst>(it);
1898 Intrinsic::ID ID = II->getIntrinsicID();
1899 for (unsigned Part = 0; Part < UF; ++Part) {
1900 SmallVector<Value*, 4> Args;
1901 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
1902 VectorParts &Arg = getVectorValue(II->getArgOperand(i));
1903 Args.push_back(Arg[Part]);
1905 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1906 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1907 Entry[Part] = Builder.CreateCall(F, Args);
1913 // All other instructions are unsupported. Scalarize them.
1914 scalarizeInstruction(it);
1917 }// end of for_each instr.
1920 void InnerLoopVectorizer::updateAnalysis() {
1921 // Forget the original basic block.
1922 SE->forgetLoop(OrigLoop);
1924 // Update the dominator tree information.
1925 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1926 "Entry does not dominate exit.");
1928 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1929 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1930 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1931 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1932 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1933 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1935 DEBUG(DT->verifyAnalysis());
1938 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1939 if (!EnableIfConversion)
1942 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1943 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1945 // Collect the blocks that need predication.
1946 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1947 BasicBlock *BB = LoopBlocks[i];
1949 // We don't support switch statements inside loops.
1950 if (!isa<BranchInst>(BB->getTerminator()))
1953 // We must have at most two predecessors because we need to convert
1954 // all PHIs to selects.
1955 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1959 // We must be able to predicate all blocks that need to be predicated.
1960 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1964 // We can if-convert this loop.
1968 bool LoopVectorizationLegality::canVectorize() {
1969 assert(TheLoop->getLoopPreheader() && "No preheader!!");
1971 // We can only vectorize innermost loops.
1972 if (TheLoop->getSubLoopsVector().size())
1975 // We must have a single backedge.
1976 if (TheLoop->getNumBackEdges() != 1)
1979 // We must have a single exiting block.
1980 if (!TheLoop->getExitingBlock())
1983 unsigned NumBlocks = TheLoop->getNumBlocks();
1985 // Check if we can if-convert non single-bb loops.
1986 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1987 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1991 // We need to have a loop header.
1992 BasicBlock *Latch = TheLoop->getLoopLatch();
1993 DEBUG(dbgs() << "LV: Found a loop: " <<
1994 TheLoop->getHeader()->getName() << "\n");
1996 // ScalarEvolution needs to be able to find the exit count.
1997 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1998 if (ExitCount == SE->getCouldNotCompute()) {
1999 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2003 // Do not loop-vectorize loops with a tiny trip count.
2004 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2005 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2006 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2007 "This loop is not worth vectorizing.\n");
2011 // Check if we can vectorize the instructions and CFG in this loop.
2012 if (!canVectorizeInstrs()) {
2013 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2017 // Go over each instruction and look at memory deps.
2018 if (!canVectorizeMemory()) {
2019 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2023 // Collect all of the variables that remain uniform after vectorization.
2024 collectLoopUniforms();
2026 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2027 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2030 // Okay! We can vectorize. At this point we don't have any other mem analysis
2031 // which may limit our maximum vectorization factor, so just return true with
2036 bool LoopVectorizationLegality::canVectorizeInstrs() {
2037 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2038 BasicBlock *Header = TheLoop->getHeader();
2040 // For each block in the loop.
2041 for (Loop::block_iterator bb = TheLoop->block_begin(),
2042 be = TheLoop->block_end(); bb != be; ++bb) {
2044 // Scan the instructions in the block and look for hazards.
2045 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2048 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2049 // This should not happen because the loop should be normalized.
2050 if (Phi->getNumIncomingValues() != 2) {
2051 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2055 // Check that this PHI type is allowed.
2056 if (!Phi->getType()->isIntegerTy() &&
2057 !Phi->getType()->isFloatingPointTy() &&
2058 !Phi->getType()->isPointerTy()) {
2059 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2063 // If this PHINode is not in the header block, then we know that we
2064 // can convert it to select during if-conversion. No need to check if
2065 // the PHIs in this block are induction or reduction variables.
2069 // This is the value coming from the preheader.
2070 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2071 // Check if this is an induction variable.
2072 InductionKind IK = isInductionVariable(Phi);
2074 if (IK_NoInduction != IK) {
2075 // Int inductions are special because we only allow one IV.
2076 if (IK == IK_IntInduction) {
2078 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2084 DEBUG(dbgs() << "LV: Found an induction variable.\n");
2085 Inductions[Phi] = InductionInfo(StartValue, IK);
2089 if (AddReductionVar(Phi, RK_IntegerAdd)) {
2090 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2093 if (AddReductionVar(Phi, RK_IntegerMult)) {
2094 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2097 if (AddReductionVar(Phi, RK_IntegerOr)) {
2098 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2101 if (AddReductionVar(Phi, RK_IntegerAnd)) {
2102 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2105 if (AddReductionVar(Phi, RK_IntegerXor)) {
2106 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2109 if (AddReductionVar(Phi, RK_FloatMult)) {
2110 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2113 if (AddReductionVar(Phi, RK_FloatAdd)) {
2114 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2118 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2120 }// end of PHI handling
2122 // We still don't handle functions.
2123 CallInst *CI = dyn_cast<CallInst>(it);
2124 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
2125 DEBUG(dbgs() << "LV: Found a call site.\n");
2129 // Check that the instruction return type is vectorizable.
2130 if (!VectorType::isValidElementType(it->getType()) &&
2131 !it->getType()->isVoidTy()) {
2132 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2136 // Check that the stored type is vectorizable.
2137 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2138 Type *T = ST->getValueOperand()->getType();
2139 if (!VectorType::isValidElementType(T))
2143 // Reduction instructions are allowed to have exit users.
2144 // All other instructions must not have external users.
2145 if (!AllowedExit.count(it))
2146 //Check that all of the users of the loop are inside the BB.
2147 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2149 Instruction *U = cast<Instruction>(*I);
2150 // This user may be a reduction exit value.
2151 if (!TheLoop->contains(U)) {
2152 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2161 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2162 assert(getInductionVars()->size() && "No induction variables");
2168 void LoopVectorizationLegality::collectLoopUniforms() {
2169 // We now know that the loop is vectorizable!
2170 // Collect variables that will remain uniform after vectorization.
2171 std::vector<Value*> Worklist;
2172 BasicBlock *Latch = TheLoop->getLoopLatch();
2174 // Start with the conditional branch and walk up the block.
2175 Worklist.push_back(Latch->getTerminator()->getOperand(0));
2177 while (Worklist.size()) {
2178 Instruction *I = dyn_cast<Instruction>(Worklist.back());
2179 Worklist.pop_back();
2181 // Look at instructions inside this loop.
2182 // Stop when reaching PHI nodes.
2183 // TODO: we need to follow values all over the loop, not only in this block.
2184 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2187 // This is a known uniform.
2190 // Insert all operands.
2191 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2192 Worklist.push_back(I->getOperand(i));
2197 bool LoopVectorizationLegality::canVectorizeMemory() {
2198 typedef SmallVector<Value*, 16> ValueVector;
2199 typedef SmallPtrSet<Value*, 16> ValueSet;
2200 // Holds the Load and Store *instructions*.
2203 PtrRtCheck.Pointers.clear();
2204 PtrRtCheck.Need = false;
2207 for (Loop::block_iterator bb = TheLoop->block_begin(),
2208 be = TheLoop->block_end(); bb != be; ++bb) {
2210 // Scan the BB and collect legal loads and stores.
2211 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2214 // If this is a load, save it. If this instruction can read from memory
2215 // but is not a load, then we quit. Notice that we don't handle function
2216 // calls that read or write.
2217 if (it->mayReadFromMemory()) {
2218 LoadInst *Ld = dyn_cast<LoadInst>(it);
2219 if (!Ld) return false;
2220 if (!Ld->isSimple()) {
2221 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2224 Loads.push_back(Ld);
2228 // Save 'store' instructions. Abort if other instructions write to memory.
2229 if (it->mayWriteToMemory()) {
2230 StoreInst *St = dyn_cast<StoreInst>(it);
2231 if (!St) return false;
2232 if (!St->isSimple()) {
2233 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2236 Stores.push_back(St);
2241 // Now we have two lists that hold the loads and the stores.
2242 // Next, we find the pointers that they use.
2244 // Check if we see any stores. If there are no stores, then we don't
2245 // care if the pointers are *restrict*.
2246 if (!Stores.size()) {
2247 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2251 // Holds the read and read-write *pointers* that we find.
2253 ValueVector ReadWrites;
2255 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2256 // multiple times on the same object. If the ptr is accessed twice, once
2257 // for read and once for write, it will only appear once (on the write
2258 // list). This is okay, since we are going to check for conflicts between
2259 // writes and between reads and writes, but not between reads and reads.
2262 ValueVector::iterator I, IE;
2263 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2264 StoreInst *ST = cast<StoreInst>(*I);
2265 Value* Ptr = ST->getPointerOperand();
2267 if (isUniform(Ptr)) {
2268 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2272 // If we did *not* see this pointer before, insert it to
2273 // the read-write list. At this phase it is only a 'write' list.
2274 if (Seen.insert(Ptr))
2275 ReadWrites.push_back(Ptr);
2278 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2279 LoadInst *LD = cast<LoadInst>(*I);
2280 Value* Ptr = LD->getPointerOperand();
2281 // If we did *not* see this pointer before, insert it to the
2282 // read list. If we *did* see it before, then it is already in
2283 // the read-write list. This allows us to vectorize expressions
2284 // such as A[i] += x; Because the address of A[i] is a read-write
2285 // pointer. This only works if the index of A[i] is consecutive.
2286 // If the address of i is unknown (for example A[B[i]]) then we may
2287 // read a few words, modify, and write a few words, and some of the
2288 // words may be written to the same address.
2289 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2290 Reads.push_back(Ptr);
2293 // If we write (or read-write) to a single destination and there are no
2294 // other reads in this loop then is it safe to vectorize.
2295 if (ReadWrites.size() == 1 && Reads.size() == 0) {
2296 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2300 // Find pointers with computable bounds. We are going to use this information
2301 // to place a runtime bound check.
2302 bool CanDoRT = true;
2303 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
2304 if (hasComputableBounds(*I)) {
2305 PtrRtCheck.insert(SE, TheLoop, *I);
2306 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2311 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
2312 if (hasComputableBounds(*I)) {
2313 PtrRtCheck.insert(SE, TheLoop, *I);
2314 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2320 // Check that we did not collect too many pointers or found a
2321 // unsizeable pointer.
2322 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2328 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2331 bool NeedRTCheck = false;
2333 // Now that the pointers are in two lists (Reads and ReadWrites), we
2334 // can check that there are no conflicts between each of the writes and
2335 // between the writes to the reads.
2336 ValueSet WriteObjects;
2337 ValueVector TempObjects;
2339 // Check that the read-writes do not conflict with other read-write
2341 bool AllWritesIdentified = true;
2342 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
2343 GetUnderlyingObjects(*I, TempObjects, DL);
2344 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2346 if (!isIdentifiedObject(*it)) {
2347 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
2349 AllWritesIdentified = false;
2351 if (!WriteObjects.insert(*it)) {
2352 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2357 TempObjects.clear();
2360 /// Check that the reads don't conflict with the read-writes.
2361 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
2362 GetUnderlyingObjects(*I, TempObjects, DL);
2363 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2365 // If all of the writes are identified then we don't care if the read
2366 // pointer is identified or not.
2367 if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
2368 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
2371 if (WriteObjects.count(*it)) {
2372 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
2377 TempObjects.clear();
2380 PtrRtCheck.Need = NeedRTCheck;
2381 if (NeedRTCheck && !CanDoRT) {
2382 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2383 "the array bounds.\n");
2388 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2389 " need a runtime memory check.\n");
2393 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2394 ReductionKind Kind) {
2395 if (Phi->getNumIncomingValues() != 2)
2398 // Reduction variables are only found in the loop header block.
2399 if (Phi->getParent() != TheLoop->getHeader())
2402 // Obtain the reduction start value from the value that comes from the loop
2404 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2406 // ExitInstruction is the single value which is used outside the loop.
2407 // We only allow for a single reduction value to be used outside the loop.
2408 // This includes users of the reduction, variables (which form a cycle
2409 // which ends in the phi node).
2410 Instruction *ExitInstruction = 0;
2411 // Indicates that we found a binary operation in our scan.
2412 bool FoundBinOp = false;
2414 // Iter is our iterator. We start with the PHI node and scan for all of the
2415 // users of this instruction. All users must be instructions that can be
2416 // used as reduction variables (such as ADD). We may have a single
2417 // out-of-block user. The cycle must end with the original PHI.
2418 Instruction *Iter = Phi;
2420 // If the instruction has no users then this is a broken
2421 // chain and can't be a reduction variable.
2422 if (Iter->use_empty())
2425 // Did we find a user inside this loop already ?
2426 bool FoundInBlockUser = false;
2427 // Did we reach the initial PHI node already ?
2428 bool FoundStartPHI = false;
2430 // Is this a bin op ?
2431 FoundBinOp |= !isa<PHINode>(Iter);
2433 // For each of the *users* of iter.
2434 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2436 Instruction *U = cast<Instruction>(*it);
2437 // We already know that the PHI is a user.
2439 FoundStartPHI = true;
2443 // Check if we found the exit user.
2444 BasicBlock *Parent = U->getParent();
2445 if (!TheLoop->contains(Parent)) {
2446 // Exit if you find multiple outside users.
2447 if (ExitInstruction != 0)
2449 ExitInstruction = Iter;
2452 // We allow in-loop PHINodes which are not the original reduction PHI
2453 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2454 // structure) then don't skip this PHI.
2455 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2456 U->getParent() != TheLoop->getHeader() &&
2457 TheLoop->contains(U) &&
2458 Iter->getNumUses() > 1)
2461 // We can't have multiple inside users.
2462 if (FoundInBlockUser)
2464 FoundInBlockUser = true;
2466 // Any reduction instr must be of one of the allowed kinds.
2467 if (!isReductionInstr(U, Kind))
2470 // Reductions of instructions such as Div, and Sub is only
2471 // possible if the LHS is the reduction variable.
2472 if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter)
2478 // We found a reduction var if we have reached the original
2479 // phi node and we only have a single instruction with out-of-loop
2481 if (FoundStartPHI) {
2482 // This instruction is allowed to have out-of-loop users.
2483 AllowedExit.insert(ExitInstruction);
2485 // Save the description of this reduction variable.
2486 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2487 Reductions[Phi] = RD;
2488 // We've ended the cycle. This is a reduction variable if we have an
2489 // outside user and it has a binary op.
2490 return FoundBinOp && ExitInstruction;
2496 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2497 ReductionKind Kind) {
2498 bool FP = I->getType()->isFloatingPointTy();
2499 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2501 switch (I->getOpcode()) {
2504 case Instruction::PHI:
2505 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2509 case Instruction::Sub:
2510 case Instruction::Add:
2511 return Kind == RK_IntegerAdd;
2512 case Instruction::SDiv:
2513 case Instruction::UDiv:
2514 case Instruction::Mul:
2515 return Kind == RK_IntegerMult;
2516 case Instruction::And:
2517 return Kind == RK_IntegerAnd;
2518 case Instruction::Or:
2519 return Kind == RK_IntegerOr;
2520 case Instruction::Xor:
2521 return Kind == RK_IntegerXor;
2522 case Instruction::FMul:
2523 return Kind == RK_FloatMult && FastMath;
2524 case Instruction::FAdd:
2525 return Kind == RK_FloatAdd && FastMath;
2529 LoopVectorizationLegality::InductionKind
2530 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2531 Type *PhiTy = Phi->getType();
2532 // We only handle integer and pointer inductions variables.
2533 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2534 return IK_NoInduction;
2536 // Check that the PHI is consecutive and starts at zero.
2537 const SCEV *PhiScev = SE->getSCEV(Phi);
2538 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2540 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2541 return IK_NoInduction;
2543 const SCEV *Step = AR->getStepRecurrence(*SE);
2545 // Integer inductions need to have a stride of one.
2546 if (PhiTy->isIntegerTy()) {
2548 return IK_IntInduction;
2549 if (Step->isAllOnesValue())
2550 return IK_ReverseIntInduction;
2551 return IK_NoInduction;
2554 // Calculate the pointer stride and check if it is consecutive.
2555 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2557 return IK_NoInduction;
2559 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2560 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2561 if (C->getValue()->equalsInt(Size))
2562 return IK_PtrInduction;
2564 return IK_NoInduction;
2567 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2568 Value *In0 = const_cast<Value*>(V);
2569 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2573 return Inductions.count(PN);
2576 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
2577 assert(TheLoop->contains(BB) && "Unknown block used");
2579 // Blocks that do not dominate the latch need predication.
2580 BasicBlock* Latch = TheLoop->getLoopLatch();
2581 return !DT->dominates(BB, Latch);
2584 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2585 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2586 // We don't predicate loads/stores at the moment.
2587 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2590 // The instructions below can trap.
2591 switch (it->getOpcode()) {
2593 case Instruction::UDiv:
2594 case Instruction::SDiv:
2595 case Instruction::URem:
2596 case Instruction::SRem:
2604 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2605 const SCEV *PhiScev = SE->getSCEV(Ptr);
2606 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2610 return AR->isAffine();
2614 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2616 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2617 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2621 // Find the trip count.
2622 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2623 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2625 unsigned WidestType = getWidestType();
2626 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
2627 unsigned MaxVectorSize = WidestRegister / WidestType;
2628 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
2629 DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
2631 if (MaxVectorSize == 0) {
2632 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
2636 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
2637 " into one vector.");
2639 unsigned VF = MaxVectorSize;
2641 // If we optimize the program for size, avoid creating the tail loop.
2643 // If we are unable to calculate the trip count then don't try to vectorize.
2645 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2649 // Find the maximum SIMD width that can fit within the trip count.
2650 VF = TC % MaxVectorSize;
2655 // If the trip count that we found modulo the vectorization factor is not
2656 // zero then we require a tail.
2658 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2664 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2665 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2670 float Cost = expectedCost(1);
2672 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2673 for (unsigned i=2; i <= VF; i*=2) {
2674 // Notice that the vector loop needs to be executed less times, so
2675 // we need to divide the cost of the vector loops by the width of
2676 // the vector elements.
2677 float VectorCost = expectedCost(i) / (float)i;
2678 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2679 (int)VectorCost << ".\n");
2680 if (VectorCost < Cost) {
2686 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2690 unsigned LoopVectorizationCostModel::getWidestType() {
2691 unsigned MaxWidth = 8;
2694 for (Loop::block_iterator bb = TheLoop->block_begin(),
2695 be = TheLoop->block_end(); bb != be; ++bb) {
2696 BasicBlock *BB = *bb;
2698 // For each instruction in the loop.
2699 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2700 if (Legal->isUniformAfterVectorization(it))
2703 Type *T = it->getType();
2705 if (StoreInst *ST = dyn_cast<StoreInst>(it))
2706 T = ST->getValueOperand()->getType();
2708 // PHINodes and pointers are difficult to analyze, but we catch all other
2709 // uses of the types in other instructions.
2710 if (isa<PHINode>(it) || T->isPointerTy() || T->isVoidTy())
2713 MaxWidth = std::max(MaxWidth, T->getScalarSizeInBits());
2721 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2723 // Use the user preference, unless 'auto' is selected.
2727 // When we optimize for size we don't unroll.
2731 // Do not unroll loops with a relatively small trip count.
2732 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
2733 TheLoop->getLoopLatch());
2734 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
2737 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
2738 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
2739 " vector registers\n");
2741 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
2742 // We divide by these constants so assume that we have at least one
2743 // instruction that uses at least one register.
2744 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
2745 R.NumInstructions = std::max(R.NumInstructions, 1U);
2747 // We calculate the unroll factor using the following formula.
2748 // Subtract the number of loop invariants from the number of available
2749 // registers. These registers are used by all of the unrolled instances.
2750 // Next, divide the remaining registers by the number of registers that is
2751 // required by the loop, in order to estimate how many parallel instances
2752 // fit without causing spills.
2753 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
2755 // We don't want to unroll the loops to the point where they do not fit into
2756 // the decoded cache. Assume that we only allow 32 IR instructions.
2757 UF = std::min(UF, (MaxLoopSizeThreshold / R.NumInstructions));
2759 // Clamp the unroll factor ranges to reasonable factors.
2760 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
2762 if (UF > MaxUnrollSize)
2770 LoopVectorizationCostModel::RegisterUsage
2771 LoopVectorizationCostModel::calculateRegisterUsage() {
2772 // This function calculates the register usage by measuring the highest number
2773 // of values that are alive at a single location. Obviously, this is a very
2774 // rough estimation. We scan the loop in a topological order in order and
2775 // assign a number to each instruction. We use RPO to ensure that defs are
2776 // met before their users. We assume that each instruction that has in-loop
2777 // users starts an interval. We record every time that an in-loop value is
2778 // used, so we have a list of the first and last occurrences of each
2779 // instruction. Next, we transpose this data structure into a multi map that
2780 // holds the list of intervals that *end* at a specific location. This multi
2781 // map allows us to perform a linear search. We scan the instructions linearly
2782 // and record each time that a new interval starts, by placing it in a set.
2783 // If we find this value in the multi-map then we remove it from the set.
2784 // The max register usage is the maximum size of the set.
2785 // We also search for instructions that are defined outside the loop, but are
2786 // used inside the loop. We need this number separately from the max-interval
2787 // usage number because when we unroll, loop-invariant values do not take
2789 LoopBlocksDFS DFS(TheLoop);
2793 R.NumInstructions = 0;
2795 // Each 'key' in the map opens a new interval. The values
2796 // of the map are the index of the 'last seen' usage of the
2797 // instruction that is the key.
2798 typedef DenseMap<Instruction*, unsigned> IntervalMap;
2799 // Maps instruction to its index.
2800 DenseMap<unsigned, Instruction*> IdxToInstr;
2801 // Marks the end of each interval.
2802 IntervalMap EndPoint;
2803 // Saves the list of instruction indices that are used in the loop.
2804 SmallSet<Instruction*, 8> Ends;
2805 // Saves the list of values that are used in the loop but are
2806 // defined outside the loop, such as arguments and constants.
2807 SmallPtrSet<Value*, 8> LoopInvariants;
2810 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2811 be = DFS.endRPO(); bb != be; ++bb) {
2812 R.NumInstructions += (*bb)->size();
2813 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2815 Instruction *I = it;
2816 IdxToInstr[Index++] = I;
2818 // Save the end location of each USE.
2819 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2820 Value *U = I->getOperand(i);
2821 Instruction *Instr = dyn_cast<Instruction>(U);
2823 // Ignore non-instruction values such as arguments, constants, etc.
2824 if (!Instr) continue;
2826 // If this instruction is outside the loop then record it and continue.
2827 if (!TheLoop->contains(Instr)) {
2828 LoopInvariants.insert(Instr);
2832 // Overwrite previous end points.
2833 EndPoint[Instr] = Index;
2839 // Saves the list of intervals that end with the index in 'key'.
2840 typedef SmallVector<Instruction*, 2> InstrList;
2841 DenseMap<unsigned, InstrList> TransposeEnds;
2843 // Transpose the EndPoints to a list of values that end at each index.
2844 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
2846 TransposeEnds[it->second].push_back(it->first);
2848 SmallSet<Instruction*, 8> OpenIntervals;
2849 unsigned MaxUsage = 0;
2852 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
2853 for (unsigned int i = 0; i < Index; ++i) {
2854 Instruction *I = IdxToInstr[i];
2855 // Ignore instructions that are never used within the loop.
2856 if (!Ends.count(I)) continue;
2858 // Remove all of the instructions that end at this location.
2859 InstrList &List = TransposeEnds[i];
2860 for (unsigned int j=0, e = List.size(); j < e; ++j)
2861 OpenIntervals.erase(List[j]);
2863 // Count the number of live interals.
2864 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
2866 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
2867 OpenIntervals.size() <<"\n");
2869 // Add the current instruction to the list of open intervals.
2870 OpenIntervals.insert(I);
2873 unsigned Invariant = LoopInvariants.size();
2874 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
2875 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
2876 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
2878 R.LoopInvariantRegs = Invariant;
2879 R.MaxLocalUsers = MaxUsage;
2883 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2887 for (Loop::block_iterator bb = TheLoop->block_begin(),
2888 be = TheLoop->block_end(); bb != be; ++bb) {
2889 unsigned BlockCost = 0;
2890 BasicBlock *BB = *bb;
2892 // For each instruction in the old loop.
2893 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2894 unsigned C = getInstructionCost(it, VF);
2896 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2897 VF << " For instruction: "<< *it << "\n");
2900 // We assume that if-converted blocks have a 50% chance of being executed.
2901 // When the code is scalar then some of the blocks are avoided due to CF.
2902 // When the code is vectorized we execute all code paths.
2903 if (Legal->blockNeedsPredication(*bb) && VF == 1)
2913 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2914 // If we know that this instruction will remain uniform, check the cost of
2915 // the scalar version.
2916 if (Legal->isUniformAfterVectorization(I))
2919 Type *RetTy = I->getType();
2920 Type *VectorTy = ToVectorTy(RetTy, VF);
2922 // TODO: We need to estimate the cost of intrinsic calls.
2923 switch (I->getOpcode()) {
2924 case Instruction::GetElementPtr:
2925 // We mark this instruction as zero-cost because scalar GEPs are usually
2926 // lowered to the intruction addressing mode. At the moment we don't
2927 // generate vector geps.
2929 case Instruction::Br: {
2930 return TTI.getCFInstrCost(I->getOpcode());
2932 case Instruction::PHI:
2933 //TODO: IF-converted IFs become selects.
2935 case Instruction::Add:
2936 case Instruction::FAdd:
2937 case Instruction::Sub:
2938 case Instruction::FSub:
2939 case Instruction::Mul:
2940 case Instruction::FMul:
2941 case Instruction::UDiv:
2942 case Instruction::SDiv:
2943 case Instruction::FDiv:
2944 case Instruction::URem:
2945 case Instruction::SRem:
2946 case Instruction::FRem:
2947 case Instruction::Shl:
2948 case Instruction::LShr:
2949 case Instruction::AShr:
2950 case Instruction::And:
2951 case Instruction::Or:
2952 case Instruction::Xor:
2953 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy);
2954 case Instruction::Select: {
2955 SelectInst *SI = cast<SelectInst>(I);
2956 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2957 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2958 Type *CondTy = SI->getCondition()->getType();
2960 CondTy = VectorType::get(CondTy, VF);
2962 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2964 case Instruction::ICmp:
2965 case Instruction::FCmp: {
2966 Type *ValTy = I->getOperand(0)->getType();
2967 VectorTy = ToVectorTy(ValTy, VF);
2968 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
2970 case Instruction::Store: {
2971 StoreInst *SI = cast<StoreInst>(I);
2972 Type *ValTy = SI->getValueOperand()->getType();
2973 VectorTy = ToVectorTy(ValTy, VF);
2976 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
2978 SI->getPointerAddressSpace());
2980 // Scalarized stores.
2981 int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
2982 bool Reverse = Stride < 0;
2986 // The cost of extracting from the value vector and pointer vector.
2987 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2988 for (unsigned i = 0; i < VF; ++i) {
2989 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
2991 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
2994 // The cost of the scalar stores.
2995 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
2997 SI->getPointerAddressSpace());
3002 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3004 SI->getPointerAddressSpace());
3006 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3010 case Instruction::Load: {
3011 LoadInst *LI = cast<LoadInst>(I);
3014 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
3015 LI->getPointerAddressSpace());
3017 // Scalarized loads.
3018 int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
3019 bool Reverse = Stride < 0;
3022 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3024 // The cost of extracting from the pointer vector.
3025 for (unsigned i = 0; i < VF; ++i)
3026 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3028 // The cost of inserting data to the result vector.
3029 for (unsigned i = 0; i < VF; ++i)
3030 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy, i);
3032 // The cost of the scalar stores.
3033 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), RetTy->getScalarType(),
3035 LI->getPointerAddressSpace());
3040 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3042 LI->getPointerAddressSpace());
3044 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
3047 case Instruction::ZExt:
3048 case Instruction::SExt:
3049 case Instruction::FPToUI:
3050 case Instruction::FPToSI:
3051 case Instruction::FPExt:
3052 case Instruction::PtrToInt:
3053 case Instruction::IntToPtr:
3054 case Instruction::SIToFP:
3055 case Instruction::UIToFP:
3056 case Instruction::Trunc:
3057 case Instruction::FPTrunc:
3058 case Instruction::BitCast: {
3059 // We optimize the truncation of induction variable.
3060 // The cost of these is the same as the scalar operation.
3061 if (I->getOpcode() == Instruction::Trunc &&
3062 Legal->isInductionVariable(I->getOperand(0)))
3063 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3064 I->getOperand(0)->getType());
3066 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3067 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3069 case Instruction::Call: {
3070 assert(isTriviallyVectorizableIntrinsic(I));
3071 IntrinsicInst *II = cast<IntrinsicInst>(I);
3072 Type *RetTy = ToVectorTy(II->getType(), VF);
3073 SmallVector<Type*, 4> Tys;
3074 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
3075 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
3076 return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
3079 // We are scalarizing the instruction. Return the cost of the scalar
3080 // instruction, plus the cost of insert and extract into vector
3081 // elements, times the vector width.
3084 if (!RetTy->isVoidTy() && VF != 1) {
3085 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3087 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3090 // The cost of inserting the results plus extracting each one of the
3092 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3095 // The cost of executing VF copies of the scalar instruction. This opcode
3096 // is unknown. Assume that it is the same as 'mul'.
3097 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3103 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3104 if (Scalar->isVoidTy() || VF == 1)
3106 return VectorType::get(Scalar, VF);
3109 char LoopVectorize::ID = 0;
3110 static const char lv_name[] = "Loop Vectorization";
3111 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3112 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3113 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3114 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3115 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3116 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3119 Pass *createLoopVectorizePass() {
3120 return new LoopVectorize();