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