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