LoopVectorize.cpp revision f3252b12e02b1fcf01abf0a79b761c53de5985d0
1//===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
14//
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.
18//
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.
28//
29//===----------------------------------------------------------------------===//
30//
31// The reduction-variable vectorization is based on the paper:
32//  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
33//
34// Variable uniformity checks are inspired by:
35// Karrenberg, R. and Hack, S. Whole Function Vectorization.
36//
37// Other ideas/concepts are from:
38//  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
39//
40//  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
41//  Vectorizing Compilers.
42//
43//===----------------------------------------------------------------------===//
44
45#define LV_NAME "loop-vectorize"
46#define DEBUG_TYPE LV_NAME
47
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"
85#include <algorithm>
86#include <map>
87
88using namespace llvm;
89
90static cl::opt<unsigned>
91VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
92                    cl::desc("Sets the SIMD width. Zero is autoselect."));
93
94static cl::opt<unsigned>
95VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
96                    cl::desc("Sets the vectorization unroll count. "
97                             "Zero is autoselect."));
98
99static cl::opt<bool>
100EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
101                   cl::desc("Enable if-conversion during vectorization."));
102
103/// We don't vectorize loops with a known constant trip count below this number.
104static const unsigned TinyTripCountThreshold = 16;
105
106/// When performing a runtime memory check, do not check more than this
107/// number of pointers. Notice that the check is quadratic!
108static const unsigned RuntimeMemoryCheckThreshold = 4;
109
110/// This is the highest vector width that we try to generate.
111static const unsigned MaxVectorSize = 8;
112
113/// This is the highest Unroll Factor.
114static const unsigned MaxUnrollSize = 4;
115
116namespace {
117
118// Forward declarations.
119class LoopVectorizationLegality;
120class LoopVectorizationCostModel;
121
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
130///   instructions.
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.
136class InnerLoopVectorizer {
137public:
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) {}
144
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.
153    updateAnalysis();
154  }
155
156private:
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;
163
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,
167                         Instruction *Loc);
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);
172
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
178  /// and DST.
179  VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
180
181  /// A helper function to vectorize a single BB within the innermost loop.
182  void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
183                            PhiVector *PV);
184
185  /// Insert the new loop to the loop hierarchy and pass manager
186  /// and update the analysis passes.
187  void updateAnalysis();
188
189  /// This instruction is un-vectorizable. Implement it as a sequence
190  /// of scalars.
191  void scalarizeInstruction(Instruction *Instr);
192
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
197  /// element.
198  Value *getBroadcastInstrs(Value *V);
199
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);
204
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);
211
212  /// Get a uniform vector of constant integers. We use this to get
213  /// vectors of ones and zeros for the reduction code.
214  Constant* getUniformVector(unsigned Val, Type* ScalarTy);
215
216  /// Generate a shuffle sequence that will reverse the vector Vec.
217  Value *reverseVector(Value *Vec);
218
219  /// This is a helper class that holds the vectorizer state. It maps scalar
220  /// instructions to vector instructions. When the code is 'unrolled' then
221  /// then a single scalar value is mapped to multiple vector parts. The parts
222  /// are stored in the VectorPart type.
223  struct ValueMap {
224    /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
225    /// are mapped.
226    ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
227
228    /// \return True if 'Key' is saved in the Value Map.
229    bool has(Value *Key) { return MapStoreage.count(Key); }
230
231    /// Initializes a new entry in the map. Sets all of the vector parts to the
232    /// save value in 'Val'.
233    /// \return A reference to a vector with splat values.
234    VectorParts &splat(Value *Key, Value *Val) {
235      MapStoreage[Key].clear();
236      MapStoreage[Key].append(UF, Val);
237      return MapStoreage[Key];
238    }
239
240    ///\return A reference to the value that is stored at 'Key'.
241    VectorParts &get(Value *Key) {
242      if (!has(Key))
243        MapStoreage[Key].resize(UF);
244      return MapStoreage[Key];
245    }
246
247    /// The unroll factor. Each entry in the map stores this number of vector
248    /// elements.
249    unsigned UF;
250
251    /// Map storage. We use std::map and not DenseMap because insertions to a
252    /// dense map invalidates its iterators.
253    std::map<Value*, VectorParts> MapStoreage;
254  };
255
256  /// The original loop.
257  Loop *OrigLoop;
258  /// Scev analysis to use.
259  ScalarEvolution *SE;
260  /// Loop Info.
261  LoopInfo *LI;
262  /// Dominator Tree.
263  DominatorTree *DT;
264  /// Data Layout.
265  DataLayout *DL;
266  /// The vectorization SIMD factor to use. Each vector will have this many
267  /// vector elements.
268  unsigned VF;
269  /// The vectorization unroll factor to use. Each scalar is vectorized to this
270  /// many different vector instructions.
271  unsigned UF;
272
273  /// The builder that we use
274  IRBuilder<> Builder;
275
276  // --- Vectorization state ---
277
278  /// The vector-loop preheader.
279  BasicBlock *LoopVectorPreHeader;
280  /// The scalar-loop preheader.
281  BasicBlock *LoopScalarPreHeader;
282  /// Middle Block between the vector and the scalar.
283  BasicBlock *LoopMiddleBlock;
284  ///The ExitBlock of the scalar loop.
285  BasicBlock *LoopExitBlock;
286  ///The vector loop body.
287  BasicBlock *LoopVectorBody;
288  ///The scalar loop body.
289  BasicBlock *LoopScalarBody;
290  ///The first bypass block.
291  BasicBlock *LoopBypassBlock;
292
293  /// The new Induction variable which was added to the new block.
294  PHINode *Induction;
295  /// The induction variable of the old basic block.
296  PHINode *OldInduction;
297  /// Maps scalars to widened vectors.
298  ValueMap WidenMap;
299};
300
301/// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
302/// to what vectorization factor.
303/// This class does not look at the profitability of vectorization, only the
304/// legality. This class has two main kinds of checks:
305/// * Memory checks - The code in canVectorizeMemory checks if vectorization
306///   will change the order of memory accesses in a way that will change the
307///   correctness of the program.
308/// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
309/// checks for a number of different conditions, such as the availability of a
310/// single induction variable, that all types are supported and vectorize-able,
311/// etc. This code reflects the capabilities of InnerLoopVectorizer.
312/// This class is also used by InnerLoopVectorizer for identifying
313/// induction variable and the different reduction variables.
314class LoopVectorizationLegality {
315public:
316  LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
317                            DominatorTree *DT)
318      : TheLoop(L), SE(SE), DL(DL), DT(DT), Induction(0) {}
319
320  /// This enum represents the kinds of reductions that we support.
321  enum ReductionKind {
322    NoReduction, ///< Not a reduction.
323    IntegerAdd,  ///< Sum of numbers.
324    IntegerMult, ///< Product of numbers.
325    IntegerOr,   ///< Bitwise or logical OR of numbers.
326    IntegerAnd,  ///< Bitwise or logical AND of numbers.
327    IntegerXor   ///< Bitwise or logical XOR of numbers.
328  };
329
330  /// This enum represents the kinds of inductions that we support.
331  enum InductionKind {
332    NoInduction,         ///< Not an induction variable.
333    IntInduction,        ///< Integer induction variable. Step = 1.
334    ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
335    PtrInduction         ///< Pointer induction variable. Step = sizeof(elem).
336  };
337
338  /// This POD struct holds information about reduction variables.
339  struct ReductionDescriptor {
340    ReductionDescriptor() : StartValue(0), LoopExitInstr(0), Kind(NoReduction) {
341    }
342
343    ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K)
344        : StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
345
346    // The starting value of the reduction.
347    // It does not have to be zero!
348    Value *StartValue;
349    // The instruction who's value is used outside the loop.
350    Instruction *LoopExitInstr;
351    // The kind of the reduction.
352    ReductionKind Kind;
353  };
354
355  // This POD struct holds information about the memory runtime legality
356  // check that a group of pointers do not overlap.
357  struct RuntimePointerCheck {
358    RuntimePointerCheck() : Need(false) {}
359
360    /// Reset the state of the pointer runtime information.
361    void reset() {
362      Need = false;
363      Pointers.clear();
364      Starts.clear();
365      Ends.clear();
366    }
367
368    /// Insert a pointer and calculate the start and end SCEVs.
369    void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
370
371    /// This flag indicates if we need to add the runtime check.
372    bool Need;
373    /// Holds the pointers that we need to check.
374    SmallVector<Value*, 2> Pointers;
375    /// Holds the pointer value at the beginning of the loop.
376    SmallVector<const SCEV*, 2> Starts;
377    /// Holds the pointer value at the end of the loop.
378    SmallVector<const SCEV*, 2> Ends;
379  };
380
381  /// A POD for saving information about induction variables.
382  struct InductionInfo {
383    InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
384    InductionInfo() : StartValue(0), IK(NoInduction) {}
385    /// Start value.
386    Value *StartValue;
387    /// Induction kind.
388    InductionKind IK;
389  };
390
391  /// ReductionList contains the reduction descriptors for all
392  /// of the reductions that were found in the loop.
393  typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
394
395  /// InductionList saves induction variables and maps them to the
396  /// induction descriptor.
397  typedef MapVector<PHINode*, InductionInfo> InductionList;
398
399  /// Returns true if it is legal to vectorize this loop.
400  /// This does not mean that it is profitable to vectorize this
401  /// loop, only that it is legal to do so.
402  bool canVectorize();
403
404  /// Returns the Induction variable.
405  PHINode *getInduction() { return Induction; }
406
407  /// Returns the reduction variables found in the loop.
408  ReductionList *getReductionVars() { return &Reductions; }
409
410  /// Returns the induction variables found in the loop.
411  InductionList *getInductionVars() { return &Inductions; }
412
413  /// Returns True if V is an induction variable in this loop.
414  bool isInductionVariable(const Value *V);
415
416  /// Return true if the block BB needs to be predicated in order for the loop
417  /// to be vectorized.
418  bool blockNeedsPredication(BasicBlock *BB);
419
420  /// Check if this  pointer is consecutive when vectorizing. This happens
421  /// when the last index of the GEP is the induction variable, or that the
422  /// pointer itself is an induction variable.
423  /// This check allows us to vectorize A[idx] into a wide load/store.
424  /// Returns:
425  /// 0 - Stride is unknown or non consecutive.
426  /// 1 - Address is consecutive.
427  /// -1 - Address is consecutive, and decreasing.
428  int isConsecutivePtr(Value *Ptr);
429
430  /// Returns true if the value V is uniform within the loop.
431  bool isUniform(Value *V);
432
433  /// Returns true if this instruction will remain scalar after vectorization.
434  bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
435
436  /// Returns the information that we collected about runtime memory check.
437  RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
438private:
439  /// Check if a single basic block loop is vectorizable.
440  /// At this point we know that this is a loop with a constant trip count
441  /// and we only need to check individual instructions.
442  bool canVectorizeInstrs();
443
444  /// When we vectorize loops we may change the order in which
445  /// we read and write from memory. This method checks if it is
446  /// legal to vectorize the code, considering only memory constrains.
447  /// Returns true if the loop is vectorizable
448  bool canVectorizeMemory();
449
450  /// Return true if we can vectorize this loop using the IF-conversion
451  /// transformation.
452  bool canVectorizeWithIfConvert();
453
454  /// Collect the variables that need to stay uniform after vectorization.
455  void collectLoopUniforms();
456
457  /// Return true if all of the instructions in the block can be speculatively
458  /// executed.
459  bool blockCanBePredicated(BasicBlock *BB);
460
461  /// Returns True, if 'Phi' is the kind of reduction variable for type
462  /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
463  bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
464  /// Returns true if the instruction I can be a reduction variable of type
465  /// 'Kind'.
466  bool isReductionInstr(Instruction *I, ReductionKind Kind);
467  /// Returns the induction kind of Phi. This function may return NoInduction
468  /// if the PHI is not an induction variable.
469  InductionKind isInductionVariable(PHINode *Phi);
470  /// Return true if can compute the address bounds of Ptr within the loop.
471  bool hasComputableBounds(Value *Ptr);
472
473  /// The loop that we evaluate.
474  Loop *TheLoop;
475  /// Scev analysis.
476  ScalarEvolution *SE;
477  /// DataLayout analysis.
478  DataLayout *DL;
479  // Dominators.
480  DominatorTree *DT;
481
482  //  ---  vectorization state --- //
483
484  /// Holds the integer induction variable. This is the counter of the
485  /// loop.
486  PHINode *Induction;
487  /// Holds the reduction variables.
488  ReductionList Reductions;
489  /// Holds all of the induction variables that we found in the loop.
490  /// Notice that inductions don't need to start at zero and that induction
491  /// variables can be pointers.
492  InductionList Inductions;
493
494  /// Allowed outside users. This holds the reduction
495  /// vars which can be accessed from outside the loop.
496  SmallPtrSet<Value*, 4> AllowedExit;
497  /// This set holds the variables which are known to be uniform after
498  /// vectorization.
499  SmallPtrSet<Instruction*, 4> Uniforms;
500  /// We need to check that all of the pointers in this list are disjoint
501  /// at runtime.
502  RuntimePointerCheck PtrRtCheck;
503};
504
505/// LoopVectorizationCostModel - estimates the expected speedups due to
506/// vectorization.
507/// In many cases vectorization is not profitable. This can happen because of
508/// a number of reasons. In this class we mainly attempt to predict the
509/// expected speedup/slowdowns due to the supported instruction set. We use the
510/// TargetTransformInfo to query the different backends for the cost of
511/// different operations.
512class LoopVectorizationCostModel {
513public:
514  LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
515                             LoopVectorizationLegality *Legal,
516                             const TargetTransformInfo *TTI)
517      : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI) {}
518
519  /// \return The most profitable vectorization factor.
520  /// This method checks every power of two up to VF. If UserVF is not ZERO
521  /// then this vectorization factor will be selected if vectorization is
522  /// possible.
523  unsigned selectVectorizationFactor(bool OptForSize, unsigned UserVF);
524
525
526  /// \return The most profitable unroll factor.
527  /// If UserUF is non-zero then this method finds the best unroll-factor
528  /// based on register pressure and other parameters.
529  unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF);
530
531  /// \brief A struct that represents some properties of the register usage
532  /// of a loop.
533  struct RegisterUsage {
534    /// Holds the number of loop invariant values that are used in the loop.
535    unsigned LoopInvariantRegs;
536    /// Holds the maximum number of concurrent live intervals in the loop.
537    unsigned MaxLocalUsers;
538    /// Holds the number of instructions in the loop.
539    unsigned NumInstructions;
540  };
541
542  /// \return  information about the register usage of the loop.
543  RegisterUsage calculateRegisterUsage();
544
545private:
546  /// Returns the expected execution cost. The unit of the cost does
547  /// not matter because we use the 'cost' units to compare different
548  /// vector widths. The cost that is returned is *not* normalized by
549  /// the factor width.
550  unsigned expectedCost(unsigned VF);
551
552  /// Returns the execution time cost of an instruction for a given vector
553  /// width. Vector width of one means scalar.
554  unsigned getInstructionCost(Instruction *I, unsigned VF);
555
556  /// A helper function for converting Scalar types to vector types.
557  /// If the incoming type is void, we return void. If the VF is 1, we return
558  /// the scalar type.
559  static Type* ToVectorTy(Type *Scalar, unsigned VF);
560
561  /// The loop that we evaluate.
562  Loop *TheLoop;
563  /// Scev analysis.
564  ScalarEvolution *SE;
565  /// Loop Info analysis.
566  LoopInfo *LI;
567  /// Vectorization legality.
568  LoopVectorizationLegality *Legal;
569  /// Vector target information.
570  const TargetTransformInfo *TTI;
571};
572
573/// The LoopVectorize Pass.
574struct LoopVectorize : public LoopPass {
575  /// Pass identification, replacement for typeid
576  static char ID;
577
578  explicit LoopVectorize() : LoopPass(ID) {
579    initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
580  }
581
582  ScalarEvolution *SE;
583  DataLayout *DL;
584  LoopInfo *LI;
585  TargetTransformInfo *TTI;
586  DominatorTree *DT;
587
588  virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
589    // We only vectorize innermost loops.
590    if (!L->empty())
591      return false;
592
593    SE = &getAnalysis<ScalarEvolution>();
594    DL = getAnalysisIfAvailable<DataLayout>();
595    LI = &getAnalysis<LoopInfo>();
596    TTI = getAnalysisIfAvailable<TargetTransformInfo>();
597    DT = &getAnalysis<DominatorTree>();
598
599    DEBUG(dbgs() << "LV: Checking a loop in \"" <<
600          L->getHeader()->getParent()->getName() << "\"\n");
601
602    // Check if it is legal to vectorize the loop.
603    LoopVectorizationLegality LVL(L, SE, DL, DT);
604    if (!LVL.canVectorize()) {
605      DEBUG(dbgs() << "LV: Not vectorizing.\n");
606      return false;
607    }
608
609    // Use the cost model.
610    LoopVectorizationCostModel CM(L, SE, LI, &LVL, TTI);
611
612    // Check the function attribues to find out if this function should be
613    // optimized for size.
614    Function *F = L->getHeader()->getParent();
615    Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
616    Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
617    unsigned FnIndex = AttributeSet::FunctionIndex;
618    bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
619    bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
620
621    if (NoFloat) {
622      DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
623            "attribute is used.\n");
624      return false;
625    }
626
627    unsigned VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
628    unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll);
629
630    if (VF == 1) {
631      DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
632      return false;
633    }
634
635    DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
636          F->getParent()->getModuleIdentifier()<<"\n");
637    DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
638
639    // If we decided that it is *legal* to vectorizer the loop then do it.
640    InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF, UF);
641    LB.vectorize(&LVL);
642
643    DEBUG(verifyFunction(*L->getHeader()->getParent()));
644    return true;
645  }
646
647  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
648    LoopPass::getAnalysisUsage(AU);
649    AU.addRequiredID(LoopSimplifyID);
650    AU.addRequiredID(LCSSAID);
651    AU.addRequired<LoopInfo>();
652    AU.addRequired<ScalarEvolution>();
653    AU.addRequired<DominatorTree>();
654    AU.addPreserved<LoopInfo>();
655    AU.addPreserved<DominatorTree>();
656  }
657
658};
659
660} // end anonymous namespace
661
662//===----------------------------------------------------------------------===//
663// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
664// LoopVectorizationCostModel.
665//===----------------------------------------------------------------------===//
666
667void
668LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
669                                                       Loop *Lp, Value *Ptr) {
670  const SCEV *Sc = SE->getSCEV(Ptr);
671  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
672  assert(AR && "Invalid addrec expression");
673  const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
674  const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
675  Pointers.push_back(Ptr);
676  Starts.push_back(AR->getStart());
677  Ends.push_back(ScEnd);
678}
679
680Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
681  // Save the current insertion location.
682  Instruction *Loc = Builder.GetInsertPoint();
683
684  // We need to place the broadcast of invariant variables outside the loop.
685  Instruction *Instr = dyn_cast<Instruction>(V);
686  bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
687  bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
688
689  // Place the code for broadcasting invariant variables in the new preheader.
690  if (Invariant)
691    Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
692
693  // Broadcast the scalar into all locations in the vector.
694  Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
695
696  // Restore the builder insertion point.
697  if (Invariant)
698    Builder.SetInsertPoint(Loc);
699
700  return Shuf;
701}
702
703Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
704                                                 bool Negate) {
705  assert(Val->getType()->isVectorTy() && "Must be a vector");
706  assert(Val->getType()->getScalarType()->isIntegerTy() &&
707         "Elem must be an integer");
708  // Create the types.
709  Type *ITy = Val->getType()->getScalarType();
710  VectorType *Ty = cast<VectorType>(Val->getType());
711  int VLen = Ty->getNumElements();
712  SmallVector<Constant*, 8> Indices;
713
714  // Create a vector of consecutive numbers from zero to VF.
715  for (int i = 0; i < VLen; ++i) {
716    int Idx = Negate ? (-i): i;
717    Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
718  }
719
720  // Add the consecutive indices to the vector value.
721  Constant *Cv = ConstantVector::get(Indices);
722  assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
723  return Builder.CreateAdd(Val, Cv, "induction");
724}
725
726int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
727  assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
728
729  // If this value is a pointer induction variable we know it is consecutive.
730  PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
731  if (Phi && Inductions.count(Phi)) {
732    InductionInfo II = Inductions[Phi];
733    if (PtrInduction == II.IK)
734      return 1;
735  }
736
737  GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
738  if (!Gep)
739    return 0;
740
741  unsigned NumOperands = Gep->getNumOperands();
742  Value *LastIndex = Gep->getOperand(NumOperands - 1);
743
744  // Check that all of the gep indices are uniform except for the last.
745  for (unsigned i = 0; i < NumOperands - 1; ++i)
746    if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
747      return 0;
748
749  // We can emit wide load/stores only if the last index is the induction
750  // variable.
751  const SCEV *Last = SE->getSCEV(LastIndex);
752  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
753    const SCEV *Step = AR->getStepRecurrence(*SE);
754
755    // The memory is consecutive because the last index is consecutive
756    // and all other indices are loop invariant.
757    if (Step->isOne())
758      return 1;
759    if (Step->isAllOnesValue())
760      return -1;
761  }
762
763  return 0;
764}
765
766bool LoopVectorizationLegality::isUniform(Value *V) {
767  return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
768}
769
770InnerLoopVectorizer::VectorParts&
771InnerLoopVectorizer::getVectorValue(Value *V) {
772  assert(V != Induction && "The new induction variable should not be used.");
773  assert(!V->getType()->isVectorTy() && "Can't widen a vector");
774
775  // If we have this scalar in the map, return it.
776  if (WidenMap.has(V))
777    return WidenMap.get(V);
778
779  // If this scalar is unknown, assume that it is a constant or that it is
780  // loop invariant. Broadcast V and save the value for future uses.
781  Value *B = getBroadcastInstrs(V);
782  WidenMap.splat(V, B);
783  return WidenMap.get(V);
784}
785
786Constant*
787InnerLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
788  return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
789}
790
791Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
792  assert(Vec->getType()->isVectorTy() && "Invalid type");
793  SmallVector<Constant*, 8> ShuffleMask;
794  for (unsigned i = 0; i < VF; ++i)
795    ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
796
797  return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
798                                     ConstantVector::get(ShuffleMask),
799                                     "reverse");
800}
801
802void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
803  assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
804  // Holds vector parameters or scalars, in case of uniform vals.
805  SmallVector<VectorParts, 4> Params;
806
807  // Find all of the vectorized parameters.
808  for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
809    Value *SrcOp = Instr->getOperand(op);
810
811    // If we are accessing the old induction variable, use the new one.
812    if (SrcOp == OldInduction) {
813      Params.push_back(getVectorValue(SrcOp));
814      continue;
815    }
816
817    // Try using previously calculated values.
818    Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
819
820    // If the src is an instruction that appeared earlier in the basic block
821    // then it should already be vectorized.
822    if (SrcInst && OrigLoop->contains(SrcInst)) {
823      assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
824      // The parameter is a vector value from earlier.
825      Params.push_back(WidenMap.get(SrcInst));
826    } else {
827      // The parameter is a scalar from outside the loop. Maybe even a constant.
828      VectorParts Scalars;
829      Scalars.append(UF, SrcOp);
830      Params.push_back(Scalars);
831    }
832  }
833
834  assert(Params.size() == Instr->getNumOperands() &&
835         "Invalid number of operands");
836
837  // Does this instruction return a value ?
838  bool IsVoidRetTy = Instr->getType()->isVoidTy();
839
840  Value *UndefVec = IsVoidRetTy ? 0 :
841    UndefValue::get(VectorType::get(Instr->getType(), VF));
842  // Create a new entry in the WidenMap and initialize it to Undef or Null.
843  VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
844
845  // For each scalar that we create:
846  for (unsigned Width = 0; Width < VF; ++Width) {
847    // For each vector unroll 'part':
848    for (unsigned Part = 0; Part < UF; ++Part) {
849      Instruction *Cloned = Instr->clone();
850      if (!IsVoidRetTy)
851        Cloned->setName(Instr->getName() + ".cloned");
852      // Replace the operands of the cloned instrucions with extracted scalars.
853      for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
854        Value *Op = Params[op][Part];
855        // Param is a vector. Need to extract the right lane.
856        if (Op->getType()->isVectorTy())
857          Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
858        Cloned->setOperand(op, Op);
859      }
860
861      // Place the cloned scalar in the new loop.
862      Builder.Insert(Cloned);
863
864      // If the original scalar returns a value we need to place it in a vector
865      // so that future users will be able to use it.
866      if (!IsVoidRetTy)
867        VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
868                                                       Builder.getInt32(Width));
869    }
870  }
871}
872
873Value*
874InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
875                                     Instruction *Loc) {
876  LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
877  Legal->getRuntimePointerCheck();
878
879  if (!PtrRtCheck->Need)
880    return NULL;
881
882  Value *MemoryRuntimeCheck = 0;
883  unsigned NumPointers = PtrRtCheck->Pointers.size();
884  SmallVector<Value* , 2> Starts;
885  SmallVector<Value* , 2> Ends;
886
887  SCEVExpander Exp(*SE, "induction");
888
889  // Use this type for pointer arithmetic.
890  Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
891
892  for (unsigned i = 0; i < NumPointers; ++i) {
893    Value *Ptr = PtrRtCheck->Pointers[i];
894    const SCEV *Sc = SE->getSCEV(Ptr);
895
896    if (SE->isLoopInvariant(Sc, OrigLoop)) {
897      DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
898            *Ptr <<"\n");
899      Starts.push_back(Ptr);
900      Ends.push_back(Ptr);
901    } else {
902      DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
903
904      Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
905      Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
906      Starts.push_back(Start);
907      Ends.push_back(End);
908    }
909  }
910
911  for (unsigned i = 0; i < NumPointers; ++i) {
912    for (unsigned j = i+1; j < NumPointers; ++j) {
913      Instruction::CastOps Op = Instruction::BitCast;
914      Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
915      Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
916      Value *End0 =   CastInst::Create(Op, Ends[i],   PtrArithTy, "bc", Loc);
917      Value *End1 =   CastInst::Create(Op, Ends[j],   PtrArithTy, "bc", Loc);
918
919      Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
920                                    Start0, End1, "bound0", Loc);
921      Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
922                                    Start1, End0, "bound1", Loc);
923      Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
924                                                 "found.conflict", Loc);
925      if (MemoryRuntimeCheck)
926        MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
927                                                    MemoryRuntimeCheck,
928                                                    IsConflict,
929                                                    "conflict.rdx", Loc);
930      else
931        MemoryRuntimeCheck = IsConflict;
932
933    }
934  }
935
936  return MemoryRuntimeCheck;
937}
938
939void
940InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
941  /*
942   In this function we generate a new loop. The new loop will contain
943   the vectorized instructions while the old loop will continue to run the
944   scalar remainder.
945
946       [ ] <-- vector loop bypass.
947     /  |
948    /   v
949   |   [ ]     <-- vector pre header.
950   |    |
951   |    v
952   |   [  ] \
953   |   [  ]_|   <-- vector loop.
954   |    |
955    \   v
956      >[ ]   <--- middle-block.
957     /  |
958    /   v
959   |   [ ]     <--- new preheader.
960   |    |
961   |    v
962   |   [ ] \
963   |   [ ]_|   <-- old scalar loop to handle remainder.
964    \   |
965     \  v
966      >[ ]     <-- exit block.
967   ...
968   */
969
970  BasicBlock *OldBasicBlock = OrigLoop->getHeader();
971  BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
972  BasicBlock *ExitBlock = OrigLoop->getExitBlock();
973  assert(ExitBlock && "Must have an exit block");
974
975  // Some loops have a single integer induction variable, while other loops
976  // don't. One example is c++ iterators that often have multiple pointer
977  // induction variables. In the code below we also support a case where we
978  // don't have a single induction variable.
979  OldInduction = Legal->getInduction();
980  Type *IdxTy = OldInduction ? OldInduction->getType() :
981  DL->getIntPtrType(SE->getContext());
982
983  // Find the loop boundaries.
984  const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
985  assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
986
987  // Get the total trip count from the count by adding 1.
988  ExitCount = SE->getAddExpr(ExitCount,
989                             SE->getConstant(ExitCount->getType(), 1));
990
991  // Expand the trip count and place the new instructions in the preheader.
992  // Notice that the pre-header does not change, only the loop body.
993  SCEVExpander Exp(*SE, "induction");
994
995  // Count holds the overall loop count (N).
996  Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
997                                   BypassBlock->getTerminator());
998
999  // The loop index does not have to start at Zero. Find the original start
1000  // value from the induction PHI node. If we don't have an induction variable
1001  // then we know that it starts at zero.
1002  Value *StartIdx = OldInduction ?
1003  OldInduction->getIncomingValueForBlock(BypassBlock):
1004  ConstantInt::get(IdxTy, 0);
1005
1006  assert(BypassBlock && "Invalid loop structure");
1007
1008  // Generate the code that checks in runtime if arrays overlap.
1009  Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
1010                                              BypassBlock->getTerminator());
1011
1012  // Split the single block loop into the two loop structure described above.
1013  BasicBlock *VectorPH =
1014  BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1015  BasicBlock *VecBody =
1016  VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1017  BasicBlock *MiddleBlock =
1018  VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1019  BasicBlock *ScalarPH =
1020  MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1021
1022  // This is the location in which we add all of the logic for bypassing
1023  // the new vector loop.
1024  Instruction *Loc = BypassBlock->getTerminator();
1025
1026  // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1027  // inside the loop.
1028  Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1029
1030  // Generate the induction variable.
1031  Induction = Builder.CreatePHI(IdxTy, 2, "index");
1032  // The loop step is equal to the vectorization factor (num of SIMD elements)
1033  // times the unroll factor (num of SIMD instructions).
1034  Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1035
1036  // We may need to extend the index in case there is a type mismatch.
1037  // We know that the count starts at zero and does not overflow.
1038  if (Count->getType() != IdxTy) {
1039    // The exit count can be of pointer type. Convert it to the correct
1040    // integer type.
1041    if (ExitCount->getType()->isPointerTy())
1042      Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
1043    else
1044      Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
1045  }
1046
1047  // Add the start index to the loop count to get the new end index.
1048  Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
1049
1050  // Now we need to generate the expression for N - (N % VF), which is
1051  // the part that the vectorized body will execute.
1052  Value *R = BinaryOperator::CreateURem(Count, Step, "n.mod.vf", Loc);
1053  Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
1054  Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
1055                                                     "end.idx.rnd.down", Loc);
1056
1057  // Now, compare the new count to zero. If it is zero skip the vector loop and
1058  // jump to the scalar loop.
1059  Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
1060                               IdxEndRoundDown,
1061                               StartIdx,
1062                               "cmp.zero", Loc);
1063
1064  // If we are using memory runtime checks, include them in.
1065  if (MemoryRuntimeCheck)
1066    Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
1067                                 "CntOrMem", Loc);
1068
1069  BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
1070  // Remove the old terminator.
1071  Loc->eraseFromParent();
1072
1073  // We are going to resume the execution of the scalar loop.
1074  // Go over all of the induction variables that we found and fix the
1075  // PHIs that are left in the scalar version of the loop.
1076  // The starting values of PHI nodes depend on the counter of the last
1077  // iteration in the vectorized loop.
1078  // If we come from a bypass edge then we need to start from the original
1079  // start value.
1080
1081  // This variable saves the new starting index for the scalar loop.
1082  PHINode *ResumeIndex = 0;
1083  LoopVectorizationLegality::InductionList::iterator I, E;
1084  LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1085  for (I = List->begin(), E = List->end(); I != E; ++I) {
1086    PHINode *OrigPhi = I->first;
1087    LoopVectorizationLegality::InductionInfo II = I->second;
1088    PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1089                                         MiddleBlock->getTerminator());
1090    Value *EndValue = 0;
1091    switch (II.IK) {
1092    case LoopVectorizationLegality::NoInduction:
1093      llvm_unreachable("Unknown induction");
1094    case LoopVectorizationLegality::IntInduction: {
1095      // Handle the integer induction counter:
1096      assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1097      assert(OrigPhi == OldInduction && "Unknown integer PHI");
1098      // We know what the end value is.
1099      EndValue = IdxEndRoundDown;
1100      // We also know which PHI node holds it.
1101      ResumeIndex = ResumeVal;
1102      break;
1103    }
1104    case LoopVectorizationLegality::ReverseIntInduction: {
1105      // Convert the CountRoundDown variable to the PHI size.
1106      unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1107      unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1108      Value *CRD = CountRoundDown;
1109      if (CRDSize > IISize)
1110        CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1111                               II.StartValue->getType(),
1112                               "tr.crd", BypassBlock->getTerminator());
1113      else if (CRDSize < IISize)
1114        CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1115                               II.StartValue->getType(),
1116                               "sext.crd", BypassBlock->getTerminator());
1117      // Handle reverse integer induction counter:
1118      EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1119                                           BypassBlock->getTerminator());
1120      break;
1121    }
1122    case LoopVectorizationLegality::PtrInduction: {
1123      // For pointer induction variables, calculate the offset using
1124      // the end index.
1125      EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
1126                                           "ptr.ind.end",
1127                                           BypassBlock->getTerminator());
1128      break;
1129    }
1130    }// end of case
1131
1132    // The new PHI merges the original incoming value, in case of a bypass,
1133    // or the value at the end of the vectorized loop.
1134    ResumeVal->addIncoming(II.StartValue, BypassBlock);
1135    ResumeVal->addIncoming(EndValue, VecBody);
1136
1137    // Fix the scalar body counter (PHI node).
1138    unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1139    OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1140  }
1141
1142  // If we are generating a new induction variable then we also need to
1143  // generate the code that calculates the exit value. This value is not
1144  // simply the end of the counter because we may skip the vectorized body
1145  // in case of a runtime check.
1146  if (!OldInduction){
1147    assert(!ResumeIndex && "Unexpected resume value found");
1148    ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1149                                  MiddleBlock->getTerminator());
1150    ResumeIndex->addIncoming(StartIdx, BypassBlock);
1151    ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1152  }
1153
1154  // Make sure that we found the index where scalar loop needs to continue.
1155  assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1156         "Invalid resume Index");
1157
1158  // Add a check in the middle block to see if we have completed
1159  // all of the iterations in the first vector loop.
1160  // If (N - N%VF) == N, then we *don't* need to run the remainder.
1161  Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1162                                ResumeIndex, "cmp.n",
1163                                MiddleBlock->getTerminator());
1164
1165  BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1166  // Remove the old terminator.
1167  MiddleBlock->getTerminator()->eraseFromParent();
1168
1169  // Create i+1 and fill the PHINode.
1170  Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1171  Induction->addIncoming(StartIdx, VectorPH);
1172  Induction->addIncoming(NextIdx, VecBody);
1173  // Create the compare.
1174  Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1175  Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1176
1177  // Now we have two terminators. Remove the old one from the block.
1178  VecBody->getTerminator()->eraseFromParent();
1179
1180  // Get ready to start creating new instructions into the vectorized body.
1181  Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1182
1183  // Create and register the new vector loop.
1184  Loop* Lp = new Loop();
1185  Loop *ParentLoop = OrigLoop->getParentLoop();
1186
1187  // Insert the new loop into the loop nest and register the new basic blocks.
1188  if (ParentLoop) {
1189    ParentLoop->addChildLoop(Lp);
1190    ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1191    ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1192    ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1193  } else {
1194    LI->addTopLevelLoop(Lp);
1195  }
1196
1197  Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1198
1199  // Save the state.
1200  LoopVectorPreHeader = VectorPH;
1201  LoopScalarPreHeader = ScalarPH;
1202  LoopMiddleBlock = MiddleBlock;
1203  LoopExitBlock = ExitBlock;
1204  LoopVectorBody = VecBody;
1205  LoopScalarBody = OldBasicBlock;
1206  LoopBypassBlock = BypassBlock;
1207}
1208
1209/// This function returns the identity element (or neutral element) for
1210/// the operation K.
1211static unsigned
1212getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
1213  switch (K) {
1214  case LoopVectorizationLegality::IntegerXor:
1215  case LoopVectorizationLegality::IntegerAdd:
1216  case LoopVectorizationLegality::IntegerOr:
1217    // Adding, Xoring, Oring zero to a number does not change it.
1218    return 0;
1219  case LoopVectorizationLegality::IntegerMult:
1220    // Multiplying a number by 1 does not change it.
1221    return 1;
1222  case LoopVectorizationLegality::IntegerAnd:
1223    // AND-ing a number with an all-1 value does not change it.
1224    return -1;
1225  default:
1226    llvm_unreachable("Unknown reduction kind");
1227  }
1228}
1229
1230static bool
1231isTriviallyVectorizableIntrinsic(Instruction *Inst) {
1232  IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
1233  if (!II)
1234    return false;
1235  switch (II->getIntrinsicID()) {
1236  case Intrinsic::sqrt:
1237  case Intrinsic::sin:
1238  case Intrinsic::cos:
1239  case Intrinsic::exp:
1240  case Intrinsic::exp2:
1241  case Intrinsic::log:
1242  case Intrinsic::log10:
1243  case Intrinsic::log2:
1244  case Intrinsic::fabs:
1245  case Intrinsic::floor:
1246  case Intrinsic::ceil:
1247  case Intrinsic::trunc:
1248  case Intrinsic::rint:
1249  case Intrinsic::nearbyint:
1250  case Intrinsic::pow:
1251  case Intrinsic::fma:
1252  case Intrinsic::fmuladd:
1253    return true;
1254  default:
1255    return false;
1256  }
1257  return false;
1258}
1259
1260void
1261InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1262  //===------------------------------------------------===//
1263  //
1264  // Notice: any optimization or new instruction that go
1265  // into the code below should be also be implemented in
1266  // the cost-model.
1267  //
1268  //===------------------------------------------------===//
1269  BasicBlock &BB = *OrigLoop->getHeader();
1270  Constant *Zero =
1271  ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
1272
1273  // In order to support reduction variables we need to be able to vectorize
1274  // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1275  // stages. First, we create a new vector PHI node with no incoming edges.
1276  // We use this value when we vectorize all of the instructions that use the
1277  // PHI. Next, after all of the instructions in the block are complete we
1278  // add the new incoming edges to the PHI. At this point all of the
1279  // instructions in the basic block are vectorized, so we can use them to
1280  // construct the PHI.
1281  PhiVector RdxPHIsToFix;
1282
1283  // Scan the loop in a topological order to ensure that defs are vectorized
1284  // before users.
1285  LoopBlocksDFS DFS(OrigLoop);
1286  DFS.perform(LI);
1287
1288  // Vectorize all of the blocks in the original loop.
1289  for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1290       be = DFS.endRPO(); bb != be; ++bb)
1291    vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1292
1293  // At this point every instruction in the original loop is widened to
1294  // a vector form. We are almost done. Now, we need to fix the PHI nodes
1295  // that we vectorized. The PHI nodes are currently empty because we did
1296  // not want to introduce cycles. Notice that the remaining PHI nodes
1297  // that we need to fix are reduction variables.
1298
1299  // Create the 'reduced' values for each of the induction vars.
1300  // The reduced values are the vector values that we scalarize and combine
1301  // after the loop is finished.
1302  for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1303       it != e; ++it) {
1304    PHINode *RdxPhi = *it;
1305    assert(RdxPhi && "Unable to recover vectorized PHI");
1306
1307    // Find the reduction variable descriptor.
1308    assert(Legal->getReductionVars()->count(RdxPhi) &&
1309           "Unable to find the reduction variable");
1310    LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1311    (*Legal->getReductionVars())[RdxPhi];
1312
1313    // We need to generate a reduction vector from the incoming scalar.
1314    // To do so, we need to generate the 'identity' vector and overide
1315    // one of the elements with the incoming scalar reduction. We need
1316    // to do it in the vector-loop preheader.
1317    Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
1318
1319    // This is the vector-clone of the value that leaves the loop.
1320    VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1321    Type *VecTy = VectorExit[0]->getType();
1322
1323    // Find the reduction identity variable. Zero for addition, or, xor,
1324    // one for multiplication, -1 for And.
1325    Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
1326                                          VecTy->getScalarType());
1327
1328    // This vector is the Identity vector where the first element is the
1329    // incoming scalar reduction.
1330    Value *VectorStart = Builder.CreateInsertElement(Identity,
1331                                                     RdxDesc.StartValue, Zero);
1332
1333    // Fix the vector-loop phi.
1334    // We created the induction variable so we know that the
1335    // preheader is the first entry.
1336    BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1337
1338    // Reductions do not have to start at zero. They can start with
1339    // any loop invariant values.
1340    VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1341    BasicBlock *Latch = OrigLoop->getLoopLatch();
1342    Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1343    VectorParts &Val = getVectorValue(LoopVal);
1344    for (unsigned part = 0; part < UF; ++part) {
1345      // Make sure to add the reduction stat value only to the
1346      // first unroll part.
1347      Value *StartVal = (part == 0) ? VectorStart : Identity;
1348      cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1349      cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1350    }
1351
1352    // Before each round, move the insertion point right between
1353    // the PHIs and the values we are going to write.
1354    // This allows us to write both PHINodes and the extractelement
1355    // instructions.
1356    Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1357
1358    VectorParts RdxParts;
1359    for (unsigned part = 0; part < UF; ++part) {
1360      // This PHINode contains the vectorized reduction variable, or
1361      // the initial value vector, if we bypass the vector loop.
1362      VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1363      PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1364      Value *StartVal = (part == 0) ? VectorStart : Identity;
1365      NewPhi->addIncoming(StartVal, LoopBypassBlock);
1366      NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1367      RdxParts.push_back(NewPhi);
1368    }
1369
1370    // Reduce all of the unrolled parts into a single vector.
1371    Value *ReducedPartRdx = RdxParts[0];
1372    for (unsigned part = 1; part < UF; ++part) {
1373      switch (RdxDesc.Kind) {
1374      case LoopVectorizationLegality::IntegerAdd:
1375        ReducedPartRdx =
1376          Builder.CreateAdd(RdxParts[part], ReducedPartRdx, "add.rdx");
1377        break;
1378      case LoopVectorizationLegality::IntegerMult:
1379        ReducedPartRdx =
1380          Builder.CreateMul(RdxParts[part], ReducedPartRdx, "mul.rdx");
1381        break;
1382      case LoopVectorizationLegality::IntegerOr:
1383        ReducedPartRdx =
1384          Builder.CreateOr(RdxParts[part], ReducedPartRdx, "or.rdx");
1385        break;
1386      case LoopVectorizationLegality::IntegerAnd:
1387        ReducedPartRdx =
1388          Builder.CreateAnd(RdxParts[part], ReducedPartRdx, "and.rdx");
1389        break;
1390      case LoopVectorizationLegality::IntegerXor:
1391        ReducedPartRdx =
1392          Builder.CreateXor(RdxParts[part], ReducedPartRdx, "xor.rdx");
1393        break;
1394      default:
1395        llvm_unreachable("Unknown reduction operation");
1396      }
1397    }
1398
1399
1400    // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1401    // and vector ops, reducing the set of values being computed by half each
1402    // round.
1403    assert(isPowerOf2_32(VF) &&
1404           "Reduction emission only supported for pow2 vectors!");
1405    Value *TmpVec = ReducedPartRdx;
1406    SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1407    for (unsigned i = VF; i != 1; i >>= 1) {
1408      // Move the upper half of the vector to the lower half.
1409      for (unsigned j = 0; j != i/2; ++j)
1410        ShuffleMask[j] = Builder.getInt32(i/2 + j);
1411
1412      // Fill the rest of the mask with undef.
1413      std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1414                UndefValue::get(Builder.getInt32Ty()));
1415
1416      Value *Shuf =
1417        Builder.CreateShuffleVector(TmpVec,
1418                                    UndefValue::get(TmpVec->getType()),
1419                                    ConstantVector::get(ShuffleMask),
1420                                    "rdx.shuf");
1421
1422      // Emit the operation on the shuffled value.
1423      switch (RdxDesc.Kind) {
1424      case LoopVectorizationLegality::IntegerAdd:
1425        TmpVec = Builder.CreateAdd(TmpVec, Shuf, "add.rdx");
1426        break;
1427      case LoopVectorizationLegality::IntegerMult:
1428        TmpVec = Builder.CreateMul(TmpVec, Shuf, "mul.rdx");
1429        break;
1430      case LoopVectorizationLegality::IntegerOr:
1431        TmpVec = Builder.CreateOr(TmpVec, Shuf, "or.rdx");
1432        break;
1433      case LoopVectorizationLegality::IntegerAnd:
1434        TmpVec = Builder.CreateAnd(TmpVec, Shuf, "and.rdx");
1435        break;
1436      case LoopVectorizationLegality::IntegerXor:
1437        TmpVec = Builder.CreateXor(TmpVec, Shuf, "xor.rdx");
1438        break;
1439      default:
1440        llvm_unreachable("Unknown reduction operation");
1441      }
1442    }
1443
1444    // The result is in the first element of the vector.
1445    Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1446
1447    // Now, we need to fix the users of the reduction variable
1448    // inside and outside of the scalar remainder loop.
1449    // We know that the loop is in LCSSA form. We need to update the
1450    // PHI nodes in the exit blocks.
1451    for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1452         LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1453      PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1454      if (!LCSSAPhi) continue;
1455
1456      // All PHINodes need to have a single entry edge, or two if
1457      // we already fixed them.
1458      assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1459
1460      // We found our reduction value exit-PHI. Update it with the
1461      // incoming bypass edge.
1462      if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1463        // Add an edge coming from the bypass.
1464        LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1465        break;
1466      }
1467    }// end of the LCSSA phi scan.
1468
1469    // Fix the scalar loop reduction variable with the incoming reduction sum
1470    // from the vector body and from the backedge value.
1471    int IncomingEdgeBlockIdx =
1472    (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1473    assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1474    // Pick the other block.
1475    int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1476    (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1477    (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1478  }// end of for each redux variable.
1479
1480  // The Loop exit block may have single value PHI nodes where the incoming
1481  // value is 'undef'. While vectorizing we only handled real values that
1482  // were defined inside the loop. Here we handle the 'undef case'.
1483  // See PR14725.
1484  for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1485       LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1486    PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1487    if (!LCSSAPhi) continue;
1488    if (LCSSAPhi->getNumIncomingValues() == 1)
1489      LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1490                            LoopMiddleBlock);
1491  }
1492}
1493
1494InnerLoopVectorizer::VectorParts
1495InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1496  assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1497         "Invalid edge");
1498
1499  VectorParts SrcMask = createBlockInMask(Src);
1500
1501  // The terminator has to be a branch inst!
1502  BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1503  assert(BI && "Unexpected terminator found");
1504
1505  if (BI->isConditional()) {
1506    VectorParts EdgeMask = getVectorValue(BI->getCondition());
1507
1508    if (BI->getSuccessor(0) != Dst)
1509      for (unsigned part = 0; part < UF; ++part)
1510        EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1511
1512    for (unsigned part = 0; part < UF; ++part)
1513      EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1514    return EdgeMask;
1515  }
1516
1517  return SrcMask;
1518}
1519
1520InnerLoopVectorizer::VectorParts
1521InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1522  assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1523
1524  // Loop incoming mask is all-one.
1525  if (OrigLoop->getHeader() == BB) {
1526    Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1527    return getVectorValue(C);
1528  }
1529
1530  // This is the block mask. We OR all incoming edges, and with zero.
1531  Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1532  VectorParts BlockMask = getVectorValue(Zero);
1533
1534  // For each pred:
1535  for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1536    VectorParts EM = createEdgeMask(*it, BB);
1537    for (unsigned part = 0; part < UF; ++part)
1538      BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1539  }
1540
1541  return BlockMask;
1542}
1543
1544void
1545InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1546                                          BasicBlock *BB, PhiVector *PV) {
1547  Constant *Zero = Builder.getInt32(0);
1548
1549  // For each instruction in the old loop.
1550  for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1551    VectorParts &Entry = WidenMap.get(it);
1552    switch (it->getOpcode()) {
1553    case Instruction::Br:
1554      // Nothing to do for PHIs and BR, since we already took care of the
1555      // loop control flow instructions.
1556      continue;
1557    case Instruction::PHI:{
1558      PHINode* P = cast<PHINode>(it);
1559      // Handle reduction variables:
1560      if (Legal->getReductionVars()->count(P)) {
1561        for (unsigned part = 0; part < UF; ++part) {
1562          // This is phase one of vectorizing PHIs.
1563          Type *VecTy = VectorType::get(it->getType(), VF);
1564          Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1565                                        LoopVectorBody-> getFirstInsertionPt());
1566        }
1567        PV->push_back(P);
1568        continue;
1569      }
1570
1571      // Check for PHI nodes that are lowered to vector selects.
1572      if (P->getParent() != OrigLoop->getHeader()) {
1573        // We know that all PHIs in non header blocks are converted into
1574        // selects, so we don't have to worry about the insertion order and we
1575        // can just use the builder.
1576
1577        // At this point we generate the predication tree. There may be
1578        // duplications since this is a simple recursive scan, but future
1579        // optimizations will clean it up.
1580        VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1581                                               P->getParent());
1582
1583        for (unsigned part = 0; part < UF; ++part) {
1584        VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1585        VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1586          Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1587                                             "predphi");
1588        }
1589        continue;
1590      }
1591
1592      // This PHINode must be an induction variable.
1593      // Make sure that we know about it.
1594      assert(Legal->getInductionVars()->count(P) &&
1595             "Not an induction variable");
1596
1597      LoopVectorizationLegality::InductionInfo II =
1598        Legal->getInductionVars()->lookup(P);
1599
1600      switch (II.IK) {
1601      case LoopVectorizationLegality::NoInduction:
1602        llvm_unreachable("Unknown induction");
1603      case LoopVectorizationLegality::IntInduction: {
1604        assert(P == OldInduction && "Unexpected PHI");
1605        Value *Broadcasted = getBroadcastInstrs(Induction);
1606        // After broadcasting the induction variable we need to make the
1607        // vector consecutive by adding 0, 1, 2 ...
1608        for (unsigned part = 0; part < UF; ++part)
1609          Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1610        continue;
1611      }
1612      case LoopVectorizationLegality::ReverseIntInduction:
1613      case LoopVectorizationLegality::PtrInduction:
1614        // Handle reverse integer and pointer inductions.
1615        Value *StartIdx = 0;
1616        // If we have a single integer induction variable then use it.
1617        // Otherwise, start counting at zero.
1618        if (OldInduction) {
1619          LoopVectorizationLegality::InductionInfo OldII =
1620            Legal->getInductionVars()->lookup(OldInduction);
1621          StartIdx = OldII.StartValue;
1622        } else {
1623          StartIdx = ConstantInt::get(Induction->getType(), 0);
1624        }
1625        // This is the normalized GEP that starts counting at zero.
1626        Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1627                                                 "normalized.idx");
1628
1629        // Handle the reverse integer induction variable case.
1630        if (LoopVectorizationLegality::ReverseIntInduction == II.IK) {
1631          IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1632          Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1633                                                 "resize.norm.idx");
1634          Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
1635                                                 "reverse.idx");
1636
1637          // This is a new value so do not hoist it out.
1638          Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1639          // After broadcasting the induction variable we need to make the
1640          // vector consecutive by adding  ... -3, -2, -1, 0.
1641          for (unsigned part = 0; part < UF; ++part)
1642            Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1643          continue;
1644        }
1645
1646        // Handle the pointer induction variable case.
1647        assert(P->getType()->isPointerTy() && "Unexpected type.");
1648
1649        // This is the vector of results. Notice that we don't generate
1650        // vector geps because scalar geps result in better code.
1651        for (unsigned part = 0; part < UF; ++part) {
1652          Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1653          for (unsigned int i = 0; i < VF; ++i) {
1654            Constant *Idx = ConstantInt::get(Induction->getType(),
1655                                             i + part * VF);
1656            Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1657                                                 "gep.idx");
1658            Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1659                                               "next.gep");
1660            VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1661                                                 Builder.getInt32(i),
1662                                                 "insert.gep");
1663          }
1664          Entry[part] = VecVal;
1665        }
1666        continue;
1667      }
1668
1669    }// End of PHI.
1670
1671    case Instruction::Add:
1672    case Instruction::FAdd:
1673    case Instruction::Sub:
1674    case Instruction::FSub:
1675    case Instruction::Mul:
1676    case Instruction::FMul:
1677    case Instruction::UDiv:
1678    case Instruction::SDiv:
1679    case Instruction::FDiv:
1680    case Instruction::URem:
1681    case Instruction::SRem:
1682    case Instruction::FRem:
1683    case Instruction::Shl:
1684    case Instruction::LShr:
1685    case Instruction::AShr:
1686    case Instruction::And:
1687    case Instruction::Or:
1688    case Instruction::Xor: {
1689      // Just widen binops.
1690      BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1691      VectorParts &A = getVectorValue(it->getOperand(0));
1692      VectorParts &B = getVectorValue(it->getOperand(1));
1693
1694      // Use this vector value for all users of the original instruction.
1695      for (unsigned Part = 0; Part < UF; ++Part) {
1696        Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1697
1698        // Update the NSW, NUW and Exact flags.
1699        BinaryOperator *VecOp = cast<BinaryOperator>(V);
1700        if (isa<OverflowingBinaryOperator>(BinOp)) {
1701          VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1702          VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1703        }
1704        if (isa<PossiblyExactOperator>(VecOp))
1705          VecOp->setIsExact(BinOp->isExact());
1706
1707        Entry[Part] = V;
1708      }
1709      break;
1710    }
1711    case Instruction::Select: {
1712      // Widen selects.
1713      // If the selector is loop invariant we can create a select
1714      // instruction with a scalar condition. Otherwise, use vector-select.
1715      bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1716                                               OrigLoop);
1717
1718      // The condition can be loop invariant  but still defined inside the
1719      // loop. This means that we can't just use the original 'cond' value.
1720      // We have to take the 'vectorized' value and pick the first lane.
1721      // Instcombine will make this a no-op.
1722      VectorParts &Cond = getVectorValue(it->getOperand(0));
1723      VectorParts &Op0  = getVectorValue(it->getOperand(1));
1724      VectorParts &Op1  = getVectorValue(it->getOperand(2));
1725      Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1726                                                       Builder.getInt32(0));
1727      for (unsigned Part = 0; Part < UF; ++Part) {
1728        Entry[Part] = Builder.CreateSelect(
1729          InvariantCond ? ScalarCond : Cond[Part],
1730          Op0[Part],
1731          Op1[Part]);
1732      }
1733      break;
1734    }
1735
1736    case Instruction::ICmp:
1737    case Instruction::FCmp: {
1738      // Widen compares. Generate vector compares.
1739      bool FCmp = (it->getOpcode() == Instruction::FCmp);
1740      CmpInst *Cmp = dyn_cast<CmpInst>(it);
1741      VectorParts &A = getVectorValue(it->getOperand(0));
1742      VectorParts &B = getVectorValue(it->getOperand(1));
1743      for (unsigned Part = 0; Part < UF; ++Part) {
1744        Value *C = 0;
1745        if (FCmp)
1746          C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1747        else
1748          C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1749        Entry[Part] = C;
1750      }
1751      break;
1752    }
1753
1754    case Instruction::Store: {
1755      // Attempt to issue a wide store.
1756      StoreInst *SI = dyn_cast<StoreInst>(it);
1757      Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1758      Value *Ptr = SI->getPointerOperand();
1759      unsigned Alignment = SI->getAlignment();
1760
1761      assert(!Legal->isUniform(Ptr) &&
1762             "We do not allow storing to uniform addresses");
1763
1764
1765      int Stride = Legal->isConsecutivePtr(Ptr);
1766      bool Reverse = Stride < 0;
1767      if (Stride == 0) {
1768        scalarizeInstruction(it);
1769        break;
1770      }
1771
1772      // Handle consecutive stores.
1773
1774      GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1775      if (Gep) {
1776        // The last index does not have to be the induction. It can be
1777        // consecutive and be a function of the index. For example A[I+1];
1778        unsigned NumOperands = Gep->getNumOperands();
1779
1780        Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1781        VectorParts &GEPParts = getVectorValue(LastGepOperand);
1782        Value *LastIndex = GEPParts[0];
1783        LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1784
1785        // Create the new GEP with the new induction variable.
1786        GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1787        Gep2->setOperand(NumOperands - 1, LastIndex);
1788        Ptr = Builder.Insert(Gep2);
1789      } else {
1790        // Use the induction element ptr.
1791        assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1792        VectorParts &PtrVal = getVectorValue(Ptr);
1793        Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1794      }
1795
1796      VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1797      for (unsigned Part = 0; Part < UF; ++Part) {
1798        // Calculate the pointer for the specific unroll-part.
1799        Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1800
1801        if (Reverse) {
1802          // If we store to reverse consecutive memory locations then we need
1803          // to reverse the order of elements in the stored value.
1804          StoredVal[Part] = reverseVector(StoredVal[Part]);
1805          // If the address is consecutive but reversed, then the
1806          // wide store needs to start at the last vector element.
1807          PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1808          PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1809        }
1810
1811        Value *VecPtr = Builder.CreateBitCast(PartPtr, StTy->getPointerTo());
1812        Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1813      }
1814      break;
1815    }
1816    case Instruction::Load: {
1817      // Attempt to issue a wide load.
1818      LoadInst *LI = dyn_cast<LoadInst>(it);
1819      Type *RetTy = VectorType::get(LI->getType(), VF);
1820      Value *Ptr = LI->getPointerOperand();
1821      unsigned Alignment = LI->getAlignment();
1822
1823      // If the pointer is loop invariant or if it is non consecutive,
1824      // scalarize the load.
1825      int Stride = Legal->isConsecutivePtr(Ptr);
1826      bool Reverse = Stride < 0;
1827      if (Legal->isUniform(Ptr) || Stride == 0) {
1828        scalarizeInstruction(it);
1829        break;
1830      }
1831
1832      GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1833      if (Gep) {
1834        // The last index does not have to be the induction. It can be
1835        // consecutive and be a function of the index. For example A[I+1];
1836        unsigned NumOperands = Gep->getNumOperands();
1837
1838        Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1839        VectorParts &GEPParts = getVectorValue(LastGepOperand);
1840        Value *LastIndex = GEPParts[0];
1841        LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1842
1843        // Create the new GEP with the new induction variable.
1844        GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1845        Gep2->setOperand(NumOperands - 1, LastIndex);
1846        Ptr = Builder.Insert(Gep2);
1847      } else {
1848        // Use the induction element ptr.
1849        assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1850        VectorParts &PtrVal = getVectorValue(Ptr);
1851        Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1852      }
1853
1854      for (unsigned Part = 0; Part < UF; ++Part) {
1855        // Calculate the pointer for the specific unroll-part.
1856        Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1857
1858        if (Reverse) {
1859          // If the address is consecutive but reversed, then the
1860          // wide store needs to start at the last vector element.
1861          PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1862          PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1863        }
1864
1865        Value *VecPtr = Builder.CreateBitCast(PartPtr, RetTy->getPointerTo());
1866        Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1867        cast<LoadInst>(LI)->setAlignment(Alignment);
1868        Entry[Part] = Reverse ? reverseVector(LI) :  LI;
1869      }
1870      break;
1871    }
1872    case Instruction::ZExt:
1873    case Instruction::SExt:
1874    case Instruction::FPToUI:
1875    case Instruction::FPToSI:
1876    case Instruction::FPExt:
1877    case Instruction::PtrToInt:
1878    case Instruction::IntToPtr:
1879    case Instruction::SIToFP:
1880    case Instruction::UIToFP:
1881    case Instruction::Trunc:
1882    case Instruction::FPTrunc:
1883    case Instruction::BitCast: {
1884      CastInst *CI = dyn_cast<CastInst>(it);
1885      /// Optimize the special case where the source is the induction
1886      /// variable. Notice that we can only optimize the 'trunc' case
1887      /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1888      /// c. other casts depend on pointer size.
1889      if (CI->getOperand(0) == OldInduction &&
1890          it->getOpcode() == Instruction::Trunc) {
1891        Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1892                                               CI->getType());
1893        Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1894        for (unsigned Part = 0; Part < UF; ++Part)
1895          Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1896        break;
1897      }
1898      /// Vectorize casts.
1899      Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1900
1901      VectorParts &A = getVectorValue(it->getOperand(0));
1902      for (unsigned Part = 0; Part < UF; ++Part)
1903        Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1904      break;
1905    }
1906
1907    case Instruction::Call: {
1908      assert(isTriviallyVectorizableIntrinsic(it));
1909      Module *M = BB->getParent()->getParent();
1910      IntrinsicInst *II = cast<IntrinsicInst>(it);
1911      Intrinsic::ID ID = II->getIntrinsicID();
1912      for (unsigned Part = 0; Part < UF; ++Part) {
1913        SmallVector<Value*, 4> Args;
1914        for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
1915          VectorParts &Arg = getVectorValue(II->getArgOperand(i));
1916          Args.push_back(Arg[Part]);
1917        }
1918        Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1919        Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1920        Entry[Part] = Builder.CreateCall(F, Args);
1921      }
1922      break;
1923    }
1924
1925    default:
1926      // All other instructions are unsupported. Scalarize them.
1927      scalarizeInstruction(it);
1928      break;
1929    }// end of switch.
1930  }// end of for_each instr.
1931}
1932
1933void InnerLoopVectorizer::updateAnalysis() {
1934  // Forget the original basic block.
1935  SE->forgetLoop(OrigLoop);
1936
1937  // Update the dominator tree information.
1938  assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1939         "Entry does not dominate exit.");
1940
1941  DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1942  DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1943  DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1944  DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1945  DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1946  DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1947
1948  DEBUG(DT->verifyAnalysis());
1949}
1950
1951bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1952  if (!EnableIfConversion)
1953    return false;
1954
1955  assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1956  std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1957
1958  // Collect the blocks that need predication.
1959  for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1960    BasicBlock *BB = LoopBlocks[i];
1961
1962    // We don't support switch statements inside loops.
1963    if (!isa<BranchInst>(BB->getTerminator()))
1964      return false;
1965
1966    // We must have at most two predecessors because we need to convert
1967    // all PHIs to selects.
1968    unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1969    if (Preds > 2)
1970      return false;
1971
1972    // We must be able to predicate all blocks that need to be predicated.
1973    if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1974      return false;
1975  }
1976
1977  // We can if-convert this loop.
1978  return true;
1979}
1980
1981bool LoopVectorizationLegality::canVectorize() {
1982  assert(TheLoop->getLoopPreheader() && "No preheader!!");
1983
1984  // We can only vectorize innermost loops.
1985  if (TheLoop->getSubLoopsVector().size())
1986    return false;
1987
1988  // We must have a single backedge.
1989  if (TheLoop->getNumBackEdges() != 1)
1990    return false;
1991
1992  // We must have a single exiting block.
1993  if (!TheLoop->getExitingBlock())
1994    return false;
1995
1996  unsigned NumBlocks = TheLoop->getNumBlocks();
1997
1998  // Check if we can if-convert non single-bb loops.
1999  if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2000    DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2001    return false;
2002  }
2003
2004  // We need to have a loop header.
2005  BasicBlock *Latch = TheLoop->getLoopLatch();
2006  DEBUG(dbgs() << "LV: Found a loop: " <<
2007        TheLoop->getHeader()->getName() << "\n");
2008
2009  // ScalarEvolution needs to be able to find the exit count.
2010  const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2011  if (ExitCount == SE->getCouldNotCompute()) {
2012    DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2013    return false;
2014  }
2015
2016  // Do not loop-vectorize loops with a tiny trip count.
2017  unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2018  if (TC > 0u && TC < TinyTripCountThreshold) {
2019    DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2020          "This loop is not worth vectorizing.\n");
2021    return false;
2022  }
2023
2024  // Check if we can vectorize the instructions and CFG in this loop.
2025  if (!canVectorizeInstrs()) {
2026    DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2027    return false;
2028  }
2029
2030  // Go over each instruction and look at memory deps.
2031  if (!canVectorizeMemory()) {
2032    DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2033    return false;
2034  }
2035
2036  // Collect all of the variables that remain uniform after vectorization.
2037  collectLoopUniforms();
2038
2039  DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2040        (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2041        <<"!\n");
2042
2043  // Okay! We can vectorize. At this point we don't have any other mem analysis
2044  // which may limit our maximum vectorization factor, so just return true with
2045  // no restrictions.
2046  return true;
2047}
2048
2049bool LoopVectorizationLegality::canVectorizeInstrs() {
2050  BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2051  BasicBlock *Header = TheLoop->getHeader();
2052
2053  // For each block in the loop.
2054  for (Loop::block_iterator bb = TheLoop->block_begin(),
2055       be = TheLoop->block_end(); bb != be; ++bb) {
2056
2057    // Scan the instructions in the block and look for hazards.
2058    for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2059         ++it) {
2060
2061      if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2062        // This should not happen because the loop should be normalized.
2063        if (Phi->getNumIncomingValues() != 2) {
2064          DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2065          return false;
2066        }
2067
2068        // Check that this PHI type is allowed.
2069        if (!Phi->getType()->isIntegerTy() &&
2070            !Phi->getType()->isPointerTy()) {
2071          DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2072          return false;
2073        }
2074
2075        // If this PHINode is not in the header block, then we know that we
2076        // can convert it to select during if-conversion. No need to check if
2077        // the PHIs in this block are induction or reduction variables.
2078        if (*bb != Header)
2079          continue;
2080
2081        // This is the value coming from the preheader.
2082        Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2083        // Check if this is an induction variable.
2084        InductionKind IK = isInductionVariable(Phi);
2085
2086        if (NoInduction != IK) {
2087          // Int inductions are special because we only allow one IV.
2088          if (IK == IntInduction) {
2089            if (Induction) {
2090              DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2091              return false;
2092            }
2093            Induction = Phi;
2094          }
2095
2096          DEBUG(dbgs() << "LV: Found an induction variable.\n");
2097          Inductions[Phi] = InductionInfo(StartValue, IK);
2098          continue;
2099        }
2100
2101        if (AddReductionVar(Phi, IntegerAdd)) {
2102          DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2103          continue;
2104        }
2105        if (AddReductionVar(Phi, IntegerMult)) {
2106          DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2107          continue;
2108        }
2109        if (AddReductionVar(Phi, IntegerOr)) {
2110          DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2111          continue;
2112        }
2113        if (AddReductionVar(Phi, IntegerAnd)) {
2114          DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2115          continue;
2116        }
2117        if (AddReductionVar(Phi, IntegerXor)) {
2118          DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2119          continue;
2120        }
2121
2122        DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2123        return false;
2124      }// end of PHI handling
2125
2126      // We still don't handle functions.
2127      CallInst *CI = dyn_cast<CallInst>(it);
2128      if (CI && !isTriviallyVectorizableIntrinsic(it)) {
2129        DEBUG(dbgs() << "LV: Found a call site.\n");
2130        return false;
2131      }
2132
2133      // Check that the instruction return type is vectorizable.
2134      if (!VectorType::isValidElementType(it->getType()) &&
2135          !it->getType()->isVoidTy()) {
2136        DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2137        return false;
2138      }
2139
2140      // Check that the stored type is vectorizable.
2141      if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2142        Type *T = ST->getValueOperand()->getType();
2143        if (!VectorType::isValidElementType(T))
2144          return false;
2145      }
2146
2147      // Reduction instructions are allowed to have exit users.
2148      // All other instructions must not have external users.
2149      if (!AllowedExit.count(it))
2150        //Check that all of the users of the loop are inside the BB.
2151        for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2152             I != E; ++I) {
2153          Instruction *U = cast<Instruction>(*I);
2154          // This user may be a reduction exit value.
2155          if (!TheLoop->contains(U)) {
2156            DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2157            return false;
2158          }
2159        }
2160    } // next instr.
2161
2162  }
2163
2164  if (!Induction) {
2165    DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2166    assert(getInductionVars()->size() && "No induction variables");
2167  }
2168
2169  return true;
2170}
2171
2172void LoopVectorizationLegality::collectLoopUniforms() {
2173  // We now know that the loop is vectorizable!
2174  // Collect variables that will remain uniform after vectorization.
2175  std::vector<Value*> Worklist;
2176  BasicBlock *Latch = TheLoop->getLoopLatch();
2177
2178  // Start with the conditional branch and walk up the block.
2179  Worklist.push_back(Latch->getTerminator()->getOperand(0));
2180
2181  while (Worklist.size()) {
2182    Instruction *I = dyn_cast<Instruction>(Worklist.back());
2183    Worklist.pop_back();
2184
2185    // Look at instructions inside this loop.
2186    // Stop when reaching PHI nodes.
2187    // TODO: we need to follow values all over the loop, not only in this block.
2188    if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2189      continue;
2190
2191    // This is a known uniform.
2192    Uniforms.insert(I);
2193
2194    // Insert all operands.
2195    for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2196      Worklist.push_back(I->getOperand(i));
2197    }
2198  }
2199}
2200
2201bool LoopVectorizationLegality::canVectorizeMemory() {
2202  typedef SmallVector<Value*, 16> ValueVector;
2203  typedef SmallPtrSet<Value*, 16> ValueSet;
2204  // Holds the Load and Store *instructions*.
2205  ValueVector Loads;
2206  ValueVector Stores;
2207  PtrRtCheck.Pointers.clear();
2208  PtrRtCheck.Need = false;
2209
2210  // For each block.
2211  for (Loop::block_iterator bb = TheLoop->block_begin(),
2212       be = TheLoop->block_end(); bb != be; ++bb) {
2213
2214    // Scan the BB and collect legal loads and stores.
2215    for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2216         ++it) {
2217
2218      // If this is a load, save it. If this instruction can read from memory
2219      // but is not a load, then we quit. Notice that we don't handle function
2220      // calls that read or write.
2221      if (it->mayReadFromMemory()) {
2222        LoadInst *Ld = dyn_cast<LoadInst>(it);
2223        if (!Ld) return false;
2224        if (!Ld->isSimple()) {
2225          DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2226          return false;
2227        }
2228        Loads.push_back(Ld);
2229        continue;
2230      }
2231
2232      // Save 'store' instructions. Abort if other instructions write to memory.
2233      if (it->mayWriteToMemory()) {
2234        StoreInst *St = dyn_cast<StoreInst>(it);
2235        if (!St) return false;
2236        if (!St->isSimple()) {
2237          DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2238          return false;
2239        }
2240        Stores.push_back(St);
2241      }
2242    } // next instr.
2243  } // next block.
2244
2245  // Now we have two lists that hold the loads and the stores.
2246  // Next, we find the pointers that they use.
2247
2248  // Check if we see any stores. If there are no stores, then we don't
2249  // care if the pointers are *restrict*.
2250  if (!Stores.size()) {
2251    DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2252    return true;
2253  }
2254
2255  // Holds the read and read-write *pointers* that we find.
2256  ValueVector Reads;
2257  ValueVector ReadWrites;
2258
2259  // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2260  // multiple times on the same object. If the ptr is accessed twice, once
2261  // for read and once for write, it will only appear once (on the write
2262  // list). This is okay, since we are going to check for conflicts between
2263  // writes and between reads and writes, but not between reads and reads.
2264  ValueSet Seen;
2265
2266  ValueVector::iterator I, IE;
2267  for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2268    StoreInst *ST = cast<StoreInst>(*I);
2269    Value* Ptr = ST->getPointerOperand();
2270
2271    if (isUniform(Ptr)) {
2272      DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2273      return false;
2274    }
2275
2276    // If we did *not* see this pointer before, insert it to
2277    // the read-write list. At this phase it is only a 'write' list.
2278    if (Seen.insert(Ptr))
2279      ReadWrites.push_back(Ptr);
2280  }
2281
2282  for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2283    LoadInst *LD = cast<LoadInst>(*I);
2284    Value* Ptr = LD->getPointerOperand();
2285    // If we did *not* see this pointer before, insert it to the
2286    // read list. If we *did* see it before, then it is already in
2287    // the read-write list. This allows us to vectorize expressions
2288    // such as A[i] += x;  Because the address of A[i] is a read-write
2289    // pointer. This only works if the index of A[i] is consecutive.
2290    // If the address of i is unknown (for example A[B[i]]) then we may
2291    // read a few words, modify, and write a few words, and some of the
2292    // words may be written to the same address.
2293    if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2294      Reads.push_back(Ptr);
2295  }
2296
2297  // If we write (or read-write) to a single destination and there are no
2298  // other reads in this loop then is it safe to vectorize.
2299  if (ReadWrites.size() == 1 && Reads.size() == 0) {
2300    DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2301    return true;
2302  }
2303
2304  // Find pointers with computable bounds. We are going to use this information
2305  // to place a runtime bound check.
2306  bool CanDoRT = true;
2307  for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
2308    if (hasComputableBounds(*I)) {
2309      PtrRtCheck.insert(SE, TheLoop, *I);
2310      DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2311    } else {
2312      CanDoRT = false;
2313      break;
2314    }
2315  for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
2316    if (hasComputableBounds(*I)) {
2317      PtrRtCheck.insert(SE, TheLoop, *I);
2318      DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2319    } else {
2320      CanDoRT = false;
2321      break;
2322    }
2323
2324  // Check that we did not collect too many pointers or found a
2325  // unsizeable pointer.
2326  if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2327    PtrRtCheck.reset();
2328    CanDoRT = false;
2329  }
2330
2331  if (CanDoRT) {
2332    DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2333  }
2334
2335  bool NeedRTCheck = false;
2336
2337  // Now that the pointers are in two lists (Reads and ReadWrites), we
2338  // can check that there are no conflicts between each of the writes and
2339  // between the writes to the reads.
2340  ValueSet WriteObjects;
2341  ValueVector TempObjects;
2342
2343  // Check that the read-writes do not conflict with other read-write
2344  // pointers.
2345  bool AllWritesIdentified = true;
2346  for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
2347    GetUnderlyingObjects(*I, TempObjects, DL);
2348    for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2349         it != e; ++it) {
2350      if (!isIdentifiedObject(*it)) {
2351        DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
2352        NeedRTCheck = true;
2353        AllWritesIdentified = false;
2354      }
2355      if (!WriteObjects.insert(*it)) {
2356        DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2357              << **it <<"\n");
2358        return false;
2359      }
2360    }
2361    TempObjects.clear();
2362  }
2363
2364  /// Check that the reads don't conflict with the read-writes.
2365  for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
2366    GetUnderlyingObjects(*I, TempObjects, DL);
2367    for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2368         it != e; ++it) {
2369      // If all of the writes are identified then we don't care if the read
2370      // pointer is identified or not.
2371      if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
2372        DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
2373        NeedRTCheck = true;
2374      }
2375      if (WriteObjects.count(*it)) {
2376        DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
2377              << **it <<"\n");
2378        return false;
2379      }
2380    }
2381    TempObjects.clear();
2382  }
2383
2384  PtrRtCheck.Need = NeedRTCheck;
2385  if (NeedRTCheck && !CanDoRT) {
2386    DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2387          "the array bounds.\n");
2388    PtrRtCheck.reset();
2389    return false;
2390  }
2391
2392  DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2393        " need a runtime memory check.\n");
2394  return true;
2395}
2396
2397bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2398                                                ReductionKind Kind) {
2399  if (Phi->getNumIncomingValues() != 2)
2400    return false;
2401
2402  // Reduction variables are only found in the loop header block.
2403  if (Phi->getParent() != TheLoop->getHeader())
2404    return false;
2405
2406  // Obtain the reduction start value from the value that comes from the loop
2407  // preheader.
2408  Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2409
2410  // ExitInstruction is the single value which is used outside the loop.
2411  // We only allow for a single reduction value to be used outside the loop.
2412  // This includes users of the reduction, variables (which form a cycle
2413  // which ends in the phi node).
2414  Instruction *ExitInstruction = 0;
2415
2416  // Iter is our iterator. We start with the PHI node and scan for all of the
2417  // users of this instruction. All users must be instructions that can be
2418  // used as reduction variables (such as ADD). We may have a single
2419  // out-of-block user. The cycle must end with the original PHI.
2420  Instruction *Iter = Phi;
2421  while (true) {
2422    // If the instruction has no users then this is a broken
2423    // chain and can't be a reduction variable.
2424    if (Iter->use_empty())
2425      return false;
2426
2427    // Did we find a user inside this loop already ?
2428    bool FoundInBlockUser = false;
2429    // Did we reach the initial PHI node already ?
2430    bool FoundStartPHI = false;
2431
2432    // For each of the *users* of iter.
2433    for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2434         it != e; ++it) {
2435      Instruction *U = cast<Instruction>(*it);
2436      // We already know that the PHI is a user.
2437      if (U == Phi) {
2438        FoundStartPHI = true;
2439        continue;
2440      }
2441
2442      // Check if we found the exit user.
2443      BasicBlock *Parent = U->getParent();
2444      if (!TheLoop->contains(Parent)) {
2445        // Exit if you find multiple outside users.
2446        if (ExitInstruction != 0)
2447          return false;
2448        ExitInstruction = Iter;
2449      }
2450
2451      // We allow in-loop PHINodes which are not the original reduction PHI
2452      // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2453      // structure) then don't skip this PHI.
2454      if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2455          U->getParent() != TheLoop->getHeader() &&
2456          TheLoop->contains(U) &&
2457          Iter->getNumUses() > 1)
2458        continue;
2459
2460      // We can't have multiple inside users.
2461      if (FoundInBlockUser)
2462        return false;
2463      FoundInBlockUser = true;
2464
2465      // Any reduction instr must be of one of the allowed kinds.
2466      if (!isReductionInstr(U, Kind))
2467        return false;
2468
2469      // Reductions of instructions such as Div, and Sub is only
2470      // possible if the LHS is the reduction variable.
2471      if (!U->isCommutative() && U->getOperand(0) != Iter)
2472        return false;
2473
2474      Iter = U;
2475    }
2476
2477    // We found a reduction var if we have reached the original
2478    // phi node and we only have a single instruction with out-of-loop
2479    // users.
2480    if (FoundStartPHI && ExitInstruction) {
2481      // This instruction is allowed to have out-of-loop users.
2482      AllowedExit.insert(ExitInstruction);
2483
2484      // Save the description of this reduction variable.
2485      ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2486      Reductions[Phi] = RD;
2487      return true;
2488    }
2489
2490    // If we've reached the start PHI but did not find an outside user then
2491    // this is dead code. Abort.
2492    if (FoundStartPHI)
2493      return false;
2494  }
2495}
2496
2497bool
2498LoopVectorizationLegality::isReductionInstr(Instruction *I,
2499                                            ReductionKind Kind) {
2500  switch (I->getOpcode()) {
2501  default:
2502    return false;
2503  case Instruction::PHI:
2504    // possibly.
2505    return true;
2506  case Instruction::Sub:
2507  case Instruction::Add:
2508    return Kind == IntegerAdd;
2509  case Instruction::SDiv:
2510  case Instruction::UDiv:
2511  case Instruction::Mul:
2512    return Kind == IntegerMult;
2513  case Instruction::And:
2514    return Kind == IntegerAnd;
2515  case Instruction::Or:
2516    return Kind == IntegerOr;
2517  case Instruction::Xor:
2518    return Kind == IntegerXor;
2519  }
2520}
2521
2522LoopVectorizationLegality::InductionKind
2523LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2524  Type *PhiTy = Phi->getType();
2525  // We only handle integer and pointer inductions variables.
2526  if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2527    return NoInduction;
2528
2529  // Check that the PHI is consecutive and starts at zero.
2530  const SCEV *PhiScev = SE->getSCEV(Phi);
2531  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2532  if (!AR) {
2533    DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2534    return NoInduction;
2535  }
2536  const SCEV *Step = AR->getStepRecurrence(*SE);
2537
2538  // Integer inductions need to have a stride of one.
2539  if (PhiTy->isIntegerTy()) {
2540    if (Step->isOne())
2541      return IntInduction;
2542    if (Step->isAllOnesValue())
2543      return ReverseIntInduction;
2544    return NoInduction;
2545  }
2546
2547  // Calculate the pointer stride and check if it is consecutive.
2548  const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2549  if (!C)
2550    return NoInduction;
2551
2552  assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2553  uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2554  if (C->getValue()->equalsInt(Size))
2555    return PtrInduction;
2556
2557  return NoInduction;
2558}
2559
2560bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2561  Value *In0 = const_cast<Value*>(V);
2562  PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2563  if (!PN)
2564    return false;
2565
2566  return Inductions.count(PN);
2567}
2568
2569bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
2570  assert(TheLoop->contains(BB) && "Unknown block used");
2571
2572  // Blocks that do not dominate the latch need predication.
2573  BasicBlock* Latch = TheLoop->getLoopLatch();
2574  return !DT->dominates(BB, Latch);
2575}
2576
2577bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2578  for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2579    // We don't predicate loads/stores at the moment.
2580    if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2581      return false;
2582
2583    // The instructions below can trap.
2584    switch (it->getOpcode()) {
2585    default: continue;
2586    case Instruction::UDiv:
2587    case Instruction::SDiv:
2588    case Instruction::URem:
2589    case Instruction::SRem:
2590             return false;
2591    }
2592  }
2593
2594  return true;
2595}
2596
2597bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2598  const SCEV *PhiScev = SE->getSCEV(Ptr);
2599  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2600  if (!AR)
2601    return false;
2602
2603  return AR->isAffine();
2604}
2605
2606unsigned
2607LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2608                                                      unsigned UserVF) {
2609  if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2610    DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2611    return 1;
2612  }
2613
2614  // Find the trip count.
2615  unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2616  DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2617
2618  unsigned VF = MaxVectorSize;
2619
2620  // If we optimize the program for size, avoid creating the tail loop.
2621  if (OptForSize) {
2622    // If we are unable to calculate the trip count then don't try to vectorize.
2623    if (TC < 2) {
2624      DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2625      return 1;
2626    }
2627
2628    // Find the maximum SIMD width that can fit within the trip count.
2629    VF = TC % MaxVectorSize;
2630
2631    if (VF == 0)
2632      VF = MaxVectorSize;
2633
2634    // If the trip count that we found modulo the vectorization factor is not
2635    // zero then we require a tail.
2636    if (VF < 2) {
2637      DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2638      return 1;
2639    }
2640  }
2641
2642  if (UserVF != 0) {
2643    assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2644    DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2645
2646    return UserVF;
2647  }
2648
2649  if (!TTI) {
2650    DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
2651    return 1;
2652  }
2653
2654  float Cost = expectedCost(1);
2655  unsigned Width = 1;
2656  DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2657  for (unsigned i=2; i <= VF; i*=2) {
2658    // Notice that the vector loop needs to be executed less times, so
2659    // we need to divide the cost of the vector loops by the width of
2660    // the vector elements.
2661    float VectorCost = expectedCost(i) / (float)i;
2662    DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2663          (int)VectorCost << ".\n");
2664    if (VectorCost < Cost) {
2665      Cost = VectorCost;
2666      Width = i;
2667    }
2668  }
2669
2670  DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2671  return Width;
2672}
2673
2674unsigned
2675LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2676                                               unsigned UserUF) {
2677  // Use the user preference, unless 'auto' is selected.
2678  if (UserUF != 0)
2679    return UserUF;
2680
2681  // When we optimize for size we don't unroll.
2682  if (OptForSize)
2683    return 1;
2684
2685  unsigned TargetVectorRegisters = TTI->getNumberOfRegisters(true);
2686  DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
2687        " vector registers\n");
2688
2689  LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
2690  // We divide by these constants so assume that we have at least one
2691  // instruction that uses at least one register.
2692  R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
2693  R.NumInstructions = std::max(R.NumInstructions, 1U);
2694
2695  // We calculate the unroll factor using the following formula.
2696  // Subtract the number of loop invariants from the number of available
2697  // registers. These registers are used by all of the unrolled instances.
2698  // Next, divide the remaining registers by the number of registers that is
2699  // required by the loop, in order to estimate how many parallel instances
2700  // fit without causing spills.
2701  unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
2702
2703  // We don't want to unroll the loops to the point where they do not fit into
2704  // the decoded cache. Assume that we only allow 32 IR instructions.
2705  UF = std::min(UF, (32 / R.NumInstructions));
2706
2707  // Clamp the unroll factor ranges to reasonable factors.
2708  if (UF > MaxUnrollSize)
2709    UF = MaxUnrollSize;
2710  else if (UF < 1)
2711    UF = 1;
2712
2713  return UF;
2714}
2715
2716LoopVectorizationCostModel::RegisterUsage
2717LoopVectorizationCostModel::calculateRegisterUsage() {
2718  // This function calculates the register usage by measuring the highest number
2719  // of values that are alive at a single location. Obviously, this is a very
2720  // rough estimation. We scan the loop in a topological order in order and
2721  // assign a number to each instruction. We use RPO to ensure that defs are
2722  // met before their users. We assume that each instruction that has in-loop
2723  // users starts an interval. We record every time that an in-loop value is
2724  // used, so we have a list of the first and last occurrences of each
2725  // instruction. Next, we transpose this data structure into a multi map that
2726  // holds the list of intervals that *end* at a specific location. This multi
2727  // map allows us to perform a linear search. We scan the instructions linearly
2728  // and record each time that a new interval starts, by placing it in a set.
2729  // If we find this value in the multi-map then we remove it from the set.
2730  // The max register usage is the maximum size of the set.
2731  // We also search for instructions that are defined outside the loop, but are
2732  // used inside the loop. We need this number separately from the max-interval
2733  // usage number because when we unroll, loop-invariant values do not take
2734  // more register.
2735  LoopBlocksDFS DFS(TheLoop);
2736  DFS.perform(LI);
2737
2738  RegisterUsage R;
2739  R.NumInstructions = 0;
2740
2741  // Each 'key' in the map opens a new interval. The values
2742  // of the map are the index of the 'last seen' usage of the
2743  // instruction that is the key.
2744  typedef DenseMap<Instruction*, unsigned> IntervalMap;
2745  // Maps instruction to its index.
2746  DenseMap<unsigned, Instruction*> IdxToInstr;
2747  // Marks the end of each interval.
2748  IntervalMap EndPoint;
2749  // Saves the list of instruction indices that are used in the loop.
2750  SmallSet<Instruction*, 8> Ends;
2751  // Saves the list of values that are used in the loop but are
2752  // defined outside the loop, such as arguments and constants.
2753  SmallPtrSet<Value*, 8> LoopInvariants;
2754
2755  unsigned Index = 0;
2756  for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2757       be = DFS.endRPO(); bb != be; ++bb) {
2758    R.NumInstructions += (*bb)->size();
2759    for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2760         ++it) {
2761      Instruction *I = it;
2762      IdxToInstr[Index++] = I;
2763
2764      // Save the end location of each USE.
2765      for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2766        Value *U = I->getOperand(i);
2767        Instruction *Instr = dyn_cast<Instruction>(U);
2768
2769        // Ignore non-instruction values such as arguments, constants, etc.
2770        if (!Instr) continue;
2771
2772        // If this instruction is outside the loop then record it and continue.
2773        if (!TheLoop->contains(Instr)) {
2774          LoopInvariants.insert(Instr);
2775          continue;
2776        }
2777
2778        // Overwrite previous end points.
2779        EndPoint[Instr] = Index;
2780        Ends.insert(Instr);
2781      }
2782    }
2783  }
2784
2785  // Saves the list of intervals that end with the index in 'key'.
2786  typedef SmallVector<Instruction*, 2> InstrList;
2787  DenseMap<unsigned, InstrList> TransposeEnds;
2788
2789  // Transpose the EndPoints to a list of values that end at each index.
2790  for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
2791       it != e; ++it)
2792    TransposeEnds[it->second].push_back(it->first);
2793
2794  SmallSet<Instruction*, 8> OpenIntervals;
2795  unsigned MaxUsage = 0;
2796
2797
2798  DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
2799  for (unsigned int i = 0; i < Index; ++i) {
2800    Instruction *I = IdxToInstr[i];
2801    // Ignore instructions that are never used within the loop.
2802    if (!Ends.count(I)) continue;
2803
2804    // Remove all of the instructions that end at this location.
2805    InstrList &List = TransposeEnds[i];
2806    for (unsigned int j=0, e = List.size(); j < e; ++j)
2807      OpenIntervals.erase(List[j]);
2808
2809    // Count the number of live interals.
2810    MaxUsage = std::max(MaxUsage, OpenIntervals.size());
2811
2812    DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
2813          OpenIntervals.size() <<"\n");
2814
2815    // Add the current instruction to the list of open intervals.
2816    OpenIntervals.insert(I);
2817  }
2818
2819  unsigned Invariant = LoopInvariants.size();
2820  DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
2821  DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
2822  DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
2823
2824  R.LoopInvariantRegs = Invariant;
2825  R.MaxLocalUsers = MaxUsage;
2826  return R;
2827}
2828
2829unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2830  unsigned Cost = 0;
2831
2832  // For each block.
2833  for (Loop::block_iterator bb = TheLoop->block_begin(),
2834       be = TheLoop->block_end(); bb != be; ++bb) {
2835    unsigned BlockCost = 0;
2836    BasicBlock *BB = *bb;
2837
2838    // For each instruction in the old loop.
2839    for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2840      unsigned C = getInstructionCost(it, VF);
2841      Cost += C;
2842      DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2843            VF << " For instruction: "<< *it << "\n");
2844    }
2845
2846    // We assume that if-converted blocks have a 50% chance of being executed.
2847    // When the code is scalar then some of the blocks are avoided due to CF.
2848    // When the code is vectorized we execute all code paths.
2849    if (Legal->blockNeedsPredication(*bb) && VF == 1)
2850      BlockCost /= 2;
2851
2852    Cost += BlockCost;
2853  }
2854
2855  return Cost;
2856}
2857
2858unsigned
2859LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2860  assert(TTI && "Invalid vector target transformation info");
2861
2862  // If we know that this instruction will remain uniform, check the cost of
2863  // the scalar version.
2864  if (Legal->isUniformAfterVectorization(I))
2865    VF = 1;
2866
2867  Type *RetTy = I->getType();
2868  Type *VectorTy = ToVectorTy(RetTy, VF);
2869
2870  // TODO: We need to estimate the cost of intrinsic calls.
2871  switch (I->getOpcode()) {
2872  case Instruction::GetElementPtr:
2873    // We mark this instruction as zero-cost because scalar GEPs are usually
2874    // lowered to the intruction addressing mode. At the moment we don't
2875    // generate vector geps.
2876    return 0;
2877  case Instruction::Br: {
2878    return TTI->getCFInstrCost(I->getOpcode());
2879  }
2880  case Instruction::PHI:
2881    //TODO: IF-converted IFs become selects.
2882    return 0;
2883  case Instruction::Add:
2884  case Instruction::FAdd:
2885  case Instruction::Sub:
2886  case Instruction::FSub:
2887  case Instruction::Mul:
2888  case Instruction::FMul:
2889  case Instruction::UDiv:
2890  case Instruction::SDiv:
2891  case Instruction::FDiv:
2892  case Instruction::URem:
2893  case Instruction::SRem:
2894  case Instruction::FRem:
2895  case Instruction::Shl:
2896  case Instruction::LShr:
2897  case Instruction::AShr:
2898  case Instruction::And:
2899  case Instruction::Or:
2900  case Instruction::Xor:
2901    return TTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2902  case Instruction::Select: {
2903    SelectInst *SI = cast<SelectInst>(I);
2904    const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2905    bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2906    Type *CondTy = SI->getCondition()->getType();
2907    if (ScalarCond)
2908      CondTy = VectorType::get(CondTy, VF);
2909
2910    return TTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2911  }
2912  case Instruction::ICmp:
2913  case Instruction::FCmp: {
2914    Type *ValTy = I->getOperand(0)->getType();
2915    VectorTy = ToVectorTy(ValTy, VF);
2916    return TTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2917  }
2918  case Instruction::Store: {
2919    StoreInst *SI = cast<StoreInst>(I);
2920    Type *ValTy = SI->getValueOperand()->getType();
2921    VectorTy = ToVectorTy(ValTy, VF);
2922
2923    if (VF == 1)
2924      return TTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2925                                   SI->getAlignment(),
2926                                   SI->getPointerAddressSpace());
2927
2928    // Scalarized stores.
2929    int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
2930    bool Reverse = Stride < 0;
2931    if (0 == Stride) {
2932      unsigned Cost = 0;
2933
2934      // The cost of extracting from the value vector and pointer vector.
2935      Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2936      for (unsigned i = 0; i < VF; ++i) {
2937        Cost += TTI->getVectorInstrCost(Instruction::ExtractElement,
2938                                        VectorTy, i);
2939        Cost += TTI->getVectorInstrCost(Instruction::ExtractElement,
2940                                        PtrTy, i);
2941      }
2942
2943      // The cost of the scalar stores.
2944      Cost += VF * TTI->getMemoryOpCost(I->getOpcode(),
2945                                        ValTy->getScalarType(),
2946                                         SI->getAlignment(),
2947                                         SI->getPointerAddressSpace());
2948      return Cost;
2949    }
2950
2951    // Wide stores.
2952    unsigned Cost = TTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2953                                         SI->getAlignment(),
2954                                         SI->getPointerAddressSpace());
2955    if (Reverse)
2956      Cost += TTI->getShuffleCost(TargetTransformInfo::SK_Reverse,
2957                                  VectorTy, 0);
2958    return Cost;
2959  }
2960  case Instruction::Load: {
2961    LoadInst *LI = cast<LoadInst>(I);
2962
2963    if (VF == 1)
2964      return TTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2965                                  LI->getAlignment(),
2966                                  LI->getPointerAddressSpace());
2967
2968    // Scalarized loads.
2969    int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
2970    bool Reverse = Stride < 0;
2971    if (0 == Stride) {
2972      unsigned Cost = 0;
2973      Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2974
2975      // The cost of extracting from the pointer vector.
2976      for (unsigned i = 0; i < VF; ++i)
2977        Cost += TTI->getVectorInstrCost(Instruction::ExtractElement,
2978                                        PtrTy, i);
2979
2980      // The cost of inserting data to the result vector.
2981      for (unsigned i = 0; i < VF; ++i)
2982        Cost += TTI->getVectorInstrCost(Instruction::InsertElement,
2983                                        VectorTy, i);
2984
2985      // The cost of the scalar stores.
2986      Cost += VF * TTI->getMemoryOpCost(I->getOpcode(),
2987                                        RetTy->getScalarType(),
2988                                        LI->getAlignment(),
2989                                        LI->getPointerAddressSpace());
2990      return Cost;
2991    }
2992
2993    // Wide loads.
2994    unsigned Cost = TTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2995                                         LI->getAlignment(),
2996                                         LI->getPointerAddressSpace());
2997    if (Reverse)
2998      Cost += TTI->getShuffleCost(TargetTransformInfo::SK_Reverse,
2999                                  VectorTy, 0);
3000    return Cost;
3001  }
3002  case Instruction::ZExt:
3003  case Instruction::SExt:
3004  case Instruction::FPToUI:
3005  case Instruction::FPToSI:
3006  case Instruction::FPExt:
3007  case Instruction::PtrToInt:
3008  case Instruction::IntToPtr:
3009  case Instruction::SIToFP:
3010  case Instruction::UIToFP:
3011  case Instruction::Trunc:
3012  case Instruction::FPTrunc:
3013  case Instruction::BitCast: {
3014    // We optimize the truncation of induction variable.
3015    // The cost of these is the same as the scalar operation.
3016    if (I->getOpcode() == Instruction::Trunc &&
3017        Legal->isInductionVariable(I->getOperand(0)))
3018         return TTI->getCastInstrCost(I->getOpcode(), I->getType(),
3019                                      I->getOperand(0)->getType());
3020
3021    Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3022    return TTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3023  }
3024  case Instruction::Call: {
3025    assert(isTriviallyVectorizableIntrinsic(I));
3026    IntrinsicInst *II = cast<IntrinsicInst>(I);
3027    Type *RetTy = ToVectorTy(II->getType(), VF);
3028    SmallVector<Type*, 4> Tys;
3029    for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
3030      Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
3031    return TTI->getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
3032  }
3033  default: {
3034    // We are scalarizing the instruction. Return the cost of the scalar
3035    // instruction, plus the cost of insert and extract into vector
3036    // elements, times the vector width.
3037    unsigned Cost = 0;
3038
3039    if (!RetTy->isVoidTy() && VF != 1) {
3040      unsigned InsCost = TTI->getVectorInstrCost(Instruction::InsertElement,
3041                                                 VectorTy);
3042      unsigned ExtCost = TTI->getVectorInstrCost(Instruction::ExtractElement,
3043                                                 VectorTy);
3044
3045      // The cost of inserting the results plus extracting each one of the
3046      // operands.
3047      Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3048    }
3049
3050    // The cost of executing VF copies of the scalar instruction. This opcode
3051    // is unknown. Assume that it is the same as 'mul'.
3052    Cost += VF * TTI->getArithmeticInstrCost(Instruction::Mul, VectorTy);
3053    return Cost;
3054  }
3055  }// end of switch.
3056}
3057
3058Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3059  if (Scalar->isVoidTy() || VF == 1)
3060    return Scalar;
3061  return VectorType::get(Scalar, VF);
3062}
3063
3064char LoopVectorize::ID = 0;
3065static const char lv_name[] = "Loop Vectorization";
3066INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3067INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3068INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3069INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3070INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3071
3072namespace llvm {
3073  Pass *createLoopVectorizePass() {
3074    return new LoopVectorize();
3075  }
3076}
3077
3078
3079