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