LoopVectorize.cpp revision 6e4a9c14f6e59b075b3a24825d2dc7dc9e163281
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.
12// The vectorizer uses the TargetTransformInfo analysis to estimate the costs
13// of instructions in order to estimate the profitability of vectorization.
14//
15// The loop vectorizer combines consecutive loop iterations into a single
16// 'wide' iteration. After this transformation the index is incremented
17// by the SIMD vector width, and not by one.
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/PatternMatch.h"
82#include "llvm/Support/raw_ostream.h"
83#include "llvm/Support/ValueHandle.h"
84#include "llvm/Target/TargetLibraryInfo.h"
85#include "llvm/Transforms/Scalar.h"
86#include "llvm/Transforms/Utils/BasicBlockUtils.h"
87#include "llvm/Transforms/Utils/Local.h"
88#include <algorithm>
89#include <map>
90
91using namespace llvm;
92using namespace llvm::PatternMatch;
93
94static cl::opt<unsigned>
95VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
96                    cl::desc("Sets the SIMD width. Zero is autoselect."));
97
98static cl::opt<unsigned>
99VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
100                    cl::desc("Sets the vectorization unroll count. "
101                             "Zero is autoselect."));
102
103static cl::opt<bool>
104EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
105                   cl::desc("Enable if-conversion during vectorization."));
106
107/// We don't vectorize loops with a known constant trip count below this number.
108static cl::opt<unsigned>
109TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
110                             cl::Hidden,
111                             cl::desc("Don't vectorize loops with a constant "
112                                      "trip count that is smaller than this "
113                                      "value."));
114
115/// We don't unroll loops with a known constant trip count below this number.
116static const unsigned TinyTripCountUnrollThreshold = 128;
117
118/// When performing memory disambiguation checks at runtime do not make more
119/// than this number of comparisons.
120static const unsigned RuntimeMemoryCheckThreshold = 8;
121
122/// We use a metadata with this name  to indicate that a scalar loop was
123/// vectorized and that we don't need to re-vectorize it if we run into it
124/// again.
125static const char*
126AlreadyVectorizedMDName = "llvm.vectorizer.already_vectorized";
127
128namespace {
129
130// Forward declarations.
131class LoopVectorizationLegality;
132class LoopVectorizationCostModel;
133
134/// InnerLoopVectorizer vectorizes loops which contain only one basic
135/// block to a specified vectorization factor (VF).
136/// This class performs the widening of scalars into vectors, or multiple
137/// scalars. This class also implements the following features:
138/// * It inserts an epilogue loop for handling loops that don't have iteration
139///   counts that are known to be a multiple of the vectorization factor.
140/// * It handles the code generation for reduction variables.
141/// * Scalarization (implementation using scalars) of un-vectorizable
142///   instructions.
143/// InnerLoopVectorizer does not perform any vectorization-legality
144/// checks, and relies on the caller to check for the different legality
145/// aspects. The InnerLoopVectorizer relies on the
146/// LoopVectorizationLegality class to provide information about the induction
147/// and reduction variables that were found to a given vectorization factor.
148class InnerLoopVectorizer {
149public:
150  InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
151                      DominatorTree *DT, DataLayout *DL,
152                      const TargetLibraryInfo *TLI, unsigned VecWidth,
153                      unsigned UnrollFactor)
154      : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
155        VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
156        OldInduction(0), WidenMap(UnrollFactor) {}
157
158  // Perform the actual loop widening (vectorization).
159  void vectorize(LoopVectorizationLegality *Legal) {
160    // Create a new empty loop. Unlink the old loop and connect the new one.
161    createEmptyLoop(Legal);
162    // Widen each instruction in the old loop to a new one in the new loop.
163    // Use the Legality module to find the induction and reduction variables.
164    vectorizeLoop(Legal);
165    // Register the new loop and update the analysis passes.
166    updateAnalysis();
167  }
168
169private:
170  /// A small list of PHINodes.
171  typedef SmallVector<PHINode*, 4> PhiVector;
172  /// When we unroll loops we have multiple vector values for each scalar.
173  /// This data structure holds the unrolled and vectorized values that
174  /// originated from one scalar instruction.
175  typedef SmallVector<Value*, 2> VectorParts;
176
177  /// Add code that checks at runtime if the accessed arrays overlap.
178  /// Returns the comparator value or NULL if no check is needed.
179  Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
180                               Instruction *Loc);
181  /// Create an empty loop, based on the loop ranges of the old loop.
182  void createEmptyLoop(LoopVectorizationLegality *Legal);
183  /// Copy and widen the instructions from the old loop.
184  void vectorizeLoop(LoopVectorizationLegality *Legal);
185
186  /// A helper function that computes the predicate of the block BB, assuming
187  /// that the header block of the loop is set to True. It returns the *entry*
188  /// mask for the block BB.
189  VectorParts createBlockInMask(BasicBlock *BB);
190  /// A helper function that computes the predicate of the edge between SRC
191  /// and DST.
192  VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
193
194  /// A helper function to vectorize a single BB within the innermost loop.
195  void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
196                            PhiVector *PV);
197
198  /// Insert the new loop to the loop hierarchy and pass manager
199  /// and update the analysis passes.
200  void updateAnalysis();
201
202  /// This instruction is un-vectorizable. Implement it as a sequence
203  /// of scalars.
204  void scalarizeInstruction(Instruction *Instr);
205
206  /// Vectorize Load and Store instructions,
207  void vectorizeMemoryInstruction(Instruction *Instr,
208                                  LoopVectorizationLegality *Legal);
209
210  /// Create a broadcast instruction. This method generates a broadcast
211  /// instruction (shuffle) for loop invariant values and for the induction
212  /// value. If this is the induction variable then we extend it to N, N+1, ...
213  /// this is needed because each iteration in the loop corresponds to a SIMD
214  /// element.
215  Value *getBroadcastInstrs(Value *V);
216
217  /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
218  /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
219  /// The sequence starts at StartIndex.
220  Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
221
222  /// When we go over instructions in the basic block we rely on previous
223  /// values within the current basic block or on loop invariant values.
224  /// When we widen (vectorize) values we place them in the map. If the values
225  /// are not within the map, they have to be loop invariant, so we simply
226  /// broadcast them into a vector.
227  VectorParts &getVectorValue(Value *V);
228
229  /// Generate a shuffle sequence that will reverse the vector Vec.
230  Value *reverseVector(Value *Vec);
231
232  /// This is a helper class that holds the vectorizer state. It maps scalar
233  /// instructions to vector instructions. When the code is 'unrolled' then
234  /// then a single scalar value is mapped to multiple vector parts. The parts
235  /// are stored in the VectorPart type.
236  struct ValueMap {
237    /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
238    /// are mapped.
239    ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
240
241    /// \return True if 'Key' is saved in the Value Map.
242    bool has(Value *Key) const { return MapStorage.count(Key); }
243
244    /// Initializes a new entry in the map. Sets all of the vector parts to the
245    /// save value in 'Val'.
246    /// \return A reference to a vector with splat values.
247    VectorParts &splat(Value *Key, Value *Val) {
248      VectorParts &Entry = MapStorage[Key];
249      Entry.assign(UF, Val);
250      return Entry;
251    }
252
253    ///\return A reference to the value that is stored at 'Key'.
254    VectorParts &get(Value *Key) {
255      VectorParts &Entry = MapStorage[Key];
256      if (Entry.empty())
257        Entry.resize(UF);
258      assert(Entry.size() == UF);
259      return Entry;
260    }
261
262  private:
263    /// The unroll factor. Each entry in the map stores this number of vector
264    /// elements.
265    unsigned UF;
266
267    /// Map storage. We use std::map and not DenseMap because insertions to a
268    /// dense map invalidates its iterators.
269    std::map<Value *, VectorParts> MapStorage;
270  };
271
272  /// The original loop.
273  Loop *OrigLoop;
274  /// Scev analysis to use.
275  ScalarEvolution *SE;
276  /// Loop Info.
277  LoopInfo *LI;
278  /// Dominator Tree.
279  DominatorTree *DT;
280  /// Data Layout.
281  DataLayout *DL;
282  /// Target Library Info.
283  const TargetLibraryInfo *TLI;
284
285  /// The vectorization SIMD factor to use. Each vector will have this many
286  /// vector elements.
287  unsigned VF;
288  /// The vectorization unroll factor to use. Each scalar is vectorized to this
289  /// many different vector instructions.
290  unsigned UF;
291
292  /// The builder that we use
293  IRBuilder<> Builder;
294
295  // --- Vectorization state ---
296
297  /// The vector-loop preheader.
298  BasicBlock *LoopVectorPreHeader;
299  /// The scalar-loop preheader.
300  BasicBlock *LoopScalarPreHeader;
301  /// Middle Block between the vector and the scalar.
302  BasicBlock *LoopMiddleBlock;
303  ///The ExitBlock of the scalar loop.
304  BasicBlock *LoopExitBlock;
305  ///The vector loop body.
306  BasicBlock *LoopVectorBody;
307  ///The scalar loop body.
308  BasicBlock *LoopScalarBody;
309  /// A list of all bypass blocks. The first block is the entry of the loop.
310  SmallVector<BasicBlock *, 4> LoopBypassBlocks;
311
312  /// The new Induction variable which was added to the new block.
313  PHINode *Induction;
314  /// The induction variable of the old basic block.
315  PHINode *OldInduction;
316  /// Holds the extended (to the widest induction type) start index.
317  Value *ExtendedIdx;
318  /// Maps scalars to widened vectors.
319  ValueMap WidenMap;
320};
321
322/// \brief Check if conditionally executed loads are hoistable.
323///
324/// This class has two functions: isHoistableLoad and canHoistAllLoads.
325/// isHoistableLoad should be called on all load instructions that are executed
326/// conditionally. After all conditional loads are processed, the client should
327/// call canHoistAllLoads to determine if all of the conditional executed loads
328/// have an unconditional memory access to the same memory address in the loop.
329class LoadHoisting {
330  typedef SmallPtrSet<Value *, 8> MemorySet;
331
332  Loop *TheLoop;
333  DominatorTree *DT;
334  MemorySet CondLoadAddrSet;
335
336public:
337  LoadHoisting(Loop *L, DominatorTree *D) : TheLoop(L), DT(D) {}
338
339  /// \brief Check if the instruction is a load with a identifiable address.
340  bool isHoistableLoad(Instruction *L);
341
342  /// \brief Check if all of the conditional loads are hoistable because there
343  /// exists an unconditional memory access to the same address in the loop.
344  bool canHoistAllLoads();
345};
346
347bool LoadHoisting::isHoistableLoad(Instruction *L) {
348  LoadInst *LI = dyn_cast<LoadInst>(L);
349  if (!LI)
350    return false;
351
352  CondLoadAddrSet.insert(LI->getPointerOperand());
353  return true;
354}
355
356static void addMemAccesses(BasicBlock *BB, SmallPtrSet<Value *, 8> &Set) {
357  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
358    if (LoadInst *LI = dyn_cast<LoadInst>(BI)) // Try a load.
359      Set.insert(LI->getPointerOperand());
360    else if (StoreInst *SI = dyn_cast<StoreInst>(BI)) // Try a store.
361      Set.insert(SI->getPointerOperand());
362  }
363}
364
365bool LoadHoisting::canHoistAllLoads() {
366  // No conditional loads.
367  if (CondLoadAddrSet.empty())
368    return true;
369
370  MemorySet UncondMemAccesses;
371  std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
372  BasicBlock *LoopLatch = TheLoop->getLoopLatch();
373
374  // Iterate over the unconditional blocks and collect memory access addresses.
375  for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
376    BasicBlock *BB = LoopBlocks[i];
377
378    // Ignore conditional blocks.
379    if (BB != LoopLatch && !DT->dominates(BB, LoopLatch))
380      continue;
381
382    addMemAccesses(BB, UncondMemAccesses);
383  }
384
385  // And make sure there is a matching unconditional access for every
386  // conditional load.
387  for (MemorySet::iterator MI = CondLoadAddrSet.begin(),
388       ME = CondLoadAddrSet.end(); MI != ME; ++MI)
389    if (!UncondMemAccesses.count(*MI))
390      return false;
391
392  return true;
393}
394
395/// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
396/// to what vectorization factor.
397/// This class does not look at the profitability of vectorization, only the
398/// legality. This class has two main kinds of checks:
399/// * Memory checks - The code in canVectorizeMemory checks if vectorization
400///   will change the order of memory accesses in a way that will change the
401///   correctness of the program.
402/// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
403/// checks for a number of different conditions, such as the availability of a
404/// single induction variable, that all types are supported and vectorize-able,
405/// etc. This code reflects the capabilities of InnerLoopVectorizer.
406/// This class is also used by InnerLoopVectorizer for identifying
407/// induction variable and the different reduction variables.
408class LoopVectorizationLegality {
409public:
410  LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
411                            DominatorTree *DT, TargetTransformInfo* TTI,
412                            AliasAnalysis *AA, TargetLibraryInfo *TLI)
413      : TheLoop(L), SE(SE), DL(DL), DT(DT), TTI(TTI), AA(AA), TLI(TLI),
414        Induction(0), WidestIndTy(0), HasFunNoNaNAttr(false),
415        LoadSpeculation(L, DT) {}
416
417  /// This enum represents the kinds of reductions that we support.
418  enum ReductionKind {
419    RK_NoReduction, ///< Not a reduction.
420    RK_IntegerAdd,  ///< Sum of integers.
421    RK_IntegerMult, ///< Product of integers.
422    RK_IntegerOr,   ///< Bitwise or logical OR of numbers.
423    RK_IntegerAnd,  ///< Bitwise or logical AND of numbers.
424    RK_IntegerXor,  ///< Bitwise or logical XOR of numbers.
425    RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
426    RK_FloatAdd,    ///< Sum of floats.
427    RK_FloatMult,   ///< Product of floats.
428    RK_FloatMinMax  ///< Min/max implemented in terms of select(cmp()).
429  };
430
431  /// This enum represents the kinds of inductions that we support.
432  enum InductionKind {
433    IK_NoInduction,         ///< Not an induction variable.
434    IK_IntInduction,        ///< Integer induction variable. Step = 1.
435    IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
436    IK_PtrInduction,        ///< Pointer induction var. Step = sizeof(elem).
437    IK_ReversePtrInduction  ///< Reverse ptr indvar. Step = - sizeof(elem).
438  };
439
440  // This enum represents the kind of minmax reduction.
441  enum MinMaxReductionKind {
442    MRK_Invalid,
443    MRK_UIntMin,
444    MRK_UIntMax,
445    MRK_SIntMin,
446    MRK_SIntMax,
447    MRK_FloatMin,
448    MRK_FloatMax
449  };
450
451  /// This POD struct holds information about reduction variables.
452  struct ReductionDescriptor {
453    ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
454      Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
455
456    ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
457                        MinMaxReductionKind MK)
458        : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
459
460    // The starting value of the reduction.
461    // It does not have to be zero!
462    TrackingVH<Value> StartValue;
463    // The instruction who's value is used outside the loop.
464    Instruction *LoopExitInstr;
465    // The kind of the reduction.
466    ReductionKind Kind;
467    // If this a min/max reduction the kind of reduction.
468    MinMaxReductionKind MinMaxKind;
469  };
470
471  /// This POD struct holds information about a potential reduction operation.
472  struct ReductionInstDesc {
473    ReductionInstDesc(bool IsRedux, Instruction *I) :
474      IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
475
476    ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
477      IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
478
479    // Is this instruction a reduction candidate.
480    bool IsReduction;
481    // The last instruction in a min/max pattern (select of the select(icmp())
482    // pattern), or the current reduction instruction otherwise.
483    Instruction *PatternLastInst;
484    // If this is a min/max pattern the comparison predicate.
485    MinMaxReductionKind MinMaxKind;
486  };
487
488  // This POD struct holds information about the memory runtime legality
489  // check that a group of pointers do not overlap.
490  struct RuntimePointerCheck {
491    RuntimePointerCheck() : Need(false) {}
492
493    /// Reset the state of the pointer runtime information.
494    void reset() {
495      Need = false;
496      Pointers.clear();
497      Starts.clear();
498      Ends.clear();
499    }
500
501    /// Insert a pointer and calculate the start and end SCEVs.
502    void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr);
503
504    /// This flag indicates if we need to add the runtime check.
505    bool Need;
506    /// Holds the pointers that we need to check.
507    SmallVector<TrackingVH<Value>, 2> Pointers;
508    /// Holds the pointer value at the beginning of the loop.
509    SmallVector<const SCEV*, 2> Starts;
510    /// Holds the pointer value at the end of the loop.
511    SmallVector<const SCEV*, 2> Ends;
512    /// Holds the information if this pointer is used for writing to memory.
513    SmallVector<bool, 2> IsWritePtr;
514  };
515
516  /// A POD for saving information about induction variables.
517  struct InductionInfo {
518    InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
519    InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
520    /// Start value.
521    TrackingVH<Value> StartValue;
522    /// Induction kind.
523    InductionKind IK;
524  };
525
526  /// ReductionList contains the reduction descriptors for all
527  /// of the reductions that were found in the loop.
528  typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
529
530  /// InductionList saves induction variables and maps them to the
531  /// induction descriptor.
532  typedef MapVector<PHINode*, InductionInfo> InductionList;
533
534  /// Alias(Multi)Map stores the values (GEPs or underlying objects and their
535  /// respective Store/Load instruction(s) to calculate aliasing.
536  typedef MapVector<Value*, Instruction* > AliasMap;
537  typedef DenseMap<Value*, std::vector<Instruction*> > AliasMultiMap;
538
539  /// Returns true if it is legal to vectorize this loop.
540  /// This does not mean that it is profitable to vectorize this
541  /// loop, only that it is legal to do so.
542  bool canVectorize();
543
544  /// Returns the Induction variable.
545  PHINode *getInduction() { return Induction; }
546
547  /// Returns the reduction variables found in the loop.
548  ReductionList *getReductionVars() { return &Reductions; }
549
550  /// Returns the induction variables found in the loop.
551  InductionList *getInductionVars() { return &Inductions; }
552
553  /// Returns the widest induction type.
554  Type *getWidestInductionType() { return WidestIndTy; }
555
556  /// Returns True if V is an induction variable in this loop.
557  bool isInductionVariable(const Value *V);
558
559  /// Return true if the block BB needs to be predicated in order for the loop
560  /// to be vectorized.
561  bool blockNeedsPredication(BasicBlock *BB);
562
563  /// Check if this  pointer is consecutive when vectorizing. This happens
564  /// when the last index of the GEP is the induction variable, or that the
565  /// pointer itself is an induction variable.
566  /// This check allows us to vectorize A[idx] into a wide load/store.
567  /// Returns:
568  /// 0 - Stride is unknown or non consecutive.
569  /// 1 - Address is consecutive.
570  /// -1 - Address is consecutive, and decreasing.
571  int isConsecutivePtr(Value *Ptr);
572
573  /// Returns true if the value V is uniform within the loop.
574  bool isUniform(Value *V);
575
576  /// Returns true if this instruction will remain scalar after vectorization.
577  bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
578
579  /// Returns the information that we collected about runtime memory check.
580  RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
581
582  /// This function returns the identity element (or neutral element) for
583  /// the operation K.
584  static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
585private:
586  /// Check if a single basic block loop is vectorizable.
587  /// At this point we know that this is a loop with a constant trip count
588  /// and we only need to check individual instructions.
589  bool canVectorizeInstrs();
590
591  /// When we vectorize loops we may change the order in which
592  /// we read and write from memory. This method checks if it is
593  /// legal to vectorize the code, considering only memory constrains.
594  /// Returns true if the loop is vectorizable
595  bool canVectorizeMemory();
596
597  /// Return true if we can vectorize this loop using the IF-conversion
598  /// transformation.
599  bool canVectorizeWithIfConvert();
600
601  /// Collect the variables that need to stay uniform after vectorization.
602  void collectLoopUniforms();
603
604  /// Return true if all of the instructions in the block can be speculatively
605  /// executed.
606  bool blockCanBePredicated(BasicBlock *BB);
607
608  /// Returns True, if 'Phi' is the kind of reduction variable for type
609  /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
610  bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
611  /// Returns a struct describing if the instruction 'I' can be a reduction
612  /// variable of type 'Kind'. If the reduction is a min/max pattern of
613  /// select(icmp()) this function advances the instruction pointer 'I' from the
614  /// compare instruction to the select instruction and stores this pointer in
615  /// 'PatternLastInst' member of the returned struct.
616  ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
617                                     ReductionInstDesc &Desc);
618  /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
619  /// pattern corresponding to a min(X, Y) or max(X, Y).
620  static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
621                                                    ReductionInstDesc &Prev);
622  /// Returns the induction kind of Phi. This function may return NoInduction
623  /// if the PHI is not an induction variable.
624  InductionKind isInductionVariable(PHINode *Phi);
625  /// Return true if can compute the address bounds of Ptr within the loop.
626  bool hasComputableBounds(Value *Ptr);
627  /// Return true if there is the chance of write reorder.
628  bool hasPossibleGlobalWriteReorder(Value *Object,
629                                     Instruction *Inst,
630                                     AliasMultiMap &WriteObjects,
631                                     unsigned MaxByteWidth);
632  /// Return the AA location for a load or a store.
633  AliasAnalysis::Location getLoadStoreLocation(Instruction *Inst);
634
635
636  /// The loop that we evaluate.
637  Loop *TheLoop;
638  /// Scev analysis.
639  ScalarEvolution *SE;
640  /// DataLayout analysis.
641  DataLayout *DL;
642  /// Dominators.
643  DominatorTree *DT;
644  /// Target Info.
645  TargetTransformInfo *TTI;
646  /// Alias Analysis.
647  AliasAnalysis *AA;
648  /// Target Library Info.
649  TargetLibraryInfo *TLI;
650
651  //  ---  vectorization state --- //
652
653  /// Holds the integer induction variable. This is the counter of the
654  /// loop.
655  PHINode *Induction;
656  /// Holds the reduction variables.
657  ReductionList Reductions;
658  /// Holds all of the induction variables that we found in the loop.
659  /// Notice that inductions don't need to start at zero and that induction
660  /// variables can be pointers.
661  InductionList Inductions;
662  /// Holds the widest induction type encountered.
663  Type *WidestIndTy;
664
665  /// Allowed outside users. This holds the reduction
666  /// vars which can be accessed from outside the loop.
667  SmallPtrSet<Value*, 4> AllowedExit;
668  /// This set holds the variables which are known to be uniform after
669  /// vectorization.
670  SmallPtrSet<Instruction*, 4> Uniforms;
671  /// We need to check that all of the pointers in this list are disjoint
672  /// at runtime.
673  RuntimePointerCheck PtrRtCheck;
674  /// Can we assume the absence of NaNs.
675  bool HasFunNoNaNAttr;
676
677  /// Utility to determine whether loads can be speculated.
678  LoadHoisting LoadSpeculation;
679};
680
681/// LoopVectorizationCostModel - estimates the expected speedups due to
682/// vectorization.
683/// In many cases vectorization is not profitable. This can happen because of
684/// a number of reasons. In this class we mainly attempt to predict the
685/// expected speedup/slowdowns due to the supported instruction set. We use the
686/// TargetTransformInfo to query the different backends for the cost of
687/// different operations.
688class LoopVectorizationCostModel {
689public:
690  LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
691                             LoopVectorizationLegality *Legal,
692                             const TargetTransformInfo &TTI,
693                             DataLayout *DL, const TargetLibraryInfo *TLI)
694      : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
695
696  /// Information about vectorization costs
697  struct VectorizationFactor {
698    unsigned Width; // Vector width with best cost
699    unsigned Cost; // Cost of the loop with that width
700  };
701  /// \return The most profitable vectorization factor and the cost of that VF.
702  /// This method checks every power of two up to VF. If UserVF is not ZERO
703  /// then this vectorization factor will be selected if vectorization is
704  /// possible.
705  VectorizationFactor selectVectorizationFactor(bool OptForSize,
706                                                unsigned UserVF);
707
708  /// \return The size (in bits) of the widest type in the code that
709  /// needs to be vectorized. We ignore values that remain scalar such as
710  /// 64 bit loop indices.
711  unsigned getWidestType();
712
713  /// \return The most profitable unroll factor.
714  /// If UserUF is non-zero then this method finds the best unroll-factor
715  /// based on register pressure and other parameters.
716  /// VF and LoopCost are the selected vectorization factor and the cost of the
717  /// selected VF.
718  unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
719                              unsigned LoopCost);
720
721  /// \brief A struct that represents some properties of the register usage
722  /// of a loop.
723  struct RegisterUsage {
724    /// Holds the number of loop invariant values that are used in the loop.
725    unsigned LoopInvariantRegs;
726    /// Holds the maximum number of concurrent live intervals in the loop.
727    unsigned MaxLocalUsers;
728    /// Holds the number of instructions in the loop.
729    unsigned NumInstructions;
730  };
731
732  /// \return  information about the register usage of the loop.
733  RegisterUsage calculateRegisterUsage();
734
735private:
736  /// Returns the expected execution cost. The unit of the cost does
737  /// not matter because we use the 'cost' units to compare different
738  /// vector widths. The cost that is returned is *not* normalized by
739  /// the factor width.
740  unsigned expectedCost(unsigned VF);
741
742  /// Returns the execution time cost of an instruction for a given vector
743  /// width. Vector width of one means scalar.
744  unsigned getInstructionCost(Instruction *I, unsigned VF);
745
746  /// A helper function for converting Scalar types to vector types.
747  /// If the incoming type is void, we return void. If the VF is 1, we return
748  /// the scalar type.
749  static Type* ToVectorTy(Type *Scalar, unsigned VF);
750
751  /// Returns whether the instruction is a load or store and will be a emitted
752  /// as a vector operation.
753  bool isConsecutiveLoadOrStore(Instruction *I);
754
755  /// The loop that we evaluate.
756  Loop *TheLoop;
757  /// Scev analysis.
758  ScalarEvolution *SE;
759  /// Loop Info analysis.
760  LoopInfo *LI;
761  /// Vectorization legality.
762  LoopVectorizationLegality *Legal;
763  /// Vector target information.
764  const TargetTransformInfo &TTI;
765  /// Target data layout information.
766  DataLayout *DL;
767  /// Target Library Info.
768  const TargetLibraryInfo *TLI;
769};
770
771/// The LoopVectorize Pass.
772struct LoopVectorize : public LoopPass {
773  /// Pass identification, replacement for typeid
774  static char ID;
775
776  explicit LoopVectorize() : LoopPass(ID) {
777    initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
778  }
779
780  ScalarEvolution *SE;
781  DataLayout *DL;
782  LoopInfo *LI;
783  TargetTransformInfo *TTI;
784  DominatorTree *DT;
785  AliasAnalysis *AA;
786  TargetLibraryInfo *TLI;
787
788  virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
789    // We only vectorize innermost loops.
790    if (!L->empty())
791      return false;
792
793    SE = &getAnalysis<ScalarEvolution>();
794    DL = getAnalysisIfAvailable<DataLayout>();
795    LI = &getAnalysis<LoopInfo>();
796    TTI = &getAnalysis<TargetTransformInfo>();
797    DT = &getAnalysis<DominatorTree>();
798    AA = getAnalysisIfAvailable<AliasAnalysis>();
799    TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
800
801    if (DL == NULL) {
802      DEBUG(dbgs() << "LV: Not vectorizing because of missing data layout");
803      return false;
804    }
805
806    DEBUG(dbgs() << "LV: Checking a loop in \"" <<
807          L->getHeader()->getParent()->getName() << "\"\n");
808
809    // Check if it is legal to vectorize the loop.
810    LoopVectorizationLegality LVL(L, SE, DL, DT, TTI, AA, TLI);
811    if (!LVL.canVectorize()) {
812      DEBUG(dbgs() << "LV: Not vectorizing.\n");
813      return false;
814    }
815
816    // Use the cost model.
817    LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
818
819    // Check the function attributes to find out if this function should be
820    // optimized for size.
821    Function *F = L->getHeader()->getParent();
822    Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
823    Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
824    unsigned FnIndex = AttributeSet::FunctionIndex;
825    bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
826    bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
827
828    if (NoFloat) {
829      DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
830            "attribute is used.\n");
831      return false;
832    }
833
834    // Select the optimal vectorization factor.
835    LoopVectorizationCostModel::VectorizationFactor VF;
836    VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
837    // Select the unroll factor.
838    unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll,
839                                        VF.Width, VF.Cost);
840
841    if (VF.Width == 1) {
842      DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
843      return false;
844    }
845
846    DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
847          F->getParent()->getModuleIdentifier()<<"\n");
848    DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
849
850    // If we decided that it is *legal* to vectorize the loop then do it.
851    InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
852    LB.vectorize(&LVL);
853
854    DEBUG(verifyFunction(*L->getHeader()->getParent()));
855    return true;
856  }
857
858  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
859    LoopPass::getAnalysisUsage(AU);
860    AU.addRequiredID(LoopSimplifyID);
861    AU.addRequiredID(LCSSAID);
862    AU.addRequired<DominatorTree>();
863    AU.addRequired<LoopInfo>();
864    AU.addRequired<ScalarEvolution>();
865    AU.addRequired<TargetTransformInfo>();
866    AU.addPreserved<LoopInfo>();
867    AU.addPreserved<DominatorTree>();
868  }
869
870};
871
872} // end anonymous namespace
873
874//===----------------------------------------------------------------------===//
875// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
876// LoopVectorizationCostModel.
877//===----------------------------------------------------------------------===//
878
879void
880LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
881                                                       Loop *Lp, Value *Ptr,
882                                                       bool WritePtr) {
883  const SCEV *Sc = SE->getSCEV(Ptr);
884  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
885  assert(AR && "Invalid addrec expression");
886  const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
887  const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
888  Pointers.push_back(Ptr);
889  Starts.push_back(AR->getStart());
890  Ends.push_back(ScEnd);
891  IsWritePtr.push_back(WritePtr);
892}
893
894Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
895  // Save the current insertion location.
896  Instruction *Loc = Builder.GetInsertPoint();
897
898  // We need to place the broadcast of invariant variables outside the loop.
899  Instruction *Instr = dyn_cast<Instruction>(V);
900  bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
901  bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
902
903  // Place the code for broadcasting invariant variables in the new preheader.
904  if (Invariant)
905    Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
906
907  // Broadcast the scalar into all locations in the vector.
908  Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
909
910  // Restore the builder insertion point.
911  if (Invariant)
912    Builder.SetInsertPoint(Loc);
913
914  return Shuf;
915}
916
917Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
918                                                 bool Negate) {
919  assert(Val->getType()->isVectorTy() && "Must be a vector");
920  assert(Val->getType()->getScalarType()->isIntegerTy() &&
921         "Elem must be an integer");
922  // Create the types.
923  Type *ITy = Val->getType()->getScalarType();
924  VectorType *Ty = cast<VectorType>(Val->getType());
925  int VLen = Ty->getNumElements();
926  SmallVector<Constant*, 8> Indices;
927
928  // Create a vector of consecutive numbers from zero to VF.
929  for (int i = 0; i < VLen; ++i) {
930    int64_t Idx = Negate ? (-i) : i;
931    Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
932  }
933
934  // Add the consecutive indices to the vector value.
935  Constant *Cv = ConstantVector::get(Indices);
936  assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
937  return Builder.CreateAdd(Val, Cv, "induction");
938}
939
940int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
941  assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
942  // Make sure that the pointer does not point to structs.
943  if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
944    return 0;
945
946  // If this value is a pointer induction variable we know it is consecutive.
947  PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
948  if (Phi && Inductions.count(Phi)) {
949    InductionInfo II = Inductions[Phi];
950    if (IK_PtrInduction == II.IK)
951      return 1;
952    else if (IK_ReversePtrInduction == II.IK)
953      return -1;
954  }
955
956  GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
957  if (!Gep)
958    return 0;
959
960  unsigned NumOperands = Gep->getNumOperands();
961  Value *LastIndex = Gep->getOperand(NumOperands - 1);
962
963  Value *GpPtr = Gep->getPointerOperand();
964  // If this GEP value is a consecutive pointer induction variable and all of
965  // the indices are constant then we know it is consecutive. We can
966  Phi = dyn_cast<PHINode>(GpPtr);
967  if (Phi && Inductions.count(Phi)) {
968
969    // Make sure that the pointer does not point to structs.
970    PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
971    if (GepPtrType->getElementType()->isAggregateType())
972      return 0;
973
974    // Make sure that all of the index operands are loop invariant.
975    for (unsigned i = 1; i < NumOperands; ++i)
976      if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
977        return 0;
978
979    InductionInfo II = Inductions[Phi];
980    if (IK_PtrInduction == II.IK)
981      return 1;
982    else if (IK_ReversePtrInduction == II.IK)
983      return -1;
984  }
985
986  // Check that all of the gep indices are uniform except for the last.
987  for (unsigned i = 0; i < NumOperands - 1; ++i)
988    if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
989      return 0;
990
991  // We can emit wide load/stores only if the last index is the induction
992  // variable.
993  const SCEV *Last = SE->getSCEV(LastIndex);
994  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
995    const SCEV *Step = AR->getStepRecurrence(*SE);
996
997    // The memory is consecutive because the last index is consecutive
998    // and all other indices are loop invariant.
999    if (Step->isOne())
1000      return 1;
1001    if (Step->isAllOnesValue())
1002      return -1;
1003  }
1004
1005  return 0;
1006}
1007
1008bool LoopVectorizationLegality::isUniform(Value *V) {
1009  return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1010}
1011
1012InnerLoopVectorizer::VectorParts&
1013InnerLoopVectorizer::getVectorValue(Value *V) {
1014  assert(V != Induction && "The new induction variable should not be used.");
1015  assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1016
1017  // If we have this scalar in the map, return it.
1018  if (WidenMap.has(V))
1019    return WidenMap.get(V);
1020
1021  // If this scalar is unknown, assume that it is a constant or that it is
1022  // loop invariant. Broadcast V and save the value for future uses.
1023  Value *B = getBroadcastInstrs(V);
1024  return WidenMap.splat(V, B);
1025}
1026
1027Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1028  assert(Vec->getType()->isVectorTy() && "Invalid type");
1029  SmallVector<Constant*, 8> ShuffleMask;
1030  for (unsigned i = 0; i < VF; ++i)
1031    ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1032
1033  return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1034                                     ConstantVector::get(ShuffleMask),
1035                                     "reverse");
1036}
1037
1038
1039void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
1040                                             LoopVectorizationLegality *Legal) {
1041  // Attempt to issue a wide load.
1042  LoadInst *LI = dyn_cast<LoadInst>(Instr);
1043  StoreInst *SI = dyn_cast<StoreInst>(Instr);
1044
1045  assert((LI || SI) && "Invalid Load/Store instruction");
1046
1047  Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1048  Type *DataTy = VectorType::get(ScalarDataTy, VF);
1049  Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1050  unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1051
1052  unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1053  unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1054
1055  if (ScalarAllocatedSize != VectorElementSize)
1056    return scalarizeInstruction(Instr);
1057
1058  // If the pointer is loop invariant or if it is non consecutive,
1059  // scalarize the load.
1060  int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1061  bool Reverse = ConsecutiveStride < 0;
1062  bool UniformLoad = LI && Legal->isUniform(Ptr);
1063  if (!ConsecutiveStride || UniformLoad)
1064    return scalarizeInstruction(Instr);
1065
1066  Constant *Zero = Builder.getInt32(0);
1067  VectorParts &Entry = WidenMap.get(Instr);
1068
1069  // Handle consecutive loads/stores.
1070  GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1071  if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1072    Value *PtrOperand = Gep->getPointerOperand();
1073    Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1074    FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1075
1076    // Create the new GEP with the new induction variable.
1077    GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1078    Gep2->setOperand(0, FirstBasePtr);
1079    Gep2->setName("gep.indvar.base");
1080    Ptr = Builder.Insert(Gep2);
1081  } else if (Gep) {
1082    assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1083                               OrigLoop) && "Base ptr must be invariant");
1084
1085    // The last index does not have to be the induction. It can be
1086    // consecutive and be a function of the index. For example A[I+1];
1087    unsigned NumOperands = Gep->getNumOperands();
1088
1089    Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1090    VectorParts &GEPParts = getVectorValue(LastGepOperand);
1091    Value *LastIndex = GEPParts[0];
1092    LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1093
1094    // Create the new GEP with the new induction variable.
1095    GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1096    Gep2->setOperand(NumOperands - 1, LastIndex);
1097    Gep2->setName("gep.indvar.idx");
1098    Ptr = Builder.Insert(Gep2);
1099  } else {
1100    // Use the induction element ptr.
1101    assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1102    VectorParts &PtrVal = getVectorValue(Ptr);
1103    Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1104  }
1105
1106  // Handle Stores:
1107  if (SI) {
1108    assert(!Legal->isUniform(SI->getPointerOperand()) &&
1109           "We do not allow storing to uniform addresses");
1110
1111    VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1112    for (unsigned Part = 0; Part < UF; ++Part) {
1113      // Calculate the pointer for the specific unroll-part.
1114      Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1115
1116      if (Reverse) {
1117        // If we store to reverse consecutive memory locations then we need
1118        // to reverse the order of elements in the stored value.
1119        StoredVal[Part] = reverseVector(StoredVal[Part]);
1120        // If the address is consecutive but reversed, then the
1121        // wide store needs to start at the last vector element.
1122        PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1123        PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1124      }
1125
1126      Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
1127      Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1128    }
1129  }
1130
1131  for (unsigned Part = 0; Part < UF; ++Part) {
1132    // Calculate the pointer for the specific unroll-part.
1133    Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1134
1135    if (Reverse) {
1136      // If the address is consecutive but reversed, then the
1137      // wide store needs to start at the last vector element.
1138      PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1139      PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1140    }
1141
1142    Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
1143    Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1144    cast<LoadInst>(LI)->setAlignment(Alignment);
1145    Entry[Part] = Reverse ? reverseVector(LI) :  LI;
1146  }
1147}
1148
1149void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
1150  assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1151  // Holds vector parameters or scalars, in case of uniform vals.
1152  SmallVector<VectorParts, 4> Params;
1153
1154  // Find all of the vectorized parameters.
1155  for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1156    Value *SrcOp = Instr->getOperand(op);
1157
1158    // If we are accessing the old induction variable, use the new one.
1159    if (SrcOp == OldInduction) {
1160      Params.push_back(getVectorValue(SrcOp));
1161      continue;
1162    }
1163
1164    // Try using previously calculated values.
1165    Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1166
1167    // If the src is an instruction that appeared earlier in the basic block
1168    // then it should already be vectorized.
1169    if (SrcInst && OrigLoop->contains(SrcInst)) {
1170      assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1171      // The parameter is a vector value from earlier.
1172      Params.push_back(WidenMap.get(SrcInst));
1173    } else {
1174      // The parameter is a scalar from outside the loop. Maybe even a constant.
1175      VectorParts Scalars;
1176      Scalars.append(UF, SrcOp);
1177      Params.push_back(Scalars);
1178    }
1179  }
1180
1181  assert(Params.size() == Instr->getNumOperands() &&
1182         "Invalid number of operands");
1183
1184  // Does this instruction return a value ?
1185  bool IsVoidRetTy = Instr->getType()->isVoidTy();
1186
1187  Value *UndefVec = IsVoidRetTy ? 0 :
1188    UndefValue::get(VectorType::get(Instr->getType(), VF));
1189  // Create a new entry in the WidenMap and initialize it to Undef or Null.
1190  VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1191
1192  // For each vector unroll 'part':
1193  for (unsigned Part = 0; Part < UF; ++Part) {
1194    // For each scalar that we create:
1195    for (unsigned Width = 0; Width < VF; ++Width) {
1196      Instruction *Cloned = Instr->clone();
1197      if (!IsVoidRetTy)
1198        Cloned->setName(Instr->getName() + ".cloned");
1199      // Replace the operands of the cloned instrucions with extracted scalars.
1200      for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1201        Value *Op = Params[op][Part];
1202        // Param is a vector. Need to extract the right lane.
1203        if (Op->getType()->isVectorTy())
1204          Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1205        Cloned->setOperand(op, Op);
1206      }
1207
1208      // Place the cloned scalar in the new loop.
1209      Builder.Insert(Cloned);
1210
1211      // If the original scalar returns a value we need to place it in a vector
1212      // so that future users will be able to use it.
1213      if (!IsVoidRetTy)
1214        VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1215                                                       Builder.getInt32(Width));
1216    }
1217  }
1218}
1219
1220Instruction *
1221InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
1222                                     Instruction *Loc) {
1223  LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1224  Legal->getRuntimePointerCheck();
1225
1226  if (!PtrRtCheck->Need)
1227    return NULL;
1228
1229  Instruction *MemoryRuntimeCheck = 0;
1230  unsigned NumPointers = PtrRtCheck->Pointers.size();
1231  SmallVector<Value* , 2> Starts;
1232  SmallVector<Value* , 2> Ends;
1233
1234  SCEVExpander Exp(*SE, "induction");
1235
1236  // Use this type for pointer arithmetic.
1237  Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
1238
1239  for (unsigned i = 0; i < NumPointers; ++i) {
1240    Value *Ptr = PtrRtCheck->Pointers[i];
1241    const SCEV *Sc = SE->getSCEV(Ptr);
1242
1243    if (SE->isLoopInvariant(Sc, OrigLoop)) {
1244      DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1245            *Ptr <<"\n");
1246      Starts.push_back(Ptr);
1247      Ends.push_back(Ptr);
1248    } else {
1249      DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
1250
1251      Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1252      Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1253      Starts.push_back(Start);
1254      Ends.push_back(End);
1255    }
1256  }
1257
1258  IRBuilder<> ChkBuilder(Loc);
1259
1260  for (unsigned i = 0; i < NumPointers; ++i) {
1261    for (unsigned j = i+1; j < NumPointers; ++j) {
1262      // No need to check if two readonly pointers intersect.
1263      if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1264        continue;
1265
1266      Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc");
1267      Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc");
1268      Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy, "bc");
1269      Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy, "bc");
1270
1271      Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1272      Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1273      Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1274      if (MemoryRuntimeCheck)
1275        IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1276                                         "conflict.rdx");
1277
1278      MemoryRuntimeCheck = cast<Instruction>(IsConflict);
1279    }
1280  }
1281
1282  return MemoryRuntimeCheck;
1283}
1284
1285void
1286InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
1287  /*
1288   In this function we generate a new loop. The new loop will contain
1289   the vectorized instructions while the old loop will continue to run the
1290   scalar remainder.
1291
1292       [ ] <-- vector loop bypass (may consist of multiple blocks).
1293     /  |
1294    /   v
1295   |   [ ]     <-- vector pre header.
1296   |    |
1297   |    v
1298   |   [  ] \
1299   |   [  ]_|   <-- vector loop.
1300   |    |
1301    \   v
1302      >[ ]   <--- middle-block.
1303     /  |
1304    /   v
1305   |   [ ]     <--- new preheader.
1306   |    |
1307   |    v
1308   |   [ ] \
1309   |   [ ]_|   <-- old scalar loop to handle remainder.
1310    \   |
1311     \  v
1312      >[ ]     <-- exit block.
1313   ...
1314   */
1315
1316  BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1317  BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1318  BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1319  assert(ExitBlock && "Must have an exit block");
1320
1321  // Mark the old scalar loop with metadata that tells us not to vectorize this
1322  // loop again if we run into it.
1323  MDNode *MD = MDNode::get(OldBasicBlock->getContext(), None);
1324  OldBasicBlock->getTerminator()->setMetadata(AlreadyVectorizedMDName, MD);
1325
1326  // Some loops have a single integer induction variable, while other loops
1327  // don't. One example is c++ iterators that often have multiple pointer
1328  // induction variables. In the code below we also support a case where we
1329  // don't have a single induction variable.
1330  OldInduction = Legal->getInduction();
1331  Type *IdxTy = Legal->getWidestInductionType();
1332
1333  // Find the loop boundaries.
1334  const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
1335  assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1336
1337  // Get the total trip count from the count by adding 1.
1338  ExitCount = SE->getAddExpr(ExitCount,
1339                             SE->getConstant(ExitCount->getType(), 1));
1340
1341  // Expand the trip count and place the new instructions in the preheader.
1342  // Notice that the pre-header does not change, only the loop body.
1343  SCEVExpander Exp(*SE, "induction");
1344
1345  // Count holds the overall loop count (N).
1346  Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1347                                   BypassBlock->getTerminator());
1348
1349  // The loop index does not have to start at Zero. Find the original start
1350  // value from the induction PHI node. If we don't have an induction variable
1351  // then we know that it starts at zero.
1352  Builder.SetInsertPoint(BypassBlock->getTerminator());
1353  Value *StartIdx = ExtendedIdx = OldInduction ?
1354    Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1355                       IdxTy):
1356    ConstantInt::get(IdxTy, 0);
1357
1358  assert(BypassBlock && "Invalid loop structure");
1359  LoopBypassBlocks.push_back(BypassBlock);
1360
1361  // Split the single block loop into the two loop structure described above.
1362  BasicBlock *VectorPH =
1363  BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1364  BasicBlock *VecBody =
1365  VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1366  BasicBlock *MiddleBlock =
1367  VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1368  BasicBlock *ScalarPH =
1369  MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1370
1371  // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1372  // inside the loop.
1373  Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1374
1375  // Generate the induction variable.
1376  Induction = Builder.CreatePHI(IdxTy, 2, "index");
1377  // The loop step is equal to the vectorization factor (num of SIMD elements)
1378  // times the unroll factor (num of SIMD instructions).
1379  Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1380
1381  // This is the IR builder that we use to add all of the logic for bypassing
1382  // the new vector loop.
1383  IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1384
1385  // We may need to extend the index in case there is a type mismatch.
1386  // We know that the count starts at zero and does not overflow.
1387  if (Count->getType() != IdxTy) {
1388    // The exit count can be of pointer type. Convert it to the correct
1389    // integer type.
1390    if (ExitCount->getType()->isPointerTy())
1391      Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1392    else
1393      Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1394  }
1395
1396  // Add the start index to the loop count to get the new end index.
1397  Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1398
1399  // Now we need to generate the expression for N - (N % VF), which is
1400  // the part that the vectorized body will execute.
1401  Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1402  Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1403  Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1404                                                     "end.idx.rnd.down");
1405
1406  // Now, compare the new count to zero. If it is zero skip the vector loop and
1407  // jump to the scalar loop.
1408  Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1409                                          "cmp.zero");
1410
1411  BasicBlock *LastBypassBlock = BypassBlock;
1412
1413  // Generate the code that checks in runtime if arrays overlap. We put the
1414  // checks into a separate block to make the more common case of few elements
1415  // faster.
1416  Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1417                                                 BypassBlock->getTerminator());
1418  if (MemRuntimeCheck) {
1419    // Create a new block containing the memory check.
1420    BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1421                                                          "vector.memcheck");
1422    LoopBypassBlocks.push_back(CheckBlock);
1423
1424    // Replace the branch into the memory check block with a conditional branch
1425    // for the "few elements case".
1426    Instruction *OldTerm = BypassBlock->getTerminator();
1427    BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1428    OldTerm->eraseFromParent();
1429
1430    Cmp = MemRuntimeCheck;
1431    LastBypassBlock = CheckBlock;
1432  }
1433
1434  LastBypassBlock->getTerminator()->eraseFromParent();
1435  BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1436                     LastBypassBlock);
1437
1438  // We are going to resume the execution of the scalar loop.
1439  // Go over all of the induction variables that we found and fix the
1440  // PHIs that are left in the scalar version of the loop.
1441  // The starting values of PHI nodes depend on the counter of the last
1442  // iteration in the vectorized loop.
1443  // If we come from a bypass edge then we need to start from the original
1444  // start value.
1445
1446  // This variable saves the new starting index for the scalar loop.
1447  PHINode *ResumeIndex = 0;
1448  LoopVectorizationLegality::InductionList::iterator I, E;
1449  LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1450  // Set builder to point to last bypass block.
1451  BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1452  for (I = List->begin(), E = List->end(); I != E; ++I) {
1453    PHINode *OrigPhi = I->first;
1454    LoopVectorizationLegality::InductionInfo II = I->second;
1455
1456    Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
1457    PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
1458                                         MiddleBlock->getTerminator());
1459    // We might have extended the type of the induction variable but we need a
1460    // truncated version for the scalar loop.
1461    PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
1462      PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
1463                      MiddleBlock->getTerminator()) : 0;
1464
1465    Value *EndValue = 0;
1466    switch (II.IK) {
1467    case LoopVectorizationLegality::IK_NoInduction:
1468      llvm_unreachable("Unknown induction");
1469    case LoopVectorizationLegality::IK_IntInduction: {
1470      // Handle the integer induction counter.
1471      assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1472
1473      // We have the canonical induction variable.
1474      if (OrigPhi == OldInduction) {
1475        // Create a truncated version of the resume value for the scalar loop,
1476        // we might have promoted the type to a larger width.
1477        EndValue =
1478          BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
1479        // The new PHI merges the original incoming value, in case of a bypass,
1480        // or the value at the end of the vectorized loop.
1481        for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1482          TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1483        TruncResumeVal->addIncoming(EndValue, VecBody);
1484
1485        // We know what the end value is.
1486        EndValue = IdxEndRoundDown;
1487        // We also know which PHI node holds it.
1488        ResumeIndex = ResumeVal;
1489        break;
1490      }
1491
1492      // Not the canonical induction variable - add the vector loop count to the
1493      // start value.
1494      Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1495                                                   II.StartValue->getType(),
1496                                                   "cast.crd");
1497      EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
1498      break;
1499    }
1500    case LoopVectorizationLegality::IK_ReverseIntInduction: {
1501      // Convert the CountRoundDown variable to the PHI size.
1502      Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1503                                                   II.StartValue->getType(),
1504                                                   "cast.crd");
1505      // Handle reverse integer induction counter.
1506      EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
1507      break;
1508    }
1509    case LoopVectorizationLegality::IK_PtrInduction: {
1510      // For pointer induction variables, calculate the offset using
1511      // the end index.
1512      EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
1513                                         "ptr.ind.end");
1514      break;
1515    }
1516    case LoopVectorizationLegality::IK_ReversePtrInduction: {
1517      // The value at the end of the loop for the reverse pointer is calculated
1518      // by creating a GEP with a negative index starting from the start value.
1519      Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1520      Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
1521                                              "rev.ind.end");
1522      EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
1523                                         "rev.ptr.ind.end");
1524      break;
1525    }
1526    }// end of case
1527
1528    // The new PHI merges the original incoming value, in case of a bypass,
1529    // or the value at the end of the vectorized loop.
1530    for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
1531      if (OrigPhi == OldInduction)
1532        ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
1533      else
1534        ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1535    }
1536    ResumeVal->addIncoming(EndValue, VecBody);
1537
1538    // Fix the scalar body counter (PHI node).
1539    unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1540    // The old inductions phi node in the scalar body needs the truncated value.
1541    if (OrigPhi == OldInduction)
1542      OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
1543    else
1544      OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1545  }
1546
1547  // If we are generating a new induction variable then we also need to
1548  // generate the code that calculates the exit value. This value is not
1549  // simply the end of the counter because we may skip the vectorized body
1550  // in case of a runtime check.
1551  if (!OldInduction){
1552    assert(!ResumeIndex && "Unexpected resume value found");
1553    ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1554                                  MiddleBlock->getTerminator());
1555    for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1556      ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1557    ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1558  }
1559
1560  // Make sure that we found the index where scalar loop needs to continue.
1561  assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1562         "Invalid resume Index");
1563
1564  // Add a check in the middle block to see if we have completed
1565  // all of the iterations in the first vector loop.
1566  // If (N - N%VF) == N, then we *don't* need to run the remainder.
1567  Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1568                                ResumeIndex, "cmp.n",
1569                                MiddleBlock->getTerminator());
1570
1571  BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1572  // Remove the old terminator.
1573  MiddleBlock->getTerminator()->eraseFromParent();
1574
1575  // Create i+1 and fill the PHINode.
1576  Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1577  Induction->addIncoming(StartIdx, VectorPH);
1578  Induction->addIncoming(NextIdx, VecBody);
1579  // Create the compare.
1580  Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1581  Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1582
1583  // Now we have two terminators. Remove the old one from the block.
1584  VecBody->getTerminator()->eraseFromParent();
1585
1586  // Get ready to start creating new instructions into the vectorized body.
1587  Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1588
1589  // Create and register the new vector loop.
1590  Loop* Lp = new Loop();
1591  Loop *ParentLoop = OrigLoop->getParentLoop();
1592
1593  // Insert the new loop into the loop nest and register the new basic blocks.
1594  if (ParentLoop) {
1595    ParentLoop->addChildLoop(Lp);
1596    for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1597      ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1598    ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1599    ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1600    ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1601  } else {
1602    LI->addTopLevelLoop(Lp);
1603  }
1604
1605  Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1606
1607  // Save the state.
1608  LoopVectorPreHeader = VectorPH;
1609  LoopScalarPreHeader = ScalarPH;
1610  LoopMiddleBlock = MiddleBlock;
1611  LoopExitBlock = ExitBlock;
1612  LoopVectorBody = VecBody;
1613  LoopScalarBody = OldBasicBlock;
1614}
1615
1616/// This function returns the identity element (or neutral element) for
1617/// the operation K.
1618Constant*
1619LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
1620  switch (K) {
1621  case RK_IntegerXor:
1622  case RK_IntegerAdd:
1623  case RK_IntegerOr:
1624    // Adding, Xoring, Oring zero to a number does not change it.
1625    return ConstantInt::get(Tp, 0);
1626  case RK_IntegerMult:
1627    // Multiplying a number by 1 does not change it.
1628    return ConstantInt::get(Tp, 1);
1629  case RK_IntegerAnd:
1630    // AND-ing a number with an all-1 value does not change it.
1631    return ConstantInt::get(Tp, -1, true);
1632  case  RK_FloatMult:
1633    // Multiplying a number by 1 does not change it.
1634    return ConstantFP::get(Tp, 1.0L);
1635  case  RK_FloatAdd:
1636    // Adding zero to a number does not change it.
1637    return ConstantFP::get(Tp, 0.0L);
1638  default:
1639    llvm_unreachable("Unknown reduction kind");
1640  }
1641}
1642
1643static Intrinsic::ID
1644getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
1645  // If we have an intrinsic call, check if it is trivially vectorizable.
1646  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1647    switch (II->getIntrinsicID()) {
1648    case Intrinsic::sqrt:
1649    case Intrinsic::sin:
1650    case Intrinsic::cos:
1651    case Intrinsic::exp:
1652    case Intrinsic::exp2:
1653    case Intrinsic::log:
1654    case Intrinsic::log10:
1655    case Intrinsic::log2:
1656    case Intrinsic::fabs:
1657    case Intrinsic::floor:
1658    case Intrinsic::ceil:
1659    case Intrinsic::trunc:
1660    case Intrinsic::rint:
1661    case Intrinsic::nearbyint:
1662    case Intrinsic::pow:
1663    case Intrinsic::fma:
1664    case Intrinsic::fmuladd:
1665      return II->getIntrinsicID();
1666    default:
1667      return Intrinsic::not_intrinsic;
1668    }
1669  }
1670
1671  if (!TLI)
1672    return Intrinsic::not_intrinsic;
1673
1674  LibFunc::Func Func;
1675  Function *F = CI->getCalledFunction();
1676  // We're going to make assumptions on the semantics of the functions, check
1677  // that the target knows that it's available in this environment.
1678  if (!F || !TLI->getLibFunc(F->getName(), Func))
1679    return Intrinsic::not_intrinsic;
1680
1681  // Otherwise check if we have a call to a function that can be turned into a
1682  // vector intrinsic.
1683  switch (Func) {
1684  default:
1685    break;
1686  case LibFunc::sin:
1687  case LibFunc::sinf:
1688  case LibFunc::sinl:
1689    return Intrinsic::sin;
1690  case LibFunc::cos:
1691  case LibFunc::cosf:
1692  case LibFunc::cosl:
1693    return Intrinsic::cos;
1694  case LibFunc::exp:
1695  case LibFunc::expf:
1696  case LibFunc::expl:
1697    return Intrinsic::exp;
1698  case LibFunc::exp2:
1699  case LibFunc::exp2f:
1700  case LibFunc::exp2l:
1701    return Intrinsic::exp2;
1702  case LibFunc::log:
1703  case LibFunc::logf:
1704  case LibFunc::logl:
1705    return Intrinsic::log;
1706  case LibFunc::log10:
1707  case LibFunc::log10f:
1708  case LibFunc::log10l:
1709    return Intrinsic::log10;
1710  case LibFunc::log2:
1711  case LibFunc::log2f:
1712  case LibFunc::log2l:
1713    return Intrinsic::log2;
1714  case LibFunc::fabs:
1715  case LibFunc::fabsf:
1716  case LibFunc::fabsl:
1717    return Intrinsic::fabs;
1718  case LibFunc::floor:
1719  case LibFunc::floorf:
1720  case LibFunc::floorl:
1721    return Intrinsic::floor;
1722  case LibFunc::ceil:
1723  case LibFunc::ceilf:
1724  case LibFunc::ceill:
1725    return Intrinsic::ceil;
1726  case LibFunc::trunc:
1727  case LibFunc::truncf:
1728  case LibFunc::truncl:
1729    return Intrinsic::trunc;
1730  case LibFunc::rint:
1731  case LibFunc::rintf:
1732  case LibFunc::rintl:
1733    return Intrinsic::rint;
1734  case LibFunc::nearbyint:
1735  case LibFunc::nearbyintf:
1736  case LibFunc::nearbyintl:
1737    return Intrinsic::nearbyint;
1738  case LibFunc::pow:
1739  case LibFunc::powf:
1740  case LibFunc::powl:
1741    return Intrinsic::pow;
1742  }
1743
1744  return Intrinsic::not_intrinsic;
1745}
1746
1747/// This function translates the reduction kind to an LLVM binary operator.
1748static unsigned
1749getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1750  switch (Kind) {
1751    case LoopVectorizationLegality::RK_IntegerAdd:
1752      return Instruction::Add;
1753    case LoopVectorizationLegality::RK_IntegerMult:
1754      return Instruction::Mul;
1755    case LoopVectorizationLegality::RK_IntegerOr:
1756      return Instruction::Or;
1757    case LoopVectorizationLegality::RK_IntegerAnd:
1758      return Instruction::And;
1759    case LoopVectorizationLegality::RK_IntegerXor:
1760      return Instruction::Xor;
1761    case LoopVectorizationLegality::RK_FloatMult:
1762      return Instruction::FMul;
1763    case LoopVectorizationLegality::RK_FloatAdd:
1764      return Instruction::FAdd;
1765    case LoopVectorizationLegality::RK_IntegerMinMax:
1766      return Instruction::ICmp;
1767    case LoopVectorizationLegality::RK_FloatMinMax:
1768      return Instruction::FCmp;
1769    default:
1770      llvm_unreachable("Unknown reduction operation");
1771  }
1772}
1773
1774Value *createMinMaxOp(IRBuilder<> &Builder,
1775                      LoopVectorizationLegality::MinMaxReductionKind RK,
1776                      Value *Left,
1777                      Value *Right) {
1778  CmpInst::Predicate P = CmpInst::ICMP_NE;
1779  switch (RK) {
1780  default:
1781    llvm_unreachable("Unknown min/max reduction kind");
1782  case LoopVectorizationLegality::MRK_UIntMin:
1783    P = CmpInst::ICMP_ULT;
1784    break;
1785  case LoopVectorizationLegality::MRK_UIntMax:
1786    P = CmpInst::ICMP_UGT;
1787    break;
1788  case LoopVectorizationLegality::MRK_SIntMin:
1789    P = CmpInst::ICMP_SLT;
1790    break;
1791  case LoopVectorizationLegality::MRK_SIntMax:
1792    P = CmpInst::ICMP_SGT;
1793    break;
1794  case LoopVectorizationLegality::MRK_FloatMin:
1795    P = CmpInst::FCMP_OLT;
1796    break;
1797  case LoopVectorizationLegality::MRK_FloatMax:
1798    P = CmpInst::FCMP_OGT;
1799    break;
1800  }
1801
1802  Value *Cmp;
1803  if (RK == LoopVectorizationLegality::MRK_FloatMin || RK == LoopVectorizationLegality::MRK_FloatMax)
1804    Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
1805  else
1806    Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
1807
1808  Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
1809  return Select;
1810}
1811
1812void
1813InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1814  //===------------------------------------------------===//
1815  //
1816  // Notice: any optimization or new instruction that go
1817  // into the code below should be also be implemented in
1818  // the cost-model.
1819  //
1820  //===------------------------------------------------===//
1821  Constant *Zero = Builder.getInt32(0);
1822
1823  // In order to support reduction variables we need to be able to vectorize
1824  // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1825  // stages. First, we create a new vector PHI node with no incoming edges.
1826  // We use this value when we vectorize all of the instructions that use the
1827  // PHI. Next, after all of the instructions in the block are complete we
1828  // add the new incoming edges to the PHI. At this point all of the
1829  // instructions in the basic block are vectorized, so we can use them to
1830  // construct the PHI.
1831  PhiVector RdxPHIsToFix;
1832
1833  // Scan the loop in a topological order to ensure that defs are vectorized
1834  // before users.
1835  LoopBlocksDFS DFS(OrigLoop);
1836  DFS.perform(LI);
1837
1838  // Vectorize all of the blocks in the original loop.
1839  for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1840       be = DFS.endRPO(); bb != be; ++bb)
1841    vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1842
1843  // At this point every instruction in the original loop is widened to
1844  // a vector form. We are almost done. Now, we need to fix the PHI nodes
1845  // that we vectorized. The PHI nodes are currently empty because we did
1846  // not want to introduce cycles. Notice that the remaining PHI nodes
1847  // that we need to fix are reduction variables.
1848
1849  // Create the 'reduced' values for each of the induction vars.
1850  // The reduced values are the vector values that we scalarize and combine
1851  // after the loop is finished.
1852  for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1853       it != e; ++it) {
1854    PHINode *RdxPhi = *it;
1855    assert(RdxPhi && "Unable to recover vectorized PHI");
1856
1857    // Find the reduction variable descriptor.
1858    assert(Legal->getReductionVars()->count(RdxPhi) &&
1859           "Unable to find the reduction variable");
1860    LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1861    (*Legal->getReductionVars())[RdxPhi];
1862
1863    // We need to generate a reduction vector from the incoming scalar.
1864    // To do so, we need to generate the 'identity' vector and overide
1865    // one of the elements with the incoming scalar reduction. We need
1866    // to do it in the vector-loop preheader.
1867    Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
1868
1869    // This is the vector-clone of the value that leaves the loop.
1870    VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1871    Type *VecTy = VectorExit[0]->getType();
1872
1873    // Find the reduction identity variable. Zero for addition, or, xor,
1874    // one for multiplication, -1 for And.
1875    Value *Identity;
1876    Value *VectorStart;
1877    if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
1878        RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
1879      // MinMax reduction have the start value as their identify.
1880      VectorStart = Identity = Builder.CreateVectorSplat(VF, RdxDesc.StartValue,
1881                                                         "minmax.ident");
1882    } else {
1883      Constant *Iden =
1884        LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
1885                                                        VecTy->getScalarType());
1886      Identity = ConstantVector::getSplat(VF, Iden);
1887
1888      // This vector is the Identity vector where the first element is the
1889      // incoming scalar reduction.
1890      VectorStart = Builder.CreateInsertElement(Identity,
1891                                                RdxDesc.StartValue, Zero);
1892    }
1893
1894    // Fix the vector-loop phi.
1895    // We created the induction variable so we know that the
1896    // preheader is the first entry.
1897    BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1898
1899    // Reductions do not have to start at zero. They can start with
1900    // any loop invariant values.
1901    VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1902    BasicBlock *Latch = OrigLoop->getLoopLatch();
1903    Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1904    VectorParts &Val = getVectorValue(LoopVal);
1905    for (unsigned part = 0; part < UF; ++part) {
1906      // Make sure to add the reduction stat value only to the
1907      // first unroll part.
1908      Value *StartVal = (part == 0) ? VectorStart : Identity;
1909      cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1910      cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1911    }
1912
1913    // Before each round, move the insertion point right between
1914    // the PHIs and the values we are going to write.
1915    // This allows us to write both PHINodes and the extractelement
1916    // instructions.
1917    Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1918
1919    VectorParts RdxParts;
1920    for (unsigned part = 0; part < UF; ++part) {
1921      // This PHINode contains the vectorized reduction variable, or
1922      // the initial value vector, if we bypass the vector loop.
1923      VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1924      PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1925      Value *StartVal = (part == 0) ? VectorStart : Identity;
1926      for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1927        NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
1928      NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1929      RdxParts.push_back(NewPhi);
1930    }
1931
1932    // Reduce all of the unrolled parts into a single vector.
1933    Value *ReducedPartRdx = RdxParts[0];
1934    unsigned Op = getReductionBinOp(RdxDesc.Kind);
1935    for (unsigned part = 1; part < UF; ++part) {
1936      if (Op != Instruction::ICmp && Op != Instruction::FCmp)
1937        ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op,
1938                                             RdxParts[part], ReducedPartRdx,
1939                                             "bin.rdx");
1940      else
1941        ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
1942                                        ReducedPartRdx, RdxParts[part]);
1943    }
1944
1945    // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1946    // and vector ops, reducing the set of values being computed by half each
1947    // round.
1948    assert(isPowerOf2_32(VF) &&
1949           "Reduction emission only supported for pow2 vectors!");
1950    Value *TmpVec = ReducedPartRdx;
1951    SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1952    for (unsigned i = VF; i != 1; i >>= 1) {
1953      // Move the upper half of the vector to the lower half.
1954      for (unsigned j = 0; j != i/2; ++j)
1955        ShuffleMask[j] = Builder.getInt32(i/2 + j);
1956
1957      // Fill the rest of the mask with undef.
1958      std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1959                UndefValue::get(Builder.getInt32Ty()));
1960
1961      Value *Shuf =
1962        Builder.CreateShuffleVector(TmpVec,
1963                                    UndefValue::get(TmpVec->getType()),
1964                                    ConstantVector::get(ShuffleMask),
1965                                    "rdx.shuf");
1966
1967      if (Op != Instruction::ICmp && Op != Instruction::FCmp)
1968        TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
1969                                     "bin.rdx");
1970      else
1971        TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
1972    }
1973
1974    // The result is in the first element of the vector.
1975    Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1976
1977    // Now, we need to fix the users of the reduction variable
1978    // inside and outside of the scalar remainder loop.
1979    // We know that the loop is in LCSSA form. We need to update the
1980    // PHI nodes in the exit blocks.
1981    for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1982         LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1983      PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1984      if (!LCSSAPhi) continue;
1985
1986      // All PHINodes need to have a single entry edge, or two if
1987      // we already fixed them.
1988      assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1989
1990      // We found our reduction value exit-PHI. Update it with the
1991      // incoming bypass edge.
1992      if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1993        // Add an edge coming from the bypass.
1994        LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1995        break;
1996      }
1997    }// end of the LCSSA phi scan.
1998
1999    // Fix the scalar loop reduction variable with the incoming reduction sum
2000    // from the vector body and from the backedge value.
2001    int IncomingEdgeBlockIdx =
2002    (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2003    assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2004    // Pick the other block.
2005    int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2006    (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
2007    (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2008  }// end of for each redux variable.
2009
2010  // The Loop exit block may have single value PHI nodes where the incoming
2011  // value is 'undef'. While vectorizing we only handled real values that
2012  // were defined inside the loop. Here we handle the 'undef case'.
2013  // See PR14725.
2014  for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2015       LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2016    PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2017    if (!LCSSAPhi) continue;
2018    if (LCSSAPhi->getNumIncomingValues() == 1)
2019      LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2020                            LoopMiddleBlock);
2021  }
2022}
2023
2024InnerLoopVectorizer::VectorParts
2025InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2026  assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2027         "Invalid edge");
2028
2029  VectorParts SrcMask = createBlockInMask(Src);
2030
2031  // The terminator has to be a branch inst!
2032  BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2033  assert(BI && "Unexpected terminator found");
2034
2035  if (BI->isConditional()) {
2036    VectorParts EdgeMask = getVectorValue(BI->getCondition());
2037
2038    if (BI->getSuccessor(0) != Dst)
2039      for (unsigned part = 0; part < UF; ++part)
2040        EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2041
2042    for (unsigned part = 0; part < UF; ++part)
2043      EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2044    return EdgeMask;
2045  }
2046
2047  return SrcMask;
2048}
2049
2050InnerLoopVectorizer::VectorParts
2051InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2052  assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2053
2054  // Loop incoming mask is all-one.
2055  if (OrigLoop->getHeader() == BB) {
2056    Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2057    return getVectorValue(C);
2058  }
2059
2060  // This is the block mask. We OR all incoming edges, and with zero.
2061  Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2062  VectorParts BlockMask = getVectorValue(Zero);
2063
2064  // For each pred:
2065  for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2066    VectorParts EM = createEdgeMask(*it, BB);
2067    for (unsigned part = 0; part < UF; ++part)
2068      BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2069  }
2070
2071  return BlockMask;
2072}
2073
2074void
2075InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
2076                                          BasicBlock *BB, PhiVector *PV) {
2077  // For each instruction in the old loop.
2078  for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2079    VectorParts &Entry = WidenMap.get(it);
2080    switch (it->getOpcode()) {
2081    case Instruction::Br:
2082      // Nothing to do for PHIs and BR, since we already took care of the
2083      // loop control flow instructions.
2084      continue;
2085    case Instruction::PHI:{
2086      PHINode* P = cast<PHINode>(it);
2087      // Handle reduction variables:
2088      if (Legal->getReductionVars()->count(P)) {
2089        for (unsigned part = 0; part < UF; ++part) {
2090          // This is phase one of vectorizing PHIs.
2091          Type *VecTy = VectorType::get(it->getType(), VF);
2092          Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2093                                        LoopVectorBody-> getFirstInsertionPt());
2094        }
2095        PV->push_back(P);
2096        continue;
2097      }
2098
2099      // Check for PHI nodes that are lowered to vector selects.
2100      if (P->getParent() != OrigLoop->getHeader()) {
2101        // We know that all PHIs in non header blocks are converted into
2102        // selects, so we don't have to worry about the insertion order and we
2103        // can just use the builder.
2104        // At this point we generate the predication tree. There may be
2105        // duplications since this is a simple recursive scan, but future
2106        // optimizations will clean it up.
2107
2108        unsigned NumIncoming = P->getNumIncomingValues();
2109
2110        // Generate a sequence of selects of the form:
2111        // SELECT(Mask3, In3,
2112        //      SELECT(Mask2, In2,
2113        //                   ( ...)))
2114        for (unsigned In = 0; In < NumIncoming; In++) {
2115          VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2116                                            P->getParent());
2117          VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2118
2119          for (unsigned part = 0; part < UF; ++part) {
2120            // We might have single edge PHIs (blocks) - use an identity
2121            // 'select' for the first PHI operand.
2122            if (In == 0)
2123              Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2124                                                 In0[part]);
2125            else
2126              // Select between the current value and the previous incoming edge
2127              // based on the incoming mask.
2128              Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2129                                                 Entry[part], "predphi");
2130          }
2131        }
2132        continue;
2133      }
2134
2135      // This PHINode must be an induction variable.
2136      // Make sure that we know about it.
2137      assert(Legal->getInductionVars()->count(P) &&
2138             "Not an induction variable");
2139
2140      LoopVectorizationLegality::InductionInfo II =
2141        Legal->getInductionVars()->lookup(P);
2142
2143      switch (II.IK) {
2144      case LoopVectorizationLegality::IK_NoInduction:
2145        llvm_unreachable("Unknown induction");
2146      case LoopVectorizationLegality::IK_IntInduction: {
2147        assert(P->getType() == II.StartValue->getType() && "Types must match");
2148        Type *PhiTy = P->getType();
2149        Value *Broadcasted;
2150        if (P == OldInduction) {
2151          // Handle the canonical induction variable. We might have had to
2152          // extend the type.
2153          Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2154        } else {
2155          // Handle other induction variables that are now based on the
2156          // canonical one.
2157          Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2158                                                   "normalized.idx");
2159          NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2160          Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2161                                          "offset.idx");
2162        }
2163        Broadcasted = getBroadcastInstrs(Broadcasted);
2164        // After broadcasting the induction variable we need to make the vector
2165        // consecutive by adding 0, 1, 2, etc.
2166        for (unsigned part = 0; part < UF; ++part)
2167          Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2168        continue;
2169      }
2170      case LoopVectorizationLegality::IK_ReverseIntInduction:
2171      case LoopVectorizationLegality::IK_PtrInduction:
2172      case LoopVectorizationLegality::IK_ReversePtrInduction:
2173        // Handle reverse integer and pointer inductions.
2174        Value *StartIdx = ExtendedIdx;
2175        // This is the normalized GEP that starts counting at zero.
2176        Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2177                                                 "normalized.idx");
2178
2179        // Handle the reverse integer induction variable case.
2180        if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2181          IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2182          Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2183                                                 "resize.norm.idx");
2184          Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
2185                                                 "reverse.idx");
2186
2187          // This is a new value so do not hoist it out.
2188          Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2189          // After broadcasting the induction variable we need to make the
2190          // vector consecutive by adding  ... -3, -2, -1, 0.
2191          for (unsigned part = 0; part < UF; ++part)
2192            Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2193                                               true);
2194          continue;
2195        }
2196
2197        // Handle the pointer induction variable case.
2198        assert(P->getType()->isPointerTy() && "Unexpected type.");
2199
2200        // Is this a reverse induction ptr or a consecutive induction ptr.
2201        bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2202                        II.IK);
2203
2204        // This is the vector of results. Notice that we don't generate
2205        // vector geps because scalar geps result in better code.
2206        for (unsigned part = 0; part < UF; ++part) {
2207          Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2208          for (unsigned int i = 0; i < VF; ++i) {
2209            int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2210            Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2211            Value *GlobalIdx;
2212            if (!Reverse)
2213              GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2214            else
2215              GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2216
2217            Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2218                                               "next.gep");
2219            VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2220                                                 Builder.getInt32(i),
2221                                                 "insert.gep");
2222          }
2223          Entry[part] = VecVal;
2224        }
2225        continue;
2226      }
2227
2228    }// End of PHI.
2229
2230    case Instruction::Add:
2231    case Instruction::FAdd:
2232    case Instruction::Sub:
2233    case Instruction::FSub:
2234    case Instruction::Mul:
2235    case Instruction::FMul:
2236    case Instruction::UDiv:
2237    case Instruction::SDiv:
2238    case Instruction::FDiv:
2239    case Instruction::URem:
2240    case Instruction::SRem:
2241    case Instruction::FRem:
2242    case Instruction::Shl:
2243    case Instruction::LShr:
2244    case Instruction::AShr:
2245    case Instruction::And:
2246    case Instruction::Or:
2247    case Instruction::Xor: {
2248      // Just widen binops.
2249      BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2250      VectorParts &A = getVectorValue(it->getOperand(0));
2251      VectorParts &B = getVectorValue(it->getOperand(1));
2252
2253      // Use this vector value for all users of the original instruction.
2254      for (unsigned Part = 0; Part < UF; ++Part) {
2255        Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2256
2257        // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2258        BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2259        if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2260          VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2261          VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2262        }
2263        if (VecOp && isa<PossiblyExactOperator>(VecOp))
2264          VecOp->setIsExact(BinOp->isExact());
2265
2266        Entry[Part] = V;
2267      }
2268      break;
2269    }
2270    case Instruction::Select: {
2271      // Widen selects.
2272      // If the selector is loop invariant we can create a select
2273      // instruction with a scalar condition. Otherwise, use vector-select.
2274      bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2275                                               OrigLoop);
2276
2277      // The condition can be loop invariant  but still defined inside the
2278      // loop. This means that we can't just use the original 'cond' value.
2279      // We have to take the 'vectorized' value and pick the first lane.
2280      // Instcombine will make this a no-op.
2281      VectorParts &Cond = getVectorValue(it->getOperand(0));
2282      VectorParts &Op0  = getVectorValue(it->getOperand(1));
2283      VectorParts &Op1  = getVectorValue(it->getOperand(2));
2284      Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
2285                                                       Builder.getInt32(0));
2286      for (unsigned Part = 0; Part < UF; ++Part) {
2287        Entry[Part] = Builder.CreateSelect(
2288          InvariantCond ? ScalarCond : Cond[Part],
2289          Op0[Part],
2290          Op1[Part]);
2291      }
2292      break;
2293    }
2294
2295    case Instruction::ICmp:
2296    case Instruction::FCmp: {
2297      // Widen compares. Generate vector compares.
2298      bool FCmp = (it->getOpcode() == Instruction::FCmp);
2299      CmpInst *Cmp = dyn_cast<CmpInst>(it);
2300      VectorParts &A = getVectorValue(it->getOperand(0));
2301      VectorParts &B = getVectorValue(it->getOperand(1));
2302      for (unsigned Part = 0; Part < UF; ++Part) {
2303        Value *C = 0;
2304        if (FCmp)
2305          C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
2306        else
2307          C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
2308        Entry[Part] = C;
2309      }
2310      break;
2311    }
2312
2313    case Instruction::Store:
2314    case Instruction::Load:
2315        vectorizeMemoryInstruction(it, Legal);
2316        break;
2317    case Instruction::ZExt:
2318    case Instruction::SExt:
2319    case Instruction::FPToUI:
2320    case Instruction::FPToSI:
2321    case Instruction::FPExt:
2322    case Instruction::PtrToInt:
2323    case Instruction::IntToPtr:
2324    case Instruction::SIToFP:
2325    case Instruction::UIToFP:
2326    case Instruction::Trunc:
2327    case Instruction::FPTrunc:
2328    case Instruction::BitCast: {
2329      CastInst *CI = dyn_cast<CastInst>(it);
2330      /// Optimize the special case where the source is the induction
2331      /// variable. Notice that we can only optimize the 'trunc' case
2332      /// because: a. FP conversions lose precision, b. sext/zext may wrap,
2333      /// c. other casts depend on pointer size.
2334      if (CI->getOperand(0) == OldInduction &&
2335          it->getOpcode() == Instruction::Trunc) {
2336        Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
2337                                               CI->getType());
2338        Value *Broadcasted = getBroadcastInstrs(ScalarCast);
2339        for (unsigned Part = 0; Part < UF; ++Part)
2340          Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
2341        break;
2342      }
2343      /// Vectorize casts.
2344      Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
2345
2346      VectorParts &A = getVectorValue(it->getOperand(0));
2347      for (unsigned Part = 0; Part < UF; ++Part)
2348        Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
2349      break;
2350    }
2351
2352    case Instruction::Call: {
2353      // Ignore dbg intrinsics.
2354      if (isa<DbgInfoIntrinsic>(it))
2355        break;
2356
2357      Module *M = BB->getParent()->getParent();
2358      CallInst *CI = cast<CallInst>(it);
2359      Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2360      assert(ID && "Not an intrinsic call!");
2361      for (unsigned Part = 0; Part < UF; ++Part) {
2362        SmallVector<Value*, 4> Args;
2363        for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
2364          VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
2365          Args.push_back(Arg[Part]);
2366        }
2367        Type *Tys[] = { VectorType::get(CI->getType()->getScalarType(), VF) };
2368        Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2369        Entry[Part] = Builder.CreateCall(F, Args);
2370      }
2371      break;
2372    }
2373
2374    default:
2375      // All other instructions are unsupported. Scalarize them.
2376      scalarizeInstruction(it);
2377      break;
2378    }// end of switch.
2379  }// end of for_each instr.
2380}
2381
2382void InnerLoopVectorizer::updateAnalysis() {
2383  // Forget the original basic block.
2384  SE->forgetLoop(OrigLoop);
2385
2386  // Update the dominator tree information.
2387  assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2388         "Entry does not dominate exit.");
2389
2390  for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2391    DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2392  DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2393  DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2394  DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2395  DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2396  DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2397  DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2398
2399  DEBUG(DT->verifyAnalysis());
2400}
2401
2402bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2403  if (!EnableIfConversion)
2404    return false;
2405
2406  assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2407  std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2408
2409  // Collect the blocks that need predication.
2410  for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2411    BasicBlock *BB = LoopBlocks[i];
2412
2413    // We don't support switch statements inside loops.
2414    if (!isa<BranchInst>(BB->getTerminator()))
2415      return false;
2416
2417    // We must be able to predicate all blocks that need to be predicated.
2418    if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
2419      return false;
2420  }
2421
2422  // Check that we can actually speculate the hoistable loads.
2423  if (!LoadSpeculation.canHoistAllLoads())
2424    return false;
2425
2426  // We can if-convert this loop.
2427  return true;
2428}
2429
2430bool LoopVectorizationLegality::canVectorize() {
2431  assert(TheLoop->getLoopPreheader() && "No preheader!!");
2432
2433  // We can only vectorize innermost loops.
2434  if (TheLoop->getSubLoopsVector().size())
2435    return false;
2436
2437  // We must have a single backedge.
2438  if (TheLoop->getNumBackEdges() != 1)
2439    return false;
2440
2441  // We must have a single exiting block.
2442  if (!TheLoop->getExitingBlock())
2443    return false;
2444
2445  unsigned NumBlocks = TheLoop->getNumBlocks();
2446
2447  // Check if we can if-convert non single-bb loops.
2448  if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2449    DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2450    return false;
2451  }
2452
2453  // We need to have a loop header.
2454  BasicBlock *Latch = TheLoop->getLoopLatch();
2455  DEBUG(dbgs() << "LV: Found a loop: " <<
2456        TheLoop->getHeader()->getName() << "\n");
2457
2458  // ScalarEvolution needs to be able to find the exit count.
2459  const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2460  if (ExitCount == SE->getCouldNotCompute()) {
2461    DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2462    return false;
2463  }
2464
2465  // Do not loop-vectorize loops with a tiny trip count.
2466  unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2467  if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2468    DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2469          "This loop is not worth vectorizing.\n");
2470    return false;
2471  }
2472
2473  // Check if we can vectorize the instructions and CFG in this loop.
2474  if (!canVectorizeInstrs()) {
2475    DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2476    return false;
2477  }
2478
2479  // Go over each instruction and look at memory deps.
2480  if (!canVectorizeMemory()) {
2481    DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2482    return false;
2483  }
2484
2485  // Collect all of the variables that remain uniform after vectorization.
2486  collectLoopUniforms();
2487
2488  DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2489        (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2490        <<"!\n");
2491
2492  // Okay! We can vectorize. At this point we don't have any other mem analysis
2493  // which may limit our maximum vectorization factor, so just return true with
2494  // no restrictions.
2495  return true;
2496}
2497
2498static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) {
2499  if (Ty->isPointerTy())
2500    return DL.getIntPtrType(Ty->getContext());
2501  return Ty;
2502}
2503
2504static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) {
2505  Ty0 = convertPointerToIntegerType(DL, Ty0);
2506  Ty1 = convertPointerToIntegerType(DL, Ty1);
2507  if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
2508    return Ty0;
2509  return Ty1;
2510}
2511
2512bool LoopVectorizationLegality::canVectorizeInstrs() {
2513  BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2514  BasicBlock *Header = TheLoop->getHeader();
2515
2516  // If we marked the scalar loop as "already vectorized" then no need
2517  // to vectorize it again.
2518  if (Header->getTerminator()->getMetadata(AlreadyVectorizedMDName)) {
2519    DEBUG(dbgs() << "LV: This loop was vectorized before\n");
2520    return false;
2521  }
2522
2523  // Look for the attribute signaling the absence of NaNs.
2524  Function &F = *Header->getParent();
2525  if (F.hasFnAttribute("no-nans-fp-math"))
2526    HasFunNoNaNAttr = F.getAttributes().getAttribute(
2527      AttributeSet::FunctionIndex,
2528      "no-nans-fp-math").getValueAsString() == "true";
2529
2530  // For each block in the loop.
2531  for (Loop::block_iterator bb = TheLoop->block_begin(),
2532       be = TheLoop->block_end(); bb != be; ++bb) {
2533
2534    // Scan the instructions in the block and look for hazards.
2535    for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2536         ++it) {
2537
2538      if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2539        Type *PhiTy = Phi->getType();
2540        // Check that this PHI type is allowed.
2541        if (!PhiTy->isIntegerTy() &&
2542            !PhiTy->isFloatingPointTy() &&
2543            !PhiTy->isPointerTy()) {
2544          DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2545          return false;
2546        }
2547
2548        // If this PHINode is not in the header block, then we know that we
2549        // can convert it to select during if-conversion. No need to check if
2550        // the PHIs in this block are induction or reduction variables.
2551        if (*bb != Header)
2552          continue;
2553
2554        // We only allow if-converted PHIs with more than two incoming values.
2555        if (Phi->getNumIncomingValues() != 2) {
2556          DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2557          return false;
2558        }
2559
2560        // This is the value coming from the preheader.
2561        Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2562        // Check if this is an induction variable.
2563        InductionKind IK = isInductionVariable(Phi);
2564
2565        if (IK_NoInduction != IK) {
2566          // Get the widest type.
2567          if (!WidestIndTy)
2568            WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
2569          else
2570            WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
2571
2572          // Int inductions are special because we only allow one IV.
2573          if (IK == IK_IntInduction) {
2574            // Use the phi node with the widest type as induction. Use the last
2575            // one if there are multiple (no good reason for doing this other
2576            // than it is expedient).
2577            if (!Induction || PhiTy == WidestIndTy)
2578              Induction = Phi;
2579          }
2580
2581          DEBUG(dbgs() << "LV: Found an induction variable.\n");
2582          Inductions[Phi] = InductionInfo(StartValue, IK);
2583          continue;
2584        }
2585
2586        if (AddReductionVar(Phi, RK_IntegerAdd)) {
2587          DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2588          continue;
2589        }
2590        if (AddReductionVar(Phi, RK_IntegerMult)) {
2591          DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2592          continue;
2593        }
2594        if (AddReductionVar(Phi, RK_IntegerOr)) {
2595          DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2596          continue;
2597        }
2598        if (AddReductionVar(Phi, RK_IntegerAnd)) {
2599          DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2600          continue;
2601        }
2602        if (AddReductionVar(Phi, RK_IntegerXor)) {
2603          DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2604          continue;
2605        }
2606        if (AddReductionVar(Phi, RK_IntegerMinMax)) {
2607          DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
2608          continue;
2609        }
2610        if (AddReductionVar(Phi, RK_FloatMult)) {
2611          DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2612          continue;
2613        }
2614        if (AddReductionVar(Phi, RK_FloatAdd)) {
2615          DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2616          continue;
2617        }
2618        if (AddReductionVar(Phi, RK_FloatMinMax)) {
2619          DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<"\n");
2620          continue;
2621        }
2622
2623        DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2624        return false;
2625      }// end of PHI handling
2626
2627      // We still don't handle functions. However, we can ignore dbg intrinsic
2628      // calls and we do handle certain intrinsic and libm functions.
2629      CallInst *CI = dyn_cast<CallInst>(it);
2630      if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
2631        DEBUG(dbgs() << "LV: Found a call site.\n");
2632        return false;
2633      }
2634
2635      // Check that the instruction return type is vectorizable.
2636      if (!VectorType::isValidElementType(it->getType()) &&
2637          !it->getType()->isVoidTy()) {
2638        DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2639        return false;
2640      }
2641
2642      // Check that the stored type is vectorizable.
2643      if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2644        Type *T = ST->getValueOperand()->getType();
2645        if (!VectorType::isValidElementType(T))
2646          return false;
2647      }
2648
2649      // Reduction instructions are allowed to have exit users.
2650      // All other instructions must not have external users.
2651      if (!AllowedExit.count(it))
2652        //Check that all of the users of the loop are inside the BB.
2653        for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2654             I != E; ++I) {
2655          Instruction *U = cast<Instruction>(*I);
2656          // This user may be a reduction exit value.
2657          if (!TheLoop->contains(U)) {
2658            DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2659            return false;
2660          }
2661        }
2662    } // next instr.
2663
2664  }
2665
2666  if (!Induction) {
2667    DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2668    if (Inductions.empty())
2669      return false;
2670  }
2671
2672  return true;
2673}
2674
2675void LoopVectorizationLegality::collectLoopUniforms() {
2676  // We now know that the loop is vectorizable!
2677  // Collect variables that will remain uniform after vectorization.
2678  std::vector<Value*> Worklist;
2679  BasicBlock *Latch = TheLoop->getLoopLatch();
2680
2681  // Start with the conditional branch and walk up the block.
2682  Worklist.push_back(Latch->getTerminator()->getOperand(0));
2683
2684  while (Worklist.size()) {
2685    Instruction *I = dyn_cast<Instruction>(Worklist.back());
2686    Worklist.pop_back();
2687
2688    // Look at instructions inside this loop.
2689    // Stop when reaching PHI nodes.
2690    // TODO: we need to follow values all over the loop, not only in this block.
2691    if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2692      continue;
2693
2694    // This is a known uniform.
2695    Uniforms.insert(I);
2696
2697    // Insert all operands.
2698    Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
2699  }
2700}
2701
2702AliasAnalysis::Location
2703LoopVectorizationLegality::getLoadStoreLocation(Instruction *Inst) {
2704  if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
2705    return AA->getLocation(Store);
2706  else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
2707    return AA->getLocation(Load);
2708
2709  llvm_unreachable("Should be either load or store instruction");
2710}
2711
2712bool
2713LoopVectorizationLegality::hasPossibleGlobalWriteReorder(
2714                                                Value *Object,
2715                                                Instruction *Inst,
2716                                                AliasMultiMap& WriteObjects,
2717                                                unsigned MaxByteWidth) {
2718
2719  AliasAnalysis::Location ThisLoc = getLoadStoreLocation(Inst);
2720
2721  std::vector<Instruction*>::iterator
2722              it = WriteObjects[Object].begin(),
2723              end = WriteObjects[Object].end();
2724
2725  for (; it != end; ++it) {
2726    Instruction* I = *it;
2727    if (I == Inst)
2728      continue;
2729
2730    AliasAnalysis::Location ThatLoc = getLoadStoreLocation(I);
2731    if (AA->alias(ThisLoc.getWithNewSize(MaxByteWidth),
2732                  ThatLoc.getWithNewSize(MaxByteWidth)))
2733      return true;
2734  }
2735  return false;
2736}
2737
2738bool LoopVectorizationLegality::canVectorizeMemory() {
2739
2740  typedef SmallVector<Value*, 16> ValueVector;
2741  typedef SmallPtrSet<Value*, 16> ValueSet;
2742  // Holds the Load and Store *instructions*.
2743  ValueVector Loads;
2744  ValueVector Stores;
2745  PtrRtCheck.Pointers.clear();
2746  PtrRtCheck.Need = false;
2747
2748  const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
2749
2750  // For each block.
2751  for (Loop::block_iterator bb = TheLoop->block_begin(),
2752       be = TheLoop->block_end(); bb != be; ++bb) {
2753
2754    // Scan the BB and collect legal loads and stores.
2755    for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2756         ++it) {
2757
2758      // If this is a load, save it. If this instruction can read from memory
2759      // but is not a load, then we quit. Notice that we don't handle function
2760      // calls that read or write.
2761      if (it->mayReadFromMemory()) {
2762        LoadInst *Ld = dyn_cast<LoadInst>(it);
2763        if (!Ld) return false;
2764        if (!Ld->isSimple() && !IsAnnotatedParallel) {
2765          DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2766          return false;
2767        }
2768        Loads.push_back(Ld);
2769        continue;
2770      }
2771
2772      // Save 'store' instructions. Abort if other instructions write to memory.
2773      if (it->mayWriteToMemory()) {
2774        StoreInst *St = dyn_cast<StoreInst>(it);
2775        if (!St) return false;
2776        if (!St->isSimple() && !IsAnnotatedParallel) {
2777          DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2778          return false;
2779        }
2780        Stores.push_back(St);
2781      }
2782    } // next instr.
2783  } // next block.
2784
2785  // Now we have two lists that hold the loads and the stores.
2786  // Next, we find the pointers that they use.
2787
2788  // Check if we see any stores. If there are no stores, then we don't
2789  // care if the pointers are *restrict*.
2790  if (!Stores.size()) {
2791    DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2792    return true;
2793  }
2794
2795  // Holds the read and read-write *pointers* that we find. These maps hold
2796  // unique values for pointers (so no need for multi-map).
2797  AliasMap Reads;
2798  AliasMap ReadWrites;
2799
2800  // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2801  // multiple times on the same object. If the ptr is accessed twice, once
2802  // for read and once for write, it will only appear once (on the write
2803  // list). This is okay, since we are going to check for conflicts between
2804  // writes and between reads and writes, but not between reads and reads.
2805  ValueSet Seen;
2806
2807  ValueVector::iterator I, IE;
2808  for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2809    StoreInst *ST = cast<StoreInst>(*I);
2810    Value* Ptr = ST->getPointerOperand();
2811
2812    if (isUniform(Ptr)) {
2813      DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2814      return false;
2815    }
2816
2817    // If we did *not* see this pointer before, insert it to
2818    // the read-write list. At this phase it is only a 'write' list.
2819    if (Seen.insert(Ptr))
2820      ReadWrites.insert(std::make_pair(Ptr, ST));
2821  }
2822
2823  if (IsAnnotatedParallel) {
2824    DEBUG(dbgs()
2825          << "LV: A loop annotated parallel, ignore memory dependency "
2826          << "checks.\n");
2827    return true;
2828  }
2829
2830  for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2831    LoadInst *LD = cast<LoadInst>(*I);
2832    Value* Ptr = LD->getPointerOperand();
2833    // If we did *not* see this pointer before, insert it to the
2834    // read list. If we *did* see it before, then it is already in
2835    // the read-write list. This allows us to vectorize expressions
2836    // such as A[i] += x;  Because the address of A[i] is a read-write
2837    // pointer. This only works if the index of A[i] is consecutive.
2838    // If the address of i is unknown (for example A[B[i]]) then we may
2839    // read a few words, modify, and write a few words, and some of the
2840    // words may be written to the same address.
2841    if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2842      Reads.insert(std::make_pair(Ptr, LD));
2843  }
2844
2845  // If we write (or read-write) to a single destination and there are no
2846  // other reads in this loop then is it safe to vectorize.
2847  if (ReadWrites.size() == 1 && Reads.size() == 0) {
2848    DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2849    return true;
2850  }
2851
2852  unsigned NumReadPtrs = 0;
2853  unsigned NumWritePtrs = 0;
2854
2855  // Find pointers with computable bounds. We are going to use this information
2856  // to place a runtime bound check.
2857  bool CanDoRT = true;
2858  AliasMap::iterator MI, ME;
2859  for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
2860    Value *V = (*MI).first;
2861    if (hasComputableBounds(V)) {
2862      PtrRtCheck.insert(SE, TheLoop, V, true);
2863      NumWritePtrs++;
2864      DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2865    } else {
2866      CanDoRT = false;
2867      break;
2868    }
2869  }
2870  for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
2871    Value *V = (*MI).first;
2872    if (hasComputableBounds(V)) {
2873      PtrRtCheck.insert(SE, TheLoop, V, false);
2874      NumReadPtrs++;
2875      DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2876    } else {
2877      CanDoRT = false;
2878      break;
2879    }
2880  }
2881
2882  // Check that we did not collect too many pointers or found a
2883  // unsizeable pointer.
2884  unsigned NumComparisons = (NumWritePtrs * (NumReadPtrs + NumWritePtrs - 1));
2885  DEBUG(dbgs() << "LV: We need to compare " << NumComparisons << " ptrs.\n");
2886  if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
2887    PtrRtCheck.reset();
2888    CanDoRT = false;
2889  }
2890
2891  if (CanDoRT) {
2892    DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2893  }
2894
2895  bool NeedRTCheck = false;
2896
2897  // Biggest vectorized access possible, vector width * unroll factor.
2898  // TODO: We're being very pessimistic here, find a way to know the
2899  // real access width before getting here.
2900  unsigned MaxByteWidth = (TTI->getRegisterBitWidth(true) / 8) *
2901                           TTI->getMaximumUnrollFactor();
2902  // Now that the pointers are in two lists (Reads and ReadWrites), we
2903  // can check that there are no conflicts between each of the writes and
2904  // between the writes to the reads.
2905  // Note that WriteObjects duplicates the stores (indexed now by underlying
2906  // objects) to avoid pointing to elements inside ReadWrites.
2907  // TODO: Maybe create a new type where they can interact without duplication.
2908  AliasMultiMap WriteObjects;
2909  ValueVector TempObjects;
2910
2911  // Check that the read-writes do not conflict with other read-write
2912  // pointers.
2913  bool AllWritesIdentified = true;
2914  for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
2915    Value *Val = (*MI).first;
2916    Instruction *Inst = (*MI).second;
2917
2918    GetUnderlyingObjects(Val, TempObjects, DL);
2919    for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
2920         UI != UE; ++UI) {
2921      if (!isIdentifiedObject(*UI)) {
2922        DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **UI <<"\n");
2923        NeedRTCheck = true;
2924        AllWritesIdentified = false;
2925      }
2926
2927      // Never seen it before, can't alias.
2928      if (WriteObjects[*UI].empty()) {
2929        DEBUG(dbgs() << "LV: Adding Underlying value:" << **UI <<"\n");
2930        WriteObjects[*UI].push_back(Inst);
2931        continue;
2932      }
2933      // Direct alias found.
2934      if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
2935        DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2936              << **UI <<"\n");
2937        return false;
2938      }
2939      DEBUG(dbgs() << "LV: Found a conflicting global value:"
2940            << **UI <<"\n");
2941      DEBUG(dbgs() << "LV: While examining store:" << *Inst <<"\n");
2942      DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
2943
2944      // If global alias, make sure they do alias.
2945      if (hasPossibleGlobalWriteReorder(*UI,
2946                                        Inst,
2947                                        WriteObjects,
2948                                        MaxByteWidth)) {
2949        DEBUG(dbgs() << "LV: Found a possible write-write reorder:" << **UI
2950                     << "\n");
2951        return false;
2952      }
2953
2954      // Didn't alias, insert into map for further reference.
2955      WriteObjects[*UI].push_back(Inst);
2956    }
2957    TempObjects.clear();
2958  }
2959
2960  /// Check that the reads don't conflict with the read-writes.
2961  for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
2962    Value *Val = (*MI).first;
2963    GetUnderlyingObjects(Val, TempObjects, DL);
2964    for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
2965         UI != UE; ++UI) {
2966      // If all of the writes are identified then we don't care if the read
2967      // pointer is identified or not.
2968      if (!AllWritesIdentified && !isIdentifiedObject(*UI)) {
2969        DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **UI <<"\n");
2970        NeedRTCheck = true;
2971      }
2972
2973      // Never seen it before, can't alias.
2974      if (WriteObjects[*UI].empty())
2975        continue;
2976      // Direct alias found.
2977      if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
2978        DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2979              << **UI <<"\n");
2980        return false;
2981      }
2982      DEBUG(dbgs() << "LV: Found a global value:  "
2983            << **UI <<"\n");
2984      Instruction *Inst = (*MI).second;
2985      DEBUG(dbgs() << "LV: While examining load:" << *Inst <<"\n");
2986      DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
2987
2988      // If global alias, make sure they do alias.
2989      if (hasPossibleGlobalWriteReorder(*UI,
2990                                        Inst,
2991                                        WriteObjects,
2992                                        MaxByteWidth)) {
2993        DEBUG(dbgs() << "LV: Found a possible read-write reorder:" << **UI
2994                     << "\n");
2995        return false;
2996      }
2997    }
2998    TempObjects.clear();
2999  }
3000
3001  PtrRtCheck.Need = NeedRTCheck;
3002  if (NeedRTCheck && !CanDoRT) {
3003    DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
3004          "the array bounds.\n");
3005    PtrRtCheck.reset();
3006    return false;
3007  }
3008
3009  DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
3010        " need a runtime memory check.\n");
3011  return true;
3012}
3013
3014static bool hasMultipleUsesOf(Instruction *I,
3015                              SmallPtrSet<Instruction *, 8> &Insts) {
3016  unsigned NumUses = 0;
3017  for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
3018    if (Insts.count(dyn_cast<Instruction>(*Use)))
3019      ++NumUses;
3020    if (NumUses > 1)
3021      return true;
3022  }
3023
3024  return false;
3025}
3026
3027static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
3028  for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
3029    if (!Set.count(dyn_cast<Instruction>(*Use)))
3030      return false;
3031  return true;
3032}
3033
3034bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
3035                                                ReductionKind Kind) {
3036  if (Phi->getNumIncomingValues() != 2)
3037    return false;
3038
3039  // Reduction variables are only found in the loop header block.
3040  if (Phi->getParent() != TheLoop->getHeader())
3041    return false;
3042
3043  // Obtain the reduction start value from the value that comes from the loop
3044  // preheader.
3045  Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
3046
3047  // ExitInstruction is the single value which is used outside the loop.
3048  // We only allow for a single reduction value to be used outside the loop.
3049  // This includes users of the reduction, variables (which form a cycle
3050  // which ends in the phi node).
3051  Instruction *ExitInstruction = 0;
3052  // Indicates that we found a reduction operation in our scan.
3053  bool FoundReduxOp = false;
3054
3055  // We start with the PHI node and scan for all of the users of this
3056  // instruction. All users must be instructions that can be used as reduction
3057  // variables (such as ADD). We must have a single out-of-block user. The cycle
3058  // must include the original PHI.
3059  bool FoundStartPHI = false;
3060
3061  // To recognize min/max patterns formed by a icmp select sequence, we store
3062  // the number of instruction we saw from the recognized min/max pattern,
3063  //  to make sure we only see exactly the two instructions.
3064  unsigned NumCmpSelectPatternInst = 0;
3065  ReductionInstDesc ReduxDesc(false, 0);
3066
3067  SmallPtrSet<Instruction *, 8> VisitedInsts;
3068  SmallVector<Instruction *, 8> Worklist;
3069  Worklist.push_back(Phi);
3070  VisitedInsts.insert(Phi);
3071
3072  // A value in the reduction can be used:
3073  //  - By the reduction:
3074  //      - Reduction operation:
3075  //        - One use of reduction value (safe).
3076  //        - Multiple use of reduction value (not safe).
3077  //      - PHI:
3078  //        - All uses of the PHI must be the reduction (safe).
3079  //        - Otherwise, not safe.
3080  //  - By one instruction outside of the loop (safe).
3081  //  - By further instructions outside of the loop (not safe).
3082  //  - By an instruction that is not part of the reduction (not safe).
3083  //    This is either:
3084  //      * An instruction type other than PHI or the reduction operation.
3085  //      * A PHI in the header other than the initial PHI.
3086  while (!Worklist.empty()) {
3087    Instruction *Cur = Worklist.back();
3088    Worklist.pop_back();
3089
3090    // No Users.
3091    // If the instruction has no users then this is a broken chain and can't be
3092    // a reduction variable.
3093    if (Cur->use_empty())
3094      return false;
3095
3096    bool IsAPhi = isa<PHINode>(Cur);
3097
3098    // A header PHI use other than the original PHI.
3099    if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
3100      return false;
3101
3102    // Reductions of instructions such as Div, and Sub is only possible if the
3103    // LHS is the reduction variable.
3104    if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
3105        !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
3106        !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
3107      return false;
3108
3109    // Any reduction instruction must be of one of the allowed kinds.
3110    ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
3111    if (!ReduxDesc.IsReduction)
3112      return false;
3113
3114    // A reduction operation must only have one use of the reduction value.
3115    if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
3116        hasMultipleUsesOf(Cur, VisitedInsts))
3117      return false;
3118
3119    // All inputs to a PHI node must be a reduction value.
3120    if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
3121      return false;
3122
3123    if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
3124                                     isa<SelectInst>(Cur)))
3125      ++NumCmpSelectPatternInst;
3126    if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
3127                                   isa<SelectInst>(Cur)))
3128      ++NumCmpSelectPatternInst;
3129
3130    // Check  whether we found a reduction operator.
3131    FoundReduxOp |= !IsAPhi;
3132
3133    // Process users of current instruction. Push non PHI nodes after PHI nodes
3134    // onto the stack. This way we are going to have seen all inputs to PHI
3135    // nodes once we get to them.
3136    SmallVector<Instruction *, 8> NonPHIs;
3137    SmallVector<Instruction *, 8> PHIs;
3138    for (Value::use_iterator UI = Cur->use_begin(), E = Cur->use_end(); UI != E;
3139         ++UI) {
3140      Instruction *Usr = cast<Instruction>(*UI);
3141
3142      // Check if we found the exit user.
3143      BasicBlock *Parent = Usr->getParent();
3144      if (!TheLoop->contains(Parent)) {
3145        // Exit if you find multiple outside users.
3146        if (ExitInstruction != 0)
3147          return false;
3148        ExitInstruction = Cur;
3149        continue;
3150      }
3151
3152      // Process instructions only once (termination).
3153      if (VisitedInsts.insert(Usr)) {
3154        if (isa<PHINode>(Usr))
3155          PHIs.push_back(Usr);
3156        else
3157          NonPHIs.push_back(Usr);
3158      }
3159      // Remember that we completed the cycle.
3160      if (Usr == Phi)
3161        FoundStartPHI = true;
3162    }
3163    Worklist.append(PHIs.begin(), PHIs.end());
3164    Worklist.append(NonPHIs.begin(), NonPHIs.end());
3165  }
3166
3167  // This means we have seen one but not the other instruction of the
3168  // pattern or more than just a select and cmp.
3169  if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
3170      NumCmpSelectPatternInst != 2)
3171    return false;
3172
3173  if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
3174    return false;
3175
3176  // We found a reduction var if we have reached the original phi node and we
3177  // only have a single instruction with out-of-loop users.
3178
3179  // This instruction is allowed to have out-of-loop users.
3180  AllowedExit.insert(ExitInstruction);
3181
3182  // Save the description of this reduction variable.
3183  ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
3184                         ReduxDesc.MinMaxKind);
3185  Reductions[Phi] = RD;
3186  // We've ended the cycle. This is a reduction variable if we have an
3187  // outside user and it has a binary op.
3188
3189  return true;
3190}
3191
3192/// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
3193/// pattern corresponding to a min(X, Y) or max(X, Y).
3194LoopVectorizationLegality::ReductionInstDesc
3195LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
3196                                                    ReductionInstDesc &Prev) {
3197
3198  assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
3199         "Expect a select instruction");
3200  Instruction *Cmp = 0;
3201  SelectInst *Select = 0;
3202
3203  // We must handle the select(cmp()) as a single instruction. Advance to the
3204  // select.
3205  if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
3206    if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->use_begin())))
3207      return ReductionInstDesc(false, I);
3208    return ReductionInstDesc(Select, Prev.MinMaxKind);
3209  }
3210
3211  // Only handle single use cases for now.
3212  if (!(Select = dyn_cast<SelectInst>(I)))
3213    return ReductionInstDesc(false, I);
3214  if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
3215      !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
3216    return ReductionInstDesc(false, I);
3217  if (!Cmp->hasOneUse())
3218    return ReductionInstDesc(false, I);
3219
3220  Value *CmpLeft;
3221  Value *CmpRight;
3222
3223  // Look for a min/max pattern.
3224  if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3225    return ReductionInstDesc(Select, MRK_UIntMin);
3226  else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3227    return ReductionInstDesc(Select, MRK_UIntMax);
3228  else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3229    return ReductionInstDesc(Select, MRK_SIntMax);
3230  else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3231    return ReductionInstDesc(Select, MRK_SIntMin);
3232  else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3233    return ReductionInstDesc(Select, MRK_FloatMin);
3234  else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3235    return ReductionInstDesc(Select, MRK_FloatMax);
3236  else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3237    return ReductionInstDesc(Select, MRK_FloatMin);
3238  else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3239    return ReductionInstDesc(Select, MRK_FloatMax);
3240
3241  return ReductionInstDesc(false, I);
3242}
3243
3244LoopVectorizationLegality::ReductionInstDesc
3245LoopVectorizationLegality::isReductionInstr(Instruction *I,
3246                                            ReductionKind Kind,
3247                                            ReductionInstDesc &Prev) {
3248  bool FP = I->getType()->isFloatingPointTy();
3249  bool FastMath = (FP && I->isCommutative() && I->isAssociative());
3250  switch (I->getOpcode()) {
3251  default:
3252    return ReductionInstDesc(false, I);
3253  case Instruction::PHI:
3254      if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
3255                 Kind != RK_FloatMinMax))
3256        return ReductionInstDesc(false, I);
3257    return ReductionInstDesc(I, Prev.MinMaxKind);
3258  case Instruction::Sub:
3259  case Instruction::Add:
3260    return ReductionInstDesc(Kind == RK_IntegerAdd, I);
3261  case Instruction::Mul:
3262    return ReductionInstDesc(Kind == RK_IntegerMult, I);
3263  case Instruction::And:
3264    return ReductionInstDesc(Kind == RK_IntegerAnd, I);
3265  case Instruction::Or:
3266    return ReductionInstDesc(Kind == RK_IntegerOr, I);
3267  case Instruction::Xor:
3268    return ReductionInstDesc(Kind == RK_IntegerXor, I);
3269  case Instruction::FMul:
3270    return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
3271  case Instruction::FAdd:
3272    return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
3273  case Instruction::FCmp:
3274  case Instruction::ICmp:
3275  case Instruction::Select:
3276    if (Kind != RK_IntegerMinMax &&
3277        (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
3278      return ReductionInstDesc(false, I);
3279    return isMinMaxSelectCmpPattern(I, Prev);
3280  }
3281}
3282
3283LoopVectorizationLegality::InductionKind
3284LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
3285  Type *PhiTy = Phi->getType();
3286  // We only handle integer and pointer inductions variables.
3287  if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
3288    return IK_NoInduction;
3289
3290  // Check that the PHI is consecutive.
3291  const SCEV *PhiScev = SE->getSCEV(Phi);
3292  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
3293  if (!AR) {
3294    DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
3295    return IK_NoInduction;
3296  }
3297  const SCEV *Step = AR->getStepRecurrence(*SE);
3298
3299  // Integer inductions need to have a stride of one.
3300  if (PhiTy->isIntegerTy()) {
3301    if (Step->isOne())
3302      return IK_IntInduction;
3303    if (Step->isAllOnesValue())
3304      return IK_ReverseIntInduction;
3305    return IK_NoInduction;
3306  }
3307
3308  // Calculate the pointer stride and check if it is consecutive.
3309  const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
3310  if (!C)
3311    return IK_NoInduction;
3312
3313  assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
3314  uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
3315  if (C->getValue()->equalsInt(Size))
3316    return IK_PtrInduction;
3317  else if (C->getValue()->equalsInt(0 - Size))
3318    return IK_ReversePtrInduction;
3319
3320  return IK_NoInduction;
3321}
3322
3323bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
3324  Value *In0 = const_cast<Value*>(V);
3325  PHINode *PN = dyn_cast_or_null<PHINode>(In0);
3326  if (!PN)
3327    return false;
3328
3329  return Inductions.count(PN);
3330}
3331
3332bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
3333  assert(TheLoop->contains(BB) && "Unknown block used");
3334
3335  // Blocks that do not dominate the latch need predication.
3336  BasicBlock* Latch = TheLoop->getLoopLatch();
3337  return !DT->dominates(BB, Latch);
3338}
3339
3340bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
3341  for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3342    // We might be able to hoist the load.
3343    if (it->mayReadFromMemory() && !LoadSpeculation.isHoistableLoad(it))
3344      return false;
3345
3346    // We don't predicate stores at the moment.
3347    if (it->mayWriteToMemory() || it->mayThrow())
3348      return false;
3349
3350    // The instructions below can trap.
3351    switch (it->getOpcode()) {
3352    default: continue;
3353    case Instruction::UDiv:
3354    case Instruction::SDiv:
3355    case Instruction::URem:
3356    case Instruction::SRem:
3357             return false;
3358    }
3359  }
3360
3361  return true;
3362}
3363
3364bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
3365  const SCEV *PhiScev = SE->getSCEV(Ptr);
3366  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
3367  if (!AR)
3368    return false;
3369
3370  return AR->isAffine();
3371}
3372
3373LoopVectorizationCostModel::VectorizationFactor
3374LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
3375                                                      unsigned UserVF) {
3376  // Width 1 means no vectorize
3377  VectorizationFactor Factor = { 1U, 0U };
3378  if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
3379    DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
3380    return Factor;
3381  }
3382
3383  // Find the trip count.
3384  unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
3385  DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
3386
3387  unsigned WidestType = getWidestType();
3388  unsigned WidestRegister = TTI.getRegisterBitWidth(true);
3389  unsigned MaxVectorSize = WidestRegister / WidestType;
3390  DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
3391  DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
3392
3393  if (MaxVectorSize == 0) {
3394    DEBUG(dbgs() << "LV: The target has no vector registers.\n");
3395    MaxVectorSize = 1;
3396  }
3397
3398  assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
3399         " into one vector!");
3400
3401  unsigned VF = MaxVectorSize;
3402
3403  // If we optimize the program for size, avoid creating the tail loop.
3404  if (OptForSize) {
3405    // If we are unable to calculate the trip count then don't try to vectorize.
3406    if (TC < 2) {
3407      DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
3408      return Factor;
3409    }
3410
3411    // Find the maximum SIMD width that can fit within the trip count.
3412    VF = TC % MaxVectorSize;
3413
3414    if (VF == 0)
3415      VF = MaxVectorSize;
3416
3417    // If the trip count that we found modulo the vectorization factor is not
3418    // zero then we require a tail.
3419    if (VF < 2) {
3420      DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
3421      return Factor;
3422    }
3423  }
3424
3425  if (UserVF != 0) {
3426    assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
3427    DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
3428
3429    Factor.Width = UserVF;
3430    return Factor;
3431  }
3432
3433  float Cost = expectedCost(1);
3434  unsigned Width = 1;
3435  DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
3436  for (unsigned i=2; i <= VF; i*=2) {
3437    // Notice that the vector loop needs to be executed less times, so
3438    // we need to divide the cost of the vector loops by the width of
3439    // the vector elements.
3440    float VectorCost = expectedCost(i) / (float)i;
3441    DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
3442          (int)VectorCost << ".\n");
3443    if (VectorCost < Cost) {
3444      Cost = VectorCost;
3445      Width = i;
3446    }
3447  }
3448
3449  DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
3450  Factor.Width = Width;
3451  Factor.Cost = Width * Cost;
3452  return Factor;
3453}
3454
3455unsigned LoopVectorizationCostModel::getWidestType() {
3456  unsigned MaxWidth = 8;
3457
3458  // For each block.
3459  for (Loop::block_iterator bb = TheLoop->block_begin(),
3460       be = TheLoop->block_end(); bb != be; ++bb) {
3461    BasicBlock *BB = *bb;
3462
3463    // For each instruction in the loop.
3464    for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3465      Type *T = it->getType();
3466
3467      // Only examine Loads, Stores and PHINodes.
3468      if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
3469        continue;
3470
3471      // Examine PHI nodes that are reduction variables.
3472      if (PHINode *PN = dyn_cast<PHINode>(it))
3473        if (!Legal->getReductionVars()->count(PN))
3474          continue;
3475
3476      // Examine the stored values.
3477      if (StoreInst *ST = dyn_cast<StoreInst>(it))
3478        T = ST->getValueOperand()->getType();
3479
3480      // Ignore loaded pointer types and stored pointer types that are not
3481      // consecutive. However, we do want to take consecutive stores/loads of
3482      // pointer vectors into account.
3483      if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
3484        continue;
3485
3486      MaxWidth = std::max(MaxWidth,
3487                          (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
3488    }
3489  }
3490
3491  return MaxWidth;
3492}
3493
3494unsigned
3495LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
3496                                               unsigned UserUF,
3497                                               unsigned VF,
3498                                               unsigned LoopCost) {
3499
3500  // -- The unroll heuristics --
3501  // We unroll the loop in order to expose ILP and reduce the loop overhead.
3502  // There are many micro-architectural considerations that we can't predict
3503  // at this level. For example frontend pressure (on decode or fetch) due to
3504  // code size, or the number and capabilities of the execution ports.
3505  //
3506  // We use the following heuristics to select the unroll factor:
3507  // 1. If the code has reductions the we unroll in order to break the cross
3508  // iteration dependency.
3509  // 2. If the loop is really small then we unroll in order to reduce the loop
3510  // overhead.
3511  // 3. We don't unroll if we think that we will spill registers to memory due
3512  // to the increased register pressure.
3513
3514  // Use the user preference, unless 'auto' is selected.
3515  if (UserUF != 0)
3516    return UserUF;
3517
3518  // When we optimize for size we don't unroll.
3519  if (OptForSize)
3520    return 1;
3521
3522  // Do not unroll loops with a relatively small trip count.
3523  unsigned TC = SE->getSmallConstantTripCount(TheLoop,
3524                                              TheLoop->getLoopLatch());
3525  if (TC > 1 && TC < TinyTripCountUnrollThreshold)
3526    return 1;
3527
3528  unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
3529  DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
3530        " vector registers\n");
3531
3532  LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
3533  // We divide by these constants so assume that we have at least one
3534  // instruction that uses at least one register.
3535  R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
3536  R.NumInstructions = std::max(R.NumInstructions, 1U);
3537
3538  // We calculate the unroll factor using the following formula.
3539  // Subtract the number of loop invariants from the number of available
3540  // registers. These registers are used by all of the unrolled instances.
3541  // Next, divide the remaining registers by the number of registers that is
3542  // required by the loop, in order to estimate how many parallel instances
3543  // fit without causing spills.
3544  unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
3545
3546  // Clamp the unroll factor ranges to reasonable factors.
3547  unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
3548
3549  // If we did not calculate the cost for VF (because the user selected the VF)
3550  // then we calculate the cost of VF here.
3551  if (LoopCost == 0)
3552    LoopCost = expectedCost(VF);
3553
3554  // Clamp the calculated UF to be between the 1 and the max unroll factor
3555  // that the target allows.
3556  if (UF > MaxUnrollSize)
3557    UF = MaxUnrollSize;
3558  else if (UF < 1)
3559    UF = 1;
3560
3561  if (Legal->getReductionVars()->size()) {
3562    DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
3563    return UF;
3564  }
3565
3566  // We want to unroll tiny loops in order to reduce the loop overhead.
3567  // We assume that the cost overhead is 1 and we use the cost model
3568  // to estimate the cost of the loop and unroll until the cost of the
3569  // loop overhead is about 5% of the cost of the loop.
3570  DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
3571  if (LoopCost < 20) {
3572    DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
3573    unsigned NewUF = 20/LoopCost + 1;
3574    return std::min(NewUF, UF);
3575  }
3576
3577  DEBUG(dbgs() << "LV: Not Unrolling. \n");
3578  return 1;
3579}
3580
3581LoopVectorizationCostModel::RegisterUsage
3582LoopVectorizationCostModel::calculateRegisterUsage() {
3583  // This function calculates the register usage by measuring the highest number
3584  // of values that are alive at a single location. Obviously, this is a very
3585  // rough estimation. We scan the loop in a topological order in order and
3586  // assign a number to each instruction. We use RPO to ensure that defs are
3587  // met before their users. We assume that each instruction that has in-loop
3588  // users starts an interval. We record every time that an in-loop value is
3589  // used, so we have a list of the first and last occurrences of each
3590  // instruction. Next, we transpose this data structure into a multi map that
3591  // holds the list of intervals that *end* at a specific location. This multi
3592  // map allows us to perform a linear search. We scan the instructions linearly
3593  // and record each time that a new interval starts, by placing it in a set.
3594  // If we find this value in the multi-map then we remove it from the set.
3595  // The max register usage is the maximum size of the set.
3596  // We also search for instructions that are defined outside the loop, but are
3597  // used inside the loop. We need this number separately from the max-interval
3598  // usage number because when we unroll, loop-invariant values do not take
3599  // more register.
3600  LoopBlocksDFS DFS(TheLoop);
3601  DFS.perform(LI);
3602
3603  RegisterUsage R;
3604  R.NumInstructions = 0;
3605
3606  // Each 'key' in the map opens a new interval. The values
3607  // of the map are the index of the 'last seen' usage of the
3608  // instruction that is the key.
3609  typedef DenseMap<Instruction*, unsigned> IntervalMap;
3610  // Maps instruction to its index.
3611  DenseMap<unsigned, Instruction*> IdxToInstr;
3612  // Marks the end of each interval.
3613  IntervalMap EndPoint;
3614  // Saves the list of instruction indices that are used in the loop.
3615  SmallSet<Instruction*, 8> Ends;
3616  // Saves the list of values that are used in the loop but are
3617  // defined outside the loop, such as arguments and constants.
3618  SmallPtrSet<Value*, 8> LoopInvariants;
3619
3620  unsigned Index = 0;
3621  for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3622       be = DFS.endRPO(); bb != be; ++bb) {
3623    R.NumInstructions += (*bb)->size();
3624    for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3625         ++it) {
3626      Instruction *I = it;
3627      IdxToInstr[Index++] = I;
3628
3629      // Save the end location of each USE.
3630      for (unsigned i = 0; i < I->getNumOperands(); ++i) {
3631        Value *U = I->getOperand(i);
3632        Instruction *Instr = dyn_cast<Instruction>(U);
3633
3634        // Ignore non-instruction values such as arguments, constants, etc.
3635        if (!Instr) continue;
3636
3637        // If this instruction is outside the loop then record it and continue.
3638        if (!TheLoop->contains(Instr)) {
3639          LoopInvariants.insert(Instr);
3640          continue;
3641        }
3642
3643        // Overwrite previous end points.
3644        EndPoint[Instr] = Index;
3645        Ends.insert(Instr);
3646      }
3647    }
3648  }
3649
3650  // Saves the list of intervals that end with the index in 'key'.
3651  typedef SmallVector<Instruction*, 2> InstrList;
3652  DenseMap<unsigned, InstrList> TransposeEnds;
3653
3654  // Transpose the EndPoints to a list of values that end at each index.
3655  for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
3656       it != e; ++it)
3657    TransposeEnds[it->second].push_back(it->first);
3658
3659  SmallSet<Instruction*, 8> OpenIntervals;
3660  unsigned MaxUsage = 0;
3661
3662
3663  DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
3664  for (unsigned int i = 0; i < Index; ++i) {
3665    Instruction *I = IdxToInstr[i];
3666    // Ignore instructions that are never used within the loop.
3667    if (!Ends.count(I)) continue;
3668
3669    // Remove all of the instructions that end at this location.
3670    InstrList &List = TransposeEnds[i];
3671    for (unsigned int j=0, e = List.size(); j < e; ++j)
3672      OpenIntervals.erase(List[j]);
3673
3674    // Count the number of live interals.
3675    MaxUsage = std::max(MaxUsage, OpenIntervals.size());
3676
3677    DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
3678          OpenIntervals.size() <<"\n");
3679
3680    // Add the current instruction to the list of open intervals.
3681    OpenIntervals.insert(I);
3682  }
3683
3684  unsigned Invariant = LoopInvariants.size();
3685  DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
3686  DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
3687  DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
3688
3689  R.LoopInvariantRegs = Invariant;
3690  R.MaxLocalUsers = MaxUsage;
3691  return R;
3692}
3693
3694unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
3695  unsigned Cost = 0;
3696
3697  // For each block.
3698  for (Loop::block_iterator bb = TheLoop->block_begin(),
3699       be = TheLoop->block_end(); bb != be; ++bb) {
3700    unsigned BlockCost = 0;
3701    BasicBlock *BB = *bb;
3702
3703    // For each instruction in the old loop.
3704    for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3705      // Skip dbg intrinsics.
3706      if (isa<DbgInfoIntrinsic>(it))
3707        continue;
3708
3709      unsigned C = getInstructionCost(it, VF);
3710      Cost += C;
3711      DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
3712            VF << " For instruction: "<< *it << "\n");
3713    }
3714
3715    // We assume that if-converted blocks have a 50% chance of being executed.
3716    // When the code is scalar then some of the blocks are avoided due to CF.
3717    // When the code is vectorized we execute all code paths.
3718    if (Legal->blockNeedsPredication(*bb) && VF == 1)
3719      BlockCost /= 2;
3720
3721    Cost += BlockCost;
3722  }
3723
3724  return Cost;
3725}
3726
3727unsigned
3728LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
3729  // If we know that this instruction will remain uniform, check the cost of
3730  // the scalar version.
3731  if (Legal->isUniformAfterVectorization(I))
3732    VF = 1;
3733
3734  Type *RetTy = I->getType();
3735  Type *VectorTy = ToVectorTy(RetTy, VF);
3736
3737  // TODO: We need to estimate the cost of intrinsic calls.
3738  switch (I->getOpcode()) {
3739  case Instruction::GetElementPtr:
3740    // We mark this instruction as zero-cost because the cost of GEPs in
3741    // vectorized code depends on whether the corresponding memory instruction
3742    // is scalarized or not. Therefore, we handle GEPs with the memory
3743    // instruction cost.
3744    return 0;
3745  case Instruction::Br: {
3746    return TTI.getCFInstrCost(I->getOpcode());
3747  }
3748  case Instruction::PHI:
3749    //TODO: IF-converted IFs become selects.
3750    return 0;
3751  case Instruction::Add:
3752  case Instruction::FAdd:
3753  case Instruction::Sub:
3754  case Instruction::FSub:
3755  case Instruction::Mul:
3756  case Instruction::FMul:
3757  case Instruction::UDiv:
3758  case Instruction::SDiv:
3759  case Instruction::FDiv:
3760  case Instruction::URem:
3761  case Instruction::SRem:
3762  case Instruction::FRem:
3763  case Instruction::Shl:
3764  case Instruction::LShr:
3765  case Instruction::AShr:
3766  case Instruction::And:
3767  case Instruction::Or:
3768  case Instruction::Xor: {
3769    // Certain instructions can be cheaper to vectorize if they have a constant
3770    // second vector operand. One example of this are shifts on x86.
3771    TargetTransformInfo::OperandValueKind Op1VK =
3772      TargetTransformInfo::OK_AnyValue;
3773    TargetTransformInfo::OperandValueKind Op2VK =
3774      TargetTransformInfo::OK_AnyValue;
3775
3776    if (isa<ConstantInt>(I->getOperand(1)))
3777      Op2VK = TargetTransformInfo::OK_UniformConstantValue;
3778
3779    return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
3780  }
3781  case Instruction::Select: {
3782    SelectInst *SI = cast<SelectInst>(I);
3783    const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
3784    bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
3785    Type *CondTy = SI->getCondition()->getType();
3786    if (!ScalarCond)
3787      CondTy = VectorType::get(CondTy, VF);
3788
3789    return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
3790  }
3791  case Instruction::ICmp:
3792  case Instruction::FCmp: {
3793    Type *ValTy = I->getOperand(0)->getType();
3794    VectorTy = ToVectorTy(ValTy, VF);
3795    return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
3796  }
3797  case Instruction::Store:
3798  case Instruction::Load: {
3799    StoreInst *SI = dyn_cast<StoreInst>(I);
3800    LoadInst *LI = dyn_cast<LoadInst>(I);
3801    Type *ValTy = (SI ? SI->getValueOperand()->getType() :
3802                   LI->getType());
3803    VectorTy = ToVectorTy(ValTy, VF);
3804
3805    unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
3806    unsigned AS = SI ? SI->getPointerAddressSpace() :
3807      LI->getPointerAddressSpace();
3808    Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
3809    // We add the cost of address computation here instead of with the gep
3810    // instruction because only here we know whether the operation is
3811    // scalarized.
3812    if (VF == 1)
3813      return TTI.getAddressComputationCost(VectorTy) +
3814        TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3815
3816    // Scalarized loads/stores.
3817    int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
3818    bool Reverse = ConsecutiveStride < 0;
3819    unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
3820    unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
3821    if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
3822      unsigned Cost = 0;
3823      // The cost of extracting from the value vector and pointer vector.
3824      Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
3825      for (unsigned i = 0; i < VF; ++i) {
3826        //  The cost of extracting the pointer operand.
3827        Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3828        // In case of STORE, the cost of ExtractElement from the vector.
3829        // In case of LOAD, the cost of InsertElement into the returned
3830        // vector.
3831        Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
3832                                            Instruction::InsertElement,
3833                                            VectorTy, i);
3834      }
3835
3836      // The cost of the scalar loads/stores.
3837      Cost += VF * TTI.getAddressComputationCost(ValTy->getScalarType());
3838      Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3839                                       Alignment, AS);
3840      return Cost;
3841    }
3842
3843    // Wide load/stores.
3844    unsigned Cost = TTI.getAddressComputationCost(VectorTy);
3845    Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3846
3847    if (Reverse)
3848      Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3849                                  VectorTy, 0);
3850    return Cost;
3851  }
3852  case Instruction::ZExt:
3853  case Instruction::SExt:
3854  case Instruction::FPToUI:
3855  case Instruction::FPToSI:
3856  case Instruction::FPExt:
3857  case Instruction::PtrToInt:
3858  case Instruction::IntToPtr:
3859  case Instruction::SIToFP:
3860  case Instruction::UIToFP:
3861  case Instruction::Trunc:
3862  case Instruction::FPTrunc:
3863  case Instruction::BitCast: {
3864    // We optimize the truncation of induction variable.
3865    // The cost of these is the same as the scalar operation.
3866    if (I->getOpcode() == Instruction::Trunc &&
3867        Legal->isInductionVariable(I->getOperand(0)))
3868      return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3869                                  I->getOperand(0)->getType());
3870
3871    Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3872    return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3873  }
3874  case Instruction::Call: {
3875    CallInst *CI = cast<CallInst>(I);
3876    Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3877    assert(ID && "Not an intrinsic call!");
3878    Type *RetTy = ToVectorTy(CI->getType(), VF);
3879    SmallVector<Type*, 4> Tys;
3880    for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3881      Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3882    return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3883  }
3884  default: {
3885    // We are scalarizing the instruction. Return the cost of the scalar
3886    // instruction, plus the cost of insert and extract into vector
3887    // elements, times the vector width.
3888    unsigned Cost = 0;
3889
3890    if (!RetTy->isVoidTy() && VF != 1) {
3891      unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3892                                                VectorTy);
3893      unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3894                                                VectorTy);
3895
3896      // The cost of inserting the results plus extracting each one of the
3897      // operands.
3898      Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3899    }
3900
3901    // The cost of executing VF copies of the scalar instruction. This opcode
3902    // is unknown. Assume that it is the same as 'mul'.
3903    Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3904    return Cost;
3905  }
3906  }// end of switch.
3907}
3908
3909Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3910  if (Scalar->isVoidTy() || VF == 1)
3911    return Scalar;
3912  return VectorType::get(Scalar, VF);
3913}
3914
3915char LoopVectorize::ID = 0;
3916static const char lv_name[] = "Loop Vectorization";
3917INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3918INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3919INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3920INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3921INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3922INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3923
3924namespace llvm {
3925  Pass *createLoopVectorizePass() {
3926    return new LoopVectorize();
3927  }
3928}
3929
3930bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
3931  // Check for a store.
3932  if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
3933    return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
3934
3935  // Check for a load.
3936  if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
3937    return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
3938
3939  return false;
3940}
3941