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