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       cast<PHINode>(UI)->addIncoming(EndValue, MiddleBlock);
3294       break;
3295     }
3296   }
3297 
3298   // An external user of the penultimate value need to see EndValue - Step.
3299   // The simplest way to get this is to recompute it from the constituent SCEVs,
3300   // that is Start + (Step * (CRD - 1)).
3301   for (User *U : OrigPhi->users()) {
3302     Instruction *UI = cast<Instruction>(U);
3303     if (!OrigLoop->contains(UI)) {
3304       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3305       const DataLayout &DL =
3306           OrigLoop->getHeader()->getModule()->getDataLayout();
3307 
3308       IRBuilder<> B(MiddleBlock->getTerminator());
3309       Value *CountMinusOne = B.CreateSub(
3310           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3311       Value *CMO = B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType(),
3312                                        "cast.cmo");
3313       Value *Escape = II.transform(B, CMO, PSE.getSE(), DL);
3314       Escape->setName("ind.escape");
3315       cast<PHINode>(UI)->addIncoming(Escape, MiddleBlock);
3316       break;
3317     }
3318   }
3319 }
3320 
3321 namespace {
3322 struct CSEDenseMapInfo {
3323   static bool canHandle(Instruction *I) {
3324     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3325            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3326   }
3327   static inline Instruction *getEmptyKey() {
3328     return DenseMapInfo<Instruction *>::getEmptyKey();
3329   }
3330   static inline Instruction *getTombstoneKey() {
3331     return DenseMapInfo<Instruction *>::getTombstoneKey();
3332   }
3333   static unsigned getHashValue(Instruction *I) {
3334     assert(canHandle(I) && "Unknown instruction!");
3335     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3336                                                            I->value_op_end()));
3337   }
3338   static bool isEqual(Instruction *LHS, Instruction *RHS) {
3339     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3340         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3341       return LHS == RHS;
3342     return LHS->isIdenticalTo(RHS);
3343   }
3344 };
3345 }
3346 
3347 ///\brief Perform cse of induction variable instructions.
3348 static void cse(BasicBlock *BB) {
3349   // Perform simple cse.
3350   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3351   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3352     Instruction *In = &*I++;
3353 
3354     if (!CSEDenseMapInfo::canHandle(In))
3355       continue;
3356 
3357     // Check if we can replace this instruction with any of the
3358     // visited instructions.
3359     if (Instruction *V = CSEMap.lookup(In)) {
3360       In->replaceAllUsesWith(V);
3361       In->eraseFromParent();
3362       continue;
3363     }
3364 
3365     CSEMap[In] = In;
3366   }
3367 }
3368 
3369 /// \brief Adds a 'fast' flag to floating point operations.
3370 static Value *addFastMathFlag(Value *V) {
3371   if (isa<FPMathOperator>(V)) {
3372     FastMathFlags Flags;
3373     Flags.setUnsafeAlgebra();
3374     cast<Instruction>(V)->setFastMathFlags(Flags);
3375   }
3376   return V;
3377 }
3378 
3379 /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
3380 /// the result needs to be inserted and/or extracted from vectors.
3381 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
3382                                          const TargetTransformInfo &TTI) {
3383   if (Ty->isVoidTy())
3384     return 0;
3385 
3386   assert(Ty->isVectorTy() && "Can only scalarize vectors");
3387   unsigned Cost = 0;
3388 
3389   for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
3390     if (Insert)
3391       Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
3392     if (Extract)
3393       Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
3394   }
3395 
3396   return Cost;
3397 }
3398 
3399 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3400 // Return the cost of the instruction, including scalarization overhead if it's
3401 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3402 // i.e. either vector version isn't available, or is too expensive.
3403 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3404                                   const TargetTransformInfo &TTI,
3405                                   const TargetLibraryInfo *TLI,
3406                                   bool &NeedToScalarize) {
3407   Function *F = CI->getCalledFunction();
3408   StringRef FnName = CI->getCalledFunction()->getName();
3409   Type *ScalarRetTy = CI->getType();
3410   SmallVector<Type *, 4> Tys, ScalarTys;
3411   for (auto &ArgOp : CI->arg_operands())
3412     ScalarTys.push_back(ArgOp->getType());
3413 
3414   // Estimate cost of scalarized vector call. The source operands are assumed
3415   // to be vectors, so we need to extract individual elements from there,
3416   // execute VF scalar calls, and then gather the result into the vector return
3417   // value.
3418   unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3419   if (VF == 1)
3420     return ScalarCallCost;
3421 
3422   // Compute corresponding vector type for return value and arguments.
3423   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3424   for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
3425     Tys.push_back(ToVectorTy(ScalarTys[i], VF));
3426 
3427   // Compute costs of unpacking argument values for the scalar calls and
3428   // packing the return values to a vector.
3429   unsigned ScalarizationCost =
3430       getScalarizationOverhead(RetTy, true, false, TTI);
3431   for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
3432     ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
3433 
3434   unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3435 
3436   // If we can't emit a vector call for this function, then the currently found
3437   // cost is the cost we need to return.
3438   NeedToScalarize = true;
3439   if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3440     return Cost;
3441 
3442   // If the corresponding vector cost is cheaper, return its cost.
3443   unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3444   if (VectorCallCost < Cost) {
3445     NeedToScalarize = false;
3446     return VectorCallCost;
3447   }
3448   return Cost;
3449 }
3450 
3451 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3452 // factor VF.  Return the cost of the instruction, including scalarization
3453 // overhead if it's needed.
3454 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3455                                        const TargetTransformInfo &TTI,
3456                                        const TargetLibraryInfo *TLI) {
3457   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3458   assert(ID && "Expected intrinsic call!");
3459 
3460   Type *RetTy = ToVectorTy(CI->getType(), VF);
3461   SmallVector<Type *, 4> Tys;
3462   for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3463     Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3464 
3465   FastMathFlags FMF;
3466   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3467     FMF = FPMO->getFastMathFlags();
3468 
3469   return TTI.getIntrinsicInstrCost(ID, RetTy, Tys, FMF);
3470 }
3471 
3472 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3473   IntegerType *I1 = cast<IntegerType>(T1->getVectorElementType());
3474   IntegerType *I2 = cast<IntegerType>(T2->getVectorElementType());
3475   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3476 }
3477 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3478   IntegerType *I1 = cast<IntegerType>(T1->getVectorElementType());
3479   IntegerType *I2 = cast<IntegerType>(T2->getVectorElementType());
3480   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3481 }
3482 
3483 void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3484   // For every instruction `I` in MinBWs, truncate the operands, create a
3485   // truncated version of `I` and reextend its result. InstCombine runs
3486   // later and will remove any ext/trunc pairs.
3487   //
3488   SmallPtrSet<Value *, 4> Erased;
3489   for (auto &KV : MinBWs) {
3490     VectorParts &Parts = WidenMap.get(KV.first);
3491     for (Value *&I : Parts) {
3492       if (Erased.count(I) || I->use_empty())
3493         continue;
3494       Type *OriginalTy = I->getType();
3495       Type *ScalarTruncatedTy =
3496           IntegerType::get(OriginalTy->getContext(), KV.second);
3497       Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3498                                           OriginalTy->getVectorNumElements());
3499       if (TruncatedTy == OriginalTy)
3500         continue;
3501 
3502       if (!isa<Instruction>(I))
3503         continue;
3504 
3505       IRBuilder<> B(cast<Instruction>(I));
3506       auto ShrinkOperand = [&](Value *V) -> Value * {
3507         if (auto *ZI = dyn_cast<ZExtInst>(V))
3508           if (ZI->getSrcTy() == TruncatedTy)
3509             return ZI->getOperand(0);
3510         return B.CreateZExtOrTrunc(V, TruncatedTy);
3511       };
3512 
3513       // The actual instruction modification depends on the instruction type,
3514       // unfortunately.
3515       Value *NewI = nullptr;
3516       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
3517         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3518                              ShrinkOperand(BO->getOperand(1)));
3519         cast<BinaryOperator>(NewI)->copyIRFlags(I);
3520       } else if (ICmpInst *CI = dyn_cast<ICmpInst>(I)) {
3521         NewI =
3522             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3523                          ShrinkOperand(CI->getOperand(1)));
3524       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
3525         NewI = B.CreateSelect(SI->getCondition(),
3526                               ShrinkOperand(SI->getTrueValue()),
3527                               ShrinkOperand(SI->getFalseValue()));
3528       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3529         switch (CI->getOpcode()) {
3530         default:
3531           llvm_unreachable("Unhandled cast!");
3532         case Instruction::Trunc:
3533           NewI = ShrinkOperand(CI->getOperand(0));
3534           break;
3535         case Instruction::SExt:
3536           NewI = B.CreateSExtOrTrunc(
3537               CI->getOperand(0),
3538               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3539           break;
3540         case Instruction::ZExt:
3541           NewI = B.CreateZExtOrTrunc(
3542               CI->getOperand(0),
3543               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3544           break;
3545         }
3546       } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
3547         auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3548         auto *O0 = B.CreateZExtOrTrunc(
3549             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3550         auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3551         auto *O1 = B.CreateZExtOrTrunc(
3552             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3553 
3554         NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3555       } else if (isa<LoadInst>(I)) {
3556         // Don't do anything with the operands, just extend the result.
3557         continue;
3558       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3559         auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
3560         auto *O0 = B.CreateZExtOrTrunc(
3561             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3562         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3563         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3564       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3565         auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
3566         auto *O0 = B.CreateZExtOrTrunc(
3567             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3568         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3569       } else {
3570         llvm_unreachable("Unhandled instruction type!");
3571       }
3572 
3573       // Lastly, extend the result.
3574       NewI->takeName(cast<Instruction>(I));
3575       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3576       I->replaceAllUsesWith(Res);
3577       cast<Instruction>(I)->eraseFromParent();
3578       Erased.insert(I);
3579       I = Res;
3580     }
3581   }
3582 
3583   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3584   for (auto &KV : MinBWs) {
3585     VectorParts &Parts = WidenMap.get(KV.first);
3586     for (Value *&I : Parts) {
3587       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3588       if (Inst && Inst->use_empty()) {
3589         Value *NewI = Inst->getOperand(0);
3590         Inst->eraseFromParent();
3591         I = NewI;
3592       }
3593     }
3594   }
3595 }
3596 
3597 void InnerLoopVectorizer::vectorizeLoop() {
3598   //===------------------------------------------------===//
3599   //
3600   // Notice: any optimization or new instruction that go
3601   // into the code below should be also be implemented in
3602   // the cost-model.
3603   //
3604   //===------------------------------------------------===//
3605   Constant *Zero = Builder.getInt32(0);
3606 
3607   // In order to support recurrences we need to be able to vectorize Phi nodes.
3608   // Phi nodes have cycles, so we need to vectorize them in two stages. First,
3609   // we create a new vector PHI node with no incoming edges. We use this value
3610   // when we vectorize all of the instructions that use the PHI. Next, after
3611   // all of the instructions in the block are complete we add the new incoming
3612   // edges to the PHI. At this point all of the instructions in the basic block
3613   // are vectorized, so we can use them to construct the PHI.
3614   PhiVector PHIsToFix;
3615 
3616   // Scan the loop in a topological order to ensure that defs are vectorized
3617   // before users.
3618   LoopBlocksDFS DFS(OrigLoop);
3619   DFS.perform(LI);
3620 
3621   // Vectorize all of the blocks in the original loop.
3622   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(), be = DFS.endRPO();
3623        bb != be; ++bb)
3624     vectorizeBlockInLoop(*bb, &PHIsToFix);
3625 
3626   // Insert truncates and extends for any truncated instructions as hints to
3627   // InstCombine.
3628   if (VF > 1)
3629     truncateToMinimalBitwidths();
3630 
3631   // At this point every instruction in the original loop is widened to a
3632   // vector form. Now we need to fix the recurrences in PHIsToFix. These PHI
3633   // nodes are currently empty because we did not want to introduce cycles.
3634   // This is the second stage of vectorizing recurrences.
3635   for (PHINode *Phi : PHIsToFix) {
3636     assert(Phi && "Unable to recover vectorized PHI");
3637 
3638     // Handle first-order recurrences that need to be fixed.
3639     if (Legal->isFirstOrderRecurrence(Phi)) {
3640       fixFirstOrderRecurrence(Phi);
3641       continue;
3642     }
3643 
3644     // If the phi node is not a first-order recurrence, it must be a reduction.
3645     // Get it's reduction variable descriptor.
3646     assert(Legal->isReductionVariable(Phi) &&
3647            "Unable to find the reduction variable");
3648     RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
3649 
3650     RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3651     TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3652     Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3653     RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3654         RdxDesc.getMinMaxRecurrenceKind();
3655     setDebugLocFromInst(Builder, ReductionStartValue);
3656 
3657     // We need to generate a reduction vector from the incoming scalar.
3658     // To do so, we need to generate the 'identity' vector and override
3659     // one of the elements with the incoming scalar reduction. We need
3660     // to do it in the vector-loop preheader.
3661     Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
3662 
3663     // This is the vector-clone of the value that leaves the loop.
3664     VectorParts &VectorExit = getVectorValue(LoopExitInst);
3665     Type *VecTy = VectorExit[0]->getType();
3666 
3667     // Find the reduction identity variable. Zero for addition, or, xor,
3668     // one for multiplication, -1 for And.
3669     Value *Identity;
3670     Value *VectorStart;
3671     if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3672         RK == RecurrenceDescriptor::RK_FloatMinMax) {
3673       // MinMax reduction have the start value as their identify.
3674       if (VF == 1) {
3675         VectorStart = Identity = ReductionStartValue;
3676       } else {
3677         VectorStart = Identity =
3678             Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3679       }
3680     } else {
3681       // Handle other reduction kinds:
3682       Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3683           RK, VecTy->getScalarType());
3684       if (VF == 1) {
3685         Identity = Iden;
3686         // This vector is the Identity vector where the first element is the
3687         // incoming scalar reduction.
3688         VectorStart = ReductionStartValue;
3689       } else {
3690         Identity = ConstantVector::getSplat(VF, Iden);
3691 
3692         // This vector is the Identity vector where the first element is the
3693         // incoming scalar reduction.
3694         VectorStart =
3695             Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3696       }
3697     }
3698 
3699     // Fix the vector-loop phi.
3700 
3701     // Reductions do not have to start at zero. They can start with
3702     // any loop invariant values.
3703     VectorParts &VecRdxPhi = WidenMap.get(Phi);
3704     BasicBlock *Latch = OrigLoop->getLoopLatch();
3705     Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
3706     VectorParts &Val = getVectorValue(LoopVal);
3707     for (unsigned part = 0; part < UF; ++part) {
3708       // Make sure to add the reduction stat value only to the
3709       // first unroll part.
3710       Value *StartVal = (part == 0) ? VectorStart : Identity;
3711       cast<PHINode>(VecRdxPhi[part])
3712           ->addIncoming(StartVal, LoopVectorPreHeader);
3713       cast<PHINode>(VecRdxPhi[part])
3714           ->addIncoming(Val[part], LoopVectorBody);
3715     }
3716 
3717     // Before each round, move the insertion point right between
3718     // the PHIs and the values we are going to write.
3719     // This allows us to write both PHINodes and the extractelement
3720     // instructions.
3721     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3722 
3723     VectorParts RdxParts = getVectorValue(LoopExitInst);
3724     setDebugLocFromInst(Builder, LoopExitInst);
3725 
3726     // If the vector reduction can be performed in a smaller type, we truncate
3727     // then extend the loop exit value to enable InstCombine to evaluate the
3728     // entire expression in the smaller type.
3729     if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
3730       Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3731       Builder.SetInsertPoint(LoopVectorBody->getTerminator());
3732       for (unsigned part = 0; part < UF; ++part) {
3733         Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3734         Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3735                                           : Builder.CreateZExt(Trunc, VecTy);
3736         for (Value::user_iterator UI = RdxParts[part]->user_begin();
3737              UI != RdxParts[part]->user_end();)
3738           if (*UI != Trunc) {
3739             (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd);
3740             RdxParts[part] = Extnd;
3741           } else {
3742             ++UI;
3743           }
3744       }
3745       Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3746       for (unsigned part = 0; part < UF; ++part)
3747         RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
3748     }
3749 
3750     // Reduce all of the unrolled parts into a single vector.
3751     Value *ReducedPartRdx = RdxParts[0];
3752     unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
3753     setDebugLocFromInst(Builder, ReducedPartRdx);
3754     for (unsigned part = 1; part < UF; ++part) {
3755       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3756         // Floating point operations had to be 'fast' to enable the reduction.
3757         ReducedPartRdx = addFastMathFlag(
3758             Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
3759                                 ReducedPartRdx, "bin.rdx"));
3760       else
3761         ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
3762             Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
3763     }
3764 
3765     if (VF > 1) {
3766       // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
3767       // and vector ops, reducing the set of values being computed by half each
3768       // round.
3769       assert(isPowerOf2_32(VF) &&
3770              "Reduction emission only supported for pow2 vectors!");
3771       Value *TmpVec = ReducedPartRdx;
3772       SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
3773       for (unsigned i = VF; i != 1; i >>= 1) {
3774         // Move the upper half of the vector to the lower half.
3775         for (unsigned j = 0; j != i / 2; ++j)
3776           ShuffleMask[j] = Builder.getInt32(i / 2 + j);
3777 
3778         // Fill the rest of the mask with undef.
3779         std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
3780                   UndefValue::get(Builder.getInt32Ty()));
3781 
3782         Value *Shuf = Builder.CreateShuffleVector(
3783             TmpVec, UndefValue::get(TmpVec->getType()),
3784             ConstantVector::get(ShuffleMask), "rdx.shuf");
3785 
3786         if (Op != Instruction::ICmp && Op != Instruction::FCmp)
3787           // Floating point operations had to be 'fast' to enable the reduction.
3788           TmpVec = addFastMathFlag(Builder.CreateBinOp(
3789               (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
3790         else
3791           TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
3792                                                         TmpVec, Shuf);
3793       }
3794 
3795       // The result is in the first element of the vector.
3796       ReducedPartRdx =
3797           Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
3798 
3799       // If the reduction can be performed in a smaller type, we need to extend
3800       // the reduction to the wider type before we branch to the original loop.
3801       if (Phi->getType() != RdxDesc.getRecurrenceType())
3802         ReducedPartRdx =
3803             RdxDesc.isSigned()
3804                 ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
3805                 : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
3806     }
3807 
3808     // Create a phi node that merges control-flow from the backedge-taken check
3809     // block and the middle block.
3810     PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
3811                                           LoopScalarPreHeader->getTerminator());
3812     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
3813       BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
3814     BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3815 
3816     // Now, we need to fix the users of the reduction variable
3817     // inside and outside of the scalar remainder loop.
3818     // We know that the loop is in LCSSA form. We need to update the
3819     // PHI nodes in the exit blocks.
3820     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
3821                               LEE = LoopExitBlock->end();
3822          LEI != LEE; ++LEI) {
3823       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
3824       if (!LCSSAPhi)
3825         break;
3826 
3827       // All PHINodes need to have a single entry edge, or two if
3828       // we already fixed them.
3829       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
3830 
3831       // We found our reduction value exit-PHI. Update it with the
3832       // incoming bypass edge.
3833       if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
3834         // Add an edge coming from the bypass.
3835         LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
3836         break;
3837       }
3838     } // end of the LCSSA phi scan.
3839 
3840     // Fix the scalar loop reduction variable with the incoming reduction sum
3841     // from the vector body and from the backedge value.
3842     int IncomingEdgeBlockIdx =
3843         Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
3844     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
3845     // Pick the other block.
3846     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
3847     Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
3848     Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
3849   } // end of for each Phi in PHIsToFix.
3850 
3851   fixLCSSAPHIs();
3852 
3853   // Make sure DomTree is updated.
3854   updateAnalysis();
3855 
3856   // Predicate any stores.
3857   for (auto KV : PredicatedStores) {
3858     BasicBlock::iterator I(KV.first);
3859     auto *BB = SplitBlock(I->getParent(), &*std::next(I), DT, LI);
3860     auto *T = SplitBlockAndInsertIfThen(KV.second, &*I, /*Unreachable=*/false,
3861                                         /*BranchWeights=*/nullptr, DT, LI);
3862     I->moveBefore(T);
3863     I->getParent()->setName("pred.store.if");
3864     BB->setName("pred.store.continue");
3865   }
3866   DEBUG(DT->verifyDomTree());
3867   // Remove redundant induction instructions.
3868   cse(LoopVectorBody);
3869 }
3870 
3871 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
3872 
3873   // This is the second phase of vectorizing first-order recurrences. An
3874   // overview of the transformation is described below. Suppose we have the
3875   // following loop.
3876   //
3877   //   for (int i = 0; i < n; ++i)
3878   //     b[i] = a[i] - a[i - 1];
3879   //
3880   // There is a first-order recurrence on "a". For this loop, the shorthand
3881   // scalar IR looks like:
3882   //
3883   //   scalar.ph:
3884   //     s_init = a[-1]
3885   //     br scalar.body
3886   //
3887   //   scalar.body:
3888   //     i = phi [0, scalar.ph], [i+1, scalar.body]
3889   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3890   //     s2 = a[i]
3891   //     b[i] = s2 - s1
3892   //     br cond, scalar.body, ...
3893   //
3894   // In this example, s1 is a recurrence because it's value depends on the
3895   // previous iteration. In the first phase of vectorization, we created a
3896   // temporary value for s1. We now complete the vectorization and produce the
3897   // shorthand vector IR shown below (for VF = 4, UF = 1).
3898   //
3899   //   vector.ph:
3900   //     v_init = vector(..., ..., ..., a[-1])
3901   //     br vector.body
3902   //
3903   //   vector.body
3904   //     i = phi [0, vector.ph], [i+4, vector.body]
3905   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
3906   //     v2 = a[i, i+1, i+2, i+3];
3907   //     v3 = vector(v1(3), v2(0, 1, 2))
3908   //     b[i, i+1, i+2, i+3] = v2 - v3
3909   //     br cond, vector.body, middle.block
3910   //
3911   //   middle.block:
3912   //     x = v2(3)
3913   //     br scalar.ph
3914   //
3915   //   scalar.ph:
3916   //     s_init = phi [x, middle.block], [a[-1], otherwise]
3917   //     br scalar.body
3918   //
3919   // After execution completes the vector loop, we extract the next value of
3920   // the recurrence (x) to use as the initial value in the scalar loop.
3921 
3922   // Get the original loop preheader and single loop latch.
3923   auto *Preheader = OrigLoop->getLoopPreheader();
3924   auto *Latch = OrigLoop->getLoopLatch();
3925 
3926   // Get the initial and previous values of the scalar recurrence.
3927   auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
3928   auto *Previous = Phi->getIncomingValueForBlock(Latch);
3929 
3930   // Create a vector from the initial value.
3931   auto *VectorInit = ScalarInit;
3932   if (VF > 1) {
3933     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
3934     VectorInit = Builder.CreateInsertElement(
3935         UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
3936         Builder.getInt32(VF - 1), "vector.recur.init");
3937   }
3938 
3939   // We constructed a temporary phi node in the first phase of vectorization.
3940   // This phi node will eventually be deleted.
3941   auto &PhiParts = getVectorValue(Phi);
3942   Builder.SetInsertPoint(cast<Instruction>(PhiParts[0]));
3943 
3944   // Create a phi node for the new recurrence. The current value will either be
3945   // the initial value inserted into a vector or loop-varying vector value.
3946   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
3947   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
3948 
3949   // Get the vectorized previous value. We ensured the previous values was an
3950   // instruction when detecting the recurrence.
3951   auto &PreviousParts = getVectorValue(Previous);
3952 
3953   // Set the insertion point to be after this instruction. We ensured the
3954   // previous value dominated all uses of the phi when detecting the
3955   // recurrence.
3956   Builder.SetInsertPoint(
3957       &*++BasicBlock::iterator(cast<Instruction>(PreviousParts[UF - 1])));
3958 
3959   // We will construct a vector for the recurrence by combining the values for
3960   // the current and previous iterations. This is the required shuffle mask.
3961   SmallVector<Constant *, 8> ShuffleMask(VF);
3962   ShuffleMask[0] = Builder.getInt32(VF - 1);
3963   for (unsigned I = 1; I < VF; ++I)
3964     ShuffleMask[I] = Builder.getInt32(I + VF - 1);
3965 
3966   // The vector from which to take the initial value for the current iteration
3967   // (actual or unrolled). Initially, this is the vector phi node.
3968   Value *Incoming = VecPhi;
3969 
3970   // Shuffle the current and previous vector and update the vector parts.
3971   for (unsigned Part = 0; Part < UF; ++Part) {
3972     auto *Shuffle =
3973         VF > 1
3974             ? Builder.CreateShuffleVector(Incoming, PreviousParts[Part],
3975                                           ConstantVector::get(ShuffleMask))
3976             : Incoming;
3977     PhiParts[Part]->replaceAllUsesWith(Shuffle);
3978     cast<Instruction>(PhiParts[Part])->eraseFromParent();
3979     PhiParts[Part] = Shuffle;
3980     Incoming = PreviousParts[Part];
3981   }
3982 
3983   // Fix the latch value of the new recurrence in the vector loop.
3984   VecPhi->addIncoming(Incoming,
3985                       LI->getLoopFor(LoopVectorBody)->getLoopLatch());
3986 
3987   // Extract the last vector element in the middle block. This will be the
3988   // initial value for the recurrence when jumping to the scalar loop.
3989   auto *Extract = Incoming;
3990   if (VF > 1) {
3991     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
3992     Extract = Builder.CreateExtractElement(Extract, Builder.getInt32(VF - 1),
3993                                            "vector.recur.extract");
3994   }
3995 
3996   // Fix the initial value of the original recurrence in the scalar loop.
3997   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
3998   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3999   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4000     auto *Incoming = BB == LoopMiddleBlock ? Extract : ScalarInit;
4001     Start->addIncoming(Incoming, BB);
4002   }
4003 
4004   Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
4005   Phi->setName("scalar.recur");
4006 
4007   // Finally, fix users of the recurrence outside the loop. The users will need
4008   // either the last value of the scalar recurrence or the last value of the
4009   // vector recurrence we extracted in the middle block. Since the loop is in
4010   // LCSSA form, we just need to find the phi node for the original scalar
4011   // recurrence in the exit block, and then add an edge for the middle block.
4012   for (auto &I : *LoopExitBlock) {
4013     auto *LCSSAPhi = dyn_cast<PHINode>(&I);
4014     if (!LCSSAPhi)
4015       break;
4016     if (LCSSAPhi->getIncomingValue(0) == Phi) {
4017       LCSSAPhi->addIncoming(Extract, LoopMiddleBlock);
4018       break;
4019     }
4020   }
4021 }
4022 
4023 void InnerLoopVectorizer::fixLCSSAPHIs() {
4024   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
4025                             LEE = LoopExitBlock->end();
4026        LEI != LEE; ++LEI) {
4027     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
4028     if (!LCSSAPhi)
4029       break;
4030     if (LCSSAPhi->getNumIncomingValues() == 1)
4031       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
4032                             LoopMiddleBlock);
4033   }
4034 }
4035 
4036 InnerLoopVectorizer::VectorParts
4037 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
4038   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
4039          "Invalid edge");
4040 
4041   // Look for cached value.
4042   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
4043   EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
4044   if (ECEntryIt != MaskCache.end())
4045     return ECEntryIt->second;
4046 
4047   VectorParts SrcMask = createBlockInMask(Src);
4048 
4049   // The terminator has to be a branch inst!
4050   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
4051   assert(BI && "Unexpected terminator found");
4052 
4053   if (BI->isConditional()) {
4054     VectorParts EdgeMask = getVectorValue(BI->getCondition());
4055 
4056     if (BI->getSuccessor(0) != Dst)
4057       for (unsigned part = 0; part < UF; ++part)
4058         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
4059 
4060     for (unsigned part = 0; part < UF; ++part)
4061       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
4062 
4063     MaskCache[Edge] = EdgeMask;
4064     return EdgeMask;
4065   }
4066 
4067   MaskCache[Edge] = SrcMask;
4068   return SrcMask;
4069 }
4070 
4071 InnerLoopVectorizer::VectorParts
4072 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
4073   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
4074 
4075   // Loop incoming mask is all-one.
4076   if (OrigLoop->getHeader() == BB) {
4077     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
4078     return getVectorValue(C);
4079   }
4080 
4081   // This is the block mask. We OR all incoming edges, and with zero.
4082   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
4083   VectorParts BlockMask = getVectorValue(Zero);
4084 
4085   // For each pred:
4086   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
4087     VectorParts EM = createEdgeMask(*it, BB);
4088     for (unsigned part = 0; part < UF; ++part)
4089       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
4090   }
4091 
4092   return BlockMask;
4093 }
4094 
4095 void InnerLoopVectorizer::widenPHIInstruction(
4096     Instruction *PN, InnerLoopVectorizer::VectorParts &Entry, unsigned UF,
4097     unsigned VF, PhiVector *PV) {
4098   PHINode *P = cast<PHINode>(PN);
4099   // Handle recurrences.
4100   if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
4101     for (unsigned part = 0; part < UF; ++part) {
4102       // This is phase one of vectorizing PHIs.
4103       Type *VecTy =
4104           (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
4105       Entry[part] = PHINode::Create(
4106           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4107     }
4108     PV->push_back(P);
4109     return;
4110   }
4111 
4112   setDebugLocFromInst(Builder, P);
4113   // Check for PHI nodes that are lowered to vector selects.
4114   if (P->getParent() != OrigLoop->getHeader()) {
4115     // We know that all PHIs in non-header blocks are converted into
4116     // selects, so we don't have to worry about the insertion order and we
4117     // can just use the builder.
4118     // At this point we generate the predication tree. There may be
4119     // duplications since this is a simple recursive scan, but future
4120     // optimizations will clean it up.
4121 
4122     unsigned NumIncoming = P->getNumIncomingValues();
4123 
4124     // Generate a sequence of selects of the form:
4125     // SELECT(Mask3, In3,
4126     //      SELECT(Mask2, In2,
4127     //                   ( ...)))
4128     for (unsigned In = 0; In < NumIncoming; In++) {
4129       VectorParts Cond =
4130           createEdgeMask(P->getIncomingBlock(In), P->getParent());
4131       VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
4132 
4133       for (unsigned part = 0; part < UF; ++part) {
4134         // We might have single edge PHIs (blocks) - use an identity
4135         // 'select' for the first PHI operand.
4136         if (In == 0)
4137           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In0[part]);
4138         else
4139           // Select between the current value and the previous incoming edge
4140           // based on the incoming mask.
4141           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], Entry[part],
4142                                              "predphi");
4143       }
4144     }
4145     return;
4146   }
4147 
4148   // This PHINode must be an induction variable.
4149   // Make sure that we know about it.
4150   assert(Legal->getInductionVars()->count(P) && "Not an induction variable");
4151 
4152   InductionDescriptor II = Legal->getInductionVars()->lookup(P);
4153   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4154 
4155   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4156   // which can be found from the original scalar operations.
4157   switch (II.getKind()) {
4158   case InductionDescriptor::IK_NoInduction:
4159     llvm_unreachable("Unknown induction");
4160   case InductionDescriptor::IK_IntInduction: {
4161     assert(P->getType() == II.getStartValue()->getType() && "Types must match");
4162     if (VF == 1 || P->getType() != Induction->getType() ||
4163         !II.getConstIntStepValue()) {
4164       Value *V = Induction;
4165       // Handle other induction variables that are now based on the
4166       // canonical one.
4167       if (P != OldInduction) {
4168         V = Builder.CreateSExtOrTrunc(Induction, P->getType());
4169         V = II.transform(Builder, V, PSE.getSE(), DL);
4170         V->setName("offset.idx");
4171       }
4172       Value *Broadcasted = getBroadcastInstrs(V);
4173       // After broadcasting the induction variable we need to make the vector
4174       // consecutive by adding 0, 1, 2, etc.
4175       for (unsigned part = 0; part < UF; ++part)
4176         Entry[part] = getStepVector(Broadcasted, VF * part, II.getStep());
4177     } else {
4178       // Instead of re-creating the vector IV by splatting the scalar IV
4179       // in each iteration, we can make a new independent vector IV.
4180       widenInductionVariable(II, Entry);
4181     }
4182     return;
4183   }
4184   case InductionDescriptor::IK_PtrInduction:
4185     // Handle the pointer induction variable case.
4186     assert(P->getType()->isPointerTy() && "Unexpected type.");
4187     // This is the normalized GEP that starts counting at zero.
4188     Value *PtrInd = Induction;
4189     PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
4190     // This is the vector of results. Notice that we don't generate
4191     // vector geps because scalar geps result in better code.
4192     for (unsigned part = 0; part < UF; ++part) {
4193       if (VF == 1) {
4194         int EltIndex = part;
4195         Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
4196         Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4197         Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
4198         SclrGep->setName("next.gep");
4199         Entry[part] = SclrGep;
4200         continue;
4201       }
4202 
4203       Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
4204       for (unsigned int i = 0; i < VF; ++i) {
4205         int EltIndex = i + part * VF;
4206         Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
4207         Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4208         Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
4209         SclrGep->setName("next.gep");
4210         VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
4211                                              Builder.getInt32(i), "insert.gep");
4212       }
4213       Entry[part] = VecVal;
4214     }
4215     return;
4216   }
4217 }
4218 
4219 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
4220   // For each instruction in the old loop.
4221   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4222     VectorParts &Entry = WidenMap.get(&*it);
4223 
4224     switch (it->getOpcode()) {
4225     case Instruction::Br:
4226       // Nothing to do for PHIs and BR, since we already took care of the
4227       // loop control flow instructions.
4228       continue;
4229     case Instruction::PHI: {
4230       // Vectorize PHINodes.
4231       widenPHIInstruction(&*it, Entry, UF, VF, PV);
4232       continue;
4233     } // End of PHI.
4234 
4235     case Instruction::Add:
4236     case Instruction::FAdd:
4237     case Instruction::Sub:
4238     case Instruction::FSub:
4239     case Instruction::Mul:
4240     case Instruction::FMul:
4241     case Instruction::UDiv:
4242     case Instruction::SDiv:
4243     case Instruction::FDiv:
4244     case Instruction::URem:
4245     case Instruction::SRem:
4246     case Instruction::FRem:
4247     case Instruction::Shl:
4248     case Instruction::LShr:
4249     case Instruction::AShr:
4250     case Instruction::And:
4251     case Instruction::Or:
4252     case Instruction::Xor: {
4253       // Just widen binops.
4254       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
4255       setDebugLocFromInst(Builder, BinOp);
4256       VectorParts &A = getVectorValue(it->getOperand(0));
4257       VectorParts &B = getVectorValue(it->getOperand(1));
4258 
4259       // Use this vector value for all users of the original instruction.
4260       for (unsigned Part = 0; Part < UF; ++Part) {
4261         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
4262 
4263         if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
4264           VecOp->copyIRFlags(BinOp);
4265 
4266         Entry[Part] = V;
4267       }
4268 
4269       addMetadata(Entry, &*it);
4270       break;
4271     }
4272     case Instruction::Select: {
4273       // Widen selects.
4274       // If the selector is loop invariant we can create a select
4275       // instruction with a scalar condition. Otherwise, use vector-select.
4276       auto *SE = PSE.getSE();
4277       bool InvariantCond =
4278           SE->isLoopInvariant(PSE.getSCEV(it->getOperand(0)), OrigLoop);
4279       setDebugLocFromInst(Builder, &*it);
4280 
4281       // The condition can be loop invariant  but still defined inside the
4282       // loop. This means that we can't just use the original 'cond' value.
4283       // We have to take the 'vectorized' value and pick the first lane.
4284       // Instcombine will make this a no-op.
4285       VectorParts &Cond = getVectorValue(it->getOperand(0));
4286       VectorParts &Op0 = getVectorValue(it->getOperand(1));
4287       VectorParts &Op1 = getVectorValue(it->getOperand(2));
4288 
4289       Value *ScalarCond =
4290           (VF == 1)
4291               ? Cond[0]
4292               : Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
4293 
4294       for (unsigned Part = 0; Part < UF; ++Part) {
4295         Entry[Part] = Builder.CreateSelect(
4296             InvariantCond ? ScalarCond : Cond[Part], Op0[Part], Op1[Part]);
4297       }
4298 
4299       addMetadata(Entry, &*it);
4300       break;
4301     }
4302 
4303     case Instruction::ICmp:
4304     case Instruction::FCmp: {
4305       // Widen compares. Generate vector compares.
4306       bool FCmp = (it->getOpcode() == Instruction::FCmp);
4307       CmpInst *Cmp = dyn_cast<CmpInst>(it);
4308       setDebugLocFromInst(Builder, &*it);
4309       VectorParts &A = getVectorValue(it->getOperand(0));
4310       VectorParts &B = getVectorValue(it->getOperand(1));
4311       for (unsigned Part = 0; Part < UF; ++Part) {
4312         Value *C = nullptr;
4313         if (FCmp) {
4314           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
4315           cast<FCmpInst>(C)->copyFastMathFlags(&*it);
4316         } else {
4317           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
4318         }
4319         Entry[Part] = C;
4320       }
4321 
4322       addMetadata(Entry, &*it);
4323       break;
4324     }
4325 
4326     case Instruction::Store:
4327     case Instruction::Load:
4328       vectorizeMemoryInstruction(&*it);
4329       break;
4330     case Instruction::ZExt:
4331     case Instruction::SExt:
4332     case Instruction::FPToUI:
4333     case Instruction::FPToSI:
4334     case Instruction::FPExt:
4335     case Instruction::PtrToInt:
4336     case Instruction::IntToPtr:
4337     case Instruction::SIToFP:
4338     case Instruction::UIToFP:
4339     case Instruction::Trunc:
4340     case Instruction::FPTrunc:
4341     case Instruction::BitCast: {
4342       CastInst *CI = dyn_cast<CastInst>(it);
4343       setDebugLocFromInst(Builder, &*it);
4344       /// Optimize the special case where the source is a constant integer
4345       /// induction variable. Notice that we can only optimize the 'trunc' case
4346       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
4347       /// c. other casts depend on pointer size.
4348 
4349       if (CI->getOperand(0) == OldInduction &&
4350           it->getOpcode() == Instruction::Trunc) {
4351         InductionDescriptor II =
4352             Legal->getInductionVars()->lookup(OldInduction);
4353         if (auto StepValue = II.getConstIntStepValue()) {
4354           IntegerType *TruncType = cast<IntegerType>(CI->getType());
4355           if (VF == 1) {
4356             StepValue =
4357                 ConstantInt::getSigned(TruncType, StepValue->getSExtValue());
4358             Value *ScalarCast =
4359                 Builder.CreateCast(CI->getOpcode(), Induction, CI->getType());
4360             Value *Broadcasted = getBroadcastInstrs(ScalarCast);
4361             for (unsigned Part = 0; Part < UF; ++Part)
4362               Entry[Part] = getStepVector(Broadcasted, VF * Part, StepValue);
4363           } else {
4364             // Truncating a vector induction variable on each iteration
4365             // may be expensive. Instead, truncate the initial value, and create
4366             // a new, truncated, vector IV based on that.
4367             widenInductionVariable(II, Entry, TruncType);
4368           }
4369           addMetadata(Entry, &*it);
4370           break;
4371         }
4372       }
4373       /// Vectorize casts.
4374       Type *DestTy =
4375           (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
4376 
4377       VectorParts &A = getVectorValue(it->getOperand(0));
4378       for (unsigned Part = 0; Part < UF; ++Part)
4379         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
4380       addMetadata(Entry, &*it);
4381       break;
4382     }
4383 
4384     case Instruction::Call: {
4385       // Ignore dbg intrinsics.
4386       if (isa<DbgInfoIntrinsic>(it))
4387         break;
4388       setDebugLocFromInst(Builder, &*it);
4389 
4390       Module *M = BB->getParent()->getParent();
4391       CallInst *CI = cast<CallInst>(it);
4392 
4393       StringRef FnName = CI->getCalledFunction()->getName();
4394       Function *F = CI->getCalledFunction();
4395       Type *RetTy = ToVectorTy(CI->getType(), VF);
4396       SmallVector<Type *, 4> Tys;
4397       for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
4398         Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
4399 
4400       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4401       if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
4402                  ID == Intrinsic::lifetime_start)) {
4403         scalarizeInstruction(&*it);
4404         break;
4405       }
4406       // The flag shows whether we use Intrinsic or a usual Call for vectorized
4407       // version of the instruction.
4408       // Is it beneficial to perform intrinsic call compared to lib call?
4409       bool NeedToScalarize;
4410       unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
4411       bool UseVectorIntrinsic =
4412           ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
4413       if (!UseVectorIntrinsic && NeedToScalarize) {
4414         scalarizeInstruction(&*it);
4415         break;
4416       }
4417 
4418       for (unsigned Part = 0; Part < UF; ++Part) {
4419         SmallVector<Value *, 4> Args;
4420         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4421           Value *Arg = CI->getArgOperand(i);
4422           // Some intrinsics have a scalar argument - don't replace it with a
4423           // vector.
4424           if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
4425             VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
4426             Arg = VectorArg[Part];
4427           }
4428           Args.push_back(Arg);
4429         }
4430 
4431         Function *VectorF;
4432         if (UseVectorIntrinsic) {
4433           // Use vector version of the intrinsic.
4434           Type *TysForDecl[] = {CI->getType()};
4435           if (VF > 1)
4436             TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4437           VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4438         } else {
4439           // Use vector version of the library call.
4440           StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
4441           assert(!VFnName.empty() && "Vector function name is empty.");
4442           VectorF = M->getFunction(VFnName);
4443           if (!VectorF) {
4444             // Generate a declaration
4445             FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
4446             VectorF =
4447                 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
4448             VectorF->copyAttributesFrom(F);
4449           }
4450         }
4451         assert(VectorF && "Can't create vector function.");
4452 
4453         SmallVector<OperandBundleDef, 1> OpBundles;
4454         CI->getOperandBundlesAsDefs(OpBundles);
4455         CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4456 
4457         if (isa<FPMathOperator>(V))
4458           V->copyFastMathFlags(CI);
4459 
4460         Entry[Part] = V;
4461       }
4462 
4463       addMetadata(Entry, &*it);
4464       break;
4465     }
4466 
4467     default:
4468       // All other instructions are unsupported. Scalarize them.
4469       scalarizeInstruction(&*it);
4470       break;
4471     } // end of switch.
4472   }   // end of for_each instr.
4473 }
4474 
4475 void InnerLoopVectorizer::updateAnalysis() {
4476   // Forget the original basic block.
4477   PSE.getSE()->forgetLoop(OrigLoop);
4478 
4479   // Update the dominator tree information.
4480   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
4481          "Entry does not dominate exit.");
4482 
4483   // We don't predicate stores by this point, so the vector body should be a
4484   // single loop.
4485   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
4486 
4487   DT->addNewBlock(LoopMiddleBlock, LoopVectorBody);
4488   DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
4489   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
4490   DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
4491 
4492   DEBUG(DT->verifyDomTree());
4493 }
4494 
4495 /// \brief Check whether it is safe to if-convert this phi node.
4496 ///
4497 /// Phi nodes with constant expressions that can trap are not safe to if
4498 /// convert.
4499 static bool canIfConvertPHINodes(BasicBlock *BB) {
4500   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
4501     PHINode *Phi = dyn_cast<PHINode>(I);
4502     if (!Phi)
4503       return true;
4504     for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
4505       if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
4506         if (C->canTrap())
4507           return false;
4508   }
4509   return true;
4510 }
4511 
4512 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
4513   if (!EnableIfConversion) {
4514     emitAnalysis(VectorizationReport() << "if-conversion is disabled");
4515     return false;
4516   }
4517 
4518   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
4519 
4520   // A list of pointers that we can safely read and write to.
4521   SmallPtrSet<Value *, 8> SafePointes;
4522 
4523   // Collect safe addresses.
4524   for (Loop::block_iterator BI = TheLoop->block_begin(),
4525                             BE = TheLoop->block_end();
4526        BI != BE; ++BI) {
4527     BasicBlock *BB = *BI;
4528 
4529     if (blockNeedsPredication(BB))
4530       continue;
4531 
4532     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
4533       if (LoadInst *LI = dyn_cast<LoadInst>(I))
4534         SafePointes.insert(LI->getPointerOperand());
4535       else if (StoreInst *SI = dyn_cast<StoreInst>(I))
4536         SafePointes.insert(SI->getPointerOperand());
4537     }
4538   }
4539 
4540   // Collect the blocks that need predication.
4541   BasicBlock *Header = TheLoop->getHeader();
4542   for (Loop::block_iterator BI = TheLoop->block_begin(),
4543                             BE = TheLoop->block_end();
4544        BI != BE; ++BI) {
4545     BasicBlock *BB = *BI;
4546 
4547     // We don't support switch statements inside loops.
4548     if (!isa<BranchInst>(BB->getTerminator())) {
4549       emitAnalysis(VectorizationReport(BB->getTerminator())
4550                    << "loop contains a switch statement");
4551       return false;
4552     }
4553 
4554     // We must be able to predicate all blocks that need to be predicated.
4555     if (blockNeedsPredication(BB)) {
4556       if (!blockCanBePredicated(BB, SafePointes)) {
4557         emitAnalysis(VectorizationReport(BB->getTerminator())
4558                      << "control flow cannot be substituted for a select");
4559         return false;
4560       }
4561     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
4562       emitAnalysis(VectorizationReport(BB->getTerminator())
4563                    << "control flow cannot be substituted for a select");
4564       return false;
4565     }
4566   }
4567 
4568   // We can if-convert this loop.
4569   return true;
4570 }
4571 
4572 bool LoopVectorizationLegality::canVectorize() {
4573   // We must have a loop in canonical form. Loops with indirectbr in them cannot
4574   // be canonicalized.
4575   if (!TheLoop->getLoopPreheader()) {
4576     emitAnalysis(VectorizationReport()
4577                  << "loop control flow is not understood by vectorizer");
4578     return false;
4579   }
4580 
4581   // We can only vectorize innermost loops.
4582   if (!TheLoop->empty()) {
4583     emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
4584     return false;
4585   }
4586 
4587   // We must have a single backedge.
4588   if (TheLoop->getNumBackEdges() != 1) {
4589     emitAnalysis(VectorizationReport()
4590                  << "loop control flow is not understood by vectorizer");
4591     return false;
4592   }
4593 
4594   // We must have a single exiting block.
4595   if (!TheLoop->getExitingBlock()) {
4596     emitAnalysis(VectorizationReport()
4597                  << "loop control flow is not understood by vectorizer");
4598     return false;
4599   }
4600 
4601   // We only handle bottom-tested loops, i.e. loop in which the condition is
4602   // checked at the end of each iteration. With that we can assume that all
4603   // instructions in the loop are executed the same number of times.
4604   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
4605     emitAnalysis(VectorizationReport()
4606                  << "loop control flow is not understood by vectorizer");
4607     return false;
4608   }
4609 
4610   // We need to have a loop header.
4611   DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
4612                << '\n');
4613 
4614   // Check if we can if-convert non-single-bb loops.
4615   unsigned NumBlocks = TheLoop->getNumBlocks();
4616   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
4617     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
4618     return false;
4619   }
4620 
4621   // ScalarEvolution needs to be able to find the exit count.
4622   const SCEV *ExitCount = PSE.getBackedgeTakenCount();
4623   if (ExitCount == PSE.getSE()->getCouldNotCompute()) {
4624     emitAnalysis(VectorizationReport()
4625                  << "could not determine number of loop iterations");
4626     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
4627     return false;
4628   }
4629 
4630   // Check if we can vectorize the instructions and CFG in this loop.
4631   if (!canVectorizeInstrs()) {
4632     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
4633     return false;
4634   }
4635 
4636   // Go over each instruction and look at memory deps.
4637   if (!canVectorizeMemory()) {
4638     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
4639     return false;
4640   }
4641 
4642   // Collect all of the variables that remain uniform after vectorization.
4643   collectLoopUniforms();
4644 
4645   DEBUG(dbgs() << "LV: We can vectorize this loop"
4646                << (LAI->getRuntimePointerChecking()->Need
4647                        ? " (with a runtime bound check)"
4648                        : "")
4649                << "!\n");
4650 
4651   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
4652 
4653   // If an override option has been passed in for interleaved accesses, use it.
4654   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
4655     UseInterleaved = EnableInterleavedMemAccesses;
4656 
4657   // Analyze interleaved memory accesses.
4658   if (UseInterleaved)
4659     InterleaveInfo.analyzeInterleaving(Strides);
4660 
4661   unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
4662   if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
4663     SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
4664 
4665   if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
4666     emitAnalysis(VectorizationReport()
4667                  << "Too many SCEV assumptions need to be made and checked "
4668                  << "at runtime");
4669     DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
4670     return false;
4671   }
4672 
4673   // Okay! We can vectorize. At this point we don't have any other mem analysis
4674   // which may limit our maximum vectorization factor, so just return true with
4675   // no restrictions.
4676   return true;
4677 }
4678 
4679 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
4680   if (Ty->isPointerTy())
4681     return DL.getIntPtrType(Ty);
4682 
4683   // It is possible that char's or short's overflow when we ask for the loop's
4684   // trip count, work around this by changing the type size.
4685   if (Ty->getScalarSizeInBits() < 32)
4686     return Type::getInt32Ty(Ty->getContext());
4687 
4688   return Ty;
4689 }
4690 
4691 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4692   Ty0 = convertPointerToIntegerType(DL, Ty0);
4693   Ty1 = convertPointerToIntegerType(DL, Ty1);
4694   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4695     return Ty0;
4696   return Ty1;
4697 }
4698 
4699 /// \brief Check that the instruction has outside loop users and is not an
4700 /// identified reduction variable.
4701 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
4702                                SmallPtrSetImpl<Value *> &AllowedExit) {
4703   // Reduction and Induction instructions are allowed to have exit users. All
4704   // other instructions must not have external users.
4705   if (!AllowedExit.count(Inst))
4706     // Check that all of the users of the loop are inside the BB.
4707     for (User *U : Inst->users()) {
4708       Instruction *UI = cast<Instruction>(U);
4709       // This user may be a reduction exit value.
4710       if (!TheLoop->contains(UI)) {
4711         DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
4712         return true;
4713       }
4714     }
4715   return false;
4716 }
4717 
4718 void LoopVectorizationLegality::addInductionPhi(
4719     PHINode *Phi, InductionDescriptor ID,
4720     SmallPtrSetImpl<Value *> &AllowedExit) {
4721   Inductions[Phi] = ID;
4722   Type *PhiTy = Phi->getType();
4723   const DataLayout &DL = Phi->getModule()->getDataLayout();
4724 
4725   // Get the widest type.
4726   if (!WidestIndTy)
4727     WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
4728   else
4729     WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
4730 
4731   // Int inductions are special because we only allow one IV.
4732   if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
4733       ID.getConstIntStepValue() &&
4734       ID.getConstIntStepValue()->isOne() &&
4735       isa<Constant>(ID.getStartValue()) &&
4736       cast<Constant>(ID.getStartValue())->isNullValue()) {
4737 
4738     // Use the phi node with the widest type as induction. Use the last
4739     // one if there are multiple (no good reason for doing this other
4740     // than it is expedient). We've checked that it begins at zero and
4741     // steps by one, so this is a canonical induction variable.
4742     if (!Induction || PhiTy == WidestIndTy)
4743       Induction = Phi;
4744   }
4745 
4746   // Both the PHI node itself, and the "post-increment" value feeding
4747   // back into the PHI node may have external users.
4748   AllowedExit.insert(Phi);
4749   AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
4750 
4751   DEBUG(dbgs() << "LV: Found an induction variable.\n");
4752   return;
4753 }
4754 
4755 bool LoopVectorizationLegality::canVectorizeInstrs() {
4756   BasicBlock *Header = TheLoop->getHeader();
4757 
4758   // Look for the attribute signaling the absence of NaNs.
4759   Function &F = *Header->getParent();
4760   HasFunNoNaNAttr =
4761       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
4762 
4763   // For each block in the loop.
4764   for (Loop::block_iterator bb = TheLoop->block_begin(),
4765                             be = TheLoop->block_end();
4766        bb != be; ++bb) {
4767 
4768     // Scan the instructions in the block and look for hazards.
4769     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4770          ++it) {
4771 
4772       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
4773         Type *PhiTy = Phi->getType();
4774         // Check that this PHI type is allowed.
4775         if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
4776             !PhiTy->isPointerTy()) {
4777           emitAnalysis(VectorizationReport(&*it)
4778                        << "loop control flow is not understood by vectorizer");
4779           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
4780           return false;
4781         }
4782 
4783         // If this PHINode is not in the header block, then we know that we
4784         // can convert it to select during if-conversion. No need to check if
4785         // the PHIs in this block are induction or reduction variables.
4786         if (*bb != Header) {
4787           // Check that this instruction has no outside users or is an
4788           // identified reduction value with an outside user.
4789           if (!hasOutsideLoopUser(TheLoop, &*it, AllowedExit))
4790             continue;
4791           emitAnalysis(VectorizationReport(&*it)
4792                        << "value could not be identified as "
4793                           "an induction or reduction variable");
4794           return false;
4795         }
4796 
4797         // We only allow if-converted PHIs with exactly two incoming values.
4798         if (Phi->getNumIncomingValues() != 2) {
4799           emitAnalysis(VectorizationReport(&*it)
4800                        << "control flow not understood by vectorizer");
4801           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
4802           return false;
4803         }
4804 
4805         RecurrenceDescriptor RedDes;
4806         if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes)) {
4807           if (RedDes.hasUnsafeAlgebra())
4808             Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
4809           AllowedExit.insert(RedDes.getLoopExitInstr());
4810           Reductions[Phi] = RedDes;
4811           continue;
4812         }
4813 
4814         InductionDescriptor ID;
4815         if (InductionDescriptor::isInductionPHI(Phi, PSE, ID)) {
4816           addInductionPhi(Phi, ID, AllowedExit);
4817           continue;
4818         }
4819 
4820         if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop, DT)) {
4821           FirstOrderRecurrences.insert(Phi);
4822           continue;
4823         }
4824 
4825         // As a last resort, coerce the PHI to a AddRec expression
4826         // and re-try classifying it a an induction PHI.
4827         if (InductionDescriptor::isInductionPHI(Phi, PSE, ID, true)) {
4828           addInductionPhi(Phi, ID, AllowedExit);
4829           continue;
4830         }
4831 
4832         emitAnalysis(VectorizationReport(&*it)
4833                      << "value that could not be identified as "
4834                         "reduction is used outside the loop");
4835         DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n");
4836         return false;
4837       } // end of PHI handling
4838 
4839       // We handle calls that:
4840       //   * Are debug info intrinsics.
4841       //   * Have a mapping to an IR intrinsic.
4842       //   * Have a vector version available.
4843       CallInst *CI = dyn_cast<CallInst>(it);
4844       if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
4845           !isa<DbgInfoIntrinsic>(CI) &&
4846           !(CI->getCalledFunction() && TLI &&
4847             TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
4848         emitAnalysis(VectorizationReport(&*it)
4849                      << "call instruction cannot be vectorized");
4850         DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
4851         return false;
4852       }
4853 
4854       // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
4855       // second argument is the same (i.e. loop invariant)
4856       if (CI && hasVectorInstrinsicScalarOpd(
4857                     getVectorIntrinsicIDForCall(CI, TLI), 1)) {
4858         auto *SE = PSE.getSE();
4859         if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
4860           emitAnalysis(VectorizationReport(&*it)
4861                        << "intrinsic instruction cannot be vectorized");
4862           DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
4863           return false;
4864         }
4865       }
4866 
4867       // Check that the instruction return type is vectorizable.
4868       // Also, we can't vectorize extractelement instructions.
4869       if ((!VectorType::isValidElementType(it->getType()) &&
4870            !it->getType()->isVoidTy()) ||
4871           isa<ExtractElementInst>(it)) {
4872         emitAnalysis(VectorizationReport(&*it)
4873                      << "instruction return type cannot be vectorized");
4874         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
4875         return false;
4876       }
4877 
4878       // Check that the stored type is vectorizable.
4879       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
4880         Type *T = ST->getValueOperand()->getType();
4881         if (!VectorType::isValidElementType(T)) {
4882           emitAnalysis(VectorizationReport(ST)
4883                        << "store instruction cannot be vectorized");
4884           return false;
4885         }
4886         if (EnableMemAccessVersioning)
4887           collectStridedAccess(ST);
4888 
4889       } else if (LoadInst *LI = dyn_cast<LoadInst>(it)) {
4890         if (EnableMemAccessVersioning)
4891           collectStridedAccess(LI);
4892 
4893         // FP instructions can allow unsafe algebra, thus vectorizable by
4894         // non-IEEE-754 compliant SIMD units.
4895         // This applies to floating-point math operations and calls, not memory
4896         // operations, shuffles, or casts, as they don't change precision or
4897         // semantics.
4898       } else if (it->getType()->isFloatingPointTy() &&
4899                  (CI || it->isBinaryOp()) && !it->hasUnsafeAlgebra()) {
4900         DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
4901         Hints->setPotentiallyUnsafe();
4902       }
4903 
4904       // Reduction instructions are allowed to have exit users.
4905       // All other instructions must not have external users.
4906       if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
4907         emitAnalysis(VectorizationReport(&*it)
4908                      << "value cannot be used outside the loop");
4909         return false;
4910       }
4911 
4912     } // next instr.
4913   }
4914 
4915   if (!Induction) {
4916     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
4917     if (Inductions.empty()) {
4918       emitAnalysis(VectorizationReport()
4919                    << "loop induction variable could not be identified");
4920       return false;
4921     }
4922   }
4923 
4924   // Now we know the widest induction type, check if our found induction
4925   // is the same size. If it's not, unset it here and InnerLoopVectorizer
4926   // will create another.
4927   if (Induction && WidestIndTy != Induction->getType())
4928     Induction = nullptr;
4929 
4930   return true;
4931 }
4932 
4933 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
4934   Value *Ptr = nullptr;
4935   if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
4936     Ptr = LI->getPointerOperand();
4937   else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
4938     Ptr = SI->getPointerOperand();
4939   else
4940     return;
4941 
4942   Value *Stride = getStrideFromPointer(Ptr, PSE.getSE(), TheLoop);
4943   if (!Stride)
4944     return;
4945 
4946   DEBUG(dbgs() << "LV: Found a strided access that we can version");
4947   DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
4948   Strides[Ptr] = Stride;
4949   StrideSet.insert(Stride);
4950 }
4951 
4952 void LoopVectorizationLegality::collectLoopUniforms() {
4953   // We now know that the loop is vectorizable!
4954   // Collect variables that will remain uniform after vectorization.
4955   std::vector<Value *> Worklist;
4956   BasicBlock *Latch = TheLoop->getLoopLatch();
4957 
4958   // Start with the conditional branch and walk up the block.
4959   Worklist.push_back(Latch->getTerminator()->getOperand(0));
4960 
4961   // Also add all consecutive pointer values; these values will be uniform
4962   // after vectorization (and subsequent cleanup) and, until revectorization is
4963   // supported, all dependencies must also be uniform.
4964   for (Loop::block_iterator B = TheLoop->block_begin(),
4965                             BE = TheLoop->block_end();
4966        B != BE; ++B)
4967     for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end(); I != IE; ++I)
4968       if (I->getType()->isPointerTy() && isConsecutivePtr(&*I))
4969         Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4970 
4971   while (!Worklist.empty()) {
4972     Instruction *I = dyn_cast<Instruction>(Worklist.back());
4973     Worklist.pop_back();
4974 
4975     // Look at instructions inside this loop.
4976     // Stop when reaching PHI nodes.
4977     // TODO: we need to follow values all over the loop, not only in this block.
4978     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
4979       continue;
4980 
4981     // This is a known uniform.
4982     Uniforms.insert(I);
4983 
4984     // Insert all operands.
4985     Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
4986   }
4987 }
4988 
4989 bool LoopVectorizationLegality::canVectorizeMemory() {
4990   LAI = &LAA->getInfo(TheLoop, Strides);
4991   auto &OptionalReport = LAI->getReport();
4992   if (OptionalReport)
4993     emitAnalysis(VectorizationReport(*OptionalReport));
4994   if (!LAI->canVectorizeMemory())
4995     return false;
4996 
4997   if (LAI->hasStoreToLoopInvariantAddress()) {
4998     emitAnalysis(
4999         VectorizationReport()
5000         << "write to a loop invariant address could not be vectorized");
5001     DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
5002     return false;
5003   }
5004 
5005   Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
5006   PSE.addPredicate(LAI->PSE.getUnionPredicate());
5007 
5008   return true;
5009 }
5010 
5011 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
5012   Value *In0 = const_cast<Value *>(V);
5013   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
5014   if (!PN)
5015     return false;
5016 
5017   return Inductions.count(PN);
5018 }
5019 
5020 bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
5021   return FirstOrderRecurrences.count(Phi);
5022 }
5023 
5024 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
5025   return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
5026 }
5027 
5028 bool LoopVectorizationLegality::blockCanBePredicated(
5029     BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) {
5030   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
5031 
5032   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5033     // Check that we don't have a constant expression that can trap as operand.
5034     for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
5035          OI != OE; ++OI) {
5036       if (Constant *C = dyn_cast<Constant>(*OI))
5037         if (C->canTrap())
5038           return false;
5039     }
5040     // We might be able to hoist the load.
5041     if (it->mayReadFromMemory()) {
5042       LoadInst *LI = dyn_cast<LoadInst>(it);
5043       if (!LI)
5044         return false;
5045       if (!SafePtrs.count(LI->getPointerOperand())) {
5046         if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand()) ||
5047             isLegalMaskedGather(LI->getType())) {
5048           MaskedOp.insert(LI);
5049           continue;
5050         }
5051         // !llvm.mem.parallel_loop_access implies if-conversion safety.
5052         if (IsAnnotatedParallel)
5053           continue;
5054         return false;
5055       }
5056     }
5057 
5058     // We don't predicate stores at the moment.
5059     if (it->mayWriteToMemory()) {
5060       StoreInst *SI = dyn_cast<StoreInst>(it);
5061       // We only support predication of stores in basic blocks with one
5062       // predecessor.
5063       if (!SI)
5064         return false;
5065 
5066       // Build a masked store if it is legal for the target.
5067       if (isLegalMaskedStore(SI->getValueOperand()->getType(),
5068                              SI->getPointerOperand()) ||
5069           isLegalMaskedScatter(SI->getValueOperand()->getType())) {
5070         MaskedOp.insert(SI);
5071         continue;
5072       }
5073 
5074       bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
5075       bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
5076 
5077       if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
5078           !isSinglePredecessor)
5079         return false;
5080     }
5081     if (it->mayThrow())
5082       return false;
5083 
5084     // The instructions below can trap.
5085     switch (it->getOpcode()) {
5086     default:
5087       continue;
5088     case Instruction::UDiv:
5089     case Instruction::SDiv:
5090     case Instruction::URem:
5091     case Instruction::SRem:
5092       return false;
5093     }
5094   }
5095 
5096   return true;
5097 }
5098 
5099 void InterleavedAccessInfo::collectConstStridedAccesses(
5100     MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
5101     const ValueToValueMap &Strides) {
5102   // Holds load/store instructions in program order.
5103   SmallVector<Instruction *, 16> AccessList;
5104 
5105   for (auto *BB : TheLoop->getBlocks()) {
5106     bool IsPred = LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
5107 
5108     for (auto &I : *BB) {
5109       if (!isa<LoadInst>(&I) && !isa<StoreInst>(&I))
5110         continue;
5111       // FIXME: Currently we can't handle mixed accesses and predicated accesses
5112       if (IsPred)
5113         return;
5114 
5115       AccessList.push_back(&I);
5116     }
5117   }
5118 
5119   if (AccessList.empty())
5120     return;
5121 
5122   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
5123   for (auto I : AccessList) {
5124     LoadInst *LI = dyn_cast<LoadInst>(I);
5125     StoreInst *SI = dyn_cast<StoreInst>(I);
5126 
5127     Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
5128     int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides);
5129 
5130     // The factor of the corresponding interleave group.
5131     unsigned Factor = std::abs(Stride);
5132 
5133     // Ignore the access if the factor is too small or too large.
5134     if (Factor < 2 || Factor > MaxInterleaveGroupFactor)
5135       continue;
5136 
5137     const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
5138     PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
5139     unsigned Size = DL.getTypeAllocSize(PtrTy->getElementType());
5140 
5141     // An alignment of 0 means target ABI alignment.
5142     unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
5143     if (!Align)
5144       Align = DL.getABITypeAlignment(PtrTy->getElementType());
5145 
5146     StrideAccesses[I] = StrideDescriptor(Stride, Scev, Size, Align);
5147   }
5148 }
5149 
5150 // Analyze interleaved accesses and collect them into interleave groups.
5151 //
5152 // Notice that the vectorization on interleaved groups will change instruction
5153 // orders and may break dependences. But the memory dependence check guarantees
5154 // that there is no overlap between two pointers of different strides, element
5155 // sizes or underlying bases.
5156 //
5157 // For pointers sharing the same stride, element size and underlying base, no
5158 // need to worry about Read-After-Write dependences and Write-After-Read
5159 // dependences.
5160 //
5161 // E.g. The RAW dependence:  A[i] = a;
5162 //                           b = A[i];
5163 // This won't exist as it is a store-load forwarding conflict, which has
5164 // already been checked and forbidden in the dependence check.
5165 //
5166 // E.g. The WAR dependence:  a = A[i];  // (1)
5167 //                           A[i] = b;  // (2)
5168 // The store group of (2) is always inserted at or below (2), and the load group
5169 // of (1) is always inserted at or above (1). The dependence is safe.
5170 void InterleavedAccessInfo::analyzeInterleaving(
5171     const ValueToValueMap &Strides) {
5172   DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
5173 
5174   // Holds all the stride accesses.
5175   MapVector<Instruction *, StrideDescriptor> StrideAccesses;
5176   collectConstStridedAccesses(StrideAccesses, Strides);
5177 
5178   if (StrideAccesses.empty())
5179     return;
5180 
5181   // Holds all interleaved store groups temporarily.
5182   SmallSetVector<InterleaveGroup *, 4> StoreGroups;
5183   // Holds all interleaved load groups temporarily.
5184   SmallSetVector<InterleaveGroup *, 4> LoadGroups;
5185 
5186   // Search the load-load/write-write pair B-A in bottom-up order and try to
5187   // insert B into the interleave group of A according to 3 rules:
5188   //   1. A and B have the same stride.
5189   //   2. A and B have the same memory object size.
5190   //   3. B belongs to the group according to the distance.
5191   //
5192   // The bottom-up order can avoid breaking the Write-After-Write dependences
5193   // between two pointers of the same base.
5194   // E.g.  A[i]   = a;   (1)
5195   //       A[i]   = b;   (2)
5196   //       A[i+1] = c    (3)
5197   // We form the group (2)+(3) in front, so (1) has to form groups with accesses
5198   // above (1), which guarantees that (1) is always above (2).
5199   for (auto I = StrideAccesses.rbegin(), E = StrideAccesses.rend(); I != E;
5200        ++I) {
5201     Instruction *A = I->first;
5202     StrideDescriptor DesA = I->second;
5203 
5204     InterleaveGroup *Group = getInterleaveGroup(A);
5205     if (!Group) {
5206       DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
5207       Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
5208     }
5209 
5210     if (A->mayWriteToMemory())
5211       StoreGroups.insert(Group);
5212     else
5213       LoadGroups.insert(Group);
5214 
5215     for (auto II = std::next(I); II != E; ++II) {
5216       Instruction *B = II->first;
5217       StrideDescriptor DesB = II->second;
5218 
5219       // Ignore if B is already in a group or B is a different memory operation.
5220       if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
5221         continue;
5222 
5223       // Check the rule 1 and 2.
5224       if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
5225         continue;
5226 
5227       // Calculate the distance and prepare for the rule 3.
5228       const SCEVConstant *DistToA = dyn_cast<SCEVConstant>(
5229           PSE.getSE()->getMinusSCEV(DesB.Scev, DesA.Scev));
5230       if (!DistToA)
5231         continue;
5232 
5233       int DistanceToA = DistToA->getAPInt().getSExtValue();
5234 
5235       // Skip if the distance is not multiple of size as they are not in the
5236       // same group.
5237       if (DistanceToA % static_cast<int>(DesA.Size))
5238         continue;
5239 
5240       // The index of B is the index of A plus the related index to A.
5241       int IndexB =
5242           Group->getIndex(A) + DistanceToA / static_cast<int>(DesA.Size);
5243 
5244       // Try to insert B into the group.
5245       if (Group->insertMember(B, IndexB, DesB.Align)) {
5246         DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
5247                      << "    into the interleave group with" << *A << '\n');
5248         InterleaveGroupMap[B] = Group;
5249 
5250         // Set the first load in program order as the insert position.
5251         if (B->mayReadFromMemory())
5252           Group->setInsertPos(B);
5253       }
5254     } // Iteration on instruction B
5255   }   // Iteration on instruction A
5256 
5257   // Remove interleaved store groups with gaps.
5258   for (InterleaveGroup *Group : StoreGroups)
5259     if (Group->getNumMembers() != Group->getFactor())
5260       releaseGroup(Group);
5261 
5262   // If there is a non-reversed interleaved load group with gaps, we will need
5263   // to execute at least one scalar epilogue iteration. This will ensure that
5264   // we don't speculatively access memory out-of-bounds. Note that we only need
5265   // to look for a member at index factor - 1, since every group must have a
5266   // member at index zero.
5267   for (InterleaveGroup *Group : LoadGroups)
5268     if (!Group->getMember(Group->getFactor() - 1)) {
5269       if (Group->isReverse()) {
5270         releaseGroup(Group);
5271       } else {
5272         DEBUG(dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
5273         RequiresScalarEpilogue = true;
5274       }
5275     }
5276 }
5277 
5278 LoopVectorizationCostModel::VectorizationFactor
5279 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
5280   // Width 1 means no vectorize
5281   VectorizationFactor Factor = {1U, 0U};
5282   if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
5283     emitAnalysis(
5284         VectorizationReport()
5285         << "runtime pointer checks needed. Enable vectorization of this "
5286            "loop with '#pragma clang loop vectorize(enable)' when "
5287            "compiling with -Os/-Oz");
5288     DEBUG(dbgs()
5289           << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
5290     return Factor;
5291   }
5292 
5293   if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
5294     emitAnalysis(
5295         VectorizationReport()
5296         << "store that is conditionally executed prevents vectorization");
5297     DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
5298     return Factor;
5299   }
5300 
5301   // Find the trip count.
5302   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5303   DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5304 
5305   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5306   unsigned SmallestType, WidestType;
5307   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5308   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
5309   unsigned MaxSafeDepDist = -1U;
5310 
5311   // Get the maximum safe dependence distance in bits computed by LAA. If the
5312   // loop contains any interleaved accesses, we divide the dependence distance
5313   // by the maximum interleave factor of all interleaved groups. Note that
5314   // although the division ensures correctness, this is a fairly conservative
5315   // computation because the maximum distance computed by LAA may not involve
5316   // any of the interleaved accesses.
5317   if (Legal->getMaxSafeDepDistBytes() != -1U)
5318     MaxSafeDepDist =
5319         Legal->getMaxSafeDepDistBytes() * 8 / Legal->getMaxInterleaveFactor();
5320 
5321   WidestRegister =
5322       ((WidestRegister < MaxSafeDepDist) ? WidestRegister : MaxSafeDepDist);
5323   unsigned MaxVectorSize = WidestRegister / WidestType;
5324 
5325   DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / "
5326                << WidestType << " bits.\n");
5327   DEBUG(dbgs() << "LV: The Widest register is: " << WidestRegister
5328                << " bits.\n");
5329 
5330   if (MaxVectorSize == 0) {
5331     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5332     MaxVectorSize = 1;
5333   }
5334 
5335   assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
5336                                 " into one vector!");
5337 
5338   unsigned VF = MaxVectorSize;
5339   if (MaximizeBandwidth && !OptForSize) {
5340     // Collect all viable vectorization factors.
5341     SmallVector<unsigned, 8> VFs;
5342     unsigned NewMaxVectorSize = WidestRegister / SmallestType;
5343     for (unsigned VS = MaxVectorSize; VS <= NewMaxVectorSize; VS *= 2)
5344       VFs.push_back(VS);
5345 
5346     // For each VF calculate its register usage.
5347     auto RUs = calculateRegisterUsage(VFs);
5348 
5349     // Select the largest VF which doesn't require more registers than existing
5350     // ones.
5351     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
5352     for (int i = RUs.size() - 1; i >= 0; --i) {
5353       if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
5354         VF = VFs[i];
5355         break;
5356       }
5357     }
5358   }
5359 
5360   // If we optimize the program for size, avoid creating the tail loop.
5361   if (OptForSize) {
5362     // If we are unable to calculate the trip count then don't try to vectorize.
5363     if (TC < 2) {
5364       emitAnalysis(
5365           VectorizationReport()
5366           << "unable to calculate the loop count due to complex control flow");
5367       DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
5368       return Factor;
5369     }
5370 
5371     // Find the maximum SIMD width that can fit within the trip count.
5372     VF = TC % MaxVectorSize;
5373 
5374     if (VF == 0)
5375       VF = MaxVectorSize;
5376     else {
5377       // If the trip count that we found modulo the vectorization factor is not
5378       // zero then we require a tail.
5379       emitAnalysis(VectorizationReport()
5380                    << "cannot optimize for size and vectorize at the "
5381                       "same time. Enable vectorization of this loop "
5382                       "with '#pragma clang loop vectorize(enable)' "
5383                       "when compiling with -Os/-Oz");
5384       DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
5385       return Factor;
5386     }
5387   }
5388 
5389   int UserVF = Hints->getWidth();
5390   if (UserVF != 0) {
5391     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
5392     DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5393 
5394     Factor.Width = UserVF;
5395     return Factor;
5396   }
5397 
5398   float Cost = expectedCost(1).first;
5399 #ifndef NDEBUG
5400   const float ScalarCost = Cost;
5401 #endif /* NDEBUG */
5402   unsigned Width = 1;
5403   DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
5404 
5405   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5406   // Ignore scalar width, because the user explicitly wants vectorization.
5407   if (ForceVectorization && VF > 1) {
5408     Width = 2;
5409     Cost = expectedCost(Width).first / (float)Width;
5410   }
5411 
5412   for (unsigned i = 2; i <= VF; i *= 2) {
5413     // Notice that the vector loop needs to be executed less times, so
5414     // we need to divide the cost of the vector loops by the width of
5415     // the vector elements.
5416     VectorizationCostTy C = expectedCost(i);
5417     float VectorCost = C.first / (float)i;
5418     DEBUG(dbgs() << "LV: Vector loop of width " << i
5419                  << " costs: " << (int)VectorCost << ".\n");
5420     if (!C.second && !ForceVectorization) {
5421       DEBUG(
5422           dbgs() << "LV: Not considering vector loop of width " << i
5423                  << " because it will not generate any vector instructions.\n");
5424       continue;
5425     }
5426     if (VectorCost < Cost) {
5427       Cost = VectorCost;
5428       Width = i;
5429     }
5430   }
5431 
5432   DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
5433         << "LV: Vectorization seems to be not beneficial, "
5434         << "but was forced by a user.\n");
5435   DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
5436   Factor.Width = Width;
5437   Factor.Cost = Width * Cost;
5438   return Factor;
5439 }
5440 
5441 std::pair<unsigned, unsigned>
5442 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
5443   unsigned MinWidth = -1U;
5444   unsigned MaxWidth = 8;
5445   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5446 
5447   // For each block.
5448   for (Loop::block_iterator bb = TheLoop->block_begin(),
5449                             be = TheLoop->block_end();
5450        bb != be; ++bb) {
5451     BasicBlock *BB = *bb;
5452 
5453     // For each instruction in the loop.
5454     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5455       Type *T = it->getType();
5456 
5457       // Skip ignored values.
5458       if (ValuesToIgnore.count(&*it))
5459         continue;
5460 
5461       // Only examine Loads, Stores and PHINodes.
5462       if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
5463         continue;
5464 
5465       // Examine PHI nodes that are reduction variables. Update the type to
5466       // account for the recurrence type.
5467       if (PHINode *PN = dyn_cast<PHINode>(it)) {
5468         if (!Legal->isReductionVariable(PN))
5469           continue;
5470         RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
5471         T = RdxDesc.getRecurrenceType();
5472       }
5473 
5474       // Examine the stored values.
5475       if (StoreInst *ST = dyn_cast<StoreInst>(it))
5476         T = ST->getValueOperand()->getType();
5477 
5478       // Ignore loaded pointer types and stored pointer types that are not
5479       // consecutive. However, we do want to take consecutive stores/loads of
5480       // pointer vectors into account.
5481       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&*it))
5482         continue;
5483 
5484       MinWidth = std::min(MinWidth,
5485                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
5486       MaxWidth = std::max(MaxWidth,
5487                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
5488     }
5489   }
5490 
5491   return {MinWidth, MaxWidth};
5492 }
5493 
5494 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
5495                                                            unsigned VF,
5496                                                            unsigned LoopCost) {
5497 
5498   // -- The interleave heuristics --
5499   // We interleave the loop in order to expose ILP and reduce the loop overhead.
5500   // There are many micro-architectural considerations that we can't predict
5501   // at this level. For example, frontend pressure (on decode or fetch) due to
5502   // code size, or the number and capabilities of the execution ports.
5503   //
5504   // We use the following heuristics to select the interleave count:
5505   // 1. If the code has reductions, then we interleave to break the cross
5506   // iteration dependency.
5507   // 2. If the loop is really small, then we interleave to reduce the loop
5508   // overhead.
5509   // 3. We don't interleave if we think that we will spill registers to memory
5510   // due to the increased register pressure.
5511 
5512   // When we optimize for size, we don't interleave.
5513   if (OptForSize)
5514     return 1;
5515 
5516   // We used the distance for the interleave count.
5517   if (Legal->getMaxSafeDepDistBytes() != -1U)
5518     return 1;
5519 
5520   // Do not interleave loops with a relatively small trip count.
5521   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5522   if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
5523     return 1;
5524 
5525   unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5526   DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
5527                << " registers\n");
5528 
5529   if (VF == 1) {
5530     if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5531       TargetNumRegisters = ForceTargetNumScalarRegs;
5532   } else {
5533     if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5534       TargetNumRegisters = ForceTargetNumVectorRegs;
5535   }
5536 
5537   RegisterUsage R = calculateRegisterUsage({VF})[0];
5538   // We divide by these constants so assume that we have at least one
5539   // instruction that uses at least one register.
5540   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5541   R.NumInstructions = std::max(R.NumInstructions, 1U);
5542 
5543   // We calculate the interleave count using the following formula.
5544   // Subtract the number of loop invariants from the number of available
5545   // registers. These registers are used by all of the interleaved instances.
5546   // Next, divide the remaining registers by the number of registers that is
5547   // required by the loop, in order to estimate how many parallel instances
5548   // fit without causing spills. All of this is rounded down if necessary to be
5549   // a power of two. We want power of two interleave count to simplify any
5550   // addressing operations or alignment considerations.
5551   unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5552                               R.MaxLocalUsers);
5553 
5554   // Don't count the induction variable as interleaved.
5555   if (EnableIndVarRegisterHeur)
5556     IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
5557                        std::max(1U, (R.MaxLocalUsers - 1)));
5558 
5559   // Clamp the interleave ranges to reasonable counts.
5560   unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
5561 
5562   // Check if the user has overridden the max.
5563   if (VF == 1) {
5564     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
5565       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
5566   } else {
5567     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
5568       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
5569   }
5570 
5571   // If we did not calculate the cost for VF (because the user selected the VF)
5572   // then we calculate the cost of VF here.
5573   if (LoopCost == 0)
5574     LoopCost = expectedCost(VF).first;
5575 
5576   // Clamp the calculated IC to be between the 1 and the max interleave count
5577   // that the target allows.
5578   if (IC > MaxInterleaveCount)
5579     IC = MaxInterleaveCount;
5580   else if (IC < 1)
5581     IC = 1;
5582 
5583   // Interleave if we vectorized this loop and there is a reduction that could
5584   // benefit from interleaving.
5585   if (VF > 1 && Legal->getReductionVars()->size()) {
5586     DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
5587     return IC;
5588   }
5589 
5590   // Note that if we've already vectorized the loop we will have done the
5591   // runtime check and so interleaving won't require further checks.
5592   bool InterleavingRequiresRuntimePointerCheck =
5593       (VF == 1 && Legal->getRuntimePointerChecking()->Need);
5594 
5595   // We want to interleave small loops in order to reduce the loop overhead and
5596   // potentially expose ILP opportunities.
5597   DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5598   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
5599     // We assume that the cost overhead is 1 and we use the cost model
5600     // to estimate the cost of the loop and interleave until the cost of the
5601     // loop overhead is about 5% of the cost of the loop.
5602     unsigned SmallIC =
5603         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5604 
5605     // Interleave until store/load ports (estimated by max interleave count) are
5606     // saturated.
5607     unsigned NumStores = Legal->getNumStores();
5608     unsigned NumLoads = Legal->getNumLoads();
5609     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5610     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5611 
5612     // If we have a scalar reduction (vector reductions are already dealt with
5613     // by this point), we can increase the critical path length if the loop
5614     // we're interleaving is inside another loop. Limit, by default to 2, so the
5615     // critical path only gets increased by one reduction operation.
5616     if (Legal->getReductionVars()->size() && TheLoop->getLoopDepth() > 1) {
5617       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
5618       SmallIC = std::min(SmallIC, F);
5619       StoresIC = std::min(StoresIC, F);
5620       LoadsIC = std::min(LoadsIC, F);
5621     }
5622 
5623     if (EnableLoadStoreRuntimeInterleave &&
5624         std::max(StoresIC, LoadsIC) > SmallIC) {
5625       DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
5626       return std::max(StoresIC, LoadsIC);
5627     }
5628 
5629     DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
5630     return SmallIC;
5631   }
5632 
5633   // Interleave if this is a large loop (small loops are already dealt with by
5634   // this point) that could benefit from interleaving.
5635   bool HasReductions = (Legal->getReductionVars()->size() > 0);
5636   if (TTI.enableAggressiveInterleaving(HasReductions)) {
5637     DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5638     return IC;
5639   }
5640 
5641   DEBUG(dbgs() << "LV: Not Interleaving.\n");
5642   return 1;
5643 }
5644 
5645 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
5646 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) {
5647   // This function calculates the register usage by measuring the highest number
5648   // of values that are alive at a single location. Obviously, this is a very
5649   // rough estimation. We scan the loop in a topological order in order and
5650   // assign a number to each instruction. We use RPO to ensure that defs are
5651   // met before their users. We assume that each instruction that has in-loop
5652   // users starts an interval. We record every time that an in-loop value is
5653   // used, so we have a list of the first and last occurrences of each
5654   // instruction. Next, we transpose this data structure into a multi map that
5655   // holds the list of intervals that *end* at a specific location. This multi
5656   // map allows us to perform a linear search. We scan the instructions linearly
5657   // and record each time that a new interval starts, by placing it in a set.
5658   // If we find this value in the multi-map then we remove it from the set.
5659   // The max register usage is the maximum size of the set.
5660   // We also search for instructions that are defined outside the loop, but are
5661   // used inside the loop. We need this number separately from the max-interval
5662   // usage number because when we unroll, loop-invariant values do not take
5663   // more register.
5664   LoopBlocksDFS DFS(TheLoop);
5665   DFS.perform(LI);
5666 
5667   RegisterUsage RU;
5668   RU.NumInstructions = 0;
5669 
5670   // Each 'key' in the map opens a new interval. The values
5671   // of the map are the index of the 'last seen' usage of the
5672   // instruction that is the key.
5673   typedef DenseMap<Instruction *, unsigned> IntervalMap;
5674   // Maps instruction to its index.
5675   DenseMap<unsigned, Instruction *> IdxToInstr;
5676   // Marks the end of each interval.
5677   IntervalMap EndPoint;
5678   // Saves the list of instruction indices that are used in the loop.
5679   SmallSet<Instruction *, 8> Ends;
5680   // Saves the list of values that are used in the loop but are
5681   // defined outside the loop, such as arguments and constants.
5682   SmallPtrSet<Value *, 8> LoopInvariants;
5683 
5684   unsigned Index = 0;
5685   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(), be = DFS.endRPO();
5686        bb != be; ++bb) {
5687     RU.NumInstructions += (*bb)->size();
5688     for (Instruction &I : **bb) {
5689       IdxToInstr[Index++] = &I;
5690 
5691       // Save the end location of each USE.
5692       for (unsigned i = 0; i < I.getNumOperands(); ++i) {
5693         Value *U = I.getOperand(i);
5694         Instruction *Instr = dyn_cast<Instruction>(U);
5695 
5696         // Ignore non-instruction values such as arguments, constants, etc.
5697         if (!Instr)
5698           continue;
5699 
5700         // If this instruction is outside the loop then record it and continue.
5701         if (!TheLoop->contains(Instr)) {
5702           LoopInvariants.insert(Instr);
5703           continue;
5704         }
5705 
5706         // Overwrite previous end points.
5707         EndPoint[Instr] = Index;
5708         Ends.insert(Instr);
5709       }
5710     }
5711   }
5712 
5713   // Saves the list of intervals that end with the index in 'key'.
5714   typedef SmallVector<Instruction *, 2> InstrList;
5715   DenseMap<unsigned, InstrList> TransposeEnds;
5716 
5717   // Transpose the EndPoints to a list of values that end at each index.
5718   for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end(); it != e;
5719        ++it)
5720     TransposeEnds[it->second].push_back(it->first);
5721 
5722   SmallSet<Instruction *, 8> OpenIntervals;
5723 
5724   // Get the size of the widest register.
5725   unsigned MaxSafeDepDist = -1U;
5726   if (Legal->getMaxSafeDepDistBytes() != -1U)
5727     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5728   unsigned WidestRegister =
5729       std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
5730   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5731 
5732   SmallVector<RegisterUsage, 8> RUs(VFs.size());
5733   SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
5734 
5735   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5736 
5737   // A lambda that gets the register usage for the given type and VF.
5738   auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
5739     if (Ty->isTokenTy())
5740       return 0U;
5741     unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
5742     return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
5743   };
5744 
5745   for (unsigned int i = 0; i < Index; ++i) {
5746     Instruction *I = IdxToInstr[i];
5747     // Ignore instructions that are never used within the loop.
5748     if (!Ends.count(I))
5749       continue;
5750 
5751     // Remove all of the instructions that end at this location.
5752     InstrList &List = TransposeEnds[i];
5753     for (unsigned int j = 0, e = List.size(); j < e; ++j)
5754       OpenIntervals.erase(List[j]);
5755 
5756     // Skip ignored values.
5757     if (ValuesToIgnore.count(I))
5758       continue;
5759 
5760     // For each VF find the maximum usage of registers.
5761     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
5762       if (VFs[j] == 1) {
5763         MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
5764         continue;
5765       }
5766 
5767       // Count the number of live intervals.
5768       unsigned RegUsage = 0;
5769       for (auto Inst : OpenIntervals) {
5770         // Skip ignored values for VF > 1.
5771         if (VecValuesToIgnore.count(Inst))
5772           continue;
5773         RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
5774       }
5775       MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
5776     }
5777 
5778     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
5779                  << OpenIntervals.size() << '\n');
5780 
5781     // Add the current instruction to the list of open intervals.
5782     OpenIntervals.insert(I);
5783   }
5784 
5785   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
5786     unsigned Invariant = 0;
5787     if (VFs[i] == 1)
5788       Invariant = LoopInvariants.size();
5789     else {
5790       for (auto Inst : LoopInvariants)
5791         Invariant += GetRegUsage(Inst->getType(), VFs[i]);
5792     }
5793 
5794     DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
5795     DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
5796     DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5797     DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n');
5798 
5799     RU.LoopInvariantRegs = Invariant;
5800     RU.MaxLocalUsers = MaxUsages[i];
5801     RUs[i] = RU;
5802   }
5803 
5804   return RUs;
5805 }
5806 
5807 LoopVectorizationCostModel::VectorizationCostTy
5808 LoopVectorizationCostModel::expectedCost(unsigned VF) {
5809   VectorizationCostTy Cost;
5810 
5811   // For each block.
5812   for (Loop::block_iterator bb = TheLoop->block_begin(),
5813                             be = TheLoop->block_end();
5814        bb != be; ++bb) {
5815     VectorizationCostTy BlockCost;
5816     BasicBlock *BB = *bb;
5817 
5818     // For each instruction in the old loop.
5819     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5820       // Skip dbg intrinsics.
5821       if (isa<DbgInfoIntrinsic>(it))
5822         continue;
5823 
5824       // Skip ignored values.
5825       if (ValuesToIgnore.count(&*it))
5826         continue;
5827 
5828       VectorizationCostTy C = getInstructionCost(&*it, VF);
5829 
5830       // Check if we should override the cost.
5831       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5832         C.first = ForceTargetInstructionCost;
5833 
5834       BlockCost.first += C.first;
5835       BlockCost.second |= C.second;
5836       DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first << " for VF "
5837                    << VF << " For instruction: " << *it << '\n');
5838     }
5839 
5840     // We assume that if-converted blocks have a 50% chance of being executed.
5841     // When the code is scalar then some of the blocks are avoided due to CF.
5842     // When the code is vectorized we execute all code paths.
5843     if (VF == 1 && Legal->blockNeedsPredication(*bb))
5844       BlockCost.first /= 2;
5845 
5846     Cost.first += BlockCost.first;
5847     Cost.second |= BlockCost.second;
5848   }
5849 
5850   return Cost;
5851 }
5852 
5853 /// \brief Check if the load/store instruction \p I may be translated into
5854 /// gather/scatter during vectorization.
5855 ///
5856 /// Pointer \p Ptr specifies address in memory for the given scalar memory
5857 /// instruction. We need it to retrieve data type.
5858 /// Using gather/scatter is possible when it is supported by target.
5859 static bool isGatherOrScatterLegal(Instruction *I, Value *Ptr,
5860                                    LoopVectorizationLegality *Legal) {
5861   Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
5862   return (isa<LoadInst>(I) && Legal->isLegalMaskedGather(DataTy)) ||
5863          (isa<StoreInst>(I) && Legal->isLegalMaskedScatter(DataTy));
5864 }
5865 
5866 /// \brief Check whether the address computation for a non-consecutive memory
5867 /// access looks like an unlikely candidate for being merged into the indexing
5868 /// mode.
5869 ///
5870 /// We look for a GEP which has one index that is an induction variable and all
5871 /// other indices are loop invariant. If the stride of this access is also
5872 /// within a small bound we decide that this address computation can likely be
5873 /// merged into the addressing mode.
5874 /// In all other cases, we identify the address computation as complex.
5875 static bool isLikelyComplexAddressComputation(Value *Ptr,
5876                                               LoopVectorizationLegality *Legal,
5877                                               ScalarEvolution *SE,
5878                                               const Loop *TheLoop) {
5879   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5880   if (!Gep)
5881     return true;
5882 
5883   // We are looking for a gep with all loop invariant indices except for one
5884   // which should be an induction variable.
5885   unsigned NumOperands = Gep->getNumOperands();
5886   for (unsigned i = 1; i < NumOperands; ++i) {
5887     Value *Opd = Gep->getOperand(i);
5888     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5889         !Legal->isInductionVariable(Opd))
5890       return true;
5891   }
5892 
5893   // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5894   // can likely be merged into the address computation.
5895   unsigned MaxMergeDistance = 64;
5896 
5897   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5898   if (!AddRec)
5899     return true;
5900 
5901   // Check the step is constant.
5902   const SCEV *Step = AddRec->getStepRecurrence(*SE);
5903   // Calculate the pointer stride and check if it is consecutive.
5904   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5905   if (!C)
5906     return true;
5907 
5908   const APInt &APStepVal = C->getAPInt();
5909 
5910   // Huge step value - give up.
5911   if (APStepVal.getBitWidth() > 64)
5912     return true;
5913 
5914   int64_t StepVal = APStepVal.getSExtValue();
5915 
5916   return StepVal > MaxMergeDistance;
5917 }
5918 
5919 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5920   return Legal->hasStride(I->getOperand(0)) ||
5921          Legal->hasStride(I->getOperand(1));
5922 }
5923 
5924 LoopVectorizationCostModel::VectorizationCostTy
5925 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5926   // If we know that this instruction will remain uniform, check the cost of
5927   // the scalar version.
5928   if (Legal->isUniformAfterVectorization(I))
5929     VF = 1;
5930 
5931   Type *VectorTy;
5932   unsigned C = getInstructionCost(I, VF, VectorTy);
5933 
5934   bool TypeNotScalarized =
5935       VF > 1 && !VectorTy->isVoidTy() && TTI.getNumberOfParts(VectorTy) < VF;
5936   return VectorizationCostTy(C, TypeNotScalarized);
5937 }
5938 
5939 unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I,
5940                                                         unsigned VF,
5941                                                         Type *&VectorTy) {
5942   Type *RetTy = I->getType();
5943   if (VF > 1 && MinBWs.count(I))
5944     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
5945   VectorTy = ToVectorTy(RetTy, VF);
5946   auto SE = PSE.getSE();
5947 
5948   // TODO: We need to estimate the cost of intrinsic calls.
5949   switch (I->getOpcode()) {
5950   case Instruction::GetElementPtr:
5951     // We mark this instruction as zero-cost because the cost of GEPs in
5952     // vectorized code depends on whether the corresponding memory instruction
5953     // is scalarized or not. Therefore, we handle GEPs with the memory
5954     // instruction cost.
5955     return 0;
5956   case Instruction::Br: {
5957     return TTI.getCFInstrCost(I->getOpcode());
5958   }
5959   case Instruction::PHI: {
5960     auto *Phi = cast<PHINode>(I);
5961 
5962     // First-order recurrences are replaced by vector shuffles inside the loop.
5963     if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
5964       return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5965                                 VectorTy, VF - 1, VectorTy);
5966 
5967     // TODO: IF-converted IFs become selects.
5968     return 0;
5969   }
5970   case Instruction::Add:
5971   case Instruction::FAdd:
5972   case Instruction::Sub:
5973   case Instruction::FSub:
5974   case Instruction::Mul:
5975   case Instruction::FMul:
5976   case Instruction::UDiv:
5977   case Instruction::SDiv:
5978   case Instruction::FDiv:
5979   case Instruction::URem:
5980   case Instruction::SRem:
5981   case Instruction::FRem:
5982   case Instruction::Shl:
5983   case Instruction::LShr:
5984   case Instruction::AShr:
5985   case Instruction::And:
5986   case Instruction::Or:
5987   case Instruction::Xor: {
5988     // Since we will replace the stride by 1 the multiplication should go away.
5989     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5990       return 0;
5991     // Certain instructions can be cheaper to vectorize if they have a constant
5992     // second vector operand. One example of this are shifts on x86.
5993     TargetTransformInfo::OperandValueKind Op1VK =
5994         TargetTransformInfo::OK_AnyValue;
5995     TargetTransformInfo::OperandValueKind Op2VK =
5996         TargetTransformInfo::OK_AnyValue;
5997     TargetTransformInfo::OperandValueProperties Op1VP =
5998         TargetTransformInfo::OP_None;
5999     TargetTransformInfo::OperandValueProperties Op2VP =
6000         TargetTransformInfo::OP_None;
6001     Value *Op2 = I->getOperand(1);
6002 
6003     // Check for a splat of a constant or for a non uniform vector of constants.
6004     if (isa<ConstantInt>(Op2)) {
6005       ConstantInt *CInt = cast<ConstantInt>(Op2);
6006       if (CInt && CInt->getValue().isPowerOf2())
6007         Op2VP = TargetTransformInfo::OP_PowerOf2;
6008       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
6009     } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
6010       Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
6011       Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
6012       if (SplatValue) {
6013         ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
6014         if (CInt && CInt->getValue().isPowerOf2())
6015           Op2VP = TargetTransformInfo::OP_PowerOf2;
6016         Op2VK = TargetTransformInfo::OK_UniformConstantValue;
6017       }
6018     }
6019 
6020     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
6021                                       Op1VP, Op2VP);
6022   }
6023   case Instruction::Select: {
6024     SelectInst *SI = cast<SelectInst>(I);
6025     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
6026     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
6027     Type *CondTy = SI->getCondition()->getType();
6028     if (!ScalarCond)
6029       CondTy = VectorType::get(CondTy, VF);
6030 
6031     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
6032   }
6033   case Instruction::ICmp:
6034   case Instruction::FCmp: {
6035     Type *ValTy = I->getOperand(0)->getType();
6036     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
6037     auto It = MinBWs.find(Op0AsInstruction);
6038     if (VF > 1 && It != MinBWs.end())
6039       ValTy = IntegerType::get(ValTy->getContext(), It->second);
6040     VectorTy = ToVectorTy(ValTy, VF);
6041     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
6042   }
6043   case Instruction::Store:
6044   case Instruction::Load: {
6045     StoreInst *SI = dyn_cast<StoreInst>(I);
6046     LoadInst *LI = dyn_cast<LoadInst>(I);
6047     Type *ValTy = (SI ? SI->getValueOperand()->getType() : LI->getType());
6048     VectorTy = ToVectorTy(ValTy, VF);
6049 
6050     unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
6051     unsigned AS =
6052         SI ? SI->getPointerAddressSpace() : LI->getPointerAddressSpace();
6053     Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
6054     // We add the cost of address computation here instead of with the gep
6055     // instruction because only here we know whether the operation is
6056     // scalarized.
6057     if (VF == 1)
6058       return TTI.getAddressComputationCost(VectorTy) +
6059              TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
6060 
6061     if (LI && Legal->isUniform(Ptr)) {
6062       // Scalar load + broadcast
6063       unsigned Cost = TTI.getAddressComputationCost(ValTy->getScalarType());
6064       Cost += TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
6065                                   Alignment, AS);
6066       return Cost +
6067              TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, ValTy);
6068     }
6069 
6070     // For an interleaved access, calculate the total cost of the whole
6071     // interleave group.
6072     if (Legal->isAccessInterleaved(I)) {
6073       auto Group = Legal->getInterleavedAccessGroup(I);
6074       assert(Group && "Fail to get an interleaved access group.");
6075 
6076       // Only calculate the cost once at the insert position.
6077       if (Group->getInsertPos() != I)
6078         return 0;
6079 
6080       unsigned InterleaveFactor = Group->getFactor();
6081       Type *WideVecTy =
6082           VectorType::get(VectorTy->getVectorElementType(),
6083                           VectorTy->getVectorNumElements() * InterleaveFactor);
6084 
6085       // Holds the indices of existing members in an interleaved load group.
6086       // An interleaved store group doesn't need this as it doesn't allow gaps.
6087       SmallVector<unsigned, 4> Indices;
6088       if (LI) {
6089         for (unsigned i = 0; i < InterleaveFactor; i++)
6090           if (Group->getMember(i))
6091             Indices.push_back(i);
6092       }
6093 
6094       // Calculate the cost of the whole interleaved group.
6095       unsigned Cost = TTI.getInterleavedMemoryOpCost(
6096           I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
6097           Group->getAlignment(), AS);
6098 
6099       if (Group->isReverse())
6100         Cost +=
6101             Group->getNumMembers() *
6102             TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
6103 
6104       // FIXME: The interleaved load group with a huge gap could be even more
6105       // expensive than scalar operations. Then we could ignore such group and
6106       // use scalar operations instead.
6107       return Cost;
6108     }
6109 
6110     // Scalarized loads/stores.
6111     int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
6112     bool UseGatherOrScatter =
6113         (ConsecutiveStride == 0) && isGatherOrScatterLegal(I, Ptr, Legal);
6114 
6115     bool Reverse = ConsecutiveStride < 0;
6116     const DataLayout &DL = I->getModule()->getDataLayout();
6117     unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
6118     unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
6119     if ((!ConsecutiveStride && !UseGatherOrScatter) ||
6120         ScalarAllocatedSize != VectorElementSize) {
6121       bool IsComplexComputation =
6122           isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
6123       unsigned Cost = 0;
6124       // The cost of extracting from the value vector and pointer vector.
6125       Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6126       for (unsigned i = 0; i < VF; ++i) {
6127         //  The cost of extracting the pointer operand.
6128         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
6129         // In case of STORE, the cost of ExtractElement from the vector.
6130         // In case of LOAD, the cost of InsertElement into the returned
6131         // vector.
6132         Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement
6133                                           : Instruction::InsertElement,
6134                                        VectorTy, i);
6135       }
6136 
6137       // The cost of the scalar loads/stores.
6138       Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
6139       Cost += VF *
6140               TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
6141                                   Alignment, AS);
6142       return Cost;
6143     }
6144 
6145     unsigned Cost = TTI.getAddressComputationCost(VectorTy);
6146     if (UseGatherOrScatter) {
6147       assert(ConsecutiveStride == 0 &&
6148              "Gather/Scatter are not used for consecutive stride");
6149       return Cost +
6150              TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
6151                                         Legal->isMaskRequired(I), Alignment);
6152     }
6153     // Wide load/stores.
6154     if (Legal->isMaskRequired(I))
6155       Cost +=
6156           TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
6157     else
6158       Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
6159 
6160     if (Reverse)
6161       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
6162     return Cost;
6163   }
6164   case Instruction::ZExt:
6165   case Instruction::SExt:
6166   case Instruction::FPToUI:
6167   case Instruction::FPToSI:
6168   case Instruction::FPExt:
6169   case Instruction::PtrToInt:
6170   case Instruction::IntToPtr:
6171   case Instruction::SIToFP:
6172   case Instruction::UIToFP:
6173   case Instruction::Trunc:
6174   case Instruction::FPTrunc:
6175   case Instruction::BitCast: {
6176     // We optimize the truncation of induction variable.
6177     // The cost of these is the same as the scalar operation.
6178     if (I->getOpcode() == Instruction::Trunc &&
6179         Legal->isInductionVariable(I->getOperand(0)))
6180       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
6181                                   I->getOperand(0)->getType());
6182 
6183     Type *SrcScalarTy = I->getOperand(0)->getType();
6184     Type *SrcVecTy = ToVectorTy(SrcScalarTy, VF);
6185     if (VF > 1 && MinBWs.count(I)) {
6186       // This cast is going to be shrunk. This may remove the cast or it might
6187       // turn it into slightly different cast. For example, if MinBW == 16,
6188       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
6189       //
6190       // Calculate the modified src and dest types.
6191       Type *MinVecTy = VectorTy;
6192       if (I->getOpcode() == Instruction::Trunc) {
6193         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
6194         VectorTy =
6195             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
6196       } else if (I->getOpcode() == Instruction::ZExt ||
6197                  I->getOpcode() == Instruction::SExt) {
6198         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
6199         VectorTy =
6200             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
6201       }
6202     }
6203 
6204     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
6205   }
6206   case Instruction::Call: {
6207     bool NeedToScalarize;
6208     CallInst *CI = cast<CallInst>(I);
6209     unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
6210     if (getVectorIntrinsicIDForCall(CI, TLI))
6211       return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
6212     return CallCost;
6213   }
6214   default: {
6215     // We are scalarizing the instruction. Return the cost of the scalar
6216     // instruction, plus the cost of insert and extract into vector
6217     // elements, times the vector width.
6218     unsigned Cost = 0;
6219 
6220     if (!RetTy->isVoidTy() && VF != 1) {
6221       unsigned InsCost =
6222           TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy);
6223       unsigned ExtCost =
6224           TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy);
6225 
6226       // The cost of inserting the results plus extracting each one of the
6227       // operands.
6228       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
6229     }
6230 
6231     // The cost of executing VF copies of the scalar instruction. This opcode
6232     // is unknown. Assume that it is the same as 'mul'.
6233     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
6234     return Cost;
6235   }
6236   } // end of switch.
6237 }
6238 
6239 char LoopVectorize::ID = 0;
6240 static const char lv_name[] = "Loop Vectorization";
6241 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
6242 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
6243 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
6244 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
6245 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
6246 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
6247 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
6248 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
6249 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
6250 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
6251 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
6252 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
6253 INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
6254 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
6255 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
6256 
6257 namespace llvm {
6258 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
6259   return new LoopVectorize(NoUnrolling, AlwaysVectorize);
6260 }
6261 }
6262 
6263 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
6264   // Check for a store.
6265   if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
6266     return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
6267 
6268   // Check for a load.
6269   if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
6270     return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
6271 
6272   return false;
6273 }
6274 
6275 void LoopVectorizationCostModel::collectValuesToIgnore() {
6276   // Ignore ephemeral values.
6277   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
6278 
6279   // Ignore type-promoting instructions we identified during reduction
6280   // detection.
6281   for (auto &Reduction : *Legal->getReductionVars()) {
6282     RecurrenceDescriptor &RedDes = Reduction.second;
6283     SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
6284     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
6285   }
6286 
6287   // Ignore induction phis that are only used in either GetElementPtr or ICmp
6288   // instruction to exit loop. Induction variables usually have large types and
6289   // can have big impact when estimating register usage.
6290   // This is for when VF > 1.
6291   for (auto &Induction : *Legal->getInductionVars()) {
6292     auto *PN = Induction.first;
6293     auto *UpdateV = PN->getIncomingValueForBlock(TheLoop->getLoopLatch());
6294 
6295     // Check that the PHI is only used by the induction increment (UpdateV) or
6296     // by GEPs. Then check that UpdateV is only used by a compare instruction or
6297     // the loop header PHI.
6298     // FIXME: Need precise def-use analysis to determine if this instruction
6299     // variable will be vectorized.
6300     if (std::all_of(PN->user_begin(), PN->user_end(),
6301                     [&](const User *U) -> bool {
6302                       return U == UpdateV || isa<GetElementPtrInst>(U);
6303                     }) &&
6304         std::all_of(UpdateV->user_begin(), UpdateV->user_end(),
6305                     [&](const User *U) -> bool {
6306                       return U == PN || isa<ICmpInst>(U);
6307                     })) {
6308       VecValuesToIgnore.insert(PN);
6309       VecValuesToIgnore.insert(UpdateV);
6310     }
6311   }
6312 
6313   // Ignore instructions that will not be vectorized.
6314   // This is for when VF > 1.
6315   for (auto bb = TheLoop->block_begin(), be = TheLoop->block_end(); bb != be;
6316        ++bb) {
6317     for (auto &Inst : **bb) {
6318       switch (Inst.getOpcode())
6319       case Instruction::GetElementPtr: {
6320         // Ignore GEP if its last operand is an induction variable so that it is
6321         // a consecutive load/store and won't be vectorized as scatter/gather
6322         // pattern.
6323 
6324         GetElementPtrInst *Gep = cast<GetElementPtrInst>(&Inst);
6325         unsigned NumOperands = Gep->getNumOperands();
6326         unsigned InductionOperand = getGEPInductionOperand(Gep);
6327         bool GepToIgnore = true;
6328 
6329         // Check that all of the gep indices are uniform except for the
6330         // induction operand.
6331         for (unsigned i = 0; i != NumOperands; ++i) {
6332           if (i != InductionOperand &&
6333               !PSE.getSE()->isLoopInvariant(PSE.getSCEV(Gep->getOperand(i)),
6334                                             TheLoop)) {
6335             GepToIgnore = false;
6336             break;
6337           }
6338         }
6339 
6340         if (GepToIgnore)
6341           VecValuesToIgnore.insert(&Inst);
6342         break;
6343       }
6344     }
6345   }
6346 }
6347 
6348 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
6349                                              bool IfPredicateStore) {
6350   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
6351   // Holds vector parameters or scalars, in case of uniform vals.
6352   SmallVector<VectorParts, 4> Params;
6353 
6354   setDebugLocFromInst(Builder, Instr);
6355 
6356   // Find all of the vectorized parameters.
6357   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
6358     Value *SrcOp = Instr->getOperand(op);
6359 
6360     // If we are accessing the old induction variable, use the new one.
6361     if (SrcOp == OldInduction) {
6362       Params.push_back(getVectorValue(SrcOp));
6363       continue;
6364     }
6365 
6366     // Try using previously calculated values.
6367     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
6368 
6369     // If the src is an instruction that appeared earlier in the basic block
6370     // then it should already be vectorized.
6371     if (SrcInst && OrigLoop->contains(SrcInst)) {
6372       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
6373       // The parameter is a vector value from earlier.
6374       Params.push_back(WidenMap.get(SrcInst));
6375     } else {
6376       // The parameter is a scalar from outside the loop. Maybe even a constant.
6377       VectorParts Scalars;
6378       Scalars.append(UF, SrcOp);
6379       Params.push_back(Scalars);
6380     }
6381   }
6382 
6383   assert(Params.size() == Instr->getNumOperands() &&
6384          "Invalid number of operands");
6385 
6386   // Does this instruction return a value ?
6387   bool IsVoidRetTy = Instr->getType()->isVoidTy();
6388 
6389   Value *UndefVec = IsVoidRetTy ? nullptr : UndefValue::get(Instr->getType());
6390   // Create a new entry in the WidenMap and initialize it to Undef or Null.
6391   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
6392 
6393   VectorParts Cond;
6394   if (IfPredicateStore) {
6395     assert(Instr->getParent()->getSinglePredecessor() &&
6396            "Only support single predecessor blocks");
6397     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
6398                           Instr->getParent());
6399   }
6400 
6401   // For each vector unroll 'part':
6402   for (unsigned Part = 0; Part < UF; ++Part) {
6403     // For each scalar that we create:
6404 
6405     // Start an "if (pred) a[i] = ..." block.
6406     Value *Cmp = nullptr;
6407     if (IfPredicateStore) {
6408       if (Cond[Part]->getType()->isVectorTy())
6409         Cond[Part] =
6410             Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
6411       Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
6412                                ConstantInt::get(Cond[Part]->getType(), 1));
6413     }
6414 
6415     Instruction *Cloned = Instr->clone();
6416     if (!IsVoidRetTy)
6417       Cloned->setName(Instr->getName() + ".cloned");
6418     // Replace the operands of the cloned instructions with extracted scalars.
6419     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
6420       Value *Op = Params[op][Part];
6421       Cloned->setOperand(op, Op);
6422     }
6423 
6424     // Place the cloned scalar in the new loop.
6425     Builder.Insert(Cloned);
6426 
6427     // If we just cloned a new assumption, add it the assumption cache.
6428     if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
6429       if (II->getIntrinsicID() == Intrinsic::assume)
6430         AC->registerAssumption(II);
6431 
6432     // If the original scalar returns a value we need to place it in a vector
6433     // so that future users will be able to use it.
6434     if (!IsVoidRetTy)
6435       VecResults[Part] = Cloned;
6436 
6437     // End if-block.
6438     if (IfPredicateStore)
6439       PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned), Cmp));
6440   }
6441 }
6442 
6443 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
6444   StoreInst *SI = dyn_cast<StoreInst>(Instr);
6445   bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
6446 
6447   return scalarizeInstruction(Instr, IfPredicateStore);
6448 }
6449 
6450 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
6451 
6452 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
6453 
6454 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx,
6455                                         const SCEV *StepSCEV) {
6456   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
6457   SCEVExpander Exp(*PSE.getSE(), DL, "induction");
6458   Value *StepValue = Exp.expandCodeFor(StepSCEV, StepSCEV->getType(),
6459                                        &*Builder.GetInsertPoint());
6460   return getStepVector(Val, StartIdx, StepValue);
6461 }
6462 
6463 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
6464   // When unrolling and the VF is 1, we only need to add a simple scalar.
6465   Type *ITy = Val->getType();
6466   assert(!ITy->isVectorTy() && "Val must be a scalar");
6467   Constant *C = ConstantInt::get(ITy, StartIdx);
6468   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
6469 }
6470