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