68d057d43f85a3f957c36ba712e1f0e90d3d865d
[oota-llvm.git] / lib / Transforms / Vectorize / LoopVectorize.cpp
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 #include "llvm/Transforms/Vectorize.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/EquivalenceClasses.h"
48 #include "llvm/ADT/Hashing.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/ADT/StringExtras.h"
56 #include "llvm/Analysis/AliasAnalysis.h"
57 #include "llvm/Analysis/AliasSetTracker.h"
58 #include "llvm/Analysis/AssumptionCache.h"
59 #include "llvm/Analysis/BlockFrequencyInfo.h"
60 #include "llvm/Analysis/CodeMetrics.h"
61 #include "llvm/Analysis/LoopInfo.h"
62 #include "llvm/Analysis/LoopIterator.h"
63 #include "llvm/Analysis/LoopPass.h"
64 #include "llvm/Analysis/ScalarEvolution.h"
65 #include "llvm/Analysis/ScalarEvolutionExpander.h"
66 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
67 #include "llvm/Analysis/TargetTransformInfo.h"
68 #include "llvm/Analysis/ValueTracking.h"
69 #include "llvm/IR/Constants.h"
70 #include "llvm/IR/DataLayout.h"
71 #include "llvm/IR/DebugInfo.h"
72 #include "llvm/IR/DerivedTypes.h"
73 #include "llvm/IR/DiagnosticInfo.h"
74 #include "llvm/IR/Dominators.h"
75 #include "llvm/IR/Function.h"
76 #include "llvm/IR/IRBuilder.h"
77 #include "llvm/IR/Instructions.h"
78 #include "llvm/IR/IntrinsicInst.h"
79 #include "llvm/IR/LLVMContext.h"
80 #include "llvm/IR/Module.h"
81 #include "llvm/IR/PatternMatch.h"
82 #include "llvm/IR/Type.h"
83 #include "llvm/IR/Value.h"
84 #include "llvm/IR/ValueHandle.h"
85 #include "llvm/IR/Verifier.h"
86 #include "llvm/Pass.h"
87 #include "llvm/Support/BranchProbability.h"
88 #include "llvm/Support/CommandLine.h"
89 #include "llvm/Support/Debug.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include "llvm/Transforms/Scalar.h"
92 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
93 #include "llvm/Transforms/Utils/Local.h"
94 #include "llvm/Transforms/Utils/VectorUtils.h"
95 #include <algorithm>
96 #include <map>
97 #include <tuple>
98
99 using namespace llvm;
100 using namespace llvm::PatternMatch;
101
102 #define LV_NAME "loop-vectorize"
103 #define DEBUG_TYPE LV_NAME
104
105 STATISTIC(LoopsVectorized, "Number of loops vectorized");
106 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
107
108 static cl::opt<unsigned>
109 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
110                     cl::desc("Sets the SIMD width. Zero is autoselect."));
111
112 static cl::opt<unsigned>
113 VectorizationInterleave("force-vector-interleave", cl::init(0), cl::Hidden,
114                     cl::desc("Sets the vectorization interleave count. "
115                              "Zero is autoselect."));
116
117 static cl::opt<bool>
118 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
119                    cl::desc("Enable if-conversion during vectorization."));
120
121 /// We don't vectorize loops with a known constant trip count below this number.
122 static cl::opt<unsigned>
123 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
124                              cl::Hidden,
125                              cl::desc("Don't vectorize loops with a constant "
126                                       "trip count that is smaller than this "
127                                       "value."));
128
129 /// This enables versioning on the strides of symbolically striding memory
130 /// accesses in code like the following.
131 ///   for (i = 0; i < N; ++i)
132 ///     A[i * Stride1] += B[i * Stride2] ...
133 ///
134 /// Will be roughly translated to
135 ///    if (Stride1 == 1 && Stride2 == 1) {
136 ///      for (i = 0; i < N; i+=4)
137 ///       A[i:i+3] += ...
138 ///    } else
139 ///      ...
140 static cl::opt<bool> EnableMemAccessVersioning(
141     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
142     cl::desc("Enable symblic stride memory access versioning"));
143
144 /// We don't unroll loops with a known constant trip count below this number.
145 static const unsigned TinyTripCountUnrollThreshold = 128;
146
147 /// When performing memory disambiguation checks at runtime do not make more
148 /// than this number of comparisons.
149 static const unsigned RuntimeMemoryCheckThreshold = 8;
150
151 /// Maximum simd width.
152 static const unsigned MaxVectorWidth = 64;
153
154 static cl::opt<unsigned> ForceTargetNumScalarRegs(
155     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
156     cl::desc("A flag that overrides the target's number of scalar registers."));
157
158 static cl::opt<unsigned> ForceTargetNumVectorRegs(
159     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
160     cl::desc("A flag that overrides the target's number of vector registers."));
161
162 /// Maximum vectorization interleave count.
163 static const unsigned MaxInterleaveFactor = 16;
164
165 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
166     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
167     cl::desc("A flag that overrides the target's max interleave factor for "
168              "scalar loops."));
169
170 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
171     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
172     cl::desc("A flag that overrides the target's max interleave factor for "
173              "vectorized loops."));
174
175 static cl::opt<unsigned> ForceTargetInstructionCost(
176     "force-target-instruction-cost", cl::init(0), cl::Hidden,
177     cl::desc("A flag that overrides the target's expected cost for "
178              "an instruction to a single constant value. Mostly "
179              "useful for getting consistent testing."));
180
181 static cl::opt<unsigned> SmallLoopCost(
182     "small-loop-cost", cl::init(20), cl::Hidden,
183     cl::desc("The cost of a loop that is considered 'small' by the unroller."));
184
185 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
186     "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
187     cl::desc("Enable the use of the block frequency analysis to access PGO "
188              "heuristics minimizing code growth in cold regions and being more "
189              "aggressive in hot regions."));
190
191 // Runtime unroll loops for load/store throughput.
192 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
193     "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
194     cl::desc("Enable runtime unrolling until load/store ports are saturated"));
195
196 /// The number of stores in a loop that are allowed to need predication.
197 static cl::opt<unsigned> NumberOfStoresToPredicate(
198     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
199     cl::desc("Max number of stores to be predicated behind an if."));
200
201 static cl::opt<bool> EnableIndVarRegisterHeur(
202     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
203     cl::desc("Count the induction variable only once when unrolling"));
204
205 static cl::opt<bool> EnableCondStoresVectorization(
206     "enable-cond-stores-vec", cl::init(false), cl::Hidden,
207     cl::desc("Enable if predication of stores during vectorization."));
208
209 static cl::opt<unsigned> MaxNestedScalarReductionUF(
210     "max-nested-scalar-reduction-unroll", cl::init(2), cl::Hidden,
211     cl::desc("The maximum unroll factor to use when unrolling a scalar "
212              "reduction in a nested loop."));
213
214 namespace {
215
216 // Forward declarations.
217 class LoopVectorizationLegality;
218 class LoopVectorizationCostModel;
219 class LoopVectorizeHints;
220
221 /// Optimization analysis message produced during vectorization. Messages inform
222 /// the user why vectorization did not occur.
223 class Report {
224   std::string Message;
225   raw_string_ostream Out;
226   Instruction *Instr;
227
228 public:
229   Report(Instruction *I = nullptr) : Out(Message), Instr(I) {
230     Out << "loop not vectorized: ";
231   }
232
233   template <typename A> Report &operator<<(const A &Value) {
234     Out << Value;
235     return *this;
236   }
237
238   Instruction *getInstr() { return Instr; }
239
240   std::string &str() { return Out.str(); }
241   operator Twine() { return Out.str(); }
242 };
243
244 /// InnerLoopVectorizer vectorizes loops which contain only one basic
245 /// block to a specified vectorization factor (VF).
246 /// This class performs the widening of scalars into vectors, or multiple
247 /// scalars. This class also implements the following features:
248 /// * It inserts an epilogue loop for handling loops that don't have iteration
249 ///   counts that are known to be a multiple of the vectorization factor.
250 /// * It handles the code generation for reduction variables.
251 /// * Scalarization (implementation using scalars) of un-vectorizable
252 ///   instructions.
253 /// InnerLoopVectorizer does not perform any vectorization-legality
254 /// checks, and relies on the caller to check for the different legality
255 /// aspects. The InnerLoopVectorizer relies on the
256 /// LoopVectorizationLegality class to provide information about the induction
257 /// and reduction variables that were found to a given vectorization factor.
258 class InnerLoopVectorizer {
259 public:
260   InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
261                       DominatorTree *DT, const DataLayout *DL,
262                       const TargetLibraryInfo *TLI, unsigned VecWidth,
263                       unsigned UnrollFactor)
264       : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
265         VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
266         Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
267         Legal(nullptr) {}
268
269   // Perform the actual loop widening (vectorization).
270   void vectorize(LoopVectorizationLegality *L) {
271     Legal = L;
272     // Create a new empty loop. Unlink the old loop and connect the new one.
273     createEmptyLoop();
274     // Widen each instruction in the old loop to a new one in the new loop.
275     // Use the Legality module to find the induction and reduction variables.
276     vectorizeLoop();
277     // Register the new loop and update the analysis passes.
278     updateAnalysis();
279   }
280
281   virtual ~InnerLoopVectorizer() {}
282
283 protected:
284   /// A small list of PHINodes.
285   typedef SmallVector<PHINode*, 4> PhiVector;
286   /// When we unroll loops we have multiple vector values for each scalar.
287   /// This data structure holds the unrolled and vectorized values that
288   /// originated from one scalar instruction.
289   typedef SmallVector<Value*, 2> VectorParts;
290
291   // When we if-convert we need create edge masks. We have to cache values so
292   // that we don't end up with exponential recursion/IR.
293   typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
294                    VectorParts> EdgeMaskCache;
295
296   /// \brief Add code that checks at runtime if the accessed arrays overlap.
297   ///
298   /// Returns a pair of instructions where the first element is the first
299   /// instruction generated in possibly a sequence of instructions and the
300   /// second value is the final comparator value or NULL if no check is needed.
301   std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
302
303   /// \brief Add checks for strides that where assumed to be 1.
304   ///
305   /// Returns the last check instruction and the first check instruction in the
306   /// pair as (first, last).
307   std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
308
309   /// Create an empty loop, based on the loop ranges of the old loop.
310   void createEmptyLoop();
311   /// Copy and widen the instructions from the old loop.
312   virtual void vectorizeLoop();
313
314   /// \brief The Loop exit block may have single value PHI nodes where the
315   /// incoming value is 'Undef'. While vectorizing we only handled real values
316   /// that were defined inside the loop. Here we fix the 'undef case'.
317   /// See PR14725.
318   void fixLCSSAPHIs();
319
320   /// A helper function that computes the predicate of the block BB, assuming
321   /// that the header block of the loop is set to True. It returns the *entry*
322   /// mask for the block BB.
323   VectorParts createBlockInMask(BasicBlock *BB);
324   /// A helper function that computes the predicate of the edge between SRC
325   /// and DST.
326   VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
327
328   /// A helper function to vectorize a single BB within the innermost loop.
329   void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
330
331   /// Vectorize a single PHINode in a block. This method handles the induction
332   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
333   /// arbitrary length vectors.
334   void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
335                            unsigned UF, unsigned VF, PhiVector *PV);
336
337   /// Insert the new loop to the loop hierarchy and pass manager
338   /// and update the analysis passes.
339   void updateAnalysis();
340
341   /// This instruction is un-vectorizable. Implement it as a sequence
342   /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
343   /// scalarized instruction behind an if block predicated on the control
344   /// dependence of the instruction.
345   virtual void scalarizeInstruction(Instruction *Instr,
346                                     bool IfPredicateStore=false);
347
348   /// Vectorize Load and Store instructions,
349   virtual void vectorizeMemoryInstruction(Instruction *Instr);
350
351   /// Create a broadcast instruction. This method generates a broadcast
352   /// instruction (shuffle) for loop invariant values and for the induction
353   /// value. If this is the induction variable then we extend it to N, N+1, ...
354   /// this is needed because each iteration in the loop corresponds to a SIMD
355   /// element.
356   virtual Value *getBroadcastInstrs(Value *V);
357
358   /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
359   /// to each vector element of Val. The sequence starts at StartIndex.
360   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
361
362   /// When we go over instructions in the basic block we rely on previous
363   /// values within the current basic block or on loop invariant values.
364   /// When we widen (vectorize) values we place them in the map. If the values
365   /// are not within the map, they have to be loop invariant, so we simply
366   /// broadcast them into a vector.
367   VectorParts &getVectorValue(Value *V);
368
369   /// Generate a shuffle sequence that will reverse the vector Vec.
370   virtual Value *reverseVector(Value *Vec);
371
372   /// This is a helper class that holds the vectorizer state. It maps scalar
373   /// instructions to vector instructions. When the code is 'unrolled' then
374   /// then a single scalar value is mapped to multiple vector parts. The parts
375   /// are stored in the VectorPart type.
376   struct ValueMap {
377     /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
378     /// are mapped.
379     ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
380
381     /// \return True if 'Key' is saved in the Value Map.
382     bool has(Value *Key) const { return MapStorage.count(Key); }
383
384     /// Initializes a new entry in the map. Sets all of the vector parts to the
385     /// save value in 'Val'.
386     /// \return A reference to a vector with splat values.
387     VectorParts &splat(Value *Key, Value *Val) {
388       VectorParts &Entry = MapStorage[Key];
389       Entry.assign(UF, Val);
390       return Entry;
391     }
392
393     ///\return A reference to the value that is stored at 'Key'.
394     VectorParts &get(Value *Key) {
395       VectorParts &Entry = MapStorage[Key];
396       if (Entry.empty())
397         Entry.resize(UF);
398       assert(Entry.size() == UF);
399       return Entry;
400     }
401
402   private:
403     /// The unroll factor. Each entry in the map stores this number of vector
404     /// elements.
405     unsigned UF;
406
407     /// Map storage. We use std::map and not DenseMap because insertions to a
408     /// dense map invalidates its iterators.
409     std::map<Value *, VectorParts> MapStorage;
410   };
411
412   /// The original loop.
413   Loop *OrigLoop;
414   /// Scev analysis to use.
415   ScalarEvolution *SE;
416   /// Loop Info.
417   LoopInfo *LI;
418   /// Dominator Tree.
419   DominatorTree *DT;
420   /// Alias Analysis.
421   AliasAnalysis *AA;
422   /// Data Layout.
423   const DataLayout *DL;
424   /// Target Library Info.
425   const TargetLibraryInfo *TLI;
426
427   /// The vectorization SIMD factor to use. Each vector will have this many
428   /// vector elements.
429   unsigned VF;
430
431 protected:
432   /// The vectorization unroll factor to use. Each scalar is vectorized to this
433   /// many different vector instructions.
434   unsigned UF;
435
436   /// The builder that we use
437   IRBuilder<> Builder;
438
439   // --- Vectorization state ---
440
441   /// The vector-loop preheader.
442   BasicBlock *LoopVectorPreHeader;
443   /// The scalar-loop preheader.
444   BasicBlock *LoopScalarPreHeader;
445   /// Middle Block between the vector and the scalar.
446   BasicBlock *LoopMiddleBlock;
447   ///The ExitBlock of the scalar loop.
448   BasicBlock *LoopExitBlock;
449   ///The vector loop body.
450   SmallVector<BasicBlock *, 4> LoopVectorBody;
451   ///The scalar loop body.
452   BasicBlock *LoopScalarBody;
453   /// A list of all bypass blocks. The first block is the entry of the loop.
454   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
455
456   /// The new Induction variable which was added to the new block.
457   PHINode *Induction;
458   /// The induction variable of the old basic block.
459   PHINode *OldInduction;
460   /// Holds the extended (to the widest induction type) start index.
461   Value *ExtendedIdx;
462   /// Maps scalars to widened vectors.
463   ValueMap WidenMap;
464   EdgeMaskCache MaskCache;
465
466   LoopVectorizationLegality *Legal;
467 };
468
469 class InnerLoopUnroller : public InnerLoopVectorizer {
470 public:
471   InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
472                     DominatorTree *DT, const DataLayout *DL,
473                     const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
474     InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
475
476 private:
477   void scalarizeInstruction(Instruction *Instr,
478                             bool IfPredicateStore = false) override;
479   void vectorizeMemoryInstruction(Instruction *Instr) override;
480   Value *getBroadcastInstrs(Value *V) override;
481   Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
482   Value *reverseVector(Value *Vec) override;
483 };
484
485 /// \brief Look for a meaningful debug location on the instruction or it's
486 /// operands.
487 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
488   if (!I)
489     return I;
490
491   DebugLoc Empty;
492   if (I->getDebugLoc() != Empty)
493     return I;
494
495   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
496     if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
497       if (OpInst->getDebugLoc() != Empty)
498         return OpInst;
499   }
500
501   return I;
502 }
503
504 /// \brief Set the debug location in the builder using the debug location in the
505 /// instruction.
506 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
507   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
508     B.SetCurrentDebugLocation(Inst->getDebugLoc());
509   else
510     B.SetCurrentDebugLocation(DebugLoc());
511 }
512
513 #ifndef NDEBUG
514 /// \return string containing a file name and a line # for the given loop.
515 static std::string getDebugLocString(const Loop *L) {
516   std::string Result;
517   if (L) {
518     raw_string_ostream OS(Result);
519     const DebugLoc LoopDbgLoc = L->getStartLoc();
520     if (!LoopDbgLoc.isUnknown())
521       LoopDbgLoc.print(L->getHeader()->getContext(), OS);
522     else
523       // Just print the module name.
524       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
525     OS.flush();
526   }
527   return Result;
528 }
529 #endif
530
531 /// \brief Propagate known metadata from one instruction to another.
532 static void propagateMetadata(Instruction *To, const Instruction *From) {
533   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
534   From->getAllMetadataOtherThanDebugLoc(Metadata);
535
536   for (auto M : Metadata) {
537     unsigned Kind = M.first;
538
539     // These are safe to transfer (this is safe for TBAA, even when we
540     // if-convert, because should that metadata have had a control dependency
541     // on the condition, and thus actually aliased with some other
542     // non-speculated memory access when the condition was false, this would be
543     // caught by the runtime overlap checks).
544     if (Kind != LLVMContext::MD_tbaa &&
545         Kind != LLVMContext::MD_alias_scope &&
546         Kind != LLVMContext::MD_noalias &&
547         Kind != LLVMContext::MD_fpmath)
548       continue;
549
550     To->setMetadata(Kind, M.second);
551   }
552 }
553
554 /// \brief Propagate known metadata from one instruction to a vector of others.
555 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
556   for (Value *V : To)
557     if (Instruction *I = dyn_cast<Instruction>(V))
558       propagateMetadata(I, From);
559 }
560
561 namespace {
562 /// This struct holds information about the memory runtime legality
563 /// check that a group of pointers do not overlap.
564 struct RuntimePointerCheck {
565   RuntimePointerCheck() : Need(false) {}
566
567   /// Reset the state of the pointer runtime information.
568   void reset() {
569     Need = false;
570     Pointers.clear();
571     Starts.clear();
572     Ends.clear();
573     IsWritePtr.clear();
574     DependencySetId.clear();
575     AliasSetId.clear();
576   }
577
578   /// Insert a pointer and calculate the start and end SCEVs.
579   void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
580               unsigned DepSetId, unsigned ASId, ValueToValueMap &Strides);
581
582   /// This flag indicates if we need to add the runtime check.
583   bool Need;
584   /// Holds the pointers that we need to check.
585   SmallVector<TrackingVH<Value>, 2> Pointers;
586   /// Holds the pointer value at the beginning of the loop.
587   SmallVector<const SCEV*, 2> Starts;
588   /// Holds the pointer value at the end of the loop.
589   SmallVector<const SCEV*, 2> Ends;
590   /// Holds the information if this pointer is used for writing to memory.
591   SmallVector<bool, 2> IsWritePtr;
592   /// Holds the id of the set of pointers that could be dependent because of a
593   /// shared underlying object.
594   SmallVector<unsigned, 2> DependencySetId;
595   /// Holds the id of the disjoint alias set to which this pointer belongs.
596   SmallVector<unsigned, 2> AliasSetId;
597 };
598 } // end anonymous namespace
599
600 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
601 /// to what vectorization factor.
602 /// This class does not look at the profitability of vectorization, only the
603 /// legality. This class has two main kinds of checks:
604 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
605 ///   will change the order of memory accesses in a way that will change the
606 ///   correctness of the program.
607 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
608 /// checks for a number of different conditions, such as the availability of a
609 /// single induction variable, that all types are supported and vectorize-able,
610 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
611 /// This class is also used by InnerLoopVectorizer for identifying
612 /// induction variable and the different reduction variables.
613 class LoopVectorizationLegality {
614 public:
615   unsigned NumLoads;
616   unsigned NumStores;
617   unsigned NumPredStores;
618
619   LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
620                             DominatorTree *DT, TargetLibraryInfo *TLI,
621                             AliasAnalysis *AA, Function *F,
622                             const TargetTransformInfo *TTI)
623       : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
624         DT(DT), TLI(TLI), AA(AA), TheFunction(F), TTI(TTI), Induction(nullptr),
625         WidestIndTy(nullptr), HasFunNoNaNAttr(false), MaxSafeDepDistBytes(-1U) {
626   }
627
628   /// This enum represents the kinds of reductions that we support.
629   enum ReductionKind {
630     RK_NoReduction, ///< Not a reduction.
631     RK_IntegerAdd,  ///< Sum of integers.
632     RK_IntegerMult, ///< Product of integers.
633     RK_IntegerOr,   ///< Bitwise or logical OR of numbers.
634     RK_IntegerAnd,  ///< Bitwise or logical AND of numbers.
635     RK_IntegerXor,  ///< Bitwise or logical XOR of numbers.
636     RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
637     RK_FloatAdd,    ///< Sum of floats.
638     RK_FloatMult,   ///< Product of floats.
639     RK_FloatMinMax  ///< Min/max implemented in terms of select(cmp()).
640   };
641
642   /// This enum represents the kinds of inductions that we support.
643   enum InductionKind {
644     IK_NoInduction,  ///< Not an induction variable.
645     IK_IntInduction, ///< Integer induction variable. Step = C.
646     IK_PtrInduction  ///< Pointer induction var. Step = C / sizeof(elem).
647   };
648
649   // This enum represents the kind of minmax reduction.
650   enum MinMaxReductionKind {
651     MRK_Invalid,
652     MRK_UIntMin,
653     MRK_UIntMax,
654     MRK_SIntMin,
655     MRK_SIntMax,
656     MRK_FloatMin,
657     MRK_FloatMax
658   };
659
660   /// This struct holds information about reduction variables.
661   struct ReductionDescriptor {
662     ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
663       Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
664
665     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
666                         MinMaxReductionKind MK)
667         : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
668
669     // The starting value of the reduction.
670     // It does not have to be zero!
671     TrackingVH<Value> StartValue;
672     // The instruction who's value is used outside the loop.
673     Instruction *LoopExitInstr;
674     // The kind of the reduction.
675     ReductionKind Kind;
676     // If this a min/max reduction the kind of reduction.
677     MinMaxReductionKind MinMaxKind;
678   };
679
680   /// This POD struct holds information about a potential reduction operation.
681   struct ReductionInstDesc {
682     ReductionInstDesc(bool IsRedux, Instruction *I) :
683       IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
684
685     ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
686       IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
687
688     // Is this instruction a reduction candidate.
689     bool IsReduction;
690     // The last instruction in a min/max pattern (select of the select(icmp())
691     // pattern), or the current reduction instruction otherwise.
692     Instruction *PatternLastInst;
693     // If this is a min/max pattern the comparison predicate.
694     MinMaxReductionKind MinMaxKind;
695   };
696
697   /// A struct for saving information about induction variables.
698   struct InductionInfo {
699     InductionInfo(Value *Start, InductionKind K, ConstantInt *Step)
700         : StartValue(Start), IK(K), StepValue(Step) {
701       assert(IK != IK_NoInduction && "Not an induction");
702       assert(StartValue && "StartValue is null");
703       assert(StepValue && !StepValue->isZero() && "StepValue is zero");
704       assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
705              "StartValue is not a pointer for pointer induction");
706       assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
707              "StartValue is not an integer for integer induction");
708       assert(StepValue->getType()->isIntegerTy() &&
709              "StepValue is not an integer");
710     }
711     InductionInfo()
712         : StartValue(nullptr), IK(IK_NoInduction), StepValue(nullptr) {}
713
714     /// Get the consecutive direction. Returns:
715     ///   0 - unknown or non-consecutive.
716     ///   1 - consecutive and increasing.
717     ///  -1 - consecutive and decreasing.
718     int getConsecutiveDirection() const {
719       if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
720         return StepValue->getSExtValue();
721       return 0;
722     }
723
724     /// Compute the transformed value of Index at offset StartValue using step
725     /// StepValue.
726     /// For integer induction, returns StartValue + Index * StepValue.
727     /// For pointer induction, returns StartValue[Index * StepValue].
728     /// FIXME: The newly created binary instructions should contain nsw/nuw
729     /// flags, which can be found from the original scalar operations.
730     Value *transform(IRBuilder<> &B, Value *Index) const {
731       switch (IK) {
732       case IK_IntInduction:
733         assert(Index->getType() == StartValue->getType() &&
734                "Index type does not match StartValue type");
735         if (StepValue->isMinusOne())
736           return B.CreateSub(StartValue, Index);
737         if (!StepValue->isOne())
738           Index = B.CreateMul(Index, StepValue);
739         return B.CreateAdd(StartValue, Index);
740
741       case IK_PtrInduction:
742         if (StepValue->isMinusOne())
743           Index = B.CreateNeg(Index);
744         else if (!StepValue->isOne())
745           Index = B.CreateMul(Index, StepValue);
746         return B.CreateGEP(StartValue, Index);
747
748       case IK_NoInduction:
749         return nullptr;
750       }
751       llvm_unreachable("invalid enum");
752     }
753
754     /// Start value.
755     TrackingVH<Value> StartValue;
756     /// Induction kind.
757     InductionKind IK;
758     /// Step value.
759     ConstantInt *StepValue;
760   };
761
762   /// ReductionList contains the reduction descriptors for all
763   /// of the reductions that were found in the loop.
764   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
765
766   /// InductionList saves induction variables and maps them to the
767   /// induction descriptor.
768   typedef MapVector<PHINode*, InductionInfo> InductionList;
769
770   /// Returns true if it is legal to vectorize this loop.
771   /// This does not mean that it is profitable to vectorize this
772   /// loop, only that it is legal to do so.
773   bool canVectorize();
774
775   /// Returns the Induction variable.
776   PHINode *getInduction() { return Induction; }
777
778   /// Returns the reduction variables found in the loop.
779   ReductionList *getReductionVars() { return &Reductions; }
780
781   /// Returns the induction variables found in the loop.
782   InductionList *getInductionVars() { return &Inductions; }
783
784   /// Returns the widest induction type.
785   Type *getWidestInductionType() { return WidestIndTy; }
786
787   /// Returns True if V is an induction variable in this loop.
788   bool isInductionVariable(const Value *V);
789
790   /// Return true if the block BB needs to be predicated in order for the loop
791   /// to be vectorized.
792   bool blockNeedsPredication(BasicBlock *BB);
793
794   /// Check if this  pointer is consecutive when vectorizing. This happens
795   /// when the last index of the GEP is the induction variable, or that the
796   /// pointer itself is an induction variable.
797   /// This check allows us to vectorize A[idx] into a wide load/store.
798   /// Returns:
799   /// 0 - Stride is unknown or non-consecutive.
800   /// 1 - Address is consecutive.
801   /// -1 - Address is consecutive, and decreasing.
802   int isConsecutivePtr(Value *Ptr);
803
804   /// Returns true if the value V is uniform within the loop.
805   bool isUniform(Value *V);
806
807   /// Returns true if this instruction will remain scalar after vectorization.
808   bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
809
810   /// Returns the information that we collected about runtime memory check.
811   RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
812
813   /// This function returns the identity element (or neutral element) for
814   /// the operation K.
815   static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
816
817   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
818
819   bool hasStride(Value *V) { return StrideSet.count(V); }
820   bool mustCheckStrides() { return !StrideSet.empty(); }
821   SmallPtrSet<Value *, 8>::iterator strides_begin() {
822     return StrideSet.begin();
823   }
824   SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
825
826   /// Returns true if the target machine supports masked store operation
827   /// for the given \p DataType and kind of access to \p Ptr.
828   bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
829     return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr));
830   }
831   /// Returns true if the target machine supports masked load operation
832   /// for the given \p DataType and kind of access to \p Ptr.
833   bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
834     return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr));
835   }
836   /// Returns true if vector representation of the instruction \p I
837   /// requires mask.
838   bool isMaskRequired(const Instruction* I) {
839     return (MaskedOp.count(I) != 0);
840   }
841 private:
842   /// Check if a single basic block loop is vectorizable.
843   /// At this point we know that this is a loop with a constant trip count
844   /// and we only need to check individual instructions.
845   bool canVectorizeInstrs();
846
847   /// When we vectorize loops we may change the order in which
848   /// we read and write from memory. This method checks if it is
849   /// legal to vectorize the code, considering only memory constrains.
850   /// Returns true if the loop is vectorizable
851   bool canVectorizeMemory();
852
853   /// Return true if we can vectorize this loop using the IF-conversion
854   /// transformation.
855   bool canVectorizeWithIfConvert();
856
857   /// Collect the variables that need to stay uniform after vectorization.
858   void collectLoopUniforms();
859
860   /// Return true if all of the instructions in the block can be speculatively
861   /// executed. \p SafePtrs is a list of addresses that are known to be legal
862   /// and we know that we can read from them without segfault.
863   bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
864
865   /// Returns True, if 'Phi' is the kind of reduction variable for type
866   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
867   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
868   /// Returns a struct describing if the instruction 'I' can be a reduction
869   /// variable of type 'Kind'. If the reduction is a min/max pattern of
870   /// select(icmp()) this function advances the instruction pointer 'I' from the
871   /// compare instruction to the select instruction and stores this pointer in
872   /// 'PatternLastInst' member of the returned struct.
873   ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
874                                      ReductionInstDesc &Desc);
875   /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
876   /// pattern corresponding to a min(X, Y) or max(X, Y).
877   static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
878                                                     ReductionInstDesc &Prev);
879   /// Returns the induction kind of Phi and record the step. This function may
880   /// return NoInduction if the PHI is not an induction variable.
881   InductionKind isInductionVariable(PHINode *Phi, ConstantInt *&StepValue);
882
883   /// \brief Collect memory access with loop invariant strides.
884   ///
885   /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
886   /// invariant.
887   void collectStridedAccess(Value *LoadOrStoreInst);
888
889   /// Report an analysis message to assist the user in diagnosing loops that are
890   /// not vectorized.
891   void emitAnalysis(Report &Message) {
892     DebugLoc DL = TheLoop->getStartLoc();
893     if (Instruction *I = Message.getInstr())
894       DL = I->getDebugLoc();
895     emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
896                                    *TheFunction, DL, Message.str());
897   }
898
899   /// The loop that we evaluate.
900   Loop *TheLoop;
901   /// Scev analysis.
902   ScalarEvolution *SE;
903   /// DataLayout analysis.
904   const DataLayout *DL;
905   /// Dominators.
906   DominatorTree *DT;
907   /// Target Library Info.
908   TargetLibraryInfo *TLI;
909   /// Alias analysis.
910   AliasAnalysis *AA;
911   /// Parent function
912   Function *TheFunction;
913   /// Target Transform Info
914   const TargetTransformInfo *TTI;
915
916   //  ---  vectorization state --- //
917
918   /// Holds the integer induction variable. This is the counter of the
919   /// loop.
920   PHINode *Induction;
921   /// Holds the reduction variables.
922   ReductionList Reductions;
923   /// Holds all of the induction variables that we found in the loop.
924   /// Notice that inductions don't need to start at zero and that induction
925   /// variables can be pointers.
926   InductionList Inductions;
927   /// Holds the widest induction type encountered.
928   Type *WidestIndTy;
929
930   /// Allowed outside users. This holds the reduction
931   /// vars which can be accessed from outside the loop.
932   SmallPtrSet<Value*, 4> AllowedExit;
933   /// This set holds the variables which are known to be uniform after
934   /// vectorization.
935   SmallPtrSet<Instruction*, 4> Uniforms;
936   /// We need to check that all of the pointers in this list are disjoint
937   /// at runtime.
938   RuntimePointerCheck PtrRtCheck;
939   /// Can we assume the absence of NaNs.
940   bool HasFunNoNaNAttr;
941
942   unsigned MaxSafeDepDistBytes;
943
944   ValueToValueMap Strides;
945   SmallPtrSet<Value *, 8> StrideSet;
946   
947   /// While vectorizing these instructions we have to generate a
948   /// call to the appropriate masked intrinsic
949   SmallPtrSet<const Instruction*, 8> MaskedOp;
950 };
951
952 /// LoopVectorizationCostModel - estimates the expected speedups due to
953 /// vectorization.
954 /// In many cases vectorization is not profitable. This can happen because of
955 /// a number of reasons. In this class we mainly attempt to predict the
956 /// expected speedup/slowdowns due to the supported instruction set. We use the
957 /// TargetTransformInfo to query the different backends for the cost of
958 /// different operations.
959 class LoopVectorizationCostModel {
960 public:
961   LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
962                              LoopVectorizationLegality *Legal,
963                              const TargetTransformInfo &TTI,
964                              const DataLayout *DL, const TargetLibraryInfo *TLI,
965                              AssumptionCache *AC, const Function *F,
966                              const LoopVectorizeHints *Hints)
967       : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI),
968         TheFunction(F), Hints(Hints) {
969     CodeMetrics::collectEphemeralValues(L, AC, EphValues);
970   }
971
972   /// Information about vectorization costs
973   struct VectorizationFactor {
974     unsigned Width; // Vector width with best cost
975     unsigned Cost; // Cost of the loop with that width
976   };
977   /// \return The most profitable vectorization factor and the cost of that VF.
978   /// This method checks every power of two up to VF. If UserVF is not ZERO
979   /// then this vectorization factor will be selected if vectorization is
980   /// possible.
981   VectorizationFactor selectVectorizationFactor(bool OptForSize);
982
983   /// \return The size (in bits) of the widest type in the code that
984   /// needs to be vectorized. We ignore values that remain scalar such as
985   /// 64 bit loop indices.
986   unsigned getWidestType();
987
988   /// \return The most profitable unroll factor.
989   /// If UserUF is non-zero then this method finds the best unroll-factor
990   /// based on register pressure and other parameters.
991   /// VF and LoopCost are the selected vectorization factor and the cost of the
992   /// selected VF.
993   unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost);
994
995   /// \brief A struct that represents some properties of the register usage
996   /// of a loop.
997   struct RegisterUsage {
998     /// Holds the number of loop invariant values that are used in the loop.
999     unsigned LoopInvariantRegs;
1000     /// Holds the maximum number of concurrent live intervals in the loop.
1001     unsigned MaxLocalUsers;
1002     /// Holds the number of instructions in the loop.
1003     unsigned NumInstructions;
1004   };
1005
1006   /// \return  information about the register usage of the loop.
1007   RegisterUsage calculateRegisterUsage();
1008
1009 private:
1010   /// Returns the expected execution cost. The unit of the cost does
1011   /// not matter because we use the 'cost' units to compare different
1012   /// vector widths. The cost that is returned is *not* normalized by
1013   /// the factor width.
1014   unsigned expectedCost(unsigned VF);
1015
1016   /// Returns the execution time cost of an instruction for a given vector
1017   /// width. Vector width of one means scalar.
1018   unsigned getInstructionCost(Instruction *I, unsigned VF);
1019
1020   /// A helper function for converting Scalar types to vector types.
1021   /// If the incoming type is void, we return void. If the VF is 1, we return
1022   /// the scalar type.
1023   static Type* ToVectorTy(Type *Scalar, unsigned VF);
1024
1025   /// Returns whether the instruction is a load or store and will be a emitted
1026   /// as a vector operation.
1027   bool isConsecutiveLoadOrStore(Instruction *I);
1028
1029   /// Report an analysis message to assist the user in diagnosing loops that are
1030   /// not vectorized.
1031   void emitAnalysis(Report &Message) {
1032     DebugLoc DL = TheLoop->getStartLoc();
1033     if (Instruction *I = Message.getInstr())
1034       DL = I->getDebugLoc();
1035     emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
1036                                    *TheFunction, DL, Message.str());
1037   }
1038
1039   /// Values used only by @llvm.assume calls.
1040   SmallPtrSet<const Value *, 32> EphValues;
1041
1042   /// The loop that we evaluate.
1043   Loop *TheLoop;
1044   /// Scev analysis.
1045   ScalarEvolution *SE;
1046   /// Loop Info analysis.
1047   LoopInfo *LI;
1048   /// Vectorization legality.
1049   LoopVectorizationLegality *Legal;
1050   /// Vector target information.
1051   const TargetTransformInfo &TTI;
1052   /// Target data layout information.
1053   const DataLayout *DL;
1054   /// Target Library Info.
1055   const TargetLibraryInfo *TLI;
1056   const Function *TheFunction;
1057   // Loop Vectorize Hint.
1058   const LoopVectorizeHints *Hints;
1059 };
1060
1061 /// Utility class for getting and setting loop vectorizer hints in the form
1062 /// of loop metadata.
1063 /// This class keeps a number of loop annotations locally (as member variables)
1064 /// and can, upon request, write them back as metadata on the loop. It will
1065 /// initially scan the loop for existing metadata, and will update the local
1066 /// values based on information in the loop.
1067 /// We cannot write all values to metadata, as the mere presence of some info,
1068 /// for example 'force', means a decision has been made. So, we need to be
1069 /// careful NOT to add them if the user hasn't specifically asked so.
1070 class LoopVectorizeHints {
1071   enum HintKind {
1072     HK_WIDTH,
1073     HK_UNROLL,
1074     HK_FORCE
1075   };
1076
1077   /// Hint - associates name and validation with the hint value.
1078   struct Hint {
1079     const char * Name;
1080     unsigned Value; // This may have to change for non-numeric values.
1081     HintKind Kind;
1082
1083     Hint(const char * Name, unsigned Value, HintKind Kind)
1084       : Name(Name), Value(Value), Kind(Kind) { }
1085
1086     bool validate(unsigned Val) {
1087       switch (Kind) {
1088       case HK_WIDTH:
1089         return isPowerOf2_32(Val) && Val <= MaxVectorWidth;
1090       case HK_UNROLL:
1091         return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1092       case HK_FORCE:
1093         return (Val <= 1);
1094       }
1095       return false;
1096     }
1097   };
1098
1099   /// Vectorization width.
1100   Hint Width;
1101   /// Vectorization interleave factor.
1102   Hint Interleave;
1103   /// Vectorization forced
1104   Hint Force;
1105
1106   /// Return the loop metadata prefix.
1107   static StringRef Prefix() { return "llvm.loop."; }
1108
1109 public:
1110   enum ForceKind {
1111     FK_Undefined = -1, ///< Not selected.
1112     FK_Disabled = 0,   ///< Forcing disabled.
1113     FK_Enabled = 1,    ///< Forcing enabled.
1114   };
1115
1116   LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
1117       : Width("vectorize.width", VectorizationFactor, HK_WIDTH),
1118         Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1119         Force("vectorize.enable", FK_Undefined, HK_FORCE),
1120         TheLoop(L) {
1121     // Populate values with existing loop metadata.
1122     getHintsFromMetadata();
1123
1124     // force-vector-interleave overrides DisableInterleaving.
1125     if (VectorizationInterleave.getNumOccurrences() > 0)
1126       Interleave.Value = VectorizationInterleave;
1127
1128     DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1129           << "LV: Interleaving disabled by the pass manager\n");
1130   }
1131
1132   /// Mark the loop L as already vectorized by setting the width to 1.
1133   void setAlreadyVectorized() {
1134     Width.Value = Interleave.Value = 1;
1135     Hint Hints[] = {Width, Interleave};
1136     writeHintsToMetadata(Hints);
1137   }
1138
1139   /// Dumps all the hint information.
1140   std::string emitRemark() const {
1141     Report R;
1142     if (Force.Value == LoopVectorizeHints::FK_Disabled)
1143       R << "vectorization is explicitly disabled";
1144     else {
1145       R << "use -Rpass-analysis=loop-vectorize for more info";
1146       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1147         R << " (Force=true";
1148         if (Width.Value != 0)
1149           R << ", Vector Width=" << Width.Value;
1150         if (Interleave.Value != 0)
1151           R << ", Interleave Count=" << Interleave.Value;
1152         R << ")";
1153       }
1154     }
1155
1156     return R.str();
1157   }
1158
1159   unsigned getWidth() const { return Width.Value; }
1160   unsigned getInterleave() const { return Interleave.Value; }
1161   enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1162
1163 private:
1164   /// Find hints specified in the loop metadata and update local values.
1165   void getHintsFromMetadata() {
1166     MDNode *LoopID = TheLoop->getLoopID();
1167     if (!LoopID)
1168       return;
1169
1170     // First operand should refer to the loop id itself.
1171     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1172     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1173
1174     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1175       const MDString *S = nullptr;
1176       SmallVector<Metadata *, 4> Args;
1177
1178       // The expected hint is either a MDString or a MDNode with the first
1179       // operand a MDString.
1180       if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1181         if (!MD || MD->getNumOperands() == 0)
1182           continue;
1183         S = dyn_cast<MDString>(MD->getOperand(0));
1184         for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1185           Args.push_back(MD->getOperand(i));
1186       } else {
1187         S = dyn_cast<MDString>(LoopID->getOperand(i));
1188         assert(Args.size() == 0 && "too many arguments for MDString");
1189       }
1190
1191       if (!S)
1192         continue;
1193
1194       // Check if the hint starts with the loop metadata prefix.
1195       StringRef Name = S->getString();
1196       if (Args.size() == 1)
1197         setHint(Name, Args[0]);
1198     }
1199   }
1200
1201   /// Checks string hint with one operand and set value if valid.
1202   void setHint(StringRef Name, Metadata *Arg) {
1203     if (!Name.startswith(Prefix()))
1204       return;
1205     Name = Name.substr(Prefix().size(), StringRef::npos);
1206
1207     const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1208     if (!C) return;
1209     unsigned Val = C->getZExtValue();
1210
1211     Hint *Hints[] = {&Width, &Interleave, &Force};
1212     for (auto H : Hints) {
1213       if (Name == H->Name) {
1214         if (H->validate(Val))
1215           H->Value = Val;
1216         else
1217           DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1218         break;
1219       }
1220     }
1221   }
1222
1223   /// Create a new hint from name / value pair.
1224   MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1225     LLVMContext &Context = TheLoop->getHeader()->getContext();
1226     Metadata *MDs[] = {MDString::get(Context, Name),
1227                        ConstantAsMetadata::get(
1228                            ConstantInt::get(Type::getInt32Ty(Context), V))};
1229     return MDNode::get(Context, MDs);
1230   }
1231
1232   /// Matches metadata with hint name.
1233   bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1234     MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
1235     if (!Name)
1236       return false;
1237
1238     for (auto H : HintTypes)
1239       if (Name->getString().endswith(H.Name))
1240         return true;
1241     return false;
1242   }
1243
1244   /// Sets current hints into loop metadata, keeping other values intact.
1245   void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1246     if (HintTypes.size() == 0)
1247       return;
1248
1249     // Reserve the first element to LoopID (see below).
1250     SmallVector<Metadata *, 4> MDs(1);
1251     // If the loop already has metadata, then ignore the existing operands.
1252     MDNode *LoopID = TheLoop->getLoopID();
1253     if (LoopID) {
1254       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1255         MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1256         // If node in update list, ignore old value.
1257         if (!matchesHintMetadataName(Node, HintTypes))
1258           MDs.push_back(Node);
1259       }
1260     }
1261
1262     // Now, add the missing hints.
1263     for (auto H : HintTypes)
1264       MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1265
1266     // Replace current metadata node with new one.
1267     LLVMContext &Context = TheLoop->getHeader()->getContext();
1268     MDNode *NewLoopID = MDNode::get(Context, MDs);
1269     // Set operand 0 to refer to the loop id itself.
1270     NewLoopID->replaceOperandWith(0, NewLoopID);
1271
1272     TheLoop->setLoopID(NewLoopID);
1273   }
1274
1275   /// The loop these hints belong to.
1276   const Loop *TheLoop;
1277 };
1278
1279 static void emitMissedWarning(Function *F, Loop *L,
1280                               const LoopVectorizeHints &LH) {
1281   emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
1282                                L->getStartLoc(), LH.emitRemark());
1283
1284   if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1285     if (LH.getWidth() != 1)
1286       emitLoopVectorizeWarning(
1287           F->getContext(), *F, L->getStartLoc(),
1288           "failed explicitly specified loop vectorization");
1289     else if (LH.getInterleave() != 1)
1290       emitLoopInterleaveWarning(
1291           F->getContext(), *F, L->getStartLoc(),
1292           "failed explicitly specified loop interleaving");
1293   }
1294 }
1295
1296 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
1297   if (L.empty())
1298     return V.push_back(&L);
1299
1300   for (Loop *InnerL : L)
1301     addInnerLoop(*InnerL, V);
1302 }
1303
1304 /// The LoopVectorize Pass.
1305 struct LoopVectorize : public FunctionPass {
1306   /// Pass identification, replacement for typeid
1307   static char ID;
1308
1309   explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
1310     : FunctionPass(ID),
1311       DisableUnrolling(NoUnrolling),
1312       AlwaysVectorize(AlwaysVectorize) {
1313     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1314   }
1315
1316   ScalarEvolution *SE;
1317   const DataLayout *DL;
1318   LoopInfo *LI;
1319   TargetTransformInfo *TTI;
1320   DominatorTree *DT;
1321   BlockFrequencyInfo *BFI;
1322   TargetLibraryInfo *TLI;
1323   AliasAnalysis *AA;
1324   AssumptionCache *AC;
1325   bool DisableUnrolling;
1326   bool AlwaysVectorize;
1327
1328   BlockFrequency ColdEntryFreq;
1329
1330   bool runOnFunction(Function &F) override {
1331     SE = &getAnalysis<ScalarEvolution>();
1332     DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1333     DL = DLP ? &DLP->getDataLayout() : nullptr;
1334     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1335     TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1336     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1337     BFI = &getAnalysis<BlockFrequencyInfo>();
1338     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1339     TLI = TLIP ? &TLIP->getTLI() : nullptr;
1340     AA = &getAnalysis<AliasAnalysis>();
1341     AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1342
1343     // Compute some weights outside of the loop over the loops. Compute this
1344     // using a BranchProbability to re-use its scaling math.
1345     const BranchProbability ColdProb(1, 5); // 20%
1346     ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1347
1348     // If the target claims to have no vector registers don't attempt
1349     // vectorization.
1350     if (!TTI->getNumberOfRegisters(true))
1351       return false;
1352
1353     if (!DL) {
1354       DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
1355                    << ": Missing data layout\n");
1356       return false;
1357     }
1358
1359     // Build up a worklist of inner-loops to vectorize. This is necessary as
1360     // the act of vectorizing or partially unrolling a loop creates new loops
1361     // and can invalidate iterators across the loops.
1362     SmallVector<Loop *, 8> Worklist;
1363
1364     for (Loop *L : *LI)
1365       addInnerLoop(*L, Worklist);
1366
1367     LoopsAnalyzed += Worklist.size();
1368
1369     // Now walk the identified inner loops.
1370     bool Changed = false;
1371     while (!Worklist.empty())
1372       Changed |= processLoop(Worklist.pop_back_val());
1373
1374     // Process each loop nest in the function.
1375     return Changed;
1376   }
1377
1378   bool processLoop(Loop *L) {
1379     assert(L->empty() && "Only process inner loops.");
1380
1381 #ifndef NDEBUG
1382     const std::string DebugLocStr = getDebugLocString(L);
1383 #endif /* NDEBUG */
1384
1385     DEBUG(dbgs() << "\nLV: Checking a loop in \""
1386                  << L->getHeader()->getParent()->getName() << "\" from "
1387                  << DebugLocStr << "\n");
1388
1389     LoopVectorizeHints Hints(L, DisableUnrolling);
1390
1391     DEBUG(dbgs() << "LV: Loop hints:"
1392                  << " force="
1393                  << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
1394                          ? "disabled"
1395                          : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
1396                                 ? "enabled"
1397                                 : "?")) << " width=" << Hints.getWidth()
1398                  << " unroll=" << Hints.getInterleave() << "\n");
1399
1400     // Function containing loop
1401     Function *F = L->getHeader()->getParent();
1402
1403     // Looking at the diagnostic output is the only way to determine if a loop
1404     // was vectorized (other than looking at the IR or machine code), so it
1405     // is important to generate an optimization remark for each loop. Most of
1406     // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
1407     // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
1408     // less verbose reporting vectorized loops and unvectorized loops that may
1409     // benefit from vectorization, respectively.
1410
1411     if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
1412       DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1413       emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1414                                      L->getStartLoc(), Hints.emitRemark());
1415       return false;
1416     }
1417
1418     if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
1419       DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1420       emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
1421                                      L->getStartLoc(), Hints.emitRemark());
1422       return false;
1423     }
1424
1425     if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
1426       DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1427       emitOptimizationRemarkAnalysis(
1428           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1429           "loop not vectorized: vector width and interleave count are "
1430           "explicitly set to 1");
1431       return false;
1432     }
1433
1434     // Check the loop for a trip count threshold:
1435     // do not vectorize loops with a tiny trip count.
1436     const unsigned TC = SE->getSmallConstantTripCount(L);
1437     if (TC > 0u && TC < TinyTripCountVectorThreshold) {
1438       DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
1439                    << "This loop is not worth vectorizing.");
1440       if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
1441         DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
1442       else {
1443         DEBUG(dbgs() << "\n");
1444         emitOptimizationRemarkAnalysis(
1445             F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1446             "vectorization is not beneficial and is not explicitly forced");
1447         return false;
1448       }
1449     }
1450
1451     // Check if it is legal to vectorize the loop.
1452     LoopVectorizationLegality LVL(L, SE, DL, DT, TLI, AA, F, TTI);
1453     if (!LVL.canVectorize()) {
1454       DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1455       emitMissedWarning(F, L, Hints);
1456       return false;
1457     }
1458
1459     // Use the cost model.
1460     LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI, AC, F,
1461                                   &Hints);
1462
1463     // Check the function attributes to find out if this function should be
1464     // optimized for size.
1465     bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1466                       F->hasFnAttribute(Attribute::OptimizeForSize);
1467
1468     // Compute the weighted frequency of this loop being executed and see if it
1469     // is less than 20% of the function entry baseline frequency. Note that we
1470     // always have a canonical loop here because we think we *can* vectoriez.
1471     // FIXME: This is hidden behind a flag due to pervasive problems with
1472     // exactly what block frequency models.
1473     if (LoopVectorizeWithBlockFrequency) {
1474       BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1475       if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
1476           LoopEntryFreq < ColdEntryFreq)
1477         OptForSize = true;
1478     }
1479
1480     // Check the function attributes to see if implicit floats are allowed.a
1481     // FIXME: This check doesn't seem possibly correct -- what if the loop is
1482     // an integer loop and the vector instructions selected are purely integer
1483     // vector instructions?
1484     if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1485       DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1486             "attribute is used.\n");
1487       emitOptimizationRemarkAnalysis(
1488           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1489           "loop not vectorized due to NoImplicitFloat attribute");
1490       emitMissedWarning(F, L, Hints);
1491       return false;
1492     }
1493
1494     // Select the optimal vectorization factor.
1495     const LoopVectorizationCostModel::VectorizationFactor VF =
1496         CM.selectVectorizationFactor(OptForSize);
1497
1498     // Select the unroll factor.
1499     const unsigned UF =
1500         CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
1501
1502     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
1503                  << DebugLocStr << '\n');
1504     DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1505
1506     if (VF.Width == 1) {
1507       DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
1508
1509       if (UF == 1) {
1510         emitOptimizationRemarkAnalysis(
1511             F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1512             "not beneficial to vectorize and user disabled interleaving");
1513         return false;
1514       }
1515       DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1516
1517       // Report the unrolling decision.
1518       emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1519                              Twine("unrolled with interleaving factor " +
1520                                    Twine(UF) +
1521                                    " (vectorization not beneficial)"));
1522
1523       // We decided not to vectorize, but we may want to unroll.
1524
1525       InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1526       Unroller.vectorize(&LVL);
1527     } else {
1528       // If we decided that it is *legal* to vectorize the loop then do it.
1529       InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1530       LB.vectorize(&LVL);
1531       ++LoopsVectorized;
1532
1533       // Report the vectorization decision.
1534       emitOptimizationRemark(
1535           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
1536           Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
1537               ", unrolling interleave factor: " + Twine(UF) + ")");
1538     }
1539
1540     // Mark the loop as already vectorized to avoid vectorizing again.
1541     Hints.setAlreadyVectorized();
1542
1543     DEBUG(verifyFunction(*L->getHeader()->getParent()));
1544     return true;
1545   }
1546
1547   void getAnalysisUsage(AnalysisUsage &AU) const override {
1548     AU.addRequired<AssumptionCacheTracker>();
1549     AU.addRequiredID(LoopSimplifyID);
1550     AU.addRequiredID(LCSSAID);
1551     AU.addRequired<BlockFrequencyInfo>();
1552     AU.addRequired<DominatorTreeWrapperPass>();
1553     AU.addRequired<LoopInfoWrapperPass>();
1554     AU.addRequired<ScalarEvolution>();
1555     AU.addRequired<TargetTransformInfoWrapperPass>();
1556     AU.addRequired<AliasAnalysis>();
1557     AU.addPreserved<LoopInfoWrapperPass>();
1558     AU.addPreserved<DominatorTreeWrapperPass>();
1559     AU.addPreserved<AliasAnalysis>();
1560   }
1561
1562 };
1563
1564 } // end anonymous namespace
1565
1566 //===----------------------------------------------------------------------===//
1567 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1568 // LoopVectorizationCostModel.
1569 //===----------------------------------------------------------------------===//
1570
1571 static Value *stripIntegerCast(Value *V) {
1572   if (CastInst *CI = dyn_cast<CastInst>(V))
1573     if (CI->getOperand(0)->getType()->isIntegerTy())
1574       return CI->getOperand(0);
1575   return V;
1576 }
1577
1578 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1579 ///
1580 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1581 /// \p Ptr.
1582 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1583                                              ValueToValueMap &PtrToStride,
1584                                              Value *Ptr, Value *OrigPtr = nullptr) {
1585
1586   const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1587
1588   // If there is an entry in the map return the SCEV of the pointer with the
1589   // symbolic stride replaced by one.
1590   ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1591   if (SI != PtrToStride.end()) {
1592     Value *StrideVal = SI->second;
1593
1594     // Strip casts.
1595     StrideVal = stripIntegerCast(StrideVal);
1596
1597     // Replace symbolic stride by one.
1598     Value *One = ConstantInt::get(StrideVal->getType(), 1);
1599     ValueToValueMap RewriteMap;
1600     RewriteMap[StrideVal] = One;
1601
1602     const SCEV *ByOne =
1603         SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1604     DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1605                  << "\n");
1606     return ByOne;
1607   }
1608
1609   // Otherwise, just return the SCEV of the original pointer.
1610   return SE->getSCEV(Ptr);
1611 }
1612
1613 void RuntimePointerCheck::insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr,
1614                                  bool WritePtr, unsigned DepSetId,
1615                                  unsigned ASId, ValueToValueMap &Strides) {
1616   // Get the stride replaced scev.
1617   const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1618   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1619   assert(AR && "Invalid addrec expression");
1620   const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1621   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1622   Pointers.push_back(Ptr);
1623   Starts.push_back(AR->getStart());
1624   Ends.push_back(ScEnd);
1625   IsWritePtr.push_back(WritePtr);
1626   DependencySetId.push_back(DepSetId);
1627   AliasSetId.push_back(ASId);
1628 }
1629
1630 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1631   // We need to place the broadcast of invariant variables outside the loop.
1632   Instruction *Instr = dyn_cast<Instruction>(V);
1633   bool NewInstr =
1634       (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
1635                           Instr->getParent()) != LoopVectorBody.end());
1636   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1637
1638   // Place the code for broadcasting invariant variables in the new preheader.
1639   IRBuilder<>::InsertPointGuard Guard(Builder);
1640   if (Invariant)
1641     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1642
1643   // Broadcast the scalar into all locations in the vector.
1644   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1645
1646   return Shuf;
1647 }
1648
1649 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
1650                                           Value *Step) {
1651   assert(Val->getType()->isVectorTy() && "Must be a vector");
1652   assert(Val->getType()->getScalarType()->isIntegerTy() &&
1653          "Elem must be an integer");
1654   assert(Step->getType() == Val->getType()->getScalarType() &&
1655          "Step has wrong type");
1656   // Create the types.
1657   Type *ITy = Val->getType()->getScalarType();
1658   VectorType *Ty = cast<VectorType>(Val->getType());
1659   int VLen = Ty->getNumElements();
1660   SmallVector<Constant*, 8> Indices;
1661
1662   // Create a vector of consecutive numbers from zero to VF.
1663   for (int i = 0; i < VLen; ++i)
1664     Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
1665
1666   // Add the consecutive indices to the vector value.
1667   Constant *Cv = ConstantVector::get(Indices);
1668   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1669   Step = Builder.CreateVectorSplat(VLen, Step);
1670   assert(Step->getType() == Val->getType() && "Invalid step vec");
1671   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
1672   // which can be found from the original scalar operations.
1673   Step = Builder.CreateMul(Cv, Step);
1674   return Builder.CreateAdd(Val, Step, "induction");
1675 }
1676
1677 /// \brief Find the operand of the GEP that should be checked for consecutive
1678 /// stores. This ignores trailing indices that have no effect on the final
1679 /// pointer.
1680 static unsigned getGEPInductionOperand(const DataLayout *DL,
1681                                        const GetElementPtrInst *Gep) {
1682   unsigned LastOperand = Gep->getNumOperands() - 1;
1683   unsigned GEPAllocSize = DL->getTypeAllocSize(
1684       cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1685
1686   // Walk backwards and try to peel off zeros.
1687   while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1688     // Find the type we're currently indexing into.
1689     gep_type_iterator GEPTI = gep_type_begin(Gep);
1690     std::advance(GEPTI, LastOperand - 1);
1691
1692     // If it's a type with the same allocation size as the result of the GEP we
1693     // can peel off the zero index.
1694     if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1695       break;
1696     --LastOperand;
1697   }
1698
1699   return LastOperand;
1700 }
1701
1702 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1703   assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1704   // Make sure that the pointer does not point to structs.
1705   if (Ptr->getType()->getPointerElementType()->isAggregateType())
1706     return 0;
1707
1708   // If this value is a pointer induction variable we know it is consecutive.
1709   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1710   if (Phi && Inductions.count(Phi)) {
1711     InductionInfo II = Inductions[Phi];
1712     return II.getConsecutiveDirection();
1713   }
1714
1715   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1716   if (!Gep)
1717     return 0;
1718
1719   unsigned NumOperands = Gep->getNumOperands();
1720   Value *GpPtr = Gep->getPointerOperand();
1721   // If this GEP value is a consecutive pointer induction variable and all of
1722   // the indices are constant then we know it is consecutive. We can
1723   Phi = dyn_cast<PHINode>(GpPtr);
1724   if (Phi && Inductions.count(Phi)) {
1725
1726     // Make sure that the pointer does not point to structs.
1727     PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1728     if (GepPtrType->getElementType()->isAggregateType())
1729       return 0;
1730
1731     // Make sure that all of the index operands are loop invariant.
1732     for (unsigned i = 1; i < NumOperands; ++i)
1733       if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1734         return 0;
1735
1736     InductionInfo II = Inductions[Phi];
1737     return II.getConsecutiveDirection();
1738   }
1739
1740   unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1741
1742   // Check that all of the gep indices are uniform except for our induction
1743   // operand.
1744   for (unsigned i = 0; i != NumOperands; ++i)
1745     if (i != InductionOperand &&
1746         !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1747       return 0;
1748
1749   // We can emit wide load/stores only if the last non-zero index is the
1750   // induction variable.
1751   const SCEV *Last = nullptr;
1752   if (!Strides.count(Gep))
1753     Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1754   else {
1755     // Because of the multiplication by a stride we can have a s/zext cast.
1756     // We are going to replace this stride by 1 so the cast is safe to ignore.
1757     //
1758     //  %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1759     //  %0 = trunc i64 %indvars.iv to i32
1760     //  %mul = mul i32 %0, %Stride1
1761     //  %idxprom = zext i32 %mul to i64  << Safe cast.
1762     //  %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1763     //
1764     Last = replaceSymbolicStrideSCEV(SE, Strides,
1765                                      Gep->getOperand(InductionOperand), Gep);
1766     if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1767       Last =
1768           (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1769               ? C->getOperand()
1770               : Last;
1771   }
1772   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1773     const SCEV *Step = AR->getStepRecurrence(*SE);
1774
1775     // The memory is consecutive because the last index is consecutive
1776     // and all other indices are loop invariant.
1777     if (Step->isOne())
1778       return 1;
1779     if (Step->isAllOnesValue())
1780       return -1;
1781   }
1782
1783   return 0;
1784 }
1785
1786 bool LoopVectorizationLegality::isUniform(Value *V) {
1787   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1788 }
1789
1790 InnerLoopVectorizer::VectorParts&
1791 InnerLoopVectorizer::getVectorValue(Value *V) {
1792   assert(V != Induction && "The new induction variable should not be used.");
1793   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1794
1795   // If we have a stride that is replaced by one, do it here.
1796   if (Legal->hasStride(V))
1797     V = ConstantInt::get(V->getType(), 1);
1798
1799   // If we have this scalar in the map, return it.
1800   if (WidenMap.has(V))
1801     return WidenMap.get(V);
1802
1803   // If this scalar is unknown, assume that it is a constant or that it is
1804   // loop invariant. Broadcast V and save the value for future uses.
1805   Value *B = getBroadcastInstrs(V);
1806   return WidenMap.splat(V, B);
1807 }
1808
1809 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1810   assert(Vec->getType()->isVectorTy() && "Invalid type");
1811   SmallVector<Constant*, 8> ShuffleMask;
1812   for (unsigned i = 0; i < VF; ++i)
1813     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1814
1815   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1816                                      ConstantVector::get(ShuffleMask),
1817                                      "reverse");
1818 }
1819
1820 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1821   // Attempt to issue a wide load.
1822   LoadInst *LI = dyn_cast<LoadInst>(Instr);
1823   StoreInst *SI = dyn_cast<StoreInst>(Instr);
1824
1825   assert((LI || SI) && "Invalid Load/Store instruction");
1826
1827   Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1828   Type *DataTy = VectorType::get(ScalarDataTy, VF);
1829   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1830   unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1831   // An alignment of 0 means target abi alignment. We need to use the scalar's
1832   // target abi alignment in such a case.
1833   if (!Alignment)
1834     Alignment = DL->getABITypeAlignment(ScalarDataTy);
1835   unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1836   unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1837   unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1838
1839   if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
1840       !Legal->isMaskRequired(SI))
1841     return scalarizeInstruction(Instr, true);
1842
1843   if (ScalarAllocatedSize != VectorElementSize)
1844     return scalarizeInstruction(Instr);
1845
1846   // If the pointer is loop invariant or if it is non-consecutive,
1847   // scalarize the load.
1848   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1849   bool Reverse = ConsecutiveStride < 0;
1850   bool UniformLoad = LI && Legal->isUniform(Ptr);
1851   if (!ConsecutiveStride || UniformLoad)
1852     return scalarizeInstruction(Instr);
1853
1854   Constant *Zero = Builder.getInt32(0);
1855   VectorParts &Entry = WidenMap.get(Instr);
1856
1857   // Handle consecutive loads/stores.
1858   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1859   if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1860     setDebugLocFromInst(Builder, Gep);
1861     Value *PtrOperand = Gep->getPointerOperand();
1862     Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1863     FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1864
1865     // Create the new GEP with the new induction variable.
1866     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1867     Gep2->setOperand(0, FirstBasePtr);
1868     Gep2->setName("gep.indvar.base");
1869     Ptr = Builder.Insert(Gep2);
1870   } else if (Gep) {
1871     setDebugLocFromInst(Builder, Gep);
1872     assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1873                                OrigLoop) && "Base ptr must be invariant");
1874
1875     // The last index does not have to be the induction. It can be
1876     // consecutive and be a function of the index. For example A[I+1];
1877     unsigned NumOperands = Gep->getNumOperands();
1878     unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1879     // Create the new GEP with the new induction variable.
1880     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1881
1882     for (unsigned i = 0; i < NumOperands; ++i) {
1883       Value *GepOperand = Gep->getOperand(i);
1884       Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1885
1886       // Update last index or loop invariant instruction anchored in loop.
1887       if (i == InductionOperand ||
1888           (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1889         assert((i == InductionOperand ||
1890                SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1891                "Must be last index or loop invariant");
1892
1893         VectorParts &GEPParts = getVectorValue(GepOperand);
1894         Value *Index = GEPParts[0];
1895         Index = Builder.CreateExtractElement(Index, Zero);
1896         Gep2->setOperand(i, Index);
1897         Gep2->setName("gep.indvar.idx");
1898       }
1899     }
1900     Ptr = Builder.Insert(Gep2);
1901   } else {
1902     // Use the induction element ptr.
1903     assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1904     setDebugLocFromInst(Builder, Ptr);
1905     VectorParts &PtrVal = getVectorValue(Ptr);
1906     Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1907   }
1908
1909   VectorParts Mask = createBlockInMask(Instr->getParent());
1910   // Handle Stores:
1911   if (SI) {
1912     assert(!Legal->isUniform(SI->getPointerOperand()) &&
1913            "We do not allow storing to uniform addresses");
1914     setDebugLocFromInst(Builder, SI);
1915     // We don't want to update the value in the map as it might be used in
1916     // another expression. So don't use a reference type for "StoredVal".
1917     VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1918     
1919     for (unsigned Part = 0; Part < UF; ++Part) {
1920       // Calculate the pointer for the specific unroll-part.
1921       Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1922
1923       if (Reverse) {
1924         // If we store to reverse consecutive memory locations then we need
1925         // to reverse the order of elements in the stored value.
1926         StoredVal[Part] = reverseVector(StoredVal[Part]);
1927         // If the address is consecutive but reversed, then the
1928         // wide store needs to start at the last vector element.
1929         PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1930         PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1931         Mask[Part] = reverseVector(Mask[Part]);
1932       }
1933
1934       Value *VecPtr = Builder.CreateBitCast(PartPtr,
1935                                             DataTy->getPointerTo(AddressSpace));
1936
1937       Instruction *NewSI;
1938       if (Legal->isMaskRequired(SI))
1939         NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
1940                                           Mask[Part]);
1941       else 
1942         NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
1943       propagateMetadata(NewSI, SI);
1944     }
1945     return;
1946   }
1947
1948   // Handle loads.
1949   assert(LI && "Must have a load instruction");
1950   setDebugLocFromInst(Builder, LI);
1951   for (unsigned Part = 0; Part < UF; ++Part) {
1952     // Calculate the pointer for the specific unroll-part.
1953     Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1954
1955     if (Reverse) {
1956       // If the address is consecutive but reversed, then the
1957       // wide load needs to start at the last vector element.
1958       PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1959       PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1960       Mask[Part] = reverseVector(Mask[Part]);
1961     }
1962
1963     Instruction* NewLI;
1964     Value *VecPtr = Builder.CreateBitCast(PartPtr,
1965                                           DataTy->getPointerTo(AddressSpace));
1966     if (Legal->isMaskRequired(LI))
1967       NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
1968                                        UndefValue::get(DataTy),
1969                                        "wide.masked.load");
1970     else
1971       NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
1972     propagateMetadata(NewLI, LI);
1973     Entry[Part] = Reverse ? reverseVector(NewLI) :  NewLI;
1974   }
1975 }
1976
1977 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
1978   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1979   // Holds vector parameters or scalars, in case of uniform vals.
1980   SmallVector<VectorParts, 4> Params;
1981
1982   setDebugLocFromInst(Builder, Instr);
1983
1984   // Find all of the vectorized parameters.
1985   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1986     Value *SrcOp = Instr->getOperand(op);
1987
1988     // If we are accessing the old induction variable, use the new one.
1989     if (SrcOp == OldInduction) {
1990       Params.push_back(getVectorValue(SrcOp));
1991       continue;
1992     }
1993
1994     // Try using previously calculated values.
1995     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1996
1997     // If the src is an instruction that appeared earlier in the basic block
1998     // then it should already be vectorized.
1999     if (SrcInst && OrigLoop->contains(SrcInst)) {
2000       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
2001       // The parameter is a vector value from earlier.
2002       Params.push_back(WidenMap.get(SrcInst));
2003     } else {
2004       // The parameter is a scalar from outside the loop. Maybe even a constant.
2005       VectorParts Scalars;
2006       Scalars.append(UF, SrcOp);
2007       Params.push_back(Scalars);
2008     }
2009   }
2010
2011   assert(Params.size() == Instr->getNumOperands() &&
2012          "Invalid number of operands");
2013
2014   // Does this instruction return a value ?
2015   bool IsVoidRetTy = Instr->getType()->isVoidTy();
2016
2017   Value *UndefVec = IsVoidRetTy ? nullptr :
2018     UndefValue::get(VectorType::get(Instr->getType(), VF));
2019   // Create a new entry in the WidenMap and initialize it to Undef or Null.
2020   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
2021
2022   Instruction *InsertPt = Builder.GetInsertPoint();
2023   BasicBlock *IfBlock = Builder.GetInsertBlock();
2024   BasicBlock *CondBlock = nullptr;
2025
2026   VectorParts Cond;
2027   Loop *VectorLp = nullptr;
2028   if (IfPredicateStore) {
2029     assert(Instr->getParent()->getSinglePredecessor() &&
2030            "Only support single predecessor blocks");
2031     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
2032                           Instr->getParent());
2033     VectorLp = LI->getLoopFor(IfBlock);
2034     assert(VectorLp && "Must have a loop for this block");
2035   }
2036
2037   // For each vector unroll 'part':
2038   for (unsigned Part = 0; Part < UF; ++Part) {
2039     // For each scalar that we create:
2040     for (unsigned Width = 0; Width < VF; ++Width) {
2041
2042       // Start if-block.
2043       Value *Cmp = nullptr;
2044       if (IfPredicateStore) {
2045         Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
2046         Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
2047         CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2048         LoopVectorBody.push_back(CondBlock);
2049         VectorLp->addBasicBlockToLoop(CondBlock, *LI);
2050         // Update Builder with newly created basic block.
2051         Builder.SetInsertPoint(InsertPt);
2052       }
2053
2054       Instruction *Cloned = Instr->clone();
2055       if (!IsVoidRetTy)
2056         Cloned->setName(Instr->getName() + ".cloned");
2057       // Replace the operands of the cloned instructions with extracted scalars.
2058       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
2059         Value *Op = Params[op][Part];
2060         // Param is a vector. Need to extract the right lane.
2061         if (Op->getType()->isVectorTy())
2062           Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
2063         Cloned->setOperand(op, Op);
2064       }
2065
2066       // Place the cloned scalar in the new loop.
2067       Builder.Insert(Cloned);
2068
2069       // If the original scalar returns a value we need to place it in a vector
2070       // so that future users will be able to use it.
2071       if (!IsVoidRetTy)
2072         VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
2073                                                        Builder.getInt32(Width));
2074       // End if-block.
2075       if (IfPredicateStore) {
2076          BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2077          LoopVectorBody.push_back(NewIfBlock);
2078          VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
2079          Builder.SetInsertPoint(InsertPt);
2080          Instruction *OldBr = IfBlock->getTerminator();
2081          BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2082          OldBr->eraseFromParent();
2083          IfBlock = NewIfBlock;
2084       }
2085     }
2086   }
2087 }
2088
2089 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
2090                                  Instruction *Loc) {
2091   if (FirstInst)
2092     return FirstInst;
2093   if (Instruction *I = dyn_cast<Instruction>(V))
2094     return I->getParent() == Loc->getParent() ? I : nullptr;
2095   return nullptr;
2096 }
2097
2098 std::pair<Instruction *, Instruction *>
2099 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
2100   Instruction *tnullptr = nullptr;
2101   if (!Legal->mustCheckStrides())
2102     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2103
2104   IRBuilder<> ChkBuilder(Loc);
2105
2106   // Emit checks.
2107   Value *Check = nullptr;
2108   Instruction *FirstInst = nullptr;
2109   for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
2110                                          SE = Legal->strides_end();
2111        SI != SE; ++SI) {
2112     Value *Ptr = stripIntegerCast(*SI);
2113     Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
2114                                        "stride.chk");
2115     // Store the first instruction we create.
2116     FirstInst = getFirstInst(FirstInst, C, Loc);
2117     if (Check)
2118       Check = ChkBuilder.CreateOr(Check, C);
2119     else
2120       Check = C;
2121   }
2122
2123   // We have to do this trickery because the IRBuilder might fold the check to a
2124   // constant expression in which case there is no Instruction anchored in a
2125   // the block.
2126   LLVMContext &Ctx = Loc->getContext();
2127   Instruction *TheCheck =
2128       BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
2129   ChkBuilder.Insert(TheCheck, "stride.not.one");
2130   FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
2131
2132   return std::make_pair(FirstInst, TheCheck);
2133 }
2134
2135 std::pair<Instruction *, Instruction *>
2136 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
2137   RuntimePointerCheck *PtrRtCheck = Legal->getRuntimePointerCheck();
2138
2139   Instruction *tnullptr = nullptr;
2140   if (!PtrRtCheck->Need)
2141     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
2142
2143   unsigned NumPointers = PtrRtCheck->Pointers.size();
2144   SmallVector<TrackingVH<Value> , 2> Starts;
2145   SmallVector<TrackingVH<Value> , 2> Ends;
2146
2147   LLVMContext &Ctx = Loc->getContext();
2148   SCEVExpander Exp(*SE, "induction");
2149   Instruction *FirstInst = nullptr;
2150
2151   for (unsigned i = 0; i < NumPointers; ++i) {
2152     Value *Ptr = PtrRtCheck->Pointers[i];
2153     const SCEV *Sc = SE->getSCEV(Ptr);
2154
2155     if (SE->isLoopInvariant(Sc, OrigLoop)) {
2156       DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
2157             *Ptr <<"\n");
2158       Starts.push_back(Ptr);
2159       Ends.push_back(Ptr);
2160     } else {
2161       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
2162       unsigned AS = Ptr->getType()->getPointerAddressSpace();
2163
2164       // Use this type for pointer arithmetic.
2165       Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
2166
2167       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
2168       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
2169       Starts.push_back(Start);
2170       Ends.push_back(End);
2171     }
2172   }
2173
2174   IRBuilder<> ChkBuilder(Loc);
2175   // Our instructions might fold to a constant.
2176   Value *MemoryRuntimeCheck = nullptr;
2177   for (unsigned i = 0; i < NumPointers; ++i) {
2178     for (unsigned j = i+1; j < NumPointers; ++j) {
2179       // No need to check if two readonly pointers intersect.
2180       if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
2181         continue;
2182
2183       // Only need to check pointers between two different dependency sets.
2184       if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
2185        continue;
2186       // Only need to check pointers in the same alias set.
2187       if (PtrRtCheck->AliasSetId[i] != PtrRtCheck->AliasSetId[j])
2188         continue;
2189
2190       unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
2191       unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
2192
2193       assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
2194              (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
2195              "Trying to bounds check pointers with different address spaces");
2196
2197       Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
2198       Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
2199
2200       Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
2201       Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
2202       Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy1, "bc");
2203       Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy0, "bc");
2204
2205       Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
2206       FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
2207       Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
2208       FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
2209       Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
2210       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2211       if (MemoryRuntimeCheck) {
2212         IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
2213                                          "conflict.rdx");
2214         FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
2215       }
2216       MemoryRuntimeCheck = IsConflict;
2217     }
2218   }
2219
2220   // We have to do this trickery because the IRBuilder might fold the check to a
2221   // constant expression in which case there is no Instruction anchored in a
2222   // the block.
2223   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
2224                                                  ConstantInt::getTrue(Ctx));
2225   ChkBuilder.Insert(Check, "memcheck.conflict");
2226   FirstInst = getFirstInst(FirstInst, Check, Loc);
2227   return std::make_pair(FirstInst, Check);
2228 }
2229
2230 void InnerLoopVectorizer::createEmptyLoop() {
2231   /*
2232    In this function we generate a new loop. The new loop will contain
2233    the vectorized instructions while the old loop will continue to run the
2234    scalar remainder.
2235
2236        [ ] <-- Back-edge taken count overflow check.
2237     /   |
2238    /    v
2239   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
2240   |  /  |
2241   | /   v
2242   ||   [ ]     <-- vector pre header.
2243   ||    |
2244   ||    v
2245   ||   [  ] \
2246   ||   [  ]_|   <-- vector loop.
2247   ||    |
2248   | \   v
2249   |   >[ ]   <--- middle-block.
2250   |  /  |
2251   | /   v
2252   -|- >[ ]     <--- new preheader.
2253    |    |
2254    |    v
2255    |   [ ] \
2256    |   [ ]_|   <-- old scalar loop to handle remainder.
2257     \   |
2258      \  v
2259       >[ ]     <-- exit block.
2260    ...
2261    */
2262
2263   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
2264   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
2265   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
2266   assert(BypassBlock && "Invalid loop structure");
2267   assert(ExitBlock && "Must have an exit block");
2268
2269   // Some loops have a single integer induction variable, while other loops
2270   // don't. One example is c++ iterators that often have multiple pointer
2271   // induction variables. In the code below we also support a case where we
2272   // don't have a single induction variable.
2273   OldInduction = Legal->getInduction();
2274   Type *IdxTy = Legal->getWidestInductionType();
2275
2276   // Find the loop boundaries.
2277   const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
2278   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
2279
2280   // The exit count might have the type of i64 while the phi is i32. This can
2281   // happen if we have an induction variable that is sign extended before the
2282   // compare. The only way that we get a backedge taken count is that the
2283   // induction variable was signed and as such will not overflow. In such a case
2284   // truncation is legal.
2285   if (ExitCount->getType()->getPrimitiveSizeInBits() >
2286       IdxTy->getPrimitiveSizeInBits())
2287     ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
2288
2289   const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
2290   // Get the total trip count from the count by adding 1.
2291   ExitCount = SE->getAddExpr(BackedgeTakeCount,
2292                              SE->getConstant(BackedgeTakeCount->getType(), 1));
2293
2294   // Expand the trip count and place the new instructions in the preheader.
2295   // Notice that the pre-header does not change, only the loop body.
2296   SCEVExpander Exp(*SE, "induction");
2297
2298   // We need to test whether the backedge-taken count is uint##_max. Adding one
2299   // to it will cause overflow and an incorrect loop trip count in the vector
2300   // body. In case of overflow we want to directly jump to the scalar remainder
2301   // loop.
2302   Value *BackedgeCount =
2303       Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
2304                         BypassBlock->getTerminator());
2305   if (BackedgeCount->getType()->isPointerTy())
2306     BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
2307                                                 "backedge.ptrcnt.to.int",
2308                                                 BypassBlock->getTerminator());
2309   Instruction *CheckBCOverflow =
2310       CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
2311                       Constant::getAllOnesValue(BackedgeCount->getType()),
2312                       "backedge.overflow", BypassBlock->getTerminator());
2313
2314   // The loop index does not have to start at Zero. Find the original start
2315   // value from the induction PHI node. If we don't have an induction variable
2316   // then we know that it starts at zero.
2317   Builder.SetInsertPoint(BypassBlock->getTerminator());
2318   Value *StartIdx = ExtendedIdx = OldInduction ?
2319     Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
2320                        IdxTy):
2321     ConstantInt::get(IdxTy, 0);
2322
2323   // We need an instruction to anchor the overflow check on. StartIdx needs to
2324   // be defined before the overflow check branch. Because the scalar preheader
2325   // is going to merge the start index and so the overflow branch block needs to
2326   // contain a definition of the start index.
2327   Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
2328       StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
2329       BypassBlock->getTerminator());
2330
2331   // Count holds the overall loop count (N).
2332   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2333                                    BypassBlock->getTerminator());
2334
2335   LoopBypassBlocks.push_back(BypassBlock);
2336
2337   // Split the single block loop into the two loop structure described above.
2338   BasicBlock *VectorPH =
2339   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
2340   BasicBlock *VecBody =
2341   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
2342   BasicBlock *MiddleBlock =
2343   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
2344   BasicBlock *ScalarPH =
2345   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
2346
2347   // Create and register the new vector loop.
2348   Loop* Lp = new Loop();
2349   Loop *ParentLoop = OrigLoop->getParentLoop();
2350
2351   // Insert the new loop into the loop nest and register the new basic blocks
2352   // before calling any utilities such as SCEV that require valid LoopInfo.
2353   if (ParentLoop) {
2354     ParentLoop->addChildLoop(Lp);
2355     ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
2356     ParentLoop->addBasicBlockToLoop(VectorPH, *LI);
2357     ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
2358   } else {
2359     LI->addTopLevelLoop(Lp);
2360   }
2361   Lp->addBasicBlockToLoop(VecBody, *LI);
2362
2363   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
2364   // inside the loop.
2365   Builder.SetInsertPoint(VecBody->getFirstNonPHI());
2366
2367   // Generate the induction variable.
2368   setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
2369   Induction = Builder.CreatePHI(IdxTy, 2, "index");
2370   // The loop step is equal to the vectorization factor (num of SIMD elements)
2371   // times the unroll factor (num of SIMD instructions).
2372   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
2373
2374   // This is the IR builder that we use to add all of the logic for bypassing
2375   // the new vector loop.
2376   IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
2377   setDebugLocFromInst(BypassBuilder,
2378                       getDebugLocFromInstOrOperands(OldInduction));
2379
2380   // We may need to extend the index in case there is a type mismatch.
2381   // We know that the count starts at zero and does not overflow.
2382   if (Count->getType() != IdxTy) {
2383     // The exit count can be of pointer type. Convert it to the correct
2384     // integer type.
2385     if (ExitCount->getType()->isPointerTy())
2386       Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
2387     else
2388       Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
2389   }
2390
2391   // Add the start index to the loop count to get the new end index.
2392   Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
2393
2394   // Now we need to generate the expression for N - (N % VF), which is
2395   // the part that the vectorized body will execute.
2396   Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
2397   Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
2398   Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
2399                                                      "end.idx.rnd.down");
2400
2401   // Now, compare the new count to zero. If it is zero skip the vector loop and
2402   // jump to the scalar loop.
2403   Value *Cmp =
2404       BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
2405
2406   BasicBlock *LastBypassBlock = BypassBlock;
2407
2408   // Generate code to check that the loops trip count that we computed by adding
2409   // one to the backedge-taken count will not overflow.
2410   {
2411     auto PastOverflowCheck =
2412         std::next(BasicBlock::iterator(OverflowCheckAnchor));
2413     BasicBlock *CheckBlock =
2414       LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
2415     if (ParentLoop)
2416       ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2417     LoopBypassBlocks.push_back(CheckBlock);
2418     Instruction *OldTerm = LastBypassBlock->getTerminator();
2419     BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
2420     OldTerm->eraseFromParent();
2421     LastBypassBlock = CheckBlock;
2422   }
2423
2424   // Generate the code to check that the strides we assumed to be one are really
2425   // one. We want the new basic block to start at the first instruction in a
2426   // sequence of instructions that form a check.
2427   Instruction *StrideCheck;
2428   Instruction *FirstCheckInst;
2429   std::tie(FirstCheckInst, StrideCheck) =
2430       addStrideCheck(LastBypassBlock->getTerminator());
2431   if (StrideCheck) {
2432     // Create a new block containing the stride check.
2433     BasicBlock *CheckBlock =
2434         LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
2435     if (ParentLoop)
2436       ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2437     LoopBypassBlocks.push_back(CheckBlock);
2438
2439     // Replace the branch into the memory check block with a conditional branch
2440     // for the "few elements case".
2441     Instruction *OldTerm = LastBypassBlock->getTerminator();
2442     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2443     OldTerm->eraseFromParent();
2444
2445     Cmp = StrideCheck;
2446     LastBypassBlock = CheckBlock;
2447   }
2448
2449   // Generate the code that checks in runtime if arrays overlap. We put the
2450   // checks into a separate block to make the more common case of few elements
2451   // faster.
2452   Instruction *MemRuntimeCheck;
2453   std::tie(FirstCheckInst, MemRuntimeCheck) =
2454       addRuntimeCheck(LastBypassBlock->getTerminator());
2455   if (MemRuntimeCheck) {
2456     // Create a new block containing the memory check.
2457     BasicBlock *CheckBlock =
2458         LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
2459     if (ParentLoop)
2460       ParentLoop->addBasicBlockToLoop(CheckBlock, *LI);
2461     LoopBypassBlocks.push_back(CheckBlock);
2462
2463     // Replace the branch into the memory check block with a conditional branch
2464     // for the "few elements case".
2465     Instruction *OldTerm = LastBypassBlock->getTerminator();
2466     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
2467     OldTerm->eraseFromParent();
2468
2469     Cmp = MemRuntimeCheck;
2470     LastBypassBlock = CheckBlock;
2471   }
2472
2473   LastBypassBlock->getTerminator()->eraseFromParent();
2474   BranchInst::Create(MiddleBlock, VectorPH, Cmp,
2475                      LastBypassBlock);
2476
2477   // We are going to resume the execution of the scalar loop.
2478   // Go over all of the induction variables that we found and fix the
2479   // PHIs that are left in the scalar version of the loop.
2480   // The starting values of PHI nodes depend on the counter of the last
2481   // iteration in the vectorized loop.
2482   // If we come from a bypass edge then we need to start from the original
2483   // start value.
2484
2485   // This variable saves the new starting index for the scalar loop.
2486   PHINode *ResumeIndex = nullptr;
2487   LoopVectorizationLegality::InductionList::iterator I, E;
2488   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
2489   // Set builder to point to last bypass block.
2490   BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
2491   for (I = List->begin(), E = List->end(); I != E; ++I) {
2492     PHINode *OrigPhi = I->first;
2493     LoopVectorizationLegality::InductionInfo II = I->second;
2494
2495     Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
2496     PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
2497                                          MiddleBlock->getTerminator());
2498     // We might have extended the type of the induction variable but we need a
2499     // truncated version for the scalar loop.
2500     PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
2501       PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
2502                       MiddleBlock->getTerminator()) : nullptr;
2503
2504     // Create phi nodes to merge from the  backedge-taken check block.
2505     PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
2506                                            ScalarPH->getTerminator());
2507     BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
2508
2509     PHINode *BCTruncResumeVal = nullptr;
2510     if (OrigPhi == OldInduction) {
2511       BCTruncResumeVal =
2512           PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
2513                           ScalarPH->getTerminator());
2514       BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
2515     }
2516
2517     Value *EndValue = nullptr;
2518     switch (II.IK) {
2519     case LoopVectorizationLegality::IK_NoInduction:
2520       llvm_unreachable("Unknown induction");
2521     case LoopVectorizationLegality::IK_IntInduction: {
2522       // Handle the integer induction counter.
2523       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
2524
2525       // We have the canonical induction variable.
2526       if (OrigPhi == OldInduction) {
2527         // Create a truncated version of the resume value for the scalar loop,
2528         // we might have promoted the type to a larger width.
2529         EndValue =
2530           BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
2531         // The new PHI merges the original incoming value, in case of a bypass,
2532         // or the value at the end of the vectorized loop.
2533         for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2534           TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2535         TruncResumeVal->addIncoming(EndValue, VecBody);
2536
2537         BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2538
2539         // We know what the end value is.
2540         EndValue = IdxEndRoundDown;
2541         // We also know which PHI node holds it.
2542         ResumeIndex = ResumeVal;
2543         break;
2544       }
2545
2546       // Not the canonical induction variable - add the vector loop count to the
2547       // start value.
2548       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2549                                                    II.StartValue->getType(),
2550                                                    "cast.crd");
2551       EndValue = II.transform(BypassBuilder, CRD);
2552       EndValue->setName("ind.end");
2553       break;
2554     }
2555     case LoopVectorizationLegality::IK_PtrInduction: {
2556       EndValue = II.transform(BypassBuilder, CountRoundDown);
2557       EndValue->setName("ptr.ind.end");
2558       break;
2559     }
2560     }// end of case
2561
2562     // The new PHI merges the original incoming value, in case of a bypass,
2563     // or the value at the end of the vectorized loop.
2564     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
2565       if (OrigPhi == OldInduction)
2566         ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2567       else
2568         ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2569     }
2570     ResumeVal->addIncoming(EndValue, VecBody);
2571
2572     // Fix the scalar body counter (PHI node).
2573     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2574
2575     // The old induction's phi node in the scalar body needs the truncated
2576     // value.
2577     if (OrigPhi == OldInduction) {
2578       BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
2579       OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
2580     } else {
2581       BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
2582       OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
2583     }
2584   }
2585
2586   // If we are generating a new induction variable then we also need to
2587   // generate the code that calculates the exit value. This value is not
2588   // simply the end of the counter because we may skip the vectorized body
2589   // in case of a runtime check.
2590   if (!OldInduction){
2591     assert(!ResumeIndex && "Unexpected resume value found");
2592     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2593                                   MiddleBlock->getTerminator());
2594     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2595       ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2596     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2597   }
2598
2599   // Make sure that we found the index where scalar loop needs to continue.
2600   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2601          "Invalid resume Index");
2602
2603   // Add a check in the middle block to see if we have completed
2604   // all of the iterations in the first vector loop.
2605   // If (N - N%VF) == N, then we *don't* need to run the remainder.
2606   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2607                                 ResumeIndex, "cmp.n",
2608                                 MiddleBlock->getTerminator());
2609
2610   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2611   // Remove the old terminator.
2612   MiddleBlock->getTerminator()->eraseFromParent();
2613
2614   // Create i+1 and fill the PHINode.
2615   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2616   Induction->addIncoming(StartIdx, VectorPH);
2617   Induction->addIncoming(NextIdx, VecBody);
2618   // Create the compare.
2619   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2620   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2621
2622   // Now we have two terminators. Remove the old one from the block.
2623   VecBody->getTerminator()->eraseFromParent();
2624
2625   // Get ready to start creating new instructions into the vectorized body.
2626   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2627
2628   // Save the state.
2629   LoopVectorPreHeader = VectorPH;
2630   LoopScalarPreHeader = ScalarPH;
2631   LoopMiddleBlock = MiddleBlock;
2632   LoopExitBlock = ExitBlock;
2633   LoopVectorBody.push_back(VecBody);
2634   LoopScalarBody = OldBasicBlock;
2635
2636   LoopVectorizeHints Hints(Lp, true);
2637   Hints.setAlreadyVectorized();
2638 }
2639
2640 /// This function returns the identity element (or neutral element) for
2641 /// the operation K.
2642 Constant*
2643 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2644   switch (K) {
2645   case RK_IntegerXor:
2646   case RK_IntegerAdd:
2647   case RK_IntegerOr:
2648     // Adding, Xoring, Oring zero to a number does not change it.
2649     return ConstantInt::get(Tp, 0);
2650   case RK_IntegerMult:
2651     // Multiplying a number by 1 does not change it.
2652     return ConstantInt::get(Tp, 1);
2653   case RK_IntegerAnd:
2654     // AND-ing a number with an all-1 value does not change it.
2655     return ConstantInt::get(Tp, -1, true);
2656   case  RK_FloatMult:
2657     // Multiplying a number by 1 does not change it.
2658     return ConstantFP::get(Tp, 1.0L);
2659   case  RK_FloatAdd:
2660     // Adding zero to a number does not change it.
2661     return ConstantFP::get(Tp, 0.0L);
2662   default:
2663     llvm_unreachable("Unknown reduction kind");
2664   }
2665 }
2666
2667 /// This function translates the reduction kind to an LLVM binary operator.
2668 static unsigned
2669 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2670   switch (Kind) {
2671     case LoopVectorizationLegality::RK_IntegerAdd:
2672       return Instruction::Add;
2673     case LoopVectorizationLegality::RK_IntegerMult:
2674       return Instruction::Mul;
2675     case LoopVectorizationLegality::RK_IntegerOr:
2676       return Instruction::Or;
2677     case LoopVectorizationLegality::RK_IntegerAnd:
2678       return Instruction::And;
2679     case LoopVectorizationLegality::RK_IntegerXor:
2680       return Instruction::Xor;
2681     case LoopVectorizationLegality::RK_FloatMult:
2682       return Instruction::FMul;
2683     case LoopVectorizationLegality::RK_FloatAdd:
2684       return Instruction::FAdd;
2685     case LoopVectorizationLegality::RK_IntegerMinMax:
2686       return Instruction::ICmp;
2687     case LoopVectorizationLegality::RK_FloatMinMax:
2688       return Instruction::FCmp;
2689     default:
2690       llvm_unreachable("Unknown reduction operation");
2691   }
2692 }
2693
2694 Value *createMinMaxOp(IRBuilder<> &Builder,
2695                       LoopVectorizationLegality::MinMaxReductionKind RK,
2696                       Value *Left,
2697                       Value *Right) {
2698   CmpInst::Predicate P = CmpInst::ICMP_NE;
2699   switch (RK) {
2700   default:
2701     llvm_unreachable("Unknown min/max reduction kind");
2702   case LoopVectorizationLegality::MRK_UIntMin:
2703     P = CmpInst::ICMP_ULT;
2704     break;
2705   case LoopVectorizationLegality::MRK_UIntMax:
2706     P = CmpInst::ICMP_UGT;
2707     break;
2708   case LoopVectorizationLegality::MRK_SIntMin:
2709     P = CmpInst::ICMP_SLT;
2710     break;
2711   case LoopVectorizationLegality::MRK_SIntMax:
2712     P = CmpInst::ICMP_SGT;
2713     break;
2714   case LoopVectorizationLegality::MRK_FloatMin:
2715     P = CmpInst::FCMP_OLT;
2716     break;
2717   case LoopVectorizationLegality::MRK_FloatMax:
2718     P = CmpInst::FCMP_OGT;
2719     break;
2720   }
2721
2722   Value *Cmp;
2723   if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2724       RK == LoopVectorizationLegality::MRK_FloatMax)
2725     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2726   else
2727     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2728
2729   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2730   return Select;
2731 }
2732
2733 namespace {
2734 struct CSEDenseMapInfo {
2735   static bool canHandle(Instruction *I) {
2736     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2737            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2738   }
2739   static inline Instruction *getEmptyKey() {
2740     return DenseMapInfo<Instruction *>::getEmptyKey();
2741   }
2742   static inline Instruction *getTombstoneKey() {
2743     return DenseMapInfo<Instruction *>::getTombstoneKey();
2744   }
2745   static unsigned getHashValue(Instruction *I) {
2746     assert(canHandle(I) && "Unknown instruction!");
2747     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2748                                                            I->value_op_end()));
2749   }
2750   static bool isEqual(Instruction *LHS, Instruction *RHS) {
2751     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2752         LHS == getTombstoneKey() || RHS == getTombstoneKey())
2753       return LHS == RHS;
2754     return LHS->isIdenticalTo(RHS);
2755   }
2756 };
2757 }
2758
2759 /// \brief Check whether this block is a predicated block.
2760 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
2761 /// = ...;  " blocks. We start with one vectorized basic block. For every
2762 /// conditional block we split this vectorized block. Therefore, every second
2763 /// block will be a predicated one.
2764 static bool isPredicatedBlock(unsigned BlockNum) {
2765   return BlockNum % 2;
2766 }
2767
2768 ///\brief Perform cse of induction variable instructions.
2769 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
2770   // Perform simple cse.
2771   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2772   for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
2773     BasicBlock *BB = BBs[i];
2774     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2775       Instruction *In = I++;
2776
2777       if (!CSEDenseMapInfo::canHandle(In))
2778         continue;
2779
2780       // Check if we can replace this instruction with any of the
2781       // visited instructions.
2782       if (Instruction *V = CSEMap.lookup(In)) {
2783         In->replaceAllUsesWith(V);
2784         In->eraseFromParent();
2785         continue;
2786       }
2787       // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
2788       // ...;" blocks for predicated stores. Every second block is a predicated
2789       // block.
2790       if (isPredicatedBlock(i))
2791         continue;
2792
2793       CSEMap[In] = In;
2794     }
2795   }
2796 }
2797
2798 /// \brief Adds a 'fast' flag to floating point operations.
2799 static Value *addFastMathFlag(Value *V) {
2800   if (isa<FPMathOperator>(V)){
2801     FastMathFlags Flags;
2802     Flags.setUnsafeAlgebra();
2803     cast<Instruction>(V)->setFastMathFlags(Flags);
2804   }
2805   return V;
2806 }
2807
2808 void InnerLoopVectorizer::vectorizeLoop() {
2809   //===------------------------------------------------===//
2810   //
2811   // Notice: any optimization or new instruction that go
2812   // into the code below should be also be implemented in
2813   // the cost-model.
2814   //
2815   //===------------------------------------------------===//
2816   Constant *Zero = Builder.getInt32(0);
2817
2818   // In order to support reduction variables we need to be able to vectorize
2819   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2820   // stages. First, we create a new vector PHI node with no incoming edges.
2821   // We use this value when we vectorize all of the instructions that use the
2822   // PHI. Next, after all of the instructions in the block are complete we
2823   // add the new incoming edges to the PHI. At this point all of the
2824   // instructions in the basic block are vectorized, so we can use them to
2825   // construct the PHI.
2826   PhiVector RdxPHIsToFix;
2827
2828   // Scan the loop in a topological order to ensure that defs are vectorized
2829   // before users.
2830   LoopBlocksDFS DFS(OrigLoop);
2831   DFS.perform(LI);
2832
2833   // Vectorize all of the blocks in the original loop.
2834   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2835        be = DFS.endRPO(); bb != be; ++bb)
2836     vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2837
2838   // At this point every instruction in the original loop is widened to
2839   // a vector form. We are almost done. Now, we need to fix the PHI nodes
2840   // that we vectorized. The PHI nodes are currently empty because we did
2841   // not want to introduce cycles. Notice that the remaining PHI nodes
2842   // that we need to fix are reduction variables.
2843
2844   // Create the 'reduced' values for each of the induction vars.
2845   // The reduced values are the vector values that we scalarize and combine
2846   // after the loop is finished.
2847   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2848        it != e; ++it) {
2849     PHINode *RdxPhi = *it;
2850     assert(RdxPhi && "Unable to recover vectorized PHI");
2851
2852     // Find the reduction variable descriptor.
2853     assert(Legal->getReductionVars()->count(RdxPhi) &&
2854            "Unable to find the reduction variable");
2855     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2856     (*Legal->getReductionVars())[RdxPhi];
2857
2858     setDebugLocFromInst(Builder, RdxDesc.StartValue);
2859
2860     // We need to generate a reduction vector from the incoming scalar.
2861     // To do so, we need to generate the 'identity' vector and override
2862     // one of the elements with the incoming scalar reduction. We need
2863     // to do it in the vector-loop preheader.
2864     Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
2865
2866     // This is the vector-clone of the value that leaves the loop.
2867     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2868     Type *VecTy = VectorExit[0]->getType();
2869
2870     // Find the reduction identity variable. Zero for addition, or, xor,
2871     // one for multiplication, -1 for And.
2872     Value *Identity;
2873     Value *VectorStart;
2874     if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2875         RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2876       // MinMax reduction have the start value as their identify.
2877       if (VF == 1) {
2878         VectorStart = Identity = RdxDesc.StartValue;
2879       } else {
2880         VectorStart = Identity = Builder.CreateVectorSplat(VF,
2881                                                            RdxDesc.StartValue,
2882                                                            "minmax.ident");
2883       }
2884     } else {
2885       // Handle other reduction kinds:
2886       Constant *Iden =
2887       LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2888                                                       VecTy->getScalarType());
2889       if (VF == 1) {
2890         Identity = Iden;
2891         // This vector is the Identity vector where the first element is the
2892         // incoming scalar reduction.
2893         VectorStart = RdxDesc.StartValue;
2894       } else {
2895         Identity = ConstantVector::getSplat(VF, Iden);
2896
2897         // This vector is the Identity vector where the first element is the
2898         // incoming scalar reduction.
2899         VectorStart = Builder.CreateInsertElement(Identity,
2900                                                   RdxDesc.StartValue, Zero);
2901       }
2902     }
2903
2904     // Fix the vector-loop phi.
2905
2906     // Reductions do not have to start at zero. They can start with
2907     // any loop invariant values.
2908     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2909     BasicBlock *Latch = OrigLoop->getLoopLatch();
2910     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2911     VectorParts &Val = getVectorValue(LoopVal);
2912     for (unsigned part = 0; part < UF; ++part) {
2913       // Make sure to add the reduction stat value only to the
2914       // first unroll part.
2915       Value *StartVal = (part == 0) ? VectorStart : Identity;
2916       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
2917                                                   LoopVectorPreHeader);
2918       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
2919                                                   LoopVectorBody.back());
2920     }
2921
2922     // Before each round, move the insertion point right between
2923     // the PHIs and the values we are going to write.
2924     // This allows us to write both PHINodes and the extractelement
2925     // instructions.
2926     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2927
2928     VectorParts RdxParts;
2929     setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2930     for (unsigned part = 0; part < UF; ++part) {
2931       // This PHINode contains the vectorized reduction variable, or
2932       // the initial value vector, if we bypass the vector loop.
2933       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2934       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2935       Value *StartVal = (part == 0) ? VectorStart : Identity;
2936       for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2937         NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2938       NewPhi->addIncoming(RdxExitVal[part],
2939                           LoopVectorBody.back());
2940       RdxParts.push_back(NewPhi);
2941     }
2942
2943     // Reduce all of the unrolled parts into a single vector.
2944     Value *ReducedPartRdx = RdxParts[0];
2945     unsigned Op = getReductionBinOp(RdxDesc.Kind);
2946     setDebugLocFromInst(Builder, ReducedPartRdx);
2947     for (unsigned part = 1; part < UF; ++part) {
2948       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2949         // Floating point operations had to be 'fast' to enable the reduction.
2950         ReducedPartRdx = addFastMathFlag(
2951             Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
2952                                 ReducedPartRdx, "bin.rdx"));
2953       else
2954         ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2955                                         ReducedPartRdx, RdxParts[part]);
2956     }
2957
2958     if (VF > 1) {
2959       // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2960       // and vector ops, reducing the set of values being computed by half each
2961       // round.
2962       assert(isPowerOf2_32(VF) &&
2963              "Reduction emission only supported for pow2 vectors!");
2964       Value *TmpVec = ReducedPartRdx;
2965       SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
2966       for (unsigned i = VF; i != 1; i >>= 1) {
2967         // Move the upper half of the vector to the lower half.
2968         for (unsigned j = 0; j != i/2; ++j)
2969           ShuffleMask[j] = Builder.getInt32(i/2 + j);
2970
2971         // Fill the rest of the mask with undef.
2972         std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2973                   UndefValue::get(Builder.getInt32Ty()));
2974
2975         Value *Shuf =
2976         Builder.CreateShuffleVector(TmpVec,
2977                                     UndefValue::get(TmpVec->getType()),
2978                                     ConstantVector::get(ShuffleMask),
2979                                     "rdx.shuf");
2980
2981         if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2982           // Floating point operations had to be 'fast' to enable the reduction.
2983           TmpVec = addFastMathFlag(Builder.CreateBinOp(
2984               (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
2985         else
2986           TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2987       }
2988
2989       // The result is in the first element of the vector.
2990       ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2991                                                     Builder.getInt32(0));
2992     }
2993
2994     // Create a phi node that merges control-flow from the backedge-taken check
2995     // block and the middle block.
2996     PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
2997                                           LoopScalarPreHeader->getTerminator());
2998     BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
2999     BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3000
3001     // Now, we need to fix the users of the reduction variable
3002     // inside and outside of the scalar remainder loop.
3003     // We know that the loop is in LCSSA form. We need to update the
3004     // PHI nodes in the exit blocks.
3005     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3006          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3007       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3008       if (!LCSSAPhi) break;
3009
3010       // All PHINodes need to have a single entry edge, or two if
3011       // we already fixed them.
3012       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3013
3014       // We found our reduction value exit-PHI. Update it with the
3015       // incoming bypass edge.
3016       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
3017         // Add an edge coming from the bypass.
3018         LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3019         break;
3020       }
3021     }// end of the LCSSA phi scan.
3022
3023     // Fix the scalar loop reduction variable with the incoming reduction sum
3024     // from the vector body and from the backedge value.
3025     int IncomingEdgeBlockIdx =
3026     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
3027     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3028     // Pick the other block.
3029     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3030     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3031     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
3032   }// end of for each redux variable.
3033
3034   fixLCSSAPHIs();
3035
3036   // Remove redundant induction instructions.
3037   cse(LoopVectorBody);
3038 }
3039
3040 void InnerLoopVectorizer::fixLCSSAPHIs() {
3041   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3042        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
3043     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3044     if (!LCSSAPhi) break;
3045     if (LCSSAPhi->getNumIncomingValues() == 1)
3046       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
3047                             LoopMiddleBlock);
3048   }
3049 }
3050
3051 InnerLoopVectorizer::VectorParts
3052 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
3053   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
3054          "Invalid edge");
3055
3056   // Look for cached value.
3057   std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
3058   EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
3059   if (ECEntryIt != MaskCache.end())
3060     return ECEntryIt->second;
3061
3062   VectorParts SrcMask = createBlockInMask(Src);
3063
3064   // The terminator has to be a branch inst!
3065   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
3066   assert(BI && "Unexpected terminator found");
3067
3068   if (BI->isConditional()) {
3069     VectorParts EdgeMask = getVectorValue(BI->getCondition());
3070
3071     if (BI->getSuccessor(0) != Dst)
3072       for (unsigned part = 0; part < UF; ++part)
3073         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
3074
3075     for (unsigned part = 0; part < UF; ++part)
3076       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
3077
3078     MaskCache[Edge] = EdgeMask;
3079     return EdgeMask;
3080   }
3081
3082   MaskCache[Edge] = SrcMask;
3083   return SrcMask;
3084 }
3085
3086 InnerLoopVectorizer::VectorParts
3087 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
3088   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
3089
3090   // Loop incoming mask is all-one.
3091   if (OrigLoop->getHeader() == BB) {
3092     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
3093     return getVectorValue(C);
3094   }
3095
3096   // This is the block mask. We OR all incoming edges, and with zero.
3097   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
3098   VectorParts BlockMask = getVectorValue(Zero);
3099
3100   // For each pred:
3101   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
3102     VectorParts EM = createEdgeMask(*it, BB);
3103     for (unsigned part = 0; part < UF; ++part)
3104       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
3105   }
3106
3107   return BlockMask;
3108 }
3109
3110 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
3111                                               InnerLoopVectorizer::VectorParts &Entry,
3112                                               unsigned UF, unsigned VF, PhiVector *PV) {
3113   PHINode* P = cast<PHINode>(PN);
3114   // Handle reduction variables:
3115   if (Legal->getReductionVars()->count(P)) {
3116     for (unsigned part = 0; part < UF; ++part) {
3117       // This is phase one of vectorizing PHIs.
3118       Type *VecTy = (VF == 1) ? PN->getType() :
3119       VectorType::get(PN->getType(), VF);
3120       Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
3121                                     LoopVectorBody.back()-> getFirstInsertionPt());
3122     }
3123     PV->push_back(P);
3124     return;
3125   }
3126
3127   setDebugLocFromInst(Builder, P);
3128   // Check for PHI nodes that are lowered to vector selects.
3129   if (P->getParent() != OrigLoop->getHeader()) {
3130     // We know that all PHIs in non-header blocks are converted into
3131     // selects, so we don't have to worry about the insertion order and we
3132     // can just use the builder.
3133     // At this point we generate the predication tree. There may be
3134     // duplications since this is a simple recursive scan, but future
3135     // optimizations will clean it up.
3136
3137     unsigned NumIncoming = P->getNumIncomingValues();
3138
3139     // Generate a sequence of selects of the form:
3140     // SELECT(Mask3, In3,
3141     //      SELECT(Mask2, In2,
3142     //                   ( ...)))
3143     for (unsigned In = 0; In < NumIncoming; In++) {
3144       VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
3145                                         P->getParent());
3146       VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
3147
3148       for (unsigned part = 0; part < UF; ++part) {
3149         // We might have single edge PHIs (blocks) - use an identity
3150         // 'select' for the first PHI operand.
3151         if (In == 0)
3152           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3153                                              In0[part]);
3154         else
3155           // Select between the current value and the previous incoming edge
3156           // based on the incoming mask.
3157           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
3158                                              Entry[part], "predphi");
3159       }
3160     }
3161     return;
3162   }
3163
3164   // This PHINode must be an induction variable.
3165   // Make sure that we know about it.
3166   assert(Legal->getInductionVars()->count(P) &&
3167          "Not an induction variable");
3168
3169   LoopVectorizationLegality::InductionInfo II =
3170   Legal->getInductionVars()->lookup(P);
3171
3172   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
3173   // which can be found from the original scalar operations.
3174   switch (II.IK) {
3175     case LoopVectorizationLegality::IK_NoInduction:
3176       llvm_unreachable("Unknown induction");
3177     case LoopVectorizationLegality::IK_IntInduction: {
3178       assert(P->getType() == II.StartValue->getType() && "Types must match");
3179       Type *PhiTy = P->getType();
3180       Value *Broadcasted;
3181       if (P == OldInduction) {
3182         // Handle the canonical induction variable. We might have had to
3183         // extend the type.
3184         Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
3185       } else {
3186         // Handle other induction variables that are now based on the
3187         // canonical one.
3188         Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
3189                                                  "normalized.idx");
3190         NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
3191         Broadcasted = II.transform(Builder, NormalizedIdx);
3192         Broadcasted->setName("offset.idx");
3193       }
3194       Broadcasted = getBroadcastInstrs(Broadcasted);
3195       // After broadcasting the induction variable we need to make the vector
3196       // consecutive by adding 0, 1, 2, etc.
3197       for (unsigned part = 0; part < UF; ++part)
3198         Entry[part] = getStepVector(Broadcasted, VF * part, II.StepValue);
3199       return;
3200     }
3201     case LoopVectorizationLegality::IK_PtrInduction:
3202       // Handle the pointer induction variable case.
3203       assert(P->getType()->isPointerTy() && "Unexpected type.");
3204       // This is the normalized GEP that starts counting at zero.
3205       Value *NormalizedIdx =
3206           Builder.CreateSub(Induction, ExtendedIdx, "normalized.idx");
3207       // This is the vector of results. Notice that we don't generate
3208       // vector geps because scalar geps result in better code.
3209       for (unsigned part = 0; part < UF; ++part) {
3210         if (VF == 1) {
3211           int EltIndex = part;
3212           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3213           Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3214           Value *SclrGep = II.transform(Builder, GlobalIdx);
3215           SclrGep->setName("next.gep");
3216           Entry[part] = SclrGep;
3217           continue;
3218         }
3219
3220         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
3221         for (unsigned int i = 0; i < VF; ++i) {
3222           int EltIndex = i + part * VF;
3223           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
3224           Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx);
3225           Value *SclrGep = II.transform(Builder, GlobalIdx);
3226           SclrGep->setName("next.gep");
3227           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
3228                                                Builder.getInt32(i),
3229                                                "insert.gep");
3230         }
3231         Entry[part] = VecVal;
3232       }
3233       return;
3234   }
3235 }
3236
3237 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
3238   // For each instruction in the old loop.
3239   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3240     VectorParts &Entry = WidenMap.get(it);
3241     switch (it->getOpcode()) {
3242     case Instruction::Br:
3243       // Nothing to do for PHIs and BR, since we already took care of the
3244       // loop control flow instructions.
3245       continue;
3246     case Instruction::PHI: {
3247       // Vectorize PHINodes.
3248       widenPHIInstruction(it, Entry, UF, VF, PV);
3249       continue;
3250     }// End of PHI.
3251
3252     case Instruction::Add:
3253     case Instruction::FAdd:
3254     case Instruction::Sub:
3255     case Instruction::FSub:
3256     case Instruction::Mul:
3257     case Instruction::FMul:
3258     case Instruction::UDiv:
3259     case Instruction::SDiv:
3260     case Instruction::FDiv:
3261     case Instruction::URem:
3262     case Instruction::SRem:
3263     case Instruction::FRem:
3264     case Instruction::Shl:
3265     case Instruction::LShr:
3266     case Instruction::AShr:
3267     case Instruction::And:
3268     case Instruction::Or:
3269     case Instruction::Xor: {
3270       // Just widen binops.
3271       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
3272       setDebugLocFromInst(Builder, BinOp);
3273       VectorParts &A = getVectorValue(it->getOperand(0));
3274       VectorParts &B = getVectorValue(it->getOperand(1));
3275
3276       // Use this vector value for all users of the original instruction.
3277       for (unsigned Part = 0; Part < UF; ++Part) {
3278         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
3279
3280         if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
3281           VecOp->copyIRFlags(BinOp);
3282
3283         Entry[Part] = V;
3284       }
3285
3286       propagateMetadata(Entry, it);
3287       break;
3288     }
3289     case Instruction::Select: {
3290       // Widen selects.
3291       // If the selector is loop invariant we can create a select
3292       // instruction with a scalar condition. Otherwise, use vector-select.
3293       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
3294                                                OrigLoop);
3295       setDebugLocFromInst(Builder, it);
3296
3297       // The condition can be loop invariant  but still defined inside the
3298       // loop. This means that we can't just use the original 'cond' value.
3299       // We have to take the 'vectorized' value and pick the first lane.
3300       // Instcombine will make this a no-op.
3301       VectorParts &Cond = getVectorValue(it->getOperand(0));
3302       VectorParts &Op0  = getVectorValue(it->getOperand(1));
3303       VectorParts &Op1  = getVectorValue(it->getOperand(2));
3304
3305       Value *ScalarCond = (VF == 1) ? Cond[0] :
3306         Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
3307
3308       for (unsigned Part = 0; Part < UF; ++Part) {
3309         Entry[Part] = Builder.CreateSelect(
3310           InvariantCond ? ScalarCond : Cond[Part],
3311           Op0[Part],
3312           Op1[Part]);
3313       }
3314
3315       propagateMetadata(Entry, it);
3316       break;
3317     }
3318
3319     case Instruction::ICmp:
3320     case Instruction::FCmp: {
3321       // Widen compares. Generate vector compares.
3322       bool FCmp = (it->getOpcode() == Instruction::FCmp);
3323       CmpInst *Cmp = dyn_cast<CmpInst>(it);
3324       setDebugLocFromInst(Builder, it);
3325       VectorParts &A = getVectorValue(it->getOperand(0));
3326       VectorParts &B = getVectorValue(it->getOperand(1));
3327       for (unsigned Part = 0; Part < UF; ++Part) {
3328         Value *C = nullptr;
3329         if (FCmp)
3330           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
3331         else
3332           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
3333         Entry[Part] = C;
3334       }
3335
3336       propagateMetadata(Entry, it);
3337       break;
3338     }
3339
3340     case Instruction::Store:
3341     case Instruction::Load:
3342       vectorizeMemoryInstruction(it);
3343         break;
3344     case Instruction::ZExt:
3345     case Instruction::SExt:
3346     case Instruction::FPToUI:
3347     case Instruction::FPToSI:
3348     case Instruction::FPExt:
3349     case Instruction::PtrToInt:
3350     case Instruction::IntToPtr:
3351     case Instruction::SIToFP:
3352     case Instruction::UIToFP:
3353     case Instruction::Trunc:
3354     case Instruction::FPTrunc:
3355     case Instruction::BitCast: {
3356       CastInst *CI = dyn_cast<CastInst>(it);
3357       setDebugLocFromInst(Builder, it);
3358       /// Optimize the special case where the source is the induction
3359       /// variable. Notice that we can only optimize the 'trunc' case
3360       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
3361       /// c. other casts depend on pointer size.
3362       if (CI->getOperand(0) == OldInduction &&
3363           it->getOpcode() == Instruction::Trunc) {
3364         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
3365                                                CI->getType());
3366         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
3367         LoopVectorizationLegality::InductionInfo II =
3368             Legal->getInductionVars()->lookup(OldInduction);
3369         Constant *Step =
3370             ConstantInt::getSigned(CI->getType(), II.StepValue->getSExtValue());
3371         for (unsigned Part = 0; Part < UF; ++Part)
3372           Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
3373         propagateMetadata(Entry, it);
3374         break;
3375       }
3376       /// Vectorize casts.
3377       Type *DestTy = (VF == 1) ? CI->getType() :
3378                                  VectorType::get(CI->getType(), VF);
3379
3380       VectorParts &A = getVectorValue(it->getOperand(0));
3381       for (unsigned Part = 0; Part < UF; ++Part)
3382         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
3383       propagateMetadata(Entry, it);
3384       break;
3385     }
3386
3387     case Instruction::Call: {
3388       // Ignore dbg intrinsics.
3389       if (isa<DbgInfoIntrinsic>(it))
3390         break;
3391       setDebugLocFromInst(Builder, it);
3392
3393       Module *M = BB->getParent()->getParent();
3394       CallInst *CI = cast<CallInst>(it);
3395       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3396       assert(ID && "Not an intrinsic call!");
3397       switch (ID) {
3398       case Intrinsic::assume:
3399       case Intrinsic::lifetime_end:
3400       case Intrinsic::lifetime_start:
3401         scalarizeInstruction(it);
3402         break;
3403       default:
3404         bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
3405         for (unsigned Part = 0; Part < UF; ++Part) {
3406           SmallVector<Value *, 4> Args;
3407           for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3408             if (HasScalarOpd && i == 1) {
3409               Args.push_back(CI->getArgOperand(i));
3410               continue;
3411             }
3412             VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3413             Args.push_back(Arg[Part]);
3414           }
3415           Type *Tys[] = {CI->getType()};
3416           if (VF > 1)
3417             Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3418
3419           Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3420           Entry[Part] = Builder.CreateCall(F, Args);
3421         }
3422
3423         propagateMetadata(Entry, it);
3424         break;
3425       }
3426       break;
3427     }
3428
3429     default:
3430       // All other instructions are unsupported. Scalarize them.
3431       scalarizeInstruction(it);
3432       break;
3433     }// end of switch.
3434   }// end of for_each instr.
3435 }
3436
3437 void InnerLoopVectorizer::updateAnalysis() {
3438   // Forget the original basic block.
3439   SE->forgetLoop(OrigLoop);
3440
3441   // Update the dominator tree information.
3442   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3443          "Entry does not dominate exit.");
3444
3445   for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3446     DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3447   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3448
3449   // Due to if predication of stores we might create a sequence of "if(pred)
3450   // a[i] = ...;  " blocks.
3451   for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
3452     if (i == 0)
3453       DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
3454     else if (isPredicatedBlock(i)) {
3455       DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
3456     } else {
3457       DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
3458     }
3459   }
3460
3461   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
3462   DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
3463   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3464   DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
3465
3466   DEBUG(DT->verifyDomTree());
3467 }
3468
3469 /// \brief Check whether it is safe to if-convert this phi node.
3470 ///
3471 /// Phi nodes with constant expressions that can trap are not safe to if
3472 /// convert.
3473 static bool canIfConvertPHINodes(BasicBlock *BB) {
3474   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3475     PHINode *Phi = dyn_cast<PHINode>(I);
3476     if (!Phi)
3477       return true;
3478     for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3479       if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3480         if (C->canTrap())
3481           return false;
3482   }
3483   return true;
3484 }
3485
3486 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3487   if (!EnableIfConversion) {
3488     emitAnalysis(Report() << "if-conversion is disabled");
3489     return false;
3490   }
3491
3492   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3493
3494   // A list of pointers that we can safely read and write to.
3495   SmallPtrSet<Value *, 8> SafePointes;
3496
3497   // Collect safe addresses.
3498   for (Loop::block_iterator BI = TheLoop->block_begin(),
3499          BE = TheLoop->block_end(); BI != BE; ++BI) {
3500     BasicBlock *BB = *BI;
3501
3502     if (blockNeedsPredication(BB))
3503       continue;
3504
3505     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3506       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3507         SafePointes.insert(LI->getPointerOperand());
3508       else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3509         SafePointes.insert(SI->getPointerOperand());
3510     }
3511   }
3512
3513   // Collect the blocks that need predication.
3514   BasicBlock *Header = TheLoop->getHeader();
3515   for (Loop::block_iterator BI = TheLoop->block_begin(),
3516          BE = TheLoop->block_end(); BI != BE; ++BI) {
3517     BasicBlock *BB = *BI;
3518
3519     // We don't support switch statements inside loops.
3520     if (!isa<BranchInst>(BB->getTerminator())) {
3521       emitAnalysis(Report(BB->getTerminator())
3522                    << "loop contains a switch statement");
3523       return false;
3524     }
3525
3526     // We must be able to predicate all blocks that need to be predicated.
3527     if (blockNeedsPredication(BB)) {
3528       if (!blockCanBePredicated(BB, SafePointes)) {
3529         emitAnalysis(Report(BB->getTerminator())
3530                      << "control flow cannot be substituted for a select");
3531         return false;
3532       }
3533     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
3534       emitAnalysis(Report(BB->getTerminator())
3535                    << "control flow cannot be substituted for a select");
3536       return false;
3537     }
3538   }
3539
3540   // We can if-convert this loop.
3541   return true;
3542 }
3543
3544 bool LoopVectorizationLegality::canVectorize() {
3545   // We must have a loop in canonical form. Loops with indirectbr in them cannot
3546   // be canonicalized.
3547   if (!TheLoop->getLoopPreheader()) {
3548     emitAnalysis(
3549         Report() << "loop control flow is not understood by vectorizer");
3550     return false;
3551   }
3552
3553   // We can only vectorize innermost loops.
3554   if (!TheLoop->getSubLoopsVector().empty()) {
3555     emitAnalysis(Report() << "loop is not the innermost loop");
3556     return false;
3557   }
3558
3559   // We must have a single backedge.
3560   if (TheLoop->getNumBackEdges() != 1) {
3561     emitAnalysis(
3562         Report() << "loop control flow is not understood by vectorizer");
3563     return false;
3564   }
3565
3566   // We must have a single exiting block.
3567   if (!TheLoop->getExitingBlock()) {
3568     emitAnalysis(
3569         Report() << "loop control flow is not understood by vectorizer");
3570     return false;
3571   }
3572
3573   // We only handle bottom-tested loops, i.e. loop in which the condition is
3574   // checked at the end of each iteration. With that we can assume that all
3575   // instructions in the loop are executed the same number of times.
3576   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
3577     emitAnalysis(
3578         Report() << "loop control flow is not understood by vectorizer");
3579     return false;
3580   }
3581
3582   // We need to have a loop header.
3583   DEBUG(dbgs() << "LV: Found a loop: " <<
3584         TheLoop->getHeader()->getName() << '\n');
3585
3586   // Check if we can if-convert non-single-bb loops.
3587   unsigned NumBlocks = TheLoop->getNumBlocks();
3588   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3589     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3590     return false;
3591   }
3592
3593   // ScalarEvolution needs to be able to find the exit count.
3594   const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3595   if (ExitCount == SE->getCouldNotCompute()) {
3596     emitAnalysis(Report() << "could not determine number of loop iterations");
3597     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3598     return false;
3599   }
3600
3601   // Check if we can vectorize the instructions and CFG in this loop.
3602   if (!canVectorizeInstrs()) {
3603     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3604     return false;
3605   }
3606
3607   // Go over each instruction and look at memory deps.
3608   if (!canVectorizeMemory()) {
3609     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3610     return false;
3611   }
3612
3613   // Collect all of the variables that remain uniform after vectorization.
3614   collectLoopUniforms();
3615
3616   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3617         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3618         <<"!\n");
3619
3620   // Okay! We can vectorize. At this point we don't have any other mem analysis
3621   // which may limit our maximum vectorization factor, so just return true with
3622   // no restrictions.
3623   return true;
3624 }
3625
3626 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
3627   if (Ty->isPointerTy())
3628     return DL.getIntPtrType(Ty);
3629
3630   // It is possible that char's or short's overflow when we ask for the loop's
3631   // trip count, work around this by changing the type size.
3632   if (Ty->getScalarSizeInBits() < 32)
3633     return Type::getInt32Ty(Ty->getContext());
3634
3635   return Ty;
3636 }
3637
3638 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
3639   Ty0 = convertPointerToIntegerType(DL, Ty0);
3640   Ty1 = convertPointerToIntegerType(DL, Ty1);
3641   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3642     return Ty0;
3643   return Ty1;
3644 }
3645
3646 /// \brief Check that the instruction has outside loop users and is not an
3647 /// identified reduction variable.
3648 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3649                                SmallPtrSetImpl<Value *> &Reductions) {
3650   // Reduction instructions are allowed to have exit users. All other
3651   // instructions must not have external users.
3652   if (!Reductions.count(Inst))
3653     //Check that all of the users of the loop are inside the BB.
3654     for (User *U : Inst->users()) {
3655       Instruction *UI = cast<Instruction>(U);
3656       // This user may be a reduction exit value.
3657       if (!TheLoop->contains(UI)) {
3658         DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
3659         return true;
3660       }
3661     }
3662   return false;
3663 }
3664
3665 bool LoopVectorizationLegality::canVectorizeInstrs() {
3666   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3667   BasicBlock *Header = TheLoop->getHeader();
3668
3669   // Look for the attribute signaling the absence of NaNs.
3670   Function &F = *Header->getParent();
3671   if (F.hasFnAttribute("no-nans-fp-math"))
3672     HasFunNoNaNAttr = F.getAttributes().getAttribute(
3673       AttributeSet::FunctionIndex,
3674       "no-nans-fp-math").getValueAsString() == "true";
3675
3676   // For each block in the loop.
3677   for (Loop::block_iterator bb = TheLoop->block_begin(),
3678        be = TheLoop->block_end(); bb != be; ++bb) {
3679
3680     // Scan the instructions in the block and look for hazards.
3681     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3682          ++it) {
3683
3684       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3685         Type *PhiTy = Phi->getType();
3686         // Check that this PHI type is allowed.
3687         if (!PhiTy->isIntegerTy() &&
3688             !PhiTy->isFloatingPointTy() &&
3689             !PhiTy->isPointerTy()) {
3690           emitAnalysis(Report(it)
3691                        << "loop control flow is not understood by vectorizer");
3692           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3693           return false;
3694         }
3695
3696         // If this PHINode is not in the header block, then we know that we
3697         // can convert it to select during if-conversion. No need to check if
3698         // the PHIs in this block are induction or reduction variables.
3699         if (*bb != Header) {
3700           // Check that this instruction has no outside users or is an
3701           // identified reduction value with an outside user.
3702           if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3703             continue;
3704           emitAnalysis(Report(it) << "value could not be identified as "
3705                                      "an induction or reduction variable");
3706           return false;
3707         }
3708
3709         // We only allow if-converted PHIs with exactly two incoming values.
3710         if (Phi->getNumIncomingValues() != 2) {
3711           emitAnalysis(Report(it)
3712                        << "control flow not understood by vectorizer");
3713           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3714           return false;
3715         }
3716
3717         // This is the value coming from the preheader.
3718         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3719         ConstantInt *StepValue = nullptr;
3720         // Check if this is an induction variable.
3721         InductionKind IK = isInductionVariable(Phi, StepValue);
3722
3723         if (IK_NoInduction != IK) {
3724           // Get the widest type.
3725           if (!WidestIndTy)
3726             WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3727           else
3728             WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3729
3730           // Int inductions are special because we only allow one IV.
3731           if (IK == IK_IntInduction && StepValue->isOne()) {
3732             // Use the phi node with the widest type as induction. Use the last
3733             // one if there are multiple (no good reason for doing this other
3734             // than it is expedient).
3735             if (!Induction || PhiTy == WidestIndTy)
3736               Induction = Phi;
3737           }
3738
3739           DEBUG(dbgs() << "LV: Found an induction variable.\n");
3740           Inductions[Phi] = InductionInfo(StartValue, IK, StepValue);
3741
3742           // Until we explicitly handle the case of an induction variable with
3743           // an outside loop user we have to give up vectorizing this loop.
3744           if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3745             emitAnalysis(Report(it) << "use of induction value outside of the "
3746                                        "loop is not handled by vectorizer");
3747             return false;
3748           }
3749
3750           continue;
3751         }
3752
3753         if (AddReductionVar(Phi, RK_IntegerAdd)) {
3754           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3755           continue;
3756         }
3757         if (AddReductionVar(Phi, RK_IntegerMult)) {
3758           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3759           continue;
3760         }
3761         if (AddReductionVar(Phi, RK_IntegerOr)) {
3762           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3763           continue;
3764         }
3765         if (AddReductionVar(Phi, RK_IntegerAnd)) {
3766           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3767           continue;
3768         }
3769         if (AddReductionVar(Phi, RK_IntegerXor)) {
3770           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3771           continue;
3772         }
3773         if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3774           DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3775           continue;
3776         }
3777         if (AddReductionVar(Phi, RK_FloatMult)) {
3778           DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3779           continue;
3780         }
3781         if (AddReductionVar(Phi, RK_FloatAdd)) {
3782           DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3783           continue;
3784         }
3785         if (AddReductionVar(Phi, RK_FloatMinMax)) {
3786           DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3787                 "\n");
3788           continue;
3789         }
3790
3791         emitAnalysis(Report(it) << "value that could not be identified as "
3792                                    "reduction is used outside the loop");
3793         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3794         return false;
3795       }// end of PHI handling
3796
3797       // We still don't handle functions. However, we can ignore dbg intrinsic
3798       // calls and we do handle certain intrinsic and libm functions.
3799       CallInst *CI = dyn_cast<CallInst>(it);
3800       if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3801         emitAnalysis(Report(it) << "call instruction cannot be vectorized");
3802         DEBUG(dbgs() << "LV: Found a call site.\n");
3803         return false;
3804       }
3805
3806       // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
3807       // second argument is the same (i.e. loop invariant)
3808       if (CI &&
3809           hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
3810         if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
3811           emitAnalysis(Report(it)
3812                        << "intrinsic instruction cannot be vectorized");
3813           DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
3814           return false;
3815         }
3816       }
3817
3818       // Check that the instruction return type is vectorizable.
3819       // Also, we can't vectorize extractelement instructions.
3820       if ((!VectorType::isValidElementType(it->getType()) &&
3821            !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3822         emitAnalysis(Report(it)
3823                      << "instruction return type cannot be vectorized");
3824         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3825         return false;
3826       }
3827
3828       // Check that the stored type is vectorizable.
3829       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3830         Type *T = ST->getValueOperand()->getType();
3831         if (!VectorType::isValidElementType(T)) {
3832           emitAnalysis(Report(ST) << "store instruction cannot be vectorized");
3833           return false;
3834         }
3835         if (EnableMemAccessVersioning)
3836           collectStridedAccess(ST);
3837       }
3838
3839       if (EnableMemAccessVersioning)
3840         if (LoadInst *LI = dyn_cast<LoadInst>(it))
3841           collectStridedAccess(LI);
3842
3843       // Reduction instructions are allowed to have exit users.
3844       // All other instructions must not have external users.
3845       if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
3846         emitAnalysis(Report(it) << "value cannot be used outside the loop");
3847         return false;
3848       }
3849
3850     } // next instr.
3851
3852   }
3853
3854   if (!Induction) {
3855     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3856     if (Inductions.empty()) {
3857       emitAnalysis(Report()
3858                    << "loop induction variable could not be identified");
3859       return false;
3860     }
3861   }
3862
3863   return true;
3864 }
3865
3866 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3867 /// return the induction operand of the gep pointer.
3868 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3869                                  const DataLayout *DL, Loop *Lp) {
3870   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3871   if (!GEP)
3872     return Ptr;
3873
3874   unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3875
3876   // Check that all of the gep indices are uniform except for our induction
3877   // operand.
3878   for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3879     if (i != InductionOperand &&
3880         !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3881       return Ptr;
3882   return GEP->getOperand(InductionOperand);
3883 }
3884
3885 ///\brief Look for a cast use of the passed value.
3886 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3887   Value *UniqueCast = nullptr;
3888   for (User *U : Ptr->users()) {
3889     CastInst *CI = dyn_cast<CastInst>(U);
3890     if (CI && CI->getType() == Ty) {
3891       if (!UniqueCast)
3892         UniqueCast = CI;
3893       else
3894         return nullptr;
3895     }
3896   }
3897   return UniqueCast;
3898 }
3899
3900 ///\brief Get the stride of a pointer access in a loop.
3901 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3902 /// pointer to the Value, or null otherwise.
3903 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3904                                    const DataLayout *DL, Loop *Lp) {
3905   const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3906   if (!PtrTy || PtrTy->isAggregateType())
3907     return nullptr;
3908
3909   // Try to remove a gep instruction to make the pointer (actually index at this
3910   // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3911   // pointer, otherwise, we are analyzing the index.
3912   Value *OrigPtr = Ptr;
3913
3914   // The size of the pointer access.
3915   int64_t PtrAccessSize = 1;
3916
3917   Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3918   const SCEV *V = SE->getSCEV(Ptr);
3919
3920   if (Ptr != OrigPtr)
3921     // Strip off casts.
3922     while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3923       V = C->getOperand();
3924
3925   const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3926   if (!S)
3927     return nullptr;
3928
3929   V = S->getStepRecurrence(*SE);
3930   if (!V)
3931     return nullptr;
3932
3933   // Strip off the size of access multiplication if we are still analyzing the
3934   // pointer.
3935   if (OrigPtr == Ptr) {
3936     DL->getTypeAllocSize(PtrTy->getElementType());
3937     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3938       if (M->getOperand(0)->getSCEVType() != scConstant)
3939         return nullptr;
3940
3941       const APInt &APStepVal =
3942           cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3943
3944       // Huge step value - give up.
3945       if (APStepVal.getBitWidth() > 64)
3946         return nullptr;
3947
3948       int64_t StepVal = APStepVal.getSExtValue();
3949       if (PtrAccessSize != StepVal)
3950         return nullptr;
3951       V = M->getOperand(1);
3952     }
3953   }
3954
3955   // Strip off casts.
3956   Type *StripedOffRecurrenceCast = nullptr;
3957   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3958     StripedOffRecurrenceCast = C->getType();
3959     V = C->getOperand();
3960   }
3961
3962   // Look for the loop invariant symbolic value.
3963   const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3964   if (!U)
3965     return nullptr;
3966
3967   Value *Stride = U->getValue();
3968   if (!Lp->isLoopInvariant(Stride))
3969     return nullptr;
3970
3971   // If we have stripped off the recurrence cast we have to make sure that we
3972   // return the value that is used in this loop so that we can replace it later.
3973   if (StripedOffRecurrenceCast)
3974     Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3975
3976   return Stride;
3977 }
3978
3979 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
3980   Value *Ptr = nullptr;
3981   if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3982     Ptr = LI->getPointerOperand();
3983   else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3984     Ptr = SI->getPointerOperand();
3985   else
3986     return;
3987
3988   Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3989   if (!Stride)
3990     return;
3991
3992   DEBUG(dbgs() << "LV: Found a strided access that we can version");
3993   DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3994   Strides[Ptr] = Stride;
3995   StrideSet.insert(Stride);
3996 }
3997
3998 void LoopVectorizationLegality::collectLoopUniforms() {
3999   // We now know that the loop is vectorizable!
4000   // Collect variables that will remain uniform after vectorization.
4001   std::vector<Value*> Worklist;
4002   BasicBlock *Latch = TheLoop->getLoopLatch();
4003
4004   // Start with the conditional branch and walk up the block.
4005   Worklist.push_back(Latch->getTerminator()->getOperand(0));
4006
4007   // Also add all consecutive pointer values; these values will be uniform
4008   // after vectorization (and subsequent cleanup) and, until revectorization is
4009   // supported, all dependencies must also be uniform.
4010   for (Loop::block_iterator B = TheLoop->block_begin(),
4011        BE = TheLoop->block_end(); B != BE; ++B)
4012     for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
4013          I != IE; ++I)
4014       if (I->getType()->isPointerTy() && isConsecutivePtr(I))
4015         Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4016
4017   while (!Worklist.empty()) {
4018     Instruction *I = dyn_cast<Instruction>(Worklist.back());
4019     Worklist.pop_back();
4020
4021     // Look at instructions inside this loop.
4022     // Stop when reaching PHI nodes.
4023     // TODO: we need to follow values all over the loop, not only in this block.
4024     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
4025       continue;
4026
4027     // This is a known uniform.
4028     Uniforms.insert(I);
4029
4030     // Insert all operands.
4031     Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4032   }
4033 }
4034
4035 namespace {
4036 /// \brief Analyses memory accesses in a loop.
4037 ///
4038 /// Checks whether run time pointer checks are needed and builds sets for data
4039 /// dependence checking.
4040 class AccessAnalysis {
4041 public:
4042   /// \brief Read or write access location.
4043   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
4044   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
4045
4046   /// \brief Set of potential dependent memory accesses.
4047   typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
4048
4049   AccessAnalysis(const DataLayout *Dl, AliasAnalysis *AA, DepCandidates &DA) :
4050     DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
4051
4052   /// \brief Register a load  and whether it is only read from.
4053   void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
4054     Value *Ptr = const_cast<Value*>(Loc.Ptr);
4055     AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
4056     Accesses.insert(MemAccessInfo(Ptr, false));
4057     if (IsReadOnly)
4058       ReadOnlyPtr.insert(Ptr);
4059   }
4060
4061   /// \brief Register a store.
4062   void addStore(AliasAnalysis::Location &Loc) {
4063     Value *Ptr = const_cast<Value*>(Loc.Ptr);
4064     AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
4065     Accesses.insert(MemAccessInfo(Ptr, true));
4066   }
4067
4068   /// \brief Check whether we can check the pointers at runtime for
4069   /// non-intersection.
4070   bool canCheckPtrAtRT(RuntimePointerCheck &RtCheck, unsigned &NumComparisons,
4071                        ScalarEvolution *SE, Loop *TheLoop,
4072                        ValueToValueMap &Strides,
4073                        bool ShouldCheckStride = false);
4074
4075   /// \brief Goes over all memory accesses, checks whether a RT check is needed
4076   /// and builds sets of dependent accesses.
4077   void buildDependenceSets() {
4078     processMemAccesses();
4079   }
4080
4081   bool isRTCheckNeeded() { return IsRTCheckNeeded; }
4082
4083   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
4084   void resetDepChecks() { CheckDeps.clear(); }
4085
4086   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
4087
4088 private:
4089   typedef SetVector<MemAccessInfo> PtrAccessSet;
4090
4091   /// \brief Go over all memory access and check whether runtime pointer checks
4092   /// are needed /// and build sets of dependency check candidates.
4093   void processMemAccesses();
4094
4095   /// Set of all accesses.
4096   PtrAccessSet Accesses;
4097
4098   /// Set of accesses that need a further dependence check.
4099   MemAccessInfoSet CheckDeps;
4100
4101   /// Set of pointers that are read only.
4102   SmallPtrSet<Value*, 16> ReadOnlyPtr;
4103
4104   const DataLayout *DL;
4105
4106   /// An alias set tracker to partition the access set by underlying object and
4107   //intrinsic property (such as TBAA metadata).
4108   AliasSetTracker AST;
4109
4110   /// Sets of potentially dependent accesses - members of one set share an
4111   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
4112   /// dependence check.
4113   DepCandidates &DepCands;
4114
4115   bool IsRTCheckNeeded;
4116 };
4117
4118 } // end anonymous namespace
4119
4120 /// \brief Check whether a pointer can participate in a runtime bounds check.
4121 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
4122                                 Value *Ptr) {
4123   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
4124   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4125   if (!AR)
4126     return false;
4127
4128   return AR->isAffine();
4129 }
4130
4131 /// \brief Check the stride of the pointer and ensure that it does not wrap in
4132 /// the address space.
4133 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
4134                         const Loop *Lp, ValueToValueMap &StridesMap);
4135
4136 bool AccessAnalysis::canCheckPtrAtRT(
4137     RuntimePointerCheck &RtCheck,
4138     unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
4139     ValueToValueMap &StridesMap, bool ShouldCheckStride) {
4140   // Find pointers with computable bounds. We are going to use this information
4141   // to place a runtime bound check.
4142   bool CanDoRT = true;
4143
4144   bool IsDepCheckNeeded = isDependencyCheckNeeded();
4145   NumComparisons = 0;
4146
4147   // We assign a consecutive id to access from different alias sets.
4148   // Accesses between different groups doesn't need to be checked.
4149   unsigned ASId = 1;
4150   for (auto &AS : AST) {
4151     unsigned NumReadPtrChecks = 0;
4152     unsigned NumWritePtrChecks = 0;
4153
4154     // We assign consecutive id to access from different dependence sets.
4155     // Accesses within the same set don't need a runtime check.
4156     unsigned RunningDepId = 1;
4157     DenseMap<Value *, unsigned> DepSetId;
4158
4159     for (auto A : AS) {
4160       Value *Ptr = A.getValue();
4161       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
4162       MemAccessInfo Access(Ptr, IsWrite);
4163
4164       if (IsWrite)
4165         ++NumWritePtrChecks;
4166       else
4167         ++NumReadPtrChecks;
4168
4169       if (hasComputableBounds(SE, StridesMap, Ptr) &&
4170           // When we run after a failing dependency check we have to make sure we
4171           // don't have wrapping pointers.
4172           (!ShouldCheckStride ||
4173            isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
4174         // The id of the dependence set.
4175         unsigned DepId;
4176
4177         if (IsDepCheckNeeded) {
4178           Value *Leader = DepCands.getLeaderValue(Access).getPointer();
4179           unsigned &LeaderId = DepSetId[Leader];
4180           if (!LeaderId)
4181             LeaderId = RunningDepId++;
4182           DepId = LeaderId;
4183         } else
4184           // Each access has its own dependence set.
4185           DepId = RunningDepId++;
4186
4187         RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
4188
4189         DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
4190       } else {
4191         CanDoRT = false;
4192       }
4193     }
4194
4195     if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
4196       NumComparisons += 0; // Only one dependence set.
4197     else {
4198       NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
4199                                               NumWritePtrChecks - 1));
4200     }
4201
4202     ++ASId;
4203   }
4204
4205   // If the pointers that we would use for the bounds comparison have different
4206   // address spaces, assume the values aren't directly comparable, so we can't
4207   // use them for the runtime check. We also have to assume they could
4208   // overlap. In the future there should be metadata for whether address spaces
4209   // are disjoint.
4210   unsigned NumPointers = RtCheck.Pointers.size();
4211   for (unsigned i = 0; i < NumPointers; ++i) {
4212     for (unsigned j = i + 1; j < NumPointers; ++j) {
4213       // Only need to check pointers between two different dependency sets.
4214       if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
4215        continue;
4216       // Only need to check pointers in the same alias set.
4217       if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
4218         continue;
4219
4220       Value *PtrI = RtCheck.Pointers[i];
4221       Value *PtrJ = RtCheck.Pointers[j];
4222
4223       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
4224       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
4225       if (ASi != ASj) {
4226         DEBUG(dbgs() << "LV: Runtime check would require comparison between"
4227                        " different address spaces\n");
4228         return false;
4229       }
4230     }
4231   }
4232
4233   return CanDoRT;
4234 }
4235
4236 void AccessAnalysis::processMemAccesses() {
4237   // We process the set twice: first we process read-write pointers, last we
4238   // process read-only pointers. This allows us to skip dependence tests for
4239   // read-only pointers.
4240
4241   DEBUG(dbgs() << "LV: Processing memory accesses...\n");
4242   DEBUG(dbgs() << "  AST: "; AST.dump());
4243   DEBUG(dbgs() << "LV:   Accesses:\n");
4244   DEBUG({
4245     for (auto A : Accesses)
4246       dbgs() << "\t" << *A.getPointer() << " (" <<
4247                 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
4248                                          "read-only" : "read")) << ")\n";
4249   });
4250
4251   // The AliasSetTracker has nicely partitioned our pointers by metadata
4252   // compatibility and potential for underlying-object overlap. As a result, we
4253   // only need to check for potential pointer dependencies within each alias
4254   // set.
4255   for (auto &AS : AST) {
4256     // Note that both the alias-set tracker and the alias sets themselves used
4257     // linked lists internally and so the iteration order here is deterministic
4258     // (matching the original instruction order within each set).
4259
4260     bool SetHasWrite = false;
4261
4262     // Map of pointers to last access encountered.
4263     typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
4264     UnderlyingObjToAccessMap ObjToLastAccess;
4265
4266     // Set of access to check after all writes have been processed.
4267     PtrAccessSet DeferredAccesses;
4268
4269     // Iterate over each alias set twice, once to process read/write pointers,
4270     // and then to process read-only pointers.
4271     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
4272       bool UseDeferred = SetIteration > 0;
4273       PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
4274
4275       for (auto AV : AS) {
4276         Value *Ptr = AV.getValue();
4277
4278         // For a single memory access in AliasSetTracker, Accesses may contain
4279         // both read and write, and they both need to be handled for CheckDeps.
4280         for (auto AC : S) {
4281           if (AC.getPointer() != Ptr)
4282             continue;
4283
4284           bool IsWrite = AC.getInt();
4285
4286           // If we're using the deferred access set, then it contains only
4287           // reads.
4288           bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
4289           if (UseDeferred && !IsReadOnlyPtr)
4290             continue;
4291           // Otherwise, the pointer must be in the PtrAccessSet, either as a
4292           // read or a write.
4293           assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
4294                   S.count(MemAccessInfo(Ptr, false))) &&
4295                  "Alias-set pointer not in the access set?");
4296
4297           MemAccessInfo Access(Ptr, IsWrite);
4298           DepCands.insert(Access);
4299
4300           // Memorize read-only pointers for later processing and skip them in
4301           // the first round (they need to be checked after we have seen all
4302           // write pointers). Note: we also mark pointer that are not
4303           // consecutive as "read-only" pointers (so that we check
4304           // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
4305           if (!UseDeferred && IsReadOnlyPtr) {
4306             DeferredAccesses.insert(Access);
4307             continue;
4308           }
4309
4310           // If this is a write - check other reads and writes for conflicts. If
4311           // this is a read only check other writes for conflicts (but only if
4312           // there is no other write to the ptr - this is an optimization to
4313           // catch "a[i] = a[i] + " without having to do a dependence check).
4314           if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
4315             CheckDeps.insert(Access);
4316             IsRTCheckNeeded = true;
4317           }
4318
4319           if (IsWrite)
4320             SetHasWrite = true;
4321
4322           // Create sets of pointers connected by a shared alias set and
4323           // underlying object.
4324           typedef SmallVector<Value *, 16> ValueVector;
4325           ValueVector TempObjects;
4326           GetUnderlyingObjects(Ptr, TempObjects, DL);
4327           for (Value *UnderlyingObj : TempObjects) {
4328             UnderlyingObjToAccessMap::iterator Prev =
4329                 ObjToLastAccess.find(UnderlyingObj);
4330             if (Prev != ObjToLastAccess.end())
4331               DepCands.unionSets(Access, Prev->second);
4332
4333             ObjToLastAccess[UnderlyingObj] = Access;
4334           }
4335         }
4336       }
4337     }
4338   }
4339 }
4340
4341 namespace {
4342 /// \brief Checks memory dependences among accesses to the same underlying
4343 /// object to determine whether there vectorization is legal or not (and at
4344 /// which vectorization factor).
4345 ///
4346 /// This class works under the assumption that we already checked that memory
4347 /// locations with different underlying pointers are "must-not alias".
4348 /// We use the ScalarEvolution framework to symbolically evalutate access
4349 /// functions pairs. Since we currently don't restructure the loop we can rely
4350 /// on the program order of memory accesses to determine their safety.
4351 /// At the moment we will only deem accesses as safe for:
4352 ///  * A negative constant distance assuming program order.
4353 ///
4354 ///      Safe: tmp = a[i + 1];     OR     a[i + 1] = x;
4355 ///            a[i] = tmp;                y = a[i];
4356 ///
4357 ///   The latter case is safe because later checks guarantuee that there can't
4358 ///   be a cycle through a phi node (that is, we check that "x" and "y" is not
4359 ///   the same variable: a header phi can only be an induction or a reduction, a
4360 ///   reduction can't have a memory sink, an induction can't have a memory
4361 ///   source). This is important and must not be violated (or we have to
4362 ///   resort to checking for cycles through memory).
4363 ///
4364 ///  * A positive constant distance assuming program order that is bigger
4365 ///    than the biggest memory access.
4366 ///
4367 ///     tmp = a[i]        OR              b[i] = x
4368 ///     a[i+2] = tmp                      y = b[i+2];
4369 ///
4370 ///     Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
4371 ///
4372 ///  * Zero distances and all accesses have the same size.
4373 ///
4374 class MemoryDepChecker {
4375 public:
4376   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
4377   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
4378
4379   MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
4380       : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
4381         ShouldRetryWithRuntimeCheck(false) {}
4382
4383   /// \brief Register the location (instructions are given increasing numbers)
4384   /// of a write access.
4385   void addAccess(StoreInst *SI) {
4386     Value *Ptr = SI->getPointerOperand();
4387     Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
4388     InstMap.push_back(SI);
4389     ++AccessIdx;
4390   }
4391
4392   /// \brief Register the location (instructions are given increasing numbers)
4393   /// of a write access.
4394   void addAccess(LoadInst *LI) {
4395     Value *Ptr = LI->getPointerOperand();
4396     Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
4397     InstMap.push_back(LI);
4398     ++AccessIdx;
4399   }
4400
4401   /// \brief Check whether the dependencies between the accesses are safe.
4402   ///
4403   /// Only checks sets with elements in \p CheckDeps.
4404   bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4405                    MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
4406
4407   /// \brief The maximum number of bytes of a vector register we can vectorize
4408   /// the accesses safely with.
4409   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
4410
4411   /// \brief In same cases when the dependency check fails we can still
4412   /// vectorize the loop with a dynamic array access check.
4413   bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
4414
4415 private:
4416   ScalarEvolution *SE;
4417   const DataLayout *DL;
4418   const Loop *InnermostLoop;
4419
4420   /// \brief Maps access locations (ptr, read/write) to program order.
4421   DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
4422
4423   /// \brief Memory access instructions in program order.
4424   SmallVector<Instruction *, 16> InstMap;
4425
4426   /// \brief The program order index to be used for the next instruction.
4427   unsigned AccessIdx;
4428
4429   // We can access this many bytes in parallel safely.
4430   unsigned MaxSafeDepDistBytes;
4431
4432   /// \brief If we see a non-constant dependence distance we can still try to
4433   /// vectorize this loop with runtime checks.
4434   bool ShouldRetryWithRuntimeCheck;
4435
4436   /// \brief Check whether there is a plausible dependence between the two
4437   /// accesses.
4438   ///
4439   /// Access \p A must happen before \p B in program order. The two indices
4440   /// identify the index into the program order map.
4441   ///
4442   /// This function checks  whether there is a plausible dependence (or the
4443   /// absence of such can't be proved) between the two accesses. If there is a
4444   /// plausible dependence but the dependence distance is bigger than one
4445   /// element access it records this distance in \p MaxSafeDepDistBytes (if this
4446   /// distance is smaller than any other distance encountered so far).
4447   /// Otherwise, this function returns true signaling a possible dependence.
4448   bool isDependent(const MemAccessInfo &A, unsigned AIdx,
4449                    const MemAccessInfo &B, unsigned BIdx,
4450                    ValueToValueMap &Strides);
4451
4452   /// \brief Check whether the data dependence could prevent store-load
4453   /// forwarding.
4454   bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
4455 };
4456
4457 } // end anonymous namespace
4458
4459 static bool isInBoundsGep(Value *Ptr) {
4460   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
4461     return GEP->isInBounds();
4462   return false;
4463 }
4464
4465 /// \brief Check whether the access through \p Ptr has a constant stride.
4466 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
4467                         const Loop *Lp, ValueToValueMap &StridesMap) {
4468   const Type *Ty = Ptr->getType();
4469   assert(Ty->isPointerTy() && "Unexpected non-ptr");
4470
4471   // Make sure that the pointer does not point to aggregate types.
4472   const PointerType *PtrTy = cast<PointerType>(Ty);
4473   if (PtrTy->getElementType()->isAggregateType()) {
4474     DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
4475           "\n");
4476     return 0;
4477   }
4478
4479   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
4480
4481   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
4482   if (!AR) {
4483     DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
4484           << *Ptr << " SCEV: " << *PtrScev << "\n");
4485     return 0;
4486   }
4487
4488   // The accesss function must stride over the innermost loop.
4489   if (Lp != AR->getLoop()) {
4490     DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
4491           *Ptr << " SCEV: " << *PtrScev << "\n");
4492   }
4493
4494   // The address calculation must not wrap. Otherwise, a dependence could be
4495   // inverted.
4496   // An inbounds getelementptr that is a AddRec with a unit stride
4497   // cannot wrap per definition. The unit stride requirement is checked later.
4498   // An getelementptr without an inbounds attribute and unit stride would have
4499   // to access the pointer value "0" which is undefined behavior in address
4500   // space 0, therefore we can also vectorize this case.
4501   bool IsInBoundsGEP = isInBoundsGep(Ptr);
4502   bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
4503   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
4504   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
4505     DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
4506           << *Ptr << " SCEV: " << *PtrScev << "\n");
4507     return 0;
4508   }
4509
4510   // Check the step is constant.
4511   const SCEV *Step = AR->getStepRecurrence(*SE);
4512
4513   // Calculate the pointer stride and check if it is consecutive.
4514   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4515   if (!C) {
4516     DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
4517           " SCEV: " << *PtrScev << "\n");
4518     return 0;
4519   }
4520
4521   int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
4522   const APInt &APStepVal = C->getValue()->getValue();
4523
4524   // Huge step value - give up.
4525   if (APStepVal.getBitWidth() > 64)
4526     return 0;
4527
4528   int64_t StepVal = APStepVal.getSExtValue();
4529
4530   // Strided access.
4531   int64_t Stride = StepVal / Size;
4532   int64_t Rem = StepVal % Size;
4533   if (Rem)
4534     return 0;
4535
4536   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
4537   // know we can't "wrap around the address space". In case of address space
4538   // zero we know that this won't happen without triggering undefined behavior.
4539   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
4540       Stride != 1 && Stride != -1)
4541     return 0;
4542
4543   return Stride;
4544 }
4545
4546 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
4547                                                     unsigned TypeByteSize) {
4548   // If loads occur at a distance that is not a multiple of a feasible vector
4549   // factor store-load forwarding does not take place.
4550   // Positive dependences might cause troubles because vectorizing them might
4551   // prevent store-load forwarding making vectorized code run a lot slower.
4552   //   a[i] = a[i-3] ^ a[i-8];
4553   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
4554   //   hence on your typical architecture store-load forwarding does not take
4555   //   place. Vectorizing in such cases does not make sense.
4556   // Store-load forwarding distance.
4557   const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
4558   // Maximum vector factor.
4559   unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
4560   if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
4561     MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
4562
4563   for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
4564        vf *= 2) {
4565     if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
4566       MaxVFWithoutSLForwardIssues = (vf >>=1);
4567       break;
4568     }
4569   }
4570
4571   if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4572     DEBUG(dbgs() << "LV: Distance " << Distance <<
4573           " that could cause a store-load forwarding conflict\n");
4574     return true;
4575   }
4576
4577   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4578       MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4579     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4580   return false;
4581 }
4582
4583 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4584                                    const MemAccessInfo &B, unsigned BIdx,
4585                                    ValueToValueMap &Strides) {
4586   assert (AIdx < BIdx && "Must pass arguments in program order");
4587
4588   Value *APtr = A.getPointer();
4589   Value *BPtr = B.getPointer();
4590   bool AIsWrite = A.getInt();
4591   bool BIsWrite = B.getInt();
4592
4593   // Two reads are independent.
4594   if (!AIsWrite && !BIsWrite)
4595     return false;
4596
4597   // We cannot check pointers in different address spaces.
4598   if (APtr->getType()->getPointerAddressSpace() !=
4599       BPtr->getType()->getPointerAddressSpace())
4600     return true;
4601
4602   const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4603   const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4604
4605   int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4606   int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4607
4608   const SCEV *Src = AScev;
4609   const SCEV *Sink = BScev;
4610
4611   // If the induction step is negative we have to invert source and sink of the
4612   // dependence.
4613   if (StrideAPtr < 0) {
4614     //Src = BScev;
4615     //Sink = AScev;
4616     std::swap(APtr, BPtr);
4617     std::swap(Src, Sink);
4618     std::swap(AIsWrite, BIsWrite);
4619     std::swap(AIdx, BIdx);
4620     std::swap(StrideAPtr, StrideBPtr);
4621   }
4622
4623   const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4624
4625   DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4626         << "(Induction step: " << StrideAPtr <<  ")\n");
4627   DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4628         << *InstMap[BIdx] << ": " << *Dist << "\n");
4629
4630   // Need consecutive accesses. We don't want to vectorize
4631   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4632   // the address space.
4633   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4634     DEBUG(dbgs() << "Non-consecutive pointer access\n");
4635     return true;
4636   }
4637
4638   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4639   if (!C) {
4640     DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4641     ShouldRetryWithRuntimeCheck = true;
4642     return true;
4643   }
4644
4645   Type *ATy = APtr->getType()->getPointerElementType();
4646   Type *BTy = BPtr->getType()->getPointerElementType();
4647   unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4648
4649   // Negative distances are not plausible dependencies.
4650   const APInt &Val = C->getValue()->getValue();
4651   if (Val.isNegative()) {
4652     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4653     if (IsTrueDataDependence &&
4654         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4655          ATy != BTy))
4656       return true;
4657
4658     DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4659     return false;
4660   }
4661
4662   // Write to the same location with the same size.
4663   // Could be improved to assert type sizes are the same (i32 == float, etc).
4664   if (Val == 0) {
4665     if (ATy == BTy)
4666       return false;
4667     DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4668     return true;
4669   }
4670
4671   assert(Val.isStrictlyPositive() && "Expect a positive value");
4672
4673   // Positive distance bigger than max vectorization factor.
4674   if (ATy != BTy) {
4675     DEBUG(dbgs() <<
4676           "LV: ReadWrite-Write positive dependency with different types\n");
4677     return false;
4678   }
4679
4680   unsigned Distance = (unsigned) Val.getZExtValue();
4681
4682   // Bail out early if passed-in parameters make vectorization not feasible.
4683   unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4684   unsigned ForcedUnroll = VectorizationInterleave ? VectorizationInterleave : 1;
4685
4686   // The distance must be bigger than the size needed for a vectorized version
4687   // of the operation and the size of the vectorized operation must not be
4688   // bigger than the currrent maximum size.
4689   if (Distance < 2*TypeByteSize ||
4690       2*TypeByteSize > MaxSafeDepDistBytes ||
4691       Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4692     DEBUG(dbgs() << "LV: Failure because of Positive distance "
4693         << Val.getSExtValue() << '\n');
4694     return true;
4695   }
4696
4697   MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4698     Distance : MaxSafeDepDistBytes;
4699
4700   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4701   if (IsTrueDataDependence &&
4702       couldPreventStoreLoadForward(Distance, TypeByteSize))
4703      return true;
4704
4705   DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4706         " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4707
4708   return false;
4709 }
4710
4711 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4712                                    MemAccessInfoSet &CheckDeps,
4713                                    ValueToValueMap &Strides) {
4714
4715   MaxSafeDepDistBytes = -1U;
4716   while (!CheckDeps.empty()) {
4717     MemAccessInfo CurAccess = *CheckDeps.begin();
4718
4719     // Get the relevant memory access set.
4720     EquivalenceClasses<MemAccessInfo>::iterator I =
4721       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4722
4723     // Check accesses within this set.
4724     EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4725     AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4726
4727     // Check every access pair.
4728     while (AI != AE) {
4729       CheckDeps.erase(*AI);
4730       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
4731       while (OI != AE) {
4732         // Check every accessing instruction pair in program order.
4733         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4734              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4735           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4736                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4737             if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4738               return false;
4739             if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4740               return false;
4741           }
4742         ++OI;
4743       }
4744       AI++;
4745     }
4746   }
4747   return true;
4748 }
4749
4750 bool LoopVectorizationLegality::canVectorizeMemory() {
4751
4752   typedef SmallVector<Value*, 16> ValueVector;
4753   typedef SmallPtrSet<Value*, 16> ValueSet;
4754
4755   // Holds the Load and Store *instructions*.
4756   ValueVector Loads;
4757   ValueVector Stores;
4758
4759   // Holds all the different accesses in the loop.
4760   unsigned NumReads = 0;
4761   unsigned NumReadWrites = 0;
4762
4763   PtrRtCheck.Pointers.clear();
4764   PtrRtCheck.Need = false;
4765
4766   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4767   MemoryDepChecker DepChecker(SE, DL, TheLoop);
4768
4769   // For each block.
4770   for (Loop::block_iterator bb = TheLoop->block_begin(),
4771        be = TheLoop->block_end(); bb != be; ++bb) {
4772
4773     // Scan the BB and collect legal loads and stores.
4774     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4775          ++it) {
4776
4777       // If this is a load, save it. If this instruction can read from memory
4778       // but is not a load, then we quit. Notice that we don't handle function
4779       // calls that read or write.
4780       if (it->mayReadFromMemory()) {
4781         // Many math library functions read the rounding mode. We will only
4782         // vectorize a loop if it contains known function calls that don't set
4783         // the flag. Therefore, it is safe to ignore this read from memory.
4784         CallInst *Call = dyn_cast<CallInst>(it);
4785         if (Call && getIntrinsicIDForCall(Call, TLI))
4786           continue;
4787
4788         LoadInst *Ld = dyn_cast<LoadInst>(it);
4789         if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
4790           emitAnalysis(Report(Ld)
4791                        << "read with atomic ordering or volatile read");
4792           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4793           return false;
4794         }
4795         NumLoads++;
4796         Loads.push_back(Ld);
4797         DepChecker.addAccess(Ld);
4798         continue;
4799       }
4800
4801       // Save 'store' instructions. Abort if other instructions write to memory.
4802       if (it->mayWriteToMemory()) {
4803         StoreInst *St = dyn_cast<StoreInst>(it);
4804         if (!St) {
4805           emitAnalysis(Report(it) << "instruction cannot be vectorized");
4806           return false;
4807         }
4808         if (!St->isSimple() && !IsAnnotatedParallel) {
4809           emitAnalysis(Report(St)
4810                        << "write with atomic ordering or volatile write");
4811           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4812           return false;
4813         }
4814         NumStores++;
4815         Stores.push_back(St);
4816         DepChecker.addAccess(St);
4817       }
4818     } // Next instr.
4819   } // Next block.
4820
4821   // Now we have two lists that hold the loads and the stores.
4822   // Next, we find the pointers that they use.
4823
4824   // Check if we see any stores. If there are no stores, then we don't
4825   // care if the pointers are *restrict*.
4826   if (!Stores.size()) {
4827     DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4828     return true;
4829   }
4830
4831   AccessAnalysis::DepCandidates DependentAccesses;
4832   AccessAnalysis Accesses(DL, AA, DependentAccesses);
4833
4834   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4835   // multiple times on the same object. If the ptr is accessed twice, once
4836   // for read and once for write, it will only appear once (on the write
4837   // list). This is okay, since we are going to check for conflicts between
4838   // writes and between reads and writes, but not between reads and reads.
4839   ValueSet Seen;
4840
4841   ValueVector::iterator I, IE;
4842   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4843     StoreInst *ST = cast<StoreInst>(*I);
4844     Value* Ptr = ST->getPointerOperand();
4845
4846     if (isUniform(Ptr)) {
4847       emitAnalysis(
4848           Report(ST)
4849           << "write to a loop invariant address could not be vectorized");
4850       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4851       return false;
4852     }
4853
4854     // If we did *not* see this pointer before, insert it to  the read-write
4855     // list. At this phase it is only a 'write' list.
4856     if (Seen.insert(Ptr).second) {
4857       ++NumReadWrites;
4858
4859       AliasAnalysis::Location Loc = AA->getLocation(ST);
4860       // The TBAA metadata could have a control dependency on the predication
4861       // condition, so we cannot rely on it when determining whether or not we
4862       // need runtime pointer checks.
4863       if (blockNeedsPredication(ST->getParent()))
4864         Loc.AATags.TBAA = nullptr;
4865
4866       Accesses.addStore(Loc);
4867     }
4868   }
4869
4870   if (IsAnnotatedParallel) {
4871     DEBUG(dbgs()
4872           << "LV: A loop annotated parallel, ignore memory dependency "
4873           << "checks.\n");
4874     return true;
4875   }
4876
4877   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4878     LoadInst *LD = cast<LoadInst>(*I);
4879     Value* Ptr = LD->getPointerOperand();
4880     // If we did *not* see this pointer before, insert it to the
4881     // read list. If we *did* see it before, then it is already in
4882     // the read-write list. This allows us to vectorize expressions
4883     // such as A[i] += x;  Because the address of A[i] is a read-write
4884     // pointer. This only works if the index of A[i] is consecutive.
4885     // If the address of i is unknown (for example A[B[i]]) then we may
4886     // read a few words, modify, and write a few words, and some of the
4887     // words may be written to the same address.
4888     bool IsReadOnlyPtr = false;
4889     if (Seen.insert(Ptr).second ||
4890         !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4891       ++NumReads;
4892       IsReadOnlyPtr = true;
4893     }
4894
4895     AliasAnalysis::Location Loc = AA->getLocation(LD);
4896     // The TBAA metadata could have a control dependency on the predication
4897     // condition, so we cannot rely on it when determining whether or not we
4898     // need runtime pointer checks.
4899     if (blockNeedsPredication(LD->getParent()))
4900       Loc.AATags.TBAA = nullptr;
4901
4902     Accesses.addLoad(Loc, IsReadOnlyPtr);
4903   }
4904
4905   // If we write (or read-write) to a single destination and there are no
4906   // other reads in this loop then is it safe to vectorize.
4907   if (NumReadWrites == 1 && NumReads == 0) {
4908     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4909     return true;
4910   }
4911
4912   // Build dependence sets and check whether we need a runtime pointer bounds
4913   // check.
4914   Accesses.buildDependenceSets();
4915   bool NeedRTCheck = Accesses.isRTCheckNeeded();
4916
4917   // Find pointers with computable bounds. We are going to use this information
4918   // to place a runtime bound check.
4919   unsigned NumComparisons = 0;
4920   bool CanDoRT = false;
4921   if (NeedRTCheck)
4922     CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4923                                        Strides);
4924
4925   DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4926         " pointer comparisons.\n");
4927
4928   // If we only have one set of dependences to check pointers among we don't
4929   // need a runtime check.
4930   if (NumComparisons == 0 && NeedRTCheck)
4931     NeedRTCheck = false;
4932
4933   // Check that we did not collect too many pointers or found an unsizeable
4934   // pointer.
4935   if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4936     PtrRtCheck.reset();
4937     CanDoRT = false;
4938   }
4939
4940   if (CanDoRT) {
4941     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4942   }
4943
4944   if (NeedRTCheck && !CanDoRT) {
4945     emitAnalysis(Report() << "cannot identify array bounds");
4946     DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4947           "the array bounds.\n");
4948     PtrRtCheck.reset();
4949     return false;
4950   }
4951
4952   PtrRtCheck.Need = NeedRTCheck;
4953
4954   bool CanVecMem = true;
4955   if (Accesses.isDependencyCheckNeeded()) {
4956     DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4957     CanVecMem = DepChecker.areDepsSafe(
4958         DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4959     MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4960
4961     if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4962       DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4963       NeedRTCheck = true;
4964
4965       // Clear the dependency checks. We assume they are not needed.
4966       Accesses.resetDepChecks();
4967
4968       PtrRtCheck.reset();
4969       PtrRtCheck.Need = true;
4970
4971       CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4972                                          TheLoop, Strides, true);
4973       // Check that we did not collect too many pointers or found an unsizeable
4974       // pointer.
4975       if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4976         if (!CanDoRT && NumComparisons > 0)
4977           emitAnalysis(Report()
4978                        << "cannot check memory dependencies at runtime");
4979         else
4980           emitAnalysis(Report()
4981                        << NumComparisons << " exceeds limit of "
4982                        << RuntimeMemoryCheckThreshold
4983                        << " dependent memory operations checked at runtime");
4984         DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4985         PtrRtCheck.reset();
4986         return false;
4987       }
4988
4989       CanVecMem = true;
4990     }
4991   }
4992
4993   if (!CanVecMem)
4994     emitAnalysis(Report() << "unsafe dependent memory operations in loop");
4995
4996   DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4997         " need a runtime memory check.\n");
4998
4999   return CanVecMem;
5000 }
5001
5002 static bool hasMultipleUsesOf(Instruction *I,
5003                               SmallPtrSetImpl<Instruction *> &Insts) {
5004   unsigned NumUses = 0;
5005   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
5006     if (Insts.count(dyn_cast<Instruction>(*Use)))
5007       ++NumUses;
5008     if (NumUses > 1)
5009       return true;
5010   }
5011
5012   return false;
5013 }
5014
5015 static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set) {
5016   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
5017     if (!Set.count(dyn_cast<Instruction>(*Use)))
5018       return false;
5019   return true;
5020 }
5021
5022 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
5023                                                 ReductionKind Kind) {
5024   if (Phi->getNumIncomingValues() != 2)
5025     return false;
5026
5027   // Reduction variables are only found in the loop header block.
5028   if (Phi->getParent() != TheLoop->getHeader())
5029     return false;
5030
5031   // Obtain the reduction start value from the value that comes from the loop
5032   // preheader.
5033   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
5034
5035   // ExitInstruction is the single value which is used outside the loop.
5036   // We only allow for a single reduction value to be used outside the loop.
5037   // This includes users of the reduction, variables (which form a cycle
5038   // which ends in the phi node).
5039   Instruction *ExitInstruction = nullptr;
5040   // Indicates that we found a reduction operation in our scan.
5041   bool FoundReduxOp = false;
5042
5043   // We start with the PHI node and scan for all of the users of this
5044   // instruction. All users must be instructions that can be used as reduction
5045   // variables (such as ADD). We must have a single out-of-block user. The cycle
5046   // must include the original PHI.
5047   bool FoundStartPHI = false;
5048
5049   // To recognize min/max patterns formed by a icmp select sequence, we store
5050   // the number of instruction we saw from the recognized min/max pattern,
5051   //  to make sure we only see exactly the two instructions.
5052   unsigned NumCmpSelectPatternInst = 0;
5053   ReductionInstDesc ReduxDesc(false, nullptr);
5054
5055   SmallPtrSet<Instruction *, 8> VisitedInsts;
5056   SmallVector<Instruction *, 8> Worklist;
5057   Worklist.push_back(Phi);
5058   VisitedInsts.insert(Phi);
5059
5060   // A value in the reduction can be used:
5061   //  - By the reduction:
5062   //      - Reduction operation:
5063   //        - One use of reduction value (safe).
5064   //        - Multiple use of reduction value (not safe).
5065   //      - PHI:
5066   //        - All uses of the PHI must be the reduction (safe).
5067   //        - Otherwise, not safe.
5068   //  - By one instruction outside of the loop (safe).
5069   //  - By further instructions outside of the loop (not safe).
5070   //  - By an instruction that is not part of the reduction (not safe).
5071   //    This is either:
5072   //      * An instruction type other than PHI or the reduction operation.
5073   //      * A PHI in the header other than the initial PHI.
5074   while (!Worklist.empty()) {
5075     Instruction *Cur = Worklist.back();
5076     Worklist.pop_back();
5077
5078     // No Users.
5079     // If the instruction has no users then this is a broken chain and can't be
5080     // a reduction variable.
5081     if (Cur->use_empty())
5082       return false;
5083
5084     bool IsAPhi = isa<PHINode>(Cur);
5085
5086     // A header PHI use other than the original PHI.
5087     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
5088       return false;
5089
5090     // Reductions of instructions such as Div, and Sub is only possible if the
5091     // LHS is the reduction variable.
5092     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
5093         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
5094         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
5095       return false;
5096
5097     // Any reduction instruction must be of one of the allowed kinds.
5098     ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
5099     if (!ReduxDesc.IsReduction)
5100       return false;
5101
5102     // A reduction operation must only have one use of the reduction value.
5103     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
5104         hasMultipleUsesOf(Cur, VisitedInsts))
5105       return false;
5106
5107     // All inputs to a PHI node must be a reduction value.
5108     if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
5109       return false;
5110
5111     if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
5112                                      isa<SelectInst>(Cur)))
5113       ++NumCmpSelectPatternInst;
5114     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
5115                                    isa<SelectInst>(Cur)))
5116       ++NumCmpSelectPatternInst;
5117
5118     // Check  whether we found a reduction operator.
5119     FoundReduxOp |= !IsAPhi;
5120
5121     // Process users of current instruction. Push non-PHI nodes after PHI nodes
5122     // onto the stack. This way we are going to have seen all inputs to PHI
5123     // nodes once we get to them.
5124     SmallVector<Instruction *, 8> NonPHIs;
5125     SmallVector<Instruction *, 8> PHIs;
5126     for (User *U : Cur->users()) {
5127       Instruction *UI = cast<Instruction>(U);
5128
5129       // Check if we found the exit user.
5130       BasicBlock *Parent = UI->getParent();
5131       if (!TheLoop->contains(Parent)) {
5132         // Exit if you find multiple outside users or if the header phi node is
5133         // being used. In this case the user uses the value of the previous
5134         // iteration, in which case we would loose "VF-1" iterations of the
5135         // reduction operation if we vectorize.
5136         if (ExitInstruction != nullptr || Cur == Phi)
5137           return false;
5138
5139         // The instruction used by an outside user must be the last instruction
5140         // before we feed back to the reduction phi. Otherwise, we loose VF-1
5141         // operations on the value.
5142         if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
5143          return false;
5144
5145         ExitInstruction = Cur;
5146         continue;
5147       }
5148
5149       // Process instructions only once (termination). Each reduction cycle
5150       // value must only be used once, except by phi nodes and min/max
5151       // reductions which are represented as a cmp followed by a select.
5152       ReductionInstDesc IgnoredVal(false, nullptr);
5153       if (VisitedInsts.insert(UI).second) {
5154         if (isa<PHINode>(UI))
5155           PHIs.push_back(UI);
5156         else
5157           NonPHIs.push_back(UI);
5158       } else if (!isa<PHINode>(UI) &&
5159                  ((!isa<FCmpInst>(UI) &&
5160                    !isa<ICmpInst>(UI) &&
5161                    !isa<SelectInst>(UI)) ||
5162                   !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
5163         return false;
5164
5165       // Remember that we completed the cycle.
5166       if (UI == Phi)
5167         FoundStartPHI = true;
5168     }
5169     Worklist.append(PHIs.begin(), PHIs.end());
5170     Worklist.append(NonPHIs.begin(), NonPHIs.end());
5171   }
5172
5173   // This means we have seen one but not the other instruction of the
5174   // pattern or more than just a select and cmp.
5175   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
5176       NumCmpSelectPatternInst != 2)
5177     return false;
5178
5179   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
5180     return false;
5181
5182   // We found a reduction var if we have reached the original phi node and we
5183   // only have a single instruction with out-of-loop users.
5184
5185   // This instruction is allowed to have out-of-loop users.
5186   AllowedExit.insert(ExitInstruction);
5187
5188   // Save the description of this reduction variable.
5189   ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
5190                          ReduxDesc.MinMaxKind);
5191   Reductions[Phi] = RD;
5192   // We've ended the cycle. This is a reduction variable if we have an
5193   // outside user and it has a binary op.
5194
5195   return true;
5196 }
5197
5198 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
5199 /// pattern corresponding to a min(X, Y) or max(X, Y).
5200 LoopVectorizationLegality::ReductionInstDesc
5201 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
5202                                                     ReductionInstDesc &Prev) {
5203
5204   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
5205          "Expect a select instruction");
5206   Instruction *Cmp = nullptr;
5207   SelectInst *Select = nullptr;
5208
5209   // We must handle the select(cmp()) as a single instruction. Advance to the
5210   // select.
5211   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
5212     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
5213       return ReductionInstDesc(false, I);
5214     return ReductionInstDesc(Select, Prev.MinMaxKind);
5215   }
5216
5217   // Only handle single use cases for now.
5218   if (!(Select = dyn_cast<SelectInst>(I)))
5219     return ReductionInstDesc(false, I);
5220   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
5221       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
5222     return ReductionInstDesc(false, I);
5223   if (!Cmp->hasOneUse())
5224     return ReductionInstDesc(false, I);
5225
5226   Value *CmpLeft;
5227   Value *CmpRight;
5228
5229   // Look for a min/max pattern.
5230   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5231     return ReductionInstDesc(Select, MRK_UIntMin);
5232   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5233     return ReductionInstDesc(Select, MRK_UIntMax);
5234   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5235     return ReductionInstDesc(Select, MRK_SIntMax);
5236   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5237     return ReductionInstDesc(Select, MRK_SIntMin);
5238   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5239     return ReductionInstDesc(Select, MRK_FloatMin);
5240   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5241     return ReductionInstDesc(Select, MRK_FloatMax);
5242   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5243     return ReductionInstDesc(Select, MRK_FloatMin);
5244   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
5245     return ReductionInstDesc(Select, MRK_FloatMax);
5246
5247   return ReductionInstDesc(false, I);
5248 }
5249
5250 LoopVectorizationLegality::ReductionInstDesc
5251 LoopVectorizationLegality::isReductionInstr(Instruction *I,
5252                                             ReductionKind Kind,
5253                                             ReductionInstDesc &Prev) {
5254   bool FP = I->getType()->isFloatingPointTy();
5255   bool FastMath = FP && I->hasUnsafeAlgebra();
5256   switch (I->getOpcode()) {
5257   default:
5258     return ReductionInstDesc(false, I);
5259   case Instruction::PHI:
5260       if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
5261                  Kind != RK_FloatMinMax))
5262         return ReductionInstDesc(false, I);
5263     return ReductionInstDesc(I, Prev.MinMaxKind);
5264   case Instruction::Sub:
5265   case Instruction::Add:
5266     return ReductionInstDesc(Kind == RK_IntegerAdd, I);
5267   case Instruction::Mul:
5268     return ReductionInstDesc(Kind == RK_IntegerMult, I);
5269   case Instruction::And:
5270     return ReductionInstDesc(Kind == RK_IntegerAnd, I);
5271   case Instruction::Or:
5272     return ReductionInstDesc(Kind == RK_IntegerOr, I);
5273   case Instruction::Xor:
5274     return ReductionInstDesc(Kind == RK_IntegerXor, I);
5275   case Instruction::FMul:
5276     return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
5277   case Instruction::FSub:
5278   case Instruction::FAdd:
5279     return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
5280   case Instruction::FCmp:
5281   case Instruction::ICmp:
5282   case Instruction::Select:
5283     if (Kind != RK_IntegerMinMax &&
5284         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
5285       return ReductionInstDesc(false, I);
5286     return isMinMaxSelectCmpPattern(I, Prev);
5287   }
5288 }
5289
5290 LoopVectorizationLegality::InductionKind
5291 LoopVectorizationLegality::isInductionVariable(PHINode *Phi,
5292                                                ConstantInt *&StepValue) {
5293   Type *PhiTy = Phi->getType();
5294   // We only handle integer and pointer inductions variables.
5295   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
5296     return IK_NoInduction;
5297
5298   // Check that the PHI is consecutive.
5299   const SCEV *PhiScev = SE->getSCEV(Phi);
5300   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
5301   if (!AR) {
5302     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
5303     return IK_NoInduction;
5304   }
5305
5306   const SCEV *Step = AR->getStepRecurrence(*SE);
5307   // Calculate the pointer stride and check if it is consecutive.
5308   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5309   if (!C)
5310     return IK_NoInduction;
5311
5312   ConstantInt *CV = C->getValue();
5313   if (PhiTy->isIntegerTy()) {
5314     StepValue = CV;
5315     return IK_IntInduction;
5316   }
5317
5318   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
5319   Type *PointerElementType = PhiTy->getPointerElementType();
5320   // The pointer stride cannot be determined if the pointer element type is not
5321   // sized.
5322   if (!PointerElementType->isSized())
5323     return IK_NoInduction;
5324
5325   int64_t Size = static_cast<int64_t>(DL->getTypeAllocSize(PointerElementType));
5326   int64_t CVSize = CV->getSExtValue();
5327   if (CVSize % Size)
5328     return IK_NoInduction;
5329   StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
5330   return IK_PtrInduction;
5331 }
5332
5333 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
5334   Value *In0 = const_cast<Value*>(V);
5335   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
5336   if (!PN)
5337     return false;
5338
5339   return Inductions.count(PN);
5340 }
5341
5342 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
5343   assert(TheLoop->contains(BB) && "Unknown block used");
5344
5345   // Blocks that do not dominate the latch need predication.
5346   BasicBlock* Latch = TheLoop->getLoopLatch();
5347   return !DT->dominates(BB, Latch);
5348 }
5349
5350 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
5351                                            SmallPtrSetImpl<Value *> &SafePtrs) {
5352   
5353   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5354     // Check that we don't have a constant expression that can trap as operand.
5355     for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
5356          OI != OE; ++OI) {
5357       if (Constant *C = dyn_cast<Constant>(*OI))
5358         if (C->canTrap())
5359           return false;
5360     }
5361     // We might be able to hoist the load.
5362     if (it->mayReadFromMemory()) {
5363       LoadInst *LI = dyn_cast<LoadInst>(it);
5364       if (!LI)
5365         return false;
5366       if (!SafePtrs.count(LI->getPointerOperand())) {
5367         if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) {
5368           MaskedOp.insert(LI);
5369           continue;
5370         }
5371         return false;
5372       }
5373     }
5374
5375     // We don't predicate stores at the moment.
5376     if (it->mayWriteToMemory()) {
5377       StoreInst *SI = dyn_cast<StoreInst>(it);
5378       // We only support predication of stores in basic blocks with one
5379       // predecessor.
5380       if (!SI)
5381         return false;
5382
5383       bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
5384       bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
5385       
5386       if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
5387           !isSinglePredecessor) {
5388         // Build a masked store if it is legal for the target, otherwise scalarize
5389         // the block.
5390         bool isLegalMaskedOp =
5391           isLegalMaskedStore(SI->getValueOperand()->getType(),
5392                              SI->getPointerOperand());
5393         if (isLegalMaskedOp) {
5394           --NumPredStores;
5395           MaskedOp.insert(SI);
5396           continue;
5397         }
5398         return false;
5399       }
5400     }
5401     if (it->mayThrow())
5402       return false;
5403
5404     // The instructions below can trap.
5405     switch (it->getOpcode()) {
5406     default: continue;
5407     case Instruction::UDiv:
5408     case Instruction::SDiv:
5409     case Instruction::URem:
5410     case Instruction::SRem:
5411       return false;
5412     }
5413   }
5414
5415   return true;
5416 }
5417
5418 LoopVectorizationCostModel::VectorizationFactor
5419 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
5420   // Width 1 means no vectorize
5421   VectorizationFactor Factor = { 1U, 0U };
5422   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
5423     emitAnalysis(Report() << "runtime pointer checks needed. Enable vectorization of this loop with '#pragma clang loop vectorize(enable)' when compiling with -Os");
5424     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
5425     return Factor;
5426   }
5427
5428   if (!EnableCondStoresVectorization && Legal->NumPredStores) {
5429     emitAnalysis(Report() << "store that is conditionally executed prevents vectorization");
5430     DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
5431     return Factor;
5432   }
5433
5434   // Find the trip count.
5435   unsigned TC = SE->getSmallConstantTripCount(TheLoop);
5436   DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5437
5438   unsigned WidestType = getWidestType();
5439   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
5440   unsigned MaxSafeDepDist = -1U;
5441   if (Legal->getMaxSafeDepDistBytes() != -1U)
5442     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5443   WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
5444                     WidestRegister : MaxSafeDepDist);
5445   unsigned MaxVectorSize = WidestRegister / WidestType;
5446   DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
5447   DEBUG(dbgs() << "LV: The Widest register is: "
5448           << WidestRegister << " bits.\n");
5449
5450   if (MaxVectorSize == 0) {
5451     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5452     MaxVectorSize = 1;
5453   }
5454
5455   assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
5456          " into one vector!");
5457
5458   unsigned VF = MaxVectorSize;
5459
5460   // If we optimize the program for size, avoid creating the tail loop.
5461   if (OptForSize) {
5462     // If we are unable to calculate the trip count then don't try to vectorize.
5463     if (TC < 2) {
5464       emitAnalysis(Report() << "unable to calculate the loop count due to complex control flow");
5465       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5466       return Factor;
5467     }
5468
5469     // Find the maximum SIMD width that can fit within the trip count.
5470     VF = TC % MaxVectorSize;
5471
5472     if (VF == 0)
5473       VF = MaxVectorSize;
5474
5475     // If the trip count that we found modulo the vectorization factor is not
5476     // zero then we require a tail.
5477     if (VF < 2) {
5478       emitAnalysis(Report() << "cannot optimize for size and vectorize at the "
5479                                "same time. Enable vectorization of this loop "
5480                                "with '#pragma clang loop vectorize(enable)' "
5481                                "when compiling with -Os");
5482       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
5483       return Factor;
5484     }
5485   }
5486
5487   int UserVF = Hints->getWidth();
5488   if (UserVF != 0) {
5489     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
5490     DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5491
5492     Factor.Width = UserVF;
5493     return Factor;
5494   }
5495
5496   float Cost = expectedCost(1);
5497 #ifndef NDEBUG
5498   const float ScalarCost = Cost;
5499 #endif /* NDEBUG */
5500   unsigned Width = 1;
5501   DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
5502
5503   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5504   // Ignore scalar width, because the user explicitly wants vectorization.
5505   if (ForceVectorization && VF > 1) {
5506     Width = 2;
5507     Cost = expectedCost(Width) / (float)Width;
5508   }
5509
5510   for (unsigned i=2; i <= VF; i*=2) {
5511     // Notice that the vector loop needs to be executed less times, so
5512     // we need to divide the cost of the vector loops by the width of
5513     // the vector elements.
5514     float VectorCost = expectedCost(i) / (float)i;
5515     DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
5516           (int)VectorCost << ".\n");
5517     if (VectorCost < Cost) {
5518       Cost = VectorCost;
5519       Width = i;
5520     }
5521   }
5522
5523   DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
5524         << "LV: Vectorization seems to be not beneficial, "
5525         << "but was forced by a user.\n");
5526   DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
5527   Factor.Width = Width;
5528   Factor.Cost = Width * Cost;
5529   return Factor;
5530 }
5531
5532 unsigned LoopVectorizationCostModel::getWidestType() {
5533   unsigned MaxWidth = 8;
5534
5535   // For each block.
5536   for (Loop::block_iterator bb = TheLoop->block_begin(),
5537        be = TheLoop->block_end(); bb != be; ++bb) {
5538     BasicBlock *BB = *bb;
5539
5540     // For each instruction in the loop.
5541     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5542       Type *T = it->getType();
5543
5544       // Ignore ephemeral values.
5545       if (EphValues.count(it))
5546         continue;
5547
5548       // Only examine Loads, Stores and PHINodes.
5549       if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
5550         continue;
5551
5552       // Examine PHI nodes that are reduction variables.
5553       if (PHINode *PN = dyn_cast<PHINode>(it))
5554         if (!Legal->getReductionVars()->count(PN))
5555           continue;
5556
5557       // Examine the stored values.
5558       if (StoreInst *ST = dyn_cast<StoreInst>(it))
5559         T = ST->getValueOperand()->getType();
5560
5561       // Ignore loaded pointer types and stored pointer types that are not
5562       // consecutive. However, we do want to take consecutive stores/loads of
5563       // pointer vectors into account.
5564       if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
5565         continue;
5566
5567       MaxWidth = std::max(MaxWidth,
5568                           (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
5569     }
5570   }
5571
5572   return MaxWidth;
5573 }
5574
5575 unsigned
5576 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
5577                                                unsigned VF,
5578                                                unsigned LoopCost) {
5579
5580   // -- The unroll heuristics --
5581   // We unroll the loop in order to expose ILP and reduce the loop overhead.
5582   // There are many micro-architectural considerations that we can't predict
5583   // at this level. For example, frontend pressure (on decode or fetch) due to
5584   // code size, or the number and capabilities of the execution ports.
5585   //
5586   // We use the following heuristics to select the unroll factor:
5587   // 1. If the code has reductions, then we unroll in order to break the cross
5588   // iteration dependency.
5589   // 2. If the loop is really small, then we unroll in order to reduce the loop
5590   // overhead.
5591   // 3. We don't unroll if we think that we will spill registers to memory due
5592   // to the increased register pressure.
5593
5594   // Use the user preference, unless 'auto' is selected.
5595   int UserUF = Hints->getInterleave();
5596   if (UserUF != 0)
5597     return UserUF;
5598
5599   // When we optimize for size, we don't unroll.
5600   if (OptForSize)
5601     return 1;
5602
5603   // We used the distance for the unroll factor.
5604   if (Legal->getMaxSafeDepDistBytes() != -1U)
5605     return 1;
5606
5607   // Do not unroll loops with a relatively small trip count.
5608   unsigned TC = SE->getSmallConstantTripCount(TheLoop);
5609   if (TC > 1 && TC < TinyTripCountUnrollThreshold)
5610     return 1;
5611
5612   unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5613   DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
5614         " registers\n");
5615
5616   if (VF == 1) {
5617     if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5618       TargetNumRegisters = ForceTargetNumScalarRegs;
5619   } else {
5620     if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5621       TargetNumRegisters = ForceTargetNumVectorRegs;
5622   }
5623
5624   LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
5625   // We divide by these constants so assume that we have at least one
5626   // instruction that uses at least one register.
5627   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5628   R.NumInstructions = std::max(R.NumInstructions, 1U);
5629
5630   // We calculate the unroll factor using the following formula.
5631   // Subtract the number of loop invariants from the number of available
5632   // registers. These registers are used by all of the unrolled instances.
5633   // Next, divide the remaining registers by the number of registers that is
5634   // required by the loop, in order to estimate how many parallel instances
5635   // fit without causing spills. All of this is rounded down if necessary to be
5636   // a power of two. We want power of two unroll factors to simplify any
5637   // addressing operations or alignment considerations.
5638   unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5639                               R.MaxLocalUsers);
5640
5641   // Don't count the induction variable as unrolled.
5642   if (EnableIndVarRegisterHeur)
5643     UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
5644                        std::max(1U, (R.MaxLocalUsers - 1)));
5645
5646   // Clamp the unroll factor ranges to reasonable factors.
5647   unsigned MaxInterleaveSize = TTI.getMaxInterleaveFactor();
5648
5649   // Check if the user has overridden the unroll max.
5650   if (VF == 1) {
5651     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
5652       MaxInterleaveSize = ForceTargetMaxScalarInterleaveFactor;
5653   } else {
5654     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
5655       MaxInterleaveSize = ForceTargetMaxVectorInterleaveFactor;
5656   }
5657
5658   // If we did not calculate the cost for VF (because the user selected the VF)
5659   // then we calculate the cost of VF here.
5660   if (LoopCost == 0)
5661     LoopCost = expectedCost(VF);
5662
5663   // Clamp the calculated UF to be between the 1 and the max unroll factor
5664   // that the target allows.
5665   if (UF > MaxInterleaveSize)
5666     UF = MaxInterleaveSize;
5667   else if (UF < 1)
5668     UF = 1;
5669
5670   // Unroll if we vectorized this loop and there is a reduction that could
5671   // benefit from unrolling.
5672   if (VF > 1 && Legal->getReductionVars()->size()) {
5673     DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
5674     return UF;
5675   }
5676
5677   // Note that if we've already vectorized the loop we will have done the
5678   // runtime check and so unrolling won't require further checks.
5679   bool UnrollingRequiresRuntimePointerCheck =
5680       (VF == 1 && Legal->getRuntimePointerCheck()->Need);
5681
5682   // We want to unroll small loops in order to reduce the loop overhead and
5683   // potentially expose ILP opportunities.
5684   DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5685   if (!UnrollingRequiresRuntimePointerCheck &&
5686       LoopCost < SmallLoopCost) {
5687     // We assume that the cost overhead is 1 and we use the cost model
5688     // to estimate the cost of the loop and unroll until the cost of the
5689     // loop overhead is about 5% of the cost of the loop.
5690     unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5691
5692     // Unroll until store/load ports (estimated by max unroll factor) are
5693     // saturated.
5694     unsigned StoresUF = UF / (Legal->NumStores ? Legal->NumStores : 1);
5695     unsigned LoadsUF = UF /  (Legal->NumLoads ? Legal->NumLoads : 1);
5696
5697     // If we have a scalar reduction (vector reductions are already dealt with
5698     // by this point), we can increase the critical path length if the loop
5699     // we're unrolling is inside another loop. Limit, by default to 2, so the
5700     // critical path only gets increased by one reduction operation.
5701     if (Legal->getReductionVars()->size() &&
5702         TheLoop->getLoopDepth() > 1) {
5703       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionUF);
5704       SmallUF = std::min(SmallUF, F);
5705       StoresUF = std::min(StoresUF, F);
5706       LoadsUF = std::min(LoadsUF, F);
5707     }
5708
5709     if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
5710       DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
5711       return std::max(StoresUF, LoadsUF);
5712     }
5713
5714     DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
5715     return SmallUF;
5716   }
5717
5718   DEBUG(dbgs() << "LV: Not Unrolling.\n");
5719   return 1;
5720 }
5721
5722 LoopVectorizationCostModel::RegisterUsage
5723 LoopVectorizationCostModel::calculateRegisterUsage() {
5724   // This function calculates the register usage by measuring the highest number
5725   // of values that are alive at a single location. Obviously, this is a very
5726   // rough estimation. We scan the loop in a topological order in order and
5727   // assign a number to each instruction. We use RPO to ensure that defs are
5728   // met before their users. We assume that each instruction that has in-loop
5729   // users starts an interval. We record every time that an in-loop value is
5730   // used, so we have a list of the first and last occurrences of each
5731   // instruction. Next, we transpose this data structure into a multi map that
5732   // holds the list of intervals that *end* at a specific location. This multi
5733   // map allows us to perform a linear search. We scan the instructions linearly
5734   // and record each time that a new interval starts, by placing it in a set.
5735   // If we find this value in the multi-map then we remove it from the set.
5736   // The max register usage is the maximum size of the set.
5737   // We also search for instructions that are defined outside the loop, but are
5738   // used inside the loop. We need this number separately from the max-interval
5739   // usage number because when we unroll, loop-invariant values do not take
5740   // more register.
5741   LoopBlocksDFS DFS(TheLoop);
5742   DFS.perform(LI);
5743
5744   RegisterUsage R;
5745   R.NumInstructions = 0;
5746
5747   // Each 'key' in the map opens a new interval. The values
5748   // of the map are the index of the 'last seen' usage of the
5749   // instruction that is the key.
5750   typedef DenseMap<Instruction*, unsigned> IntervalMap;
5751   // Maps instruction to its index.
5752   DenseMap<unsigned, Instruction*> IdxToInstr;
5753   // Marks the end of each interval.
5754   IntervalMap EndPoint;
5755   // Saves the list of instruction indices that are used in the loop.
5756   SmallSet<Instruction*, 8> Ends;
5757   // Saves the list of values that are used in the loop but are
5758   // defined outside the loop, such as arguments and constants.
5759   SmallPtrSet<Value*, 8> LoopInvariants;
5760
5761   unsigned Index = 0;
5762   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5763        be = DFS.endRPO(); bb != be; ++bb) {
5764     R.NumInstructions += (*bb)->size();
5765     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5766          ++it) {
5767       Instruction *I = it;
5768       IdxToInstr[Index++] = I;
5769
5770       // Save the end location of each USE.
5771       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5772         Value *U = I->getOperand(i);
5773         Instruction *Instr = dyn_cast<Instruction>(U);
5774
5775         // Ignore non-instruction values such as arguments, constants, etc.
5776         if (!Instr) continue;
5777
5778         // If this instruction is outside the loop then record it and continue.
5779         if (!TheLoop->contains(Instr)) {
5780           LoopInvariants.insert(Instr);
5781           continue;
5782         }
5783
5784         // Overwrite previous end points.
5785         EndPoint[Instr] = Index;
5786         Ends.insert(Instr);
5787       }
5788     }
5789   }
5790
5791   // Saves the list of intervals that end with the index in 'key'.
5792   typedef SmallVector<Instruction*, 2> InstrList;
5793   DenseMap<unsigned, InstrList> TransposeEnds;
5794
5795   // Transpose the EndPoints to a list of values that end at each index.
5796   for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5797        it != e; ++it)
5798     TransposeEnds[it->second].push_back(it->first);
5799
5800   SmallSet<Instruction*, 8> OpenIntervals;
5801   unsigned MaxUsage = 0;
5802
5803
5804   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5805   for (unsigned int i = 0; i < Index; ++i) {
5806     Instruction *I = IdxToInstr[i];
5807     // Ignore instructions that are never used within the loop.
5808     if (!Ends.count(I)) continue;
5809
5810     // Ignore ephemeral values.
5811     if (EphValues.count(I))
5812       continue;
5813
5814     // Remove all of the instructions that end at this location.
5815     InstrList &List = TransposeEnds[i];
5816     for (unsigned int j=0, e = List.size(); j < e; ++j)
5817       OpenIntervals.erase(List[j]);
5818
5819     // Count the number of live interals.
5820     MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5821
5822     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5823           OpenIntervals.size() << '\n');
5824
5825     // Add the current instruction to the list of open intervals.
5826     OpenIntervals.insert(I);
5827   }
5828
5829   unsigned Invariant = LoopInvariants.size();
5830   DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5831   DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5832   DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5833
5834   R.LoopInvariantRegs = Invariant;
5835   R.MaxLocalUsers = MaxUsage;
5836   return R;
5837 }
5838
5839 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5840   unsigned Cost = 0;
5841
5842   // For each block.
5843   for (Loop::block_iterator bb = TheLoop->block_begin(),
5844        be = TheLoop->block_end(); bb != be; ++bb) {
5845     unsigned BlockCost = 0;
5846     BasicBlock *BB = *bb;
5847
5848     // For each instruction in the old loop.
5849     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5850       // Skip dbg intrinsics.
5851       if (isa<DbgInfoIntrinsic>(it))
5852         continue;
5853
5854       // Ignore ephemeral values.
5855       if (EphValues.count(it))
5856         continue;
5857
5858       unsigned C = getInstructionCost(it, VF);
5859
5860       // Check if we should override the cost.
5861       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5862         C = ForceTargetInstructionCost;
5863
5864       BlockCost += C;
5865       DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5866             VF << " For instruction: " << *it << '\n');
5867     }
5868
5869     // We assume that if-converted blocks have a 50% chance of being executed.
5870     // When the code is scalar then some of the blocks are avoided due to CF.
5871     // When the code is vectorized we execute all code paths.
5872     if (VF == 1 && Legal->blockNeedsPredication(*bb))
5873       BlockCost /= 2;
5874
5875     Cost += BlockCost;
5876   }
5877
5878   return Cost;
5879 }
5880
5881 /// \brief Check whether the address computation for a non-consecutive memory
5882 /// access looks like an unlikely candidate for being merged into the indexing
5883 /// mode.
5884 ///
5885 /// We look for a GEP which has one index that is an induction variable and all
5886 /// other indices are loop invariant. If the stride of this access is also
5887 /// within a small bound we decide that this address computation can likely be
5888 /// merged into the addressing mode.
5889 /// In all other cases, we identify the address computation as complex.
5890 static bool isLikelyComplexAddressComputation(Value *Ptr,
5891                                               LoopVectorizationLegality *Legal,
5892                                               ScalarEvolution *SE,
5893                                               const Loop *TheLoop) {
5894   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5895   if (!Gep)
5896     return true;
5897
5898   // We are looking for a gep with all loop invariant indices except for one
5899   // which should be an induction variable.
5900   unsigned NumOperands = Gep->getNumOperands();
5901   for (unsigned i = 1; i < NumOperands; ++i) {
5902     Value *Opd = Gep->getOperand(i);
5903     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5904         !Legal->isInductionVariable(Opd))
5905       return true;
5906   }
5907
5908   // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5909   // can likely be merged into the address computation.
5910   unsigned MaxMergeDistance = 64;
5911
5912   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5913   if (!AddRec)
5914     return true;
5915
5916   // Check the step is constant.
5917   const SCEV *Step = AddRec->getStepRecurrence(*SE);
5918   // Calculate the pointer stride and check if it is consecutive.
5919   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5920   if (!C)
5921     return true;
5922
5923   const APInt &APStepVal = C->getValue()->getValue();
5924
5925   // Huge step value - give up.
5926   if (APStepVal.getBitWidth() > 64)
5927     return true;
5928
5929   int64_t StepVal = APStepVal.getSExtValue();
5930
5931   return StepVal > MaxMergeDistance;
5932 }
5933
5934 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5935   if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5936     return true;
5937   return false;
5938 }
5939
5940 unsigned
5941 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5942   // If we know that this instruction will remain uniform, check the cost of
5943   // the scalar version.
5944   if (Legal->isUniformAfterVectorization(I))
5945     VF = 1;
5946
5947   Type *RetTy = I->getType();
5948   Type *VectorTy = ToVectorTy(RetTy, VF);
5949
5950   // TODO: We need to estimate the cost of intrinsic calls.
5951   switch (I->getOpcode()) {
5952   case Instruction::GetElementPtr:
5953     // We mark this instruction as zero-cost because the cost of GEPs in
5954     // vectorized code depends on whether the corresponding memory instruction
5955     // is scalarized or not. Therefore, we handle GEPs with the memory
5956     // instruction cost.
5957     return 0;
5958   case Instruction::Br: {
5959     return TTI.getCFInstrCost(I->getOpcode());
5960   }
5961   case Instruction::PHI:
5962     //TODO: IF-converted IFs become selects.
5963     return 0;
5964   case Instruction::Add:
5965   case Instruction::FAdd:
5966   case Instruction::Sub:
5967   case Instruction::FSub:
5968   case Instruction::Mul:
5969   case Instruction::FMul:
5970   case Instruction::UDiv:
5971   case Instruction::SDiv:
5972   case Instruction::FDiv:
5973   case Instruction::URem:
5974   case Instruction::SRem:
5975   case Instruction::FRem:
5976   case Instruction::Shl:
5977   case Instruction::LShr:
5978   case Instruction::AShr:
5979   case Instruction::And:
5980   case Instruction::Or:
5981   case Instruction::Xor: {
5982     // Since we will replace the stride by 1 the multiplication should go away.
5983     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5984       return 0;
5985     // Certain instructions can be cheaper to vectorize if they have a constant
5986     // second vector operand. One example of this are shifts on x86.
5987     TargetTransformInfo::OperandValueKind Op1VK =
5988       TargetTransformInfo::OK_AnyValue;
5989     TargetTransformInfo::OperandValueKind Op2VK =
5990       TargetTransformInfo::OK_AnyValue;
5991     TargetTransformInfo::OperandValueProperties Op1VP =
5992         TargetTransformInfo::OP_None;
5993     TargetTransformInfo::OperandValueProperties Op2VP =
5994         TargetTransformInfo::OP_None;
5995     Value *Op2 = I->getOperand(1);
5996
5997     // Check for a splat of a constant or for a non uniform vector of constants.
5998     if (isa<ConstantInt>(Op2)) {
5999       ConstantInt *CInt = cast<ConstantInt>(Op2);
6000       if (CInt && CInt->getValue().isPowerOf2())
6001         Op2VP = TargetTransformInfo::OP_PowerOf2;
6002       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
6003     } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
6004       Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
6005       Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
6006       if (SplatValue) {
6007         ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
6008         if (CInt && CInt->getValue().isPowerOf2())
6009           Op2VP = TargetTransformInfo::OP_PowerOf2;
6010         Op2VK = TargetTransformInfo::OK_UniformConstantValue;
6011       }
6012     }
6013
6014     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
6015                                       Op1VP, Op2VP);
6016   }
6017   case Instruction::Select: {
6018     SelectInst *SI = cast<SelectInst>(I);
6019     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
6020     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
6021     Type *CondTy = SI->getCondition()->getType();
6022     if (!ScalarCond)
6023       CondTy = VectorType::get(CondTy, VF);
6024
6025     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
6026   }
6027   case Instruction::ICmp:
6028   case Instruction::FCmp: {
6029     Type *ValTy = I->getOperand(0)->getType();
6030     VectorTy = ToVectorTy(ValTy, VF);
6031     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
6032   }
6033   case Instruction::Store:
6034   case Instruction::Load: {
6035     StoreInst *SI = dyn_cast<StoreInst>(I);
6036     LoadInst *LI = dyn_cast<LoadInst>(I);
6037     Type *ValTy = (SI ? SI->getValueOperand()->getType() :
6038                    LI->getType());
6039     VectorTy = ToVectorTy(ValTy, VF);
6040
6041     unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
6042     unsigned AS = SI ? SI->getPointerAddressSpace() :
6043       LI->getPointerAddressSpace();
6044     Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
6045     // We add the cost of address computation here instead of with the gep
6046     // instruction because only here we know whether the operation is
6047     // scalarized.
6048     if (VF == 1)
6049       return TTI.getAddressComputationCost(VectorTy) +
6050         TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
6051
6052     // Scalarized loads/stores.
6053     int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
6054     bool Reverse = ConsecutiveStride < 0;
6055     unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
6056     unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
6057     if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
6058       bool IsComplexComputation =
6059         isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
6060       unsigned Cost = 0;
6061       // The cost of extracting from the value vector and pointer vector.
6062       Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6063       for (unsigned i = 0; i < VF; ++i) {
6064         //  The cost of extracting the pointer operand.
6065         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
6066         // In case of STORE, the cost of ExtractElement from the vector.
6067         // In case of LOAD, the cost of InsertElement into the returned
6068         // vector.
6069         Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
6070                                             Instruction::InsertElement,
6071                                             VectorTy, i);
6072       }
6073
6074       // The cost of the scalar loads/stores.
6075       Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
6076       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
6077                                        Alignment, AS);
6078       return Cost;
6079     }
6080
6081     // Wide load/stores.
6082     unsigned Cost = TTI.getAddressComputationCost(VectorTy);
6083     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
6084
6085     if (Reverse)
6086       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
6087                                   VectorTy, 0);
6088     return Cost;
6089   }
6090   case Instruction::ZExt:
6091   case Instruction::SExt:
6092   case Instruction::FPToUI:
6093   case Instruction::FPToSI:
6094   case Instruction::FPExt:
6095   case Instruction::PtrToInt:
6096   case Instruction::IntToPtr:
6097   case Instruction::SIToFP:
6098   case Instruction::UIToFP:
6099   case Instruction::Trunc:
6100   case Instruction::FPTrunc:
6101   case Instruction::BitCast: {
6102     // We optimize the truncation of induction variable.
6103     // The cost of these is the same as the scalar operation.
6104     if (I->getOpcode() == Instruction::Trunc &&
6105         Legal->isInductionVariable(I->getOperand(0)))
6106       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
6107                                   I->getOperand(0)->getType());
6108
6109     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
6110     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
6111   }
6112   case Instruction::Call: {
6113     CallInst *CI = cast<CallInst>(I);
6114     Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
6115     assert(ID && "Not an intrinsic call!");
6116     Type *RetTy = ToVectorTy(CI->getType(), VF);
6117     SmallVector<Type*, 4> Tys;
6118     for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
6119       Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
6120     return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
6121   }
6122   default: {
6123     // We are scalarizing the instruction. Return the cost of the scalar
6124     // instruction, plus the cost of insert and extract into vector
6125     // elements, times the vector width.
6126     unsigned Cost = 0;
6127
6128     if (!RetTy->isVoidTy() && VF != 1) {
6129       unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
6130                                                 VectorTy);
6131       unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
6132                                                 VectorTy);
6133
6134       // The cost of inserting the results plus extracting each one of the
6135       // operands.
6136       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
6137     }
6138
6139     // The cost of executing VF copies of the scalar instruction. This opcode
6140     // is unknown. Assume that it is the same as 'mul'.
6141     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
6142     return Cost;
6143   }
6144   }// end of switch.
6145 }
6146
6147 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
6148   if (Scalar->isVoidTy() || VF == 1)
6149     return Scalar;
6150   return VectorType::get(Scalar, VF);
6151 }
6152
6153 char LoopVectorize::ID = 0;
6154 static const char lv_name[] = "Loop Vectorization";
6155 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
6156 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
6157 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
6158 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
6159 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
6160 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
6161 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
6162 INITIALIZE_PASS_DEPENDENCY(LCSSA)
6163 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
6164 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
6165 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
6166
6167 namespace llvm {
6168   Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
6169     return new LoopVectorize(NoUnrolling, AlwaysVectorize);
6170   }
6171 }
6172
6173 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
6174   // Check for a store.
6175   if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
6176     return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
6177
6178   // Check for a load.
6179   if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
6180     return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
6181
6182   return false;
6183 }
6184
6185
6186 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
6187                                              bool IfPredicateStore) {
6188   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
6189   // Holds vector parameters or scalars, in case of uniform vals.
6190   SmallVector<VectorParts, 4> Params;
6191
6192   setDebugLocFromInst(Builder, Instr);
6193
6194   // Find all of the vectorized parameters.
6195   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
6196     Value *SrcOp = Instr->getOperand(op);
6197
6198     // If we are accessing the old induction variable, use the new one.
6199     if (SrcOp == OldInduction) {
6200       Params.push_back(getVectorValue(SrcOp));
6201       continue;
6202     }
6203
6204     // Try using previously calculated values.
6205     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
6206
6207     // If the src is an instruction that appeared earlier in the basic block
6208     // then it should already be vectorized.
6209     if (SrcInst && OrigLoop->contains(SrcInst)) {
6210       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
6211       // The parameter is a vector value from earlier.
6212       Params.push_back(WidenMap.get(SrcInst));
6213     } else {
6214       // The parameter is a scalar from outside the loop. Maybe even a constant.
6215       VectorParts Scalars;
6216       Scalars.append(UF, SrcOp);
6217       Params.push_back(Scalars);
6218     }
6219   }
6220
6221   assert(Params.size() == Instr->getNumOperands() &&
6222          "Invalid number of operands");
6223
6224   // Does this instruction return a value ?
6225   bool IsVoidRetTy = Instr->getType()->isVoidTy();
6226
6227   Value *UndefVec = IsVoidRetTy ? nullptr :
6228   UndefValue::get(Instr->getType());
6229   // Create a new entry in the WidenMap and initialize it to Undef or Null.
6230   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
6231
6232   Instruction *InsertPt = Builder.GetInsertPoint();
6233   BasicBlock *IfBlock = Builder.GetInsertBlock();
6234   BasicBlock *CondBlock = nullptr;
6235
6236   VectorParts Cond;
6237   Loop *VectorLp = nullptr;
6238   if (IfPredicateStore) {
6239     assert(Instr->getParent()->getSinglePredecessor() &&
6240            "Only support single predecessor blocks");
6241     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
6242                           Instr->getParent());
6243     VectorLp = LI->getLoopFor(IfBlock);
6244     assert(VectorLp && "Must have a loop for this block");
6245   }
6246
6247   // For each vector unroll 'part':
6248   for (unsigned Part = 0; Part < UF; ++Part) {
6249     // For each scalar that we create:
6250
6251     // Start an "if (pred) a[i] = ..." block.
6252     Value *Cmp = nullptr;
6253     if (IfPredicateStore) {
6254       if (Cond[Part]->getType()->isVectorTy())
6255         Cond[Part] =
6256             Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
6257       Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
6258                                ConstantInt::get(Cond[Part]->getType(), 1));
6259       CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
6260       LoopVectorBody.push_back(CondBlock);
6261       VectorLp->addBasicBlockToLoop(CondBlock, *LI);
6262       // Update Builder with newly created basic block.
6263       Builder.SetInsertPoint(InsertPt);
6264     }
6265
6266     Instruction *Cloned = Instr->clone();
6267       if (!IsVoidRetTy)
6268         Cloned->setName(Instr->getName() + ".cloned");
6269       // Replace the operands of the cloned instructions with extracted scalars.
6270       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
6271         Value *Op = Params[op][Part];
6272         Cloned->setOperand(op, Op);
6273       }
6274
6275       // Place the cloned scalar in the new loop.
6276       Builder.Insert(Cloned);
6277
6278       // If the original scalar returns a value we need to place it in a vector
6279       // so that future users will be able to use it.
6280       if (!IsVoidRetTy)
6281         VecResults[Part] = Cloned;
6282
6283     // End if-block.
6284       if (IfPredicateStore) {
6285         BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
6286         LoopVectorBody.push_back(NewIfBlock);
6287         VectorLp->addBasicBlockToLoop(NewIfBlock, *LI);
6288         Builder.SetInsertPoint(InsertPt);
6289         Instruction *OldBr = IfBlock->getTerminator();
6290         BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
6291         OldBr->eraseFromParent();
6292         IfBlock = NewIfBlock;
6293       }
6294   }
6295 }
6296
6297 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
6298   StoreInst *SI = dyn_cast<StoreInst>(Instr);
6299   bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
6300
6301   return scalarizeInstruction(Instr, IfPredicateStore);
6302 }
6303
6304 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
6305   return Vec;
6306 }
6307
6308 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
6309   return V;
6310 }
6311
6312 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
6313   // When unrolling and the VF is 1, we only need to add a simple scalar.
6314   Type *ITy = Val->getType();
6315   assert(!ITy->isVectorTy() && "Val must be a scalar");
6316   Constant *C = ConstantInt::get(ITy, StartIdx);
6317   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
6318 }