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