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