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