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