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