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