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