LLVM API Documentation

LoopVectorize.cpp
Go to the documentation of this file.
00001 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
00011 // and generates target-independent LLVM-IR.
00012 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
00013 // of instructions in order to estimate the profitability of vectorization.
00014 //
00015 // The loop vectorizer combines consecutive loop iterations into a single
00016 // 'wide' iteration. After this transformation the index is incremented
00017 // by the SIMD vector width, and not by one.
00018 //
00019 // This pass has three parts:
00020 // 1. The main loop pass that drives the different parts.
00021 // 2. LoopVectorizationLegality - A unit that checks for the legality
00022 //    of the vectorization.
00023 // 3. InnerLoopVectorizer - A unit that performs the actual
00024 //    widening of instructions.
00025 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
00026 //    of vectorization. It decides on the optimal vector width, which
00027 //    can be one, if vectorization is not profitable.
00028 //
00029 //===----------------------------------------------------------------------===//
00030 //
00031 // The reduction-variable vectorization is based on the paper:
00032 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
00033 //
00034 // Variable uniformity checks are inspired by:
00035 //  Karrenberg, R. and Hack, S. Whole Function Vectorization.
00036 //
00037 // Other ideas/concepts are from:
00038 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
00039 //
00040 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
00041 //  Vectorizing Compilers.
00042 //
00043 //===----------------------------------------------------------------------===//
00044 
00045 #include "llvm/Transforms/Vectorize.h"
00046 #include "llvm/ADT/DenseMap.h"
00047 #include "llvm/ADT/EquivalenceClasses.h"
00048 #include "llvm/ADT/Hashing.h"
00049 #include "llvm/ADT/MapVector.h"
00050 #include "llvm/ADT/SetVector.h"
00051 #include "llvm/ADT/SmallPtrSet.h"
00052 #include "llvm/ADT/SmallSet.h"
00053 #include "llvm/ADT/SmallVector.h"
00054 #include "llvm/ADT/Statistic.h"
00055 #include "llvm/ADT/StringExtras.h"
00056 #include "llvm/Analysis/AliasAnalysis.h"
00057 #include "llvm/Analysis/AliasSetTracker.h"
00058 #include "llvm/Analysis/AssumptionTracker.h"
00059 #include "llvm/Analysis/BlockFrequencyInfo.h"
00060 #include "llvm/Analysis/CodeMetrics.h"
00061 #include "llvm/Analysis/LoopInfo.h"
00062 #include "llvm/Analysis/LoopIterator.h"
00063 #include "llvm/Analysis/LoopPass.h"
00064 #include "llvm/Analysis/ScalarEvolution.h"
00065 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00066 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
00067 #include "llvm/Analysis/TargetTransformInfo.h"
00068 #include "llvm/Analysis/ValueTracking.h"
00069 #include "llvm/IR/Constants.h"
00070 #include "llvm/IR/DataLayout.h"
00071 #include "llvm/IR/DebugInfo.h"
00072 #include "llvm/IR/DerivedTypes.h"
00073 #include "llvm/IR/DiagnosticInfo.h"
00074 #include "llvm/IR/Dominators.h"
00075 #include "llvm/IR/Function.h"
00076 #include "llvm/IR/IRBuilder.h"
00077 #include "llvm/IR/Instructions.h"
00078 #include "llvm/IR/IntrinsicInst.h"
00079 #include "llvm/IR/LLVMContext.h"
00080 #include "llvm/IR/Module.h"
00081 #include "llvm/IR/PatternMatch.h"
00082 #include "llvm/IR/Type.h"
00083 #include "llvm/IR/Value.h"
00084 #include "llvm/IR/ValueHandle.h"
00085 #include "llvm/IR/Verifier.h"
00086 #include "llvm/Pass.h"
00087 #include "llvm/Support/BranchProbability.h"
00088 #include "llvm/Support/CommandLine.h"
00089 #include "llvm/Support/Debug.h"
00090 #include "llvm/Support/raw_ostream.h"
00091 #include "llvm/Transforms/Scalar.h"
00092 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00093 #include "llvm/Transforms/Utils/Local.h"
00094 #include "llvm/Transforms/Utils/VectorUtils.h"
00095 #include <algorithm>
00096 #include <map>
00097 #include <tuple>
00098 
00099 using namespace llvm;
00100 using namespace llvm::PatternMatch;
00101 
00102 #define LV_NAME "loop-vectorize"
00103 #define DEBUG_TYPE LV_NAME
00104 
00105 STATISTIC(LoopsVectorized, "Number of loops vectorized");
00106 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
00107 
00108 static cl::opt<unsigned>
00109 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
00110                     cl::desc("Sets the SIMD width. Zero is autoselect."));
00111 
00112 static cl::opt<unsigned>
00113 VectorizationInterleave("force-vector-interleave", cl::init(0), cl::Hidden,
00114                     cl::desc("Sets the vectorization interleave count. "
00115                              "Zero is autoselect."));
00116 
00117 static cl::opt<bool>
00118 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
00119                    cl::desc("Enable if-conversion during vectorization."));
00120 
00121 /// We don't vectorize loops with a known constant trip count below this number.
00122 static cl::opt<unsigned>
00123 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
00124                              cl::Hidden,
00125                              cl::desc("Don't vectorize loops with a constant "
00126                                       "trip count that is smaller than this "
00127                                       "value."));
00128 
00129 /// This enables versioning on the strides of symbolically striding memory
00130 /// accesses in code like the following.
00131 ///   for (i = 0; i < N; ++i)
00132 ///     A[i * Stride1] += B[i * Stride2] ...
00133 ///
00134 /// Will be roughly translated to
00135 ///    if (Stride1 == 1 && Stride2 == 1) {
00136 ///      for (i = 0; i < N; i+=4)
00137 ///       A[i:i+3] += ...
00138 ///    } else
00139 ///      ...
00140 static cl::opt<bool> EnableMemAccessVersioning(
00141     "enable-mem-access-versioning", cl::init(true), cl::Hidden,
00142     cl::desc("Enable symblic stride memory access versioning"));
00143 
00144 /// We don't unroll loops with a known constant trip count below this number.
00145 static const unsigned TinyTripCountUnrollThreshold = 128;
00146 
00147 /// When performing memory disambiguation checks at runtime do not make more
00148 /// than this number of comparisons.
00149 static const unsigned RuntimeMemoryCheckThreshold = 8;
00150 
00151 /// Maximum simd width.
00152 static const unsigned MaxVectorWidth = 64;
00153 
00154 static cl::opt<unsigned> ForceTargetNumScalarRegs(
00155     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
00156     cl::desc("A flag that overrides the target's number of scalar registers."));
00157 
00158 static cl::opt<unsigned> ForceTargetNumVectorRegs(
00159     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
00160     cl::desc("A flag that overrides the target's number of vector registers."));
00161 
00162 /// Maximum vectorization interleave count.
00163 static const unsigned MaxInterleaveFactor = 16;
00164 
00165 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
00166     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
00167     cl::desc("A flag that overrides the target's max interleave factor for "
00168              "scalar loops."));
00169 
00170 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
00171     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
00172     cl::desc("A flag that overrides the target's max interleave factor for "
00173              "vectorized loops."));
00174 
00175 static cl::opt<unsigned> ForceTargetInstructionCost(
00176     "force-target-instruction-cost", cl::init(0), cl::Hidden,
00177     cl::desc("A flag that overrides the target's expected cost for "
00178              "an instruction to a single constant value. Mostly "
00179              "useful for getting consistent testing."));
00180 
00181 static cl::opt<unsigned> SmallLoopCost(
00182     "small-loop-cost", cl::init(20), cl::Hidden,
00183     cl::desc("The cost of a loop that is considered 'small' by the unroller."));
00184 
00185 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
00186     "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
00187     cl::desc("Enable the use of the block frequency analysis to access PGO "
00188              "heuristics minimizing code growth in cold regions and being more "
00189              "aggressive in hot regions."));
00190 
00191 // Runtime unroll loops for load/store throughput.
00192 static cl::opt<bool> EnableLoadStoreRuntimeUnroll(
00193     "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden,
00194     cl::desc("Enable runtime unrolling until load/store ports are saturated"));
00195 
00196 /// The number of stores in a loop that are allowed to need predication.
00197 static cl::opt<unsigned> NumberOfStoresToPredicate(
00198     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
00199     cl::desc("Max number of stores to be predicated behind an if."));
00200 
00201 static cl::opt<bool> EnableIndVarRegisterHeur(
00202     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
00203     cl::desc("Count the induction variable only once when unrolling"));
00204 
00205 static cl::opt<bool> EnableCondStoresVectorization(
00206     "enable-cond-stores-vec", cl::init(false), cl::Hidden,
00207     cl::desc("Enable if predication of stores during vectorization."));
00208 
00209 static cl::opt<unsigned> MaxNestedScalarReductionUF(
00210     "max-nested-scalar-reduction-unroll", cl::init(2), cl::Hidden,
00211     cl::desc("The maximum unroll factor to use when unrolling a scalar "
00212              "reduction in a nested loop."));
00213 
00214 namespace {
00215 
00216 // Forward declarations.
00217 class LoopVectorizationLegality;
00218 class LoopVectorizationCostModel;
00219 class LoopVectorizeHints;
00220 
00221 /// Optimization analysis message produced during vectorization. Messages inform
00222 /// the user why vectorization did not occur.
00223 class Report {
00224   std::string Message;
00225   raw_string_ostream Out;
00226   Instruction *Instr;
00227 
00228 public:
00229   Report(Instruction *I = nullptr) : Out(Message), Instr(I) {
00230     Out << "loop not vectorized: ";
00231   }
00232 
00233   template <typename A> Report &operator<<(const A &Value) {
00234     Out << Value;
00235     return *this;
00236   }
00237 
00238   Instruction *getInstr() { return Instr; }
00239 
00240   std::string &str() { return Out.str(); }
00241   operator Twine() { return Out.str(); }
00242 };
00243 
00244 /// InnerLoopVectorizer vectorizes loops which contain only one basic
00245 /// block to a specified vectorization factor (VF).
00246 /// This class performs the widening of scalars into vectors, or multiple
00247 /// scalars. This class also implements the following features:
00248 /// * It inserts an epilogue loop for handling loops that don't have iteration
00249 ///   counts that are known to be a multiple of the vectorization factor.
00250 /// * It handles the code generation for reduction variables.
00251 /// * Scalarization (implementation using scalars) of un-vectorizable
00252 ///   instructions.
00253 /// InnerLoopVectorizer does not perform any vectorization-legality
00254 /// checks, and relies on the caller to check for the different legality
00255 /// aspects. The InnerLoopVectorizer relies on the
00256 /// LoopVectorizationLegality class to provide information about the induction
00257 /// and reduction variables that were found to a given vectorization factor.
00258 class InnerLoopVectorizer {
00259 public:
00260   InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
00261                       DominatorTree *DT, const DataLayout *DL,
00262                       const TargetLibraryInfo *TLI, unsigned VecWidth,
00263                       unsigned UnrollFactor)
00264       : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
00265         VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()),
00266         Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor),
00267         Legal(nullptr) {}
00268 
00269   // Perform the actual loop widening (vectorization).
00270   void vectorize(LoopVectorizationLegality *L) {
00271     Legal = L;
00272     // Create a new empty loop. Unlink the old loop and connect the new one.
00273     createEmptyLoop();
00274     // Widen each instruction in the old loop to a new one in the new loop.
00275     // Use the Legality module to find the induction and reduction variables.
00276     vectorizeLoop();
00277     // Register the new loop and update the analysis passes.
00278     updateAnalysis();
00279   }
00280 
00281   virtual ~InnerLoopVectorizer() {}
00282 
00283 protected:
00284   /// A small list of PHINodes.
00285   typedef SmallVector<PHINode*, 4> PhiVector;
00286   /// When we unroll loops we have multiple vector values for each scalar.
00287   /// This data structure holds the unrolled and vectorized values that
00288   /// originated from one scalar instruction.
00289   typedef SmallVector<Value*, 2> VectorParts;
00290 
00291   // When we if-convert we need create edge masks. We have to cache values so
00292   // that we don't end up with exponential recursion/IR.
00293   typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
00294                    VectorParts> EdgeMaskCache;
00295 
00296   /// \brief Add code that checks at runtime if the accessed arrays overlap.
00297   ///
00298   /// Returns a pair of instructions where the first element is the first
00299   /// instruction generated in possibly a sequence of instructions and the
00300   /// second value is the final comparator value or NULL if no check is needed.
00301   std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
00302 
00303   /// \brief Add checks for strides that where assumed to be 1.
00304   ///
00305   /// Returns the last check instruction and the first check instruction in the
00306   /// pair as (first, last).
00307   std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
00308 
00309   /// Create an empty loop, based on the loop ranges of the old loop.
00310   void createEmptyLoop();
00311   /// Copy and widen the instructions from the old loop.
00312   virtual void vectorizeLoop();
00313 
00314   /// \brief The Loop exit block may have single value PHI nodes where the
00315   /// incoming value is 'Undef'. While vectorizing we only handled real values
00316   /// that were defined inside the loop. Here we fix the 'undef case'.
00317   /// See PR14725.
00318   void fixLCSSAPHIs();
00319 
00320   /// A helper function that computes the predicate of the block BB, assuming
00321   /// that the header block of the loop is set to True. It returns the *entry*
00322   /// mask for the block BB.
00323   VectorParts createBlockInMask(BasicBlock *BB);
00324   /// A helper function that computes the predicate of the edge between SRC
00325   /// and DST.
00326   VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
00327 
00328   /// A helper function to vectorize a single BB within the innermost loop.
00329   void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
00330 
00331   /// Vectorize a single PHINode in a block. This method handles the induction
00332   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
00333   /// arbitrary length vectors.
00334   void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
00335                            unsigned UF, unsigned VF, PhiVector *PV);
00336 
00337   /// Insert the new loop to the loop hierarchy and pass manager
00338   /// and update the analysis passes.
00339   void updateAnalysis();
00340 
00341   /// This instruction is un-vectorizable. Implement it as a sequence
00342   /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
00343   /// scalarized instruction behind an if block predicated on the control
00344   /// dependence of the instruction.
00345   virtual void scalarizeInstruction(Instruction *Instr,
00346                                     bool IfPredicateStore=false);
00347 
00348   /// Vectorize Load and Store instructions,
00349   virtual void vectorizeMemoryInstruction(Instruction *Instr);
00350 
00351   /// Create a broadcast instruction. This method generates a broadcast
00352   /// instruction (shuffle) for loop invariant values and for the induction
00353   /// value. If this is the induction variable then we extend it to N, N+1, ...
00354   /// this is needed because each iteration in the loop corresponds to a SIMD
00355   /// element.
00356   virtual Value *getBroadcastInstrs(Value *V);
00357 
00358   /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
00359   /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
00360   /// The sequence starts at StartIndex.
00361   virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
00362 
00363   /// When we go over instructions in the basic block we rely on previous
00364   /// values within the current basic block or on loop invariant values.
00365   /// When we widen (vectorize) values we place them in the map. If the values
00366   /// are not within the map, they have to be loop invariant, so we simply
00367   /// broadcast them into a vector.
00368   VectorParts &getVectorValue(Value *V);
00369 
00370   /// Generate a shuffle sequence that will reverse the vector Vec.
00371   virtual Value *reverseVector(Value *Vec);
00372 
00373   /// This is a helper class that holds the vectorizer state. It maps scalar
00374   /// instructions to vector instructions. When the code is 'unrolled' then
00375   /// then a single scalar value is mapped to multiple vector parts. The parts
00376   /// are stored in the VectorPart type.
00377   struct ValueMap {
00378     /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
00379     /// are mapped.
00380     ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
00381 
00382     /// \return True if 'Key' is saved in the Value Map.
00383     bool has(Value *Key) const { return MapStorage.count(Key); }
00384 
00385     /// Initializes a new entry in the map. Sets all of the vector parts to the
00386     /// save value in 'Val'.
00387     /// \return A reference to a vector with splat values.
00388     VectorParts &splat(Value *Key, Value *Val) {
00389       VectorParts &Entry = MapStorage[Key];
00390       Entry.assign(UF, Val);
00391       return Entry;
00392     }
00393 
00394     ///\return A reference to the value that is stored at 'Key'.
00395     VectorParts &get(Value *Key) {
00396       VectorParts &Entry = MapStorage[Key];
00397       if (Entry.empty())
00398         Entry.resize(UF);
00399       assert(Entry.size() == UF);
00400       return Entry;
00401     }
00402 
00403   private:
00404     /// The unroll factor. Each entry in the map stores this number of vector
00405     /// elements.
00406     unsigned UF;
00407 
00408     /// Map storage. We use std::map and not DenseMap because insertions to a
00409     /// dense map invalidates its iterators.
00410     std::map<Value *, VectorParts> MapStorage;
00411   };
00412 
00413   /// The original loop.
00414   Loop *OrigLoop;
00415   /// Scev analysis to use.
00416   ScalarEvolution *SE;
00417   /// Loop Info.
00418   LoopInfo *LI;
00419   /// Dominator Tree.
00420   DominatorTree *DT;
00421   /// Alias Analysis.
00422   AliasAnalysis *AA;
00423   /// Data Layout.
00424   const DataLayout *DL;
00425   /// Target Library Info.
00426   const TargetLibraryInfo *TLI;
00427 
00428   /// The vectorization SIMD factor to use. Each vector will have this many
00429   /// vector elements.
00430   unsigned VF;
00431 
00432 protected:
00433   /// The vectorization unroll factor to use. Each scalar is vectorized to this
00434   /// many different vector instructions.
00435   unsigned UF;
00436 
00437   /// The builder that we use
00438   IRBuilder<> Builder;
00439 
00440   // --- Vectorization state ---
00441 
00442   /// The vector-loop preheader.
00443   BasicBlock *LoopVectorPreHeader;
00444   /// The scalar-loop preheader.
00445   BasicBlock *LoopScalarPreHeader;
00446   /// Middle Block between the vector and the scalar.
00447   BasicBlock *LoopMiddleBlock;
00448   ///The ExitBlock of the scalar loop.
00449   BasicBlock *LoopExitBlock;
00450   ///The vector loop body.
00451   SmallVector<BasicBlock *, 4> LoopVectorBody;
00452   ///The scalar loop body.
00453   BasicBlock *LoopScalarBody;
00454   /// A list of all bypass blocks. The first block is the entry of the loop.
00455   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
00456 
00457   /// The new Induction variable which was added to the new block.
00458   PHINode *Induction;
00459   /// The induction variable of the old basic block.
00460   PHINode *OldInduction;
00461   /// Holds the extended (to the widest induction type) start index.
00462   Value *ExtendedIdx;
00463   /// Maps scalars to widened vectors.
00464   ValueMap WidenMap;
00465   EdgeMaskCache MaskCache;
00466 
00467   LoopVectorizationLegality *Legal;
00468 };
00469 
00470 class InnerLoopUnroller : public InnerLoopVectorizer {
00471 public:
00472   InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
00473                     DominatorTree *DT, const DataLayout *DL,
00474                     const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
00475     InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
00476 
00477 private:
00478   void scalarizeInstruction(Instruction *Instr,
00479                             bool IfPredicateStore = false) override;
00480   void vectorizeMemoryInstruction(Instruction *Instr) override;
00481   Value *getBroadcastInstrs(Value *V) override;
00482   Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate) override;
00483   Value *reverseVector(Value *Vec) override;
00484 };
00485 
00486 /// \brief Look for a meaningful debug location on the instruction or it's
00487 /// operands.
00488 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
00489   if (!I)
00490     return I;
00491 
00492   DebugLoc Empty;
00493   if (I->getDebugLoc() != Empty)
00494     return I;
00495 
00496   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
00497     if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
00498       if (OpInst->getDebugLoc() != Empty)
00499         return OpInst;
00500   }
00501 
00502   return I;
00503 }
00504 
00505 /// \brief Set the debug location in the builder using the debug location in the
00506 /// instruction.
00507 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
00508   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
00509     B.SetCurrentDebugLocation(Inst->getDebugLoc());
00510   else
00511     B.SetCurrentDebugLocation(DebugLoc());
00512 }
00513 
00514 #ifndef NDEBUG
00515 /// \return string containing a file name and a line # for the given loop.
00516 static std::string getDebugLocString(const Loop *L) {
00517   std::string Result;
00518   if (L) {
00519     raw_string_ostream OS(Result);
00520     const DebugLoc LoopDbgLoc = L->getStartLoc();
00521     if (!LoopDbgLoc.isUnknown())
00522       LoopDbgLoc.print(L->getHeader()->getContext(), OS);
00523     else
00524       // Just print the module name.
00525       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
00526     OS.flush();
00527   }
00528   return Result;
00529 }
00530 #endif
00531 
00532 /// \brief Propagate known metadata from one instruction to another.
00533 static void propagateMetadata(Instruction *To, const Instruction *From) {
00534   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
00535   From->getAllMetadataOtherThanDebugLoc(Metadata);
00536 
00537   for (auto M : Metadata) {
00538     unsigned Kind = M.first;
00539 
00540     // These are safe to transfer (this is safe for TBAA, even when we
00541     // if-convert, because should that metadata have had a control dependency
00542     // on the condition, and thus actually aliased with some other
00543     // non-speculated memory access when the condition was false, this would be
00544     // caught by the runtime overlap checks).
00545     if (Kind != LLVMContext::MD_tbaa &&
00546         Kind != LLVMContext::MD_alias_scope &&
00547         Kind != LLVMContext::MD_noalias &&
00548         Kind != LLVMContext::MD_fpmath)
00549       continue;
00550 
00551     To->setMetadata(Kind, M.second);
00552   }
00553 }
00554 
00555 /// \brief Propagate known metadata from one instruction to a vector of others.
00556 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) {
00557   for (Value *V : To)
00558     if (Instruction *I = dyn_cast<Instruction>(V))
00559       propagateMetadata(I, From);
00560 }
00561 
00562 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
00563 /// to what vectorization factor.
00564 /// This class does not look at the profitability of vectorization, only the
00565 /// legality. This class has two main kinds of checks:
00566 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
00567 ///   will change the order of memory accesses in a way that will change the
00568 ///   correctness of the program.
00569 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
00570 /// checks for a number of different conditions, such as the availability of a
00571 /// single induction variable, that all types are supported and vectorize-able,
00572 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
00573 /// This class is also used by InnerLoopVectorizer for identifying
00574 /// induction variable and the different reduction variables.
00575 class LoopVectorizationLegality {
00576 public:
00577   unsigned NumLoads;
00578   unsigned NumStores;
00579   unsigned NumPredStores;
00580 
00581   LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
00582                             DominatorTree *DT, TargetLibraryInfo *TLI,
00583                             AliasAnalysis *AA, Function *F)
00584       : NumLoads(0), NumStores(0), NumPredStores(0), TheLoop(L), SE(SE), DL(DL),
00585         DT(DT), TLI(TLI), AA(AA), TheFunction(F), Induction(nullptr),
00586         WidestIndTy(nullptr), HasFunNoNaNAttr(false), MaxSafeDepDistBytes(-1U) {
00587   }
00588 
00589   /// This enum represents the kinds of reductions that we support.
00590   enum ReductionKind {
00591     RK_NoReduction, ///< Not a reduction.
00592     RK_IntegerAdd,  ///< Sum of integers.
00593     RK_IntegerMult, ///< Product of integers.
00594     RK_IntegerOr,   ///< Bitwise or logical OR of numbers.
00595     RK_IntegerAnd,  ///< Bitwise or logical AND of numbers.
00596     RK_IntegerXor,  ///< Bitwise or logical XOR of numbers.
00597     RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
00598     RK_FloatAdd,    ///< Sum of floats.
00599     RK_FloatMult,   ///< Product of floats.
00600     RK_FloatMinMax  ///< Min/max implemented in terms of select(cmp()).
00601   };
00602 
00603   /// This enum represents the kinds of inductions that we support.
00604   enum InductionKind {
00605     IK_NoInduction,         ///< Not an induction variable.
00606     IK_IntInduction,        ///< Integer induction variable. Step = 1.
00607     IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
00608     IK_PtrInduction,        ///< Pointer induction var. Step = sizeof(elem).
00609     IK_ReversePtrInduction  ///< Reverse ptr indvar. Step = - sizeof(elem).
00610   };
00611 
00612   // This enum represents the kind of minmax reduction.
00613   enum MinMaxReductionKind {
00614     MRK_Invalid,
00615     MRK_UIntMin,
00616     MRK_UIntMax,
00617     MRK_SIntMin,
00618     MRK_SIntMax,
00619     MRK_FloatMin,
00620     MRK_FloatMax
00621   };
00622 
00623   /// This struct holds information about reduction variables.
00624   struct ReductionDescriptor {
00625     ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr),
00626       Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
00627 
00628     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
00629                         MinMaxReductionKind MK)
00630         : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
00631 
00632     // The starting value of the reduction.
00633     // It does not have to be zero!
00634     TrackingVH<Value> StartValue;
00635     // The instruction who's value is used outside the loop.
00636     Instruction *LoopExitInstr;
00637     // The kind of the reduction.
00638     ReductionKind Kind;
00639     // If this a min/max reduction the kind of reduction.
00640     MinMaxReductionKind MinMaxKind;
00641   };
00642 
00643   /// This POD struct holds information about a potential reduction operation.
00644   struct ReductionInstDesc {
00645     ReductionInstDesc(bool IsRedux, Instruction *I) :
00646       IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
00647 
00648     ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
00649       IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
00650 
00651     // Is this instruction a reduction candidate.
00652     bool IsReduction;
00653     // The last instruction in a min/max pattern (select of the select(icmp())
00654     // pattern), or the current reduction instruction otherwise.
00655     Instruction *PatternLastInst;
00656     // If this is a min/max pattern the comparison predicate.
00657     MinMaxReductionKind MinMaxKind;
00658   };
00659 
00660   /// This struct holds information about the memory runtime legality
00661   /// check that a group of pointers do not overlap.
00662   struct RuntimePointerCheck {
00663     RuntimePointerCheck() : Need(false) {}
00664 
00665     /// Reset the state of the pointer runtime information.
00666     void reset() {
00667       Need = false;
00668       Pointers.clear();
00669       Starts.clear();
00670       Ends.clear();
00671       IsWritePtr.clear();
00672       DependencySetId.clear();
00673       AliasSetId.clear();
00674     }
00675 
00676     /// Insert a pointer and calculate the start and end SCEVs.
00677     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
00678                 unsigned DepSetId, unsigned ASId, ValueToValueMap &Strides);
00679 
00680     /// This flag indicates if we need to add the runtime check.
00681     bool Need;
00682     /// Holds the pointers that we need to check.
00683     SmallVector<TrackingVH<Value>, 2> Pointers;
00684     /// Holds the pointer value at the beginning of the loop.
00685     SmallVector<const SCEV*, 2> Starts;
00686     /// Holds the pointer value at the end of the loop.
00687     SmallVector<const SCEV*, 2> Ends;
00688     /// Holds the information if this pointer is used for writing to memory.
00689     SmallVector<bool, 2> IsWritePtr;
00690     /// Holds the id of the set of pointers that could be dependent because of a
00691     /// shared underlying object.
00692     SmallVector<unsigned, 2> DependencySetId;
00693     /// Holds the id of the disjoint alias set to which this pointer belongs.
00694     SmallVector<unsigned, 2> AliasSetId;
00695   };
00696 
00697   /// A struct for saving information about induction variables.
00698   struct InductionInfo {
00699     InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
00700     InductionInfo() : StartValue(nullptr), IK(IK_NoInduction) {}
00701     /// Start value.
00702     TrackingVH<Value> StartValue;
00703     /// Induction kind.
00704     InductionKind IK;
00705   };
00706 
00707   /// ReductionList contains the reduction descriptors for all
00708   /// of the reductions that were found in the loop.
00709   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
00710 
00711   /// InductionList saves induction variables and maps them to the
00712   /// induction descriptor.
00713   typedef MapVector<PHINode*, InductionInfo> InductionList;
00714 
00715   /// Returns true if it is legal to vectorize this loop.
00716   /// This does not mean that it is profitable to vectorize this
00717   /// loop, only that it is legal to do so.
00718   bool canVectorize();
00719 
00720   /// Returns the Induction variable.
00721   PHINode *getInduction() { return Induction; }
00722 
00723   /// Returns the reduction variables found in the loop.
00724   ReductionList *getReductionVars() { return &Reductions; }
00725 
00726   /// Returns the induction variables found in the loop.
00727   InductionList *getInductionVars() { return &Inductions; }
00728 
00729   /// Returns the widest induction type.
00730   Type *getWidestInductionType() { return WidestIndTy; }
00731 
00732   /// Returns True if V is an induction variable in this loop.
00733   bool isInductionVariable(const Value *V);
00734 
00735   /// Return true if the block BB needs to be predicated in order for the loop
00736   /// to be vectorized.
00737   bool blockNeedsPredication(BasicBlock *BB);
00738 
00739   /// Check if this  pointer is consecutive when vectorizing. This happens
00740   /// when the last index of the GEP is the induction variable, or that the
00741   /// pointer itself is an induction variable.
00742   /// This check allows us to vectorize A[idx] into a wide load/store.
00743   /// Returns:
00744   /// 0 - Stride is unknown or non-consecutive.
00745   /// 1 - Address is consecutive.
00746   /// -1 - Address is consecutive, and decreasing.
00747   int isConsecutivePtr(Value *Ptr);
00748 
00749   /// Returns true if the value V is uniform within the loop.
00750   bool isUniform(Value *V);
00751 
00752   /// Returns true if this instruction will remain scalar after vectorization.
00753   bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
00754 
00755   /// Returns the information that we collected about runtime memory check.
00756   RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
00757 
00758   /// This function returns the identity element (or neutral element) for
00759   /// the operation K.
00760   static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
00761 
00762   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
00763 
00764   bool hasStride(Value *V) { return StrideSet.count(V); }
00765   bool mustCheckStrides() { return !StrideSet.empty(); }
00766   SmallPtrSet<Value *, 8>::iterator strides_begin() {
00767     return StrideSet.begin();
00768   }
00769   SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
00770 
00771 private:
00772   /// Check if a single basic block loop is vectorizable.
00773   /// At this point we know that this is a loop with a constant trip count
00774   /// and we only need to check individual instructions.
00775   bool canVectorizeInstrs();
00776 
00777   /// When we vectorize loops we may change the order in which
00778   /// we read and write from memory. This method checks if it is
00779   /// legal to vectorize the code, considering only memory constrains.
00780   /// Returns true if the loop is vectorizable
00781   bool canVectorizeMemory();
00782 
00783   /// Return true if we can vectorize this loop using the IF-conversion
00784   /// transformation.
00785   bool canVectorizeWithIfConvert();
00786 
00787   /// Collect the variables that need to stay uniform after vectorization.
00788   void collectLoopUniforms();
00789 
00790   /// Return true if all of the instructions in the block can be speculatively
00791   /// executed. \p SafePtrs is a list of addresses that are known to be legal
00792   /// and we know that we can read from them without segfault.
00793   bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
00794 
00795   /// Returns True, if 'Phi' is the kind of reduction variable for type
00796   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
00797   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
00798   /// Returns a struct describing if the instruction 'I' can be a reduction
00799   /// variable of type 'Kind'. If the reduction is a min/max pattern of
00800   /// select(icmp()) this function advances the instruction pointer 'I' from the
00801   /// compare instruction to the select instruction and stores this pointer in
00802   /// 'PatternLastInst' member of the returned struct.
00803   ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
00804                                      ReductionInstDesc &Desc);
00805   /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
00806   /// pattern corresponding to a min(X, Y) or max(X, Y).
00807   static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
00808                                                     ReductionInstDesc &Prev);
00809   /// Returns the induction kind of Phi. This function may return NoInduction
00810   /// if the PHI is not an induction variable.
00811   InductionKind isInductionVariable(PHINode *Phi);
00812 
00813   /// \brief Collect memory access with loop invariant strides.
00814   ///
00815   /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
00816   /// invariant.
00817   void collectStridedAcccess(Value *LoadOrStoreInst);
00818 
00819   /// Report an analysis message to assist the user in diagnosing loops that are
00820   /// not vectorized.
00821   void emitAnalysis(Report &Message) {
00822     DebugLoc DL = TheLoop->getStartLoc();
00823     if (Instruction *I = Message.getInstr())
00824       DL = I->getDebugLoc();
00825     emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
00826                                    *TheFunction, DL, Message.str());
00827   }
00828 
00829   /// The loop that we evaluate.
00830   Loop *TheLoop;
00831   /// Scev analysis.
00832   ScalarEvolution *SE;
00833   /// DataLayout analysis.
00834   const DataLayout *DL;
00835   /// Dominators.
00836   DominatorTree *DT;
00837   /// Target Library Info.
00838   TargetLibraryInfo *TLI;
00839   /// Alias analysis.
00840   AliasAnalysis *AA;
00841   /// Parent function
00842   Function *TheFunction;
00843 
00844   //  ---  vectorization state --- //
00845 
00846   /// Holds the integer induction variable. This is the counter of the
00847   /// loop.
00848   PHINode *Induction;
00849   /// Holds the reduction variables.
00850   ReductionList Reductions;
00851   /// Holds all of the induction variables that we found in the loop.
00852   /// Notice that inductions don't need to start at zero and that induction
00853   /// variables can be pointers.
00854   InductionList Inductions;
00855   /// Holds the widest induction type encountered.
00856   Type *WidestIndTy;
00857 
00858   /// Allowed outside users. This holds the reduction
00859   /// vars which can be accessed from outside the loop.
00860   SmallPtrSet<Value*, 4> AllowedExit;
00861   /// This set holds the variables which are known to be uniform after
00862   /// vectorization.
00863   SmallPtrSet<Instruction*, 4> Uniforms;
00864   /// We need to check that all of the pointers in this list are disjoint
00865   /// at runtime.
00866   RuntimePointerCheck PtrRtCheck;
00867   /// Can we assume the absence of NaNs.
00868   bool HasFunNoNaNAttr;
00869 
00870   unsigned MaxSafeDepDistBytes;
00871 
00872   ValueToValueMap Strides;
00873   SmallPtrSet<Value *, 8> StrideSet;
00874 };
00875 
00876 /// LoopVectorizationCostModel - estimates the expected speedups due to
00877 /// vectorization.
00878 /// In many cases vectorization is not profitable. This can happen because of
00879 /// a number of reasons. In this class we mainly attempt to predict the
00880 /// expected speedup/slowdowns due to the supported instruction set. We use the
00881 /// TargetTransformInfo to query the different backends for the cost of
00882 /// different operations.
00883 class LoopVectorizationCostModel {
00884 public:
00885   LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
00886                              LoopVectorizationLegality *Legal,
00887                              const TargetTransformInfo &TTI,
00888                              const DataLayout *DL, const TargetLibraryInfo *TLI,
00889                              AssumptionTracker *AT, const Function *F,
00890                              const LoopVectorizeHints *Hints)
00891       : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI),
00892         TheFunction(F), Hints(Hints) {
00893     CodeMetrics::collectEphemeralValues(L, AT, EphValues);
00894   }
00895 
00896   /// Information about vectorization costs
00897   struct VectorizationFactor {
00898     unsigned Width; // Vector width with best cost
00899     unsigned Cost; // Cost of the loop with that width
00900   };
00901   /// \return The most profitable vectorization factor and the cost of that VF.
00902   /// This method checks every power of two up to VF. If UserVF is not ZERO
00903   /// then this vectorization factor will be selected if vectorization is
00904   /// possible.
00905   VectorizationFactor selectVectorizationFactor(bool OptForSize);
00906 
00907   /// \return The size (in bits) of the widest type in the code that
00908   /// needs to be vectorized. We ignore values that remain scalar such as
00909   /// 64 bit loop indices.
00910   unsigned getWidestType();
00911 
00912   /// \return The most profitable unroll factor.
00913   /// If UserUF is non-zero then this method finds the best unroll-factor
00914   /// based on register pressure and other parameters.
00915   /// VF and LoopCost are the selected vectorization factor and the cost of the
00916   /// selected VF.
00917   unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost);
00918 
00919   /// \brief A struct that represents some properties of the register usage
00920   /// of a loop.
00921   struct RegisterUsage {
00922     /// Holds the number of loop invariant values that are used in the loop.
00923     unsigned LoopInvariantRegs;
00924     /// Holds the maximum number of concurrent live intervals in the loop.
00925     unsigned MaxLocalUsers;
00926     /// Holds the number of instructions in the loop.
00927     unsigned NumInstructions;
00928   };
00929 
00930   /// \return  information about the register usage of the loop.
00931   RegisterUsage calculateRegisterUsage();
00932 
00933 private:
00934   /// Returns the expected execution cost. The unit of the cost does
00935   /// not matter because we use the 'cost' units to compare different
00936   /// vector widths. The cost that is returned is *not* normalized by
00937   /// the factor width.
00938   unsigned expectedCost(unsigned VF);
00939 
00940   /// Returns the execution time cost of an instruction for a given vector
00941   /// width. Vector width of one means scalar.
00942   unsigned getInstructionCost(Instruction *I, unsigned VF);
00943 
00944   /// A helper function for converting Scalar types to vector types.
00945   /// If the incoming type is void, we return void. If the VF is 1, we return
00946   /// the scalar type.
00947   static Type* ToVectorTy(Type *Scalar, unsigned VF);
00948 
00949   /// Returns whether the instruction is a load or store and will be a emitted
00950   /// as a vector operation.
00951   bool isConsecutiveLoadOrStore(Instruction *I);
00952 
00953   /// Report an analysis message to assist the user in diagnosing loops that are
00954   /// not vectorized.
00955   void emitAnalysis(Report &Message) {
00956     DebugLoc DL = TheLoop->getStartLoc();
00957     if (Instruction *I = Message.getInstr())
00958       DL = I->getDebugLoc();
00959     emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE,
00960                                    *TheFunction, DL, Message.str());
00961   }
00962 
00963   /// Values used only by @llvm.assume calls.
00964   SmallPtrSet<const Value *, 32> EphValues;
00965 
00966   /// The loop that we evaluate.
00967   Loop *TheLoop;
00968   /// Scev analysis.
00969   ScalarEvolution *SE;
00970   /// Loop Info analysis.
00971   LoopInfo *LI;
00972   /// Vectorization legality.
00973   LoopVectorizationLegality *Legal;
00974   /// Vector target information.
00975   const TargetTransformInfo &TTI;
00976   /// Target data layout information.
00977   const DataLayout *DL;
00978   /// Target Library Info.
00979   const TargetLibraryInfo *TLI;
00980   const Function *TheFunction;
00981   // Loop Vectorize Hint.
00982   const LoopVectorizeHints *Hints;
00983 };
00984 
00985 /// Utility class for getting and setting loop vectorizer hints in the form
00986 /// of loop metadata.
00987 /// This class keeps a number of loop annotations locally (as member variables)
00988 /// and can, upon request, write them back as metadata on the loop. It will
00989 /// initially scan the loop for existing metadata, and will update the local
00990 /// values based on information in the loop.
00991 /// We cannot write all values to metadata, as the mere presence of some info,
00992 /// for example 'force', means a decision has been made. So, we need to be
00993 /// careful NOT to add them if the user hasn't specifically asked so.
00994 class LoopVectorizeHints {
00995   enum HintKind {
00996     HK_WIDTH,
00997     HK_UNROLL,
00998     HK_FORCE
00999   };
01000 
01001   /// Hint - associates name and validation with the hint value.
01002   struct Hint {
01003     const char * Name;
01004     unsigned Value; // This may have to change for non-numeric values.
01005     HintKind Kind;
01006 
01007     Hint(const char * Name, unsigned Value, HintKind Kind)
01008       : Name(Name), Value(Value), Kind(Kind) { }
01009 
01010     bool validate(unsigned Val) {
01011       switch (Kind) {
01012       case HK_WIDTH:
01013         return isPowerOf2_32(Val) && Val <= MaxVectorWidth;
01014       case HK_UNROLL:
01015         return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
01016       case HK_FORCE:
01017         return (Val <= 1);
01018       }
01019       return false;
01020     }
01021   };
01022 
01023   /// Vectorization width.
01024   Hint Width;
01025   /// Vectorization interleave factor.
01026   Hint Interleave;
01027   /// Vectorization forced
01028   Hint Force;
01029   /// Array to help iterating through all hints.
01030   Hint *Hints[3]; // avoiding initialisation due to MSVC2012
01031 
01032   /// Return the loop metadata prefix.
01033   static StringRef Prefix() { return "llvm.loop."; }
01034 
01035 public:
01036   enum ForceKind {
01037     FK_Undefined = -1, ///< Not selected.
01038     FK_Disabled = 0,   ///< Forcing disabled.
01039     FK_Enabled = 1,    ///< Forcing enabled.
01040   };
01041 
01042   LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
01043       : Width("vectorize.width", VectorizationFactor, HK_WIDTH),
01044         Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
01045         Force("vectorize.enable", FK_Undefined, HK_FORCE),
01046         TheLoop(L) {
01047     // FIXME: Move this up initialisation when MSVC requirement is 2013+
01048     Hints[0] = &Width;
01049     Hints[1] = &Interleave;
01050     Hints[2] = &Force;
01051 
01052     // Populate values with existing loop metadata.
01053     getHintsFromMetadata();
01054 
01055     // force-vector-interleave overrides DisableInterleaving.
01056     if (VectorizationInterleave.getNumOccurrences() > 0)
01057       Interleave.Value = VectorizationInterleave;
01058 
01059     DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
01060           << "LV: Interleaving disabled by the pass manager\n");
01061   }
01062 
01063   /// Mark the loop L as already vectorized by setting the width to 1.
01064   void setAlreadyVectorized() {
01065     Width.Value = Interleave.Value = 1;
01066     // FIXME: Change all lines below for this when we can use MSVC 2013+
01067     //writeHintsToMetadata({ Width, Unroll });
01068     std::vector<Hint> hints;
01069     hints.reserve(2);
01070     hints.emplace_back(Width);
01071     hints.emplace_back(Interleave);
01072     writeHintsToMetadata(std::move(hints));
01073   }
01074 
01075   /// Dumps all the hint information.
01076   std::string emitRemark() const {
01077     Report R;
01078     if (Force.Value == LoopVectorizeHints::FK_Disabled)
01079       R << "vectorization is explicitly disabled";
01080     else {
01081       R << "use -Rpass-analysis=loop-vectorize for more info";
01082       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
01083         R << " (Force=true";
01084         if (Width.Value != 0)
01085           R << ", Vector Width=" << Width.Value;
01086         if (Interleave.Value != 0)
01087           R << ", Interleave Count=" << Interleave.Value;
01088         R << ")";
01089       }
01090     }
01091 
01092     return R.str();
01093   }
01094 
01095   unsigned getWidth() const { return Width.Value; }
01096   unsigned getInterleave() const { return Interleave.Value; }
01097   enum ForceKind getForce() const { return (ForceKind)Force.Value; }
01098 
01099 private:
01100   /// Find hints specified in the loop metadata and update local values.
01101   void getHintsFromMetadata() {
01102     MDNode *LoopID = TheLoop->getLoopID();
01103     if (!LoopID)
01104       return;
01105 
01106     // First operand should refer to the loop id itself.
01107     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
01108     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
01109 
01110     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
01111       const MDString *S = nullptr;
01112       SmallVector<Value*, 4> Args;
01113 
01114       // The expected hint is either a MDString or a MDNode with the first
01115       // operand a MDString.
01116       if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
01117         if (!MD || MD->getNumOperands() == 0)
01118           continue;
01119         S = dyn_cast<MDString>(MD->getOperand(0));
01120         for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
01121           Args.push_back(MD->getOperand(i));
01122       } else {
01123         S = dyn_cast<MDString>(LoopID->getOperand(i));
01124         assert(Args.size() == 0 && "too many arguments for MDString");
01125       }
01126 
01127       if (!S)
01128         continue;
01129 
01130       // Check if the hint starts with the loop metadata prefix.
01131       StringRef Name = S->getString();
01132       if (Args.size() == 1)
01133         setHint(Name, Args[0]);
01134     }
01135   }
01136 
01137   /// Checks string hint with one operand and set value if valid.
01138   void setHint(StringRef Name, Value *Arg) {
01139     if (!Name.startswith(Prefix()))
01140       return;
01141     Name = Name.substr(Prefix().size(), StringRef::npos);
01142 
01143     const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
01144     if (!C) return;
01145     unsigned Val = C->getZExtValue();
01146 
01147     for (auto H : Hints) {
01148       if (Name == H->Name) {
01149         if (H->validate(Val))
01150           H->Value = Val;
01151         else
01152           DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
01153         break;
01154       }
01155     }
01156   }
01157 
01158   /// Create a new hint from name / value pair.
01159   MDNode *createHintMetadata(StringRef Name, unsigned V) const {
01160     LLVMContext &Context = TheLoop->getHeader()->getContext();
01161     SmallVector<Value*, 2> Vals;
01162     Vals.push_back(MDString::get(Context, Name));
01163     Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
01164     return MDNode::get(Context, Vals);
01165   }
01166 
01167   /// Matches metadata with hint name.
01168   bool matchesHintMetadataName(MDNode *Node, std::vector<Hint> &HintTypes) {
01169     MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
01170     if (!Name)
01171       return false;
01172 
01173     for (auto H : HintTypes)
01174       if (Name->getName().endswith(H.Name))
01175         return true;
01176     return false;
01177   }
01178 
01179   /// Sets current hints into loop metadata, keeping other values intact.
01180   void writeHintsToMetadata(std::vector<Hint> HintTypes) {
01181     if (HintTypes.size() == 0)
01182       return;
01183 
01184     // Reserve the first element to LoopID (see below).
01185     SmallVector<Value*, 4> Vals(1);
01186     // If the loop already has metadata, then ignore the existing operands.
01187     MDNode *LoopID = TheLoop->getLoopID();
01188     if (LoopID) {
01189       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
01190         MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
01191         // If node in update list, ignore old value.
01192         if (!matchesHintMetadataName(Node, HintTypes))
01193           Vals.push_back(Node);
01194       }
01195     }
01196 
01197     // Now, add the missing hints.
01198     for (auto H : HintTypes)
01199       Vals.push_back(
01200           createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
01201 
01202     // Replace current metadata node with new one.
01203     LLVMContext &Context = TheLoop->getHeader()->getContext();
01204     MDNode *NewLoopID = MDNode::get(Context, Vals);
01205     // Set operand 0 to refer to the loop id itself.
01206     NewLoopID->replaceOperandWith(0, NewLoopID);
01207 
01208     TheLoop->setLoopID(NewLoopID);
01209     if (LoopID)
01210       LoopID->replaceAllUsesWith(NewLoopID);
01211     LoopID = NewLoopID;
01212   }
01213 
01214   /// The loop these hints belong to.
01215   const Loop *TheLoop;
01216 };
01217 
01218 static void emitMissedWarning(Function *F, Loop *L,
01219                               const LoopVectorizeHints &LH) {
01220   emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F,
01221                                L->getStartLoc(), LH.emitRemark());
01222 
01223   if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
01224     if (LH.getWidth() != 1)
01225       emitLoopVectorizeWarning(
01226           F->getContext(), *F, L->getStartLoc(),
01227           "failed explicitly specified loop vectorization");
01228     else if (LH.getInterleave() != 1)
01229       emitLoopInterleaveWarning(
01230           F->getContext(), *F, L->getStartLoc(),
01231           "failed explicitly specified loop interleaving");
01232   }
01233 }
01234 
01235 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
01236   if (L.empty())
01237     return V.push_back(&L);
01238 
01239   for (Loop *InnerL : L)
01240     addInnerLoop(*InnerL, V);
01241 }
01242 
01243 /// The LoopVectorize Pass.
01244 struct LoopVectorize : public FunctionPass {
01245   /// Pass identification, replacement for typeid
01246   static char ID;
01247 
01248   explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
01249     : FunctionPass(ID),
01250       DisableUnrolling(NoUnrolling),
01251       AlwaysVectorize(AlwaysVectorize) {
01252     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
01253   }
01254 
01255   ScalarEvolution *SE;
01256   const DataLayout *DL;
01257   LoopInfo *LI;
01258   TargetTransformInfo *TTI;
01259   DominatorTree *DT;
01260   BlockFrequencyInfo *BFI;
01261   TargetLibraryInfo *TLI;
01262   AliasAnalysis *AA;
01263   AssumptionTracker *AT;
01264   bool DisableUnrolling;
01265   bool AlwaysVectorize;
01266 
01267   BlockFrequency ColdEntryFreq;
01268 
01269   bool runOnFunction(Function &F) override {
01270     SE = &getAnalysis<ScalarEvolution>();
01271     DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01272     DL = DLP ? &DLP->getDataLayout() : nullptr;
01273     LI = &getAnalysis<LoopInfo>();
01274     TTI = &getAnalysis<TargetTransformInfo>();
01275     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
01276     BFI = &getAnalysis<BlockFrequencyInfo>();
01277     TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
01278     AA = &getAnalysis<AliasAnalysis>();
01279     AT = &getAnalysis<AssumptionTracker>();
01280 
01281     // Compute some weights outside of the loop over the loops. Compute this
01282     // using a BranchProbability to re-use its scaling math.
01283     const BranchProbability ColdProb(1, 5); // 20%
01284     ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
01285 
01286     // If the target claims to have no vector registers don't attempt
01287     // vectorization.
01288     if (!TTI->getNumberOfRegisters(true))
01289       return false;
01290 
01291     if (!DL) {
01292       DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName()
01293                    << ": Missing data layout\n");
01294       return false;
01295     }
01296 
01297     // Build up a worklist of inner-loops to vectorize. This is necessary as
01298     // the act of vectorizing or partially unrolling a loop creates new loops
01299     // and can invalidate iterators across the loops.
01300     SmallVector<Loop *, 8> Worklist;
01301 
01302     for (Loop *L : *LI)
01303       addInnerLoop(*L, Worklist);
01304 
01305     LoopsAnalyzed += Worklist.size();
01306 
01307     // Now walk the identified inner loops.
01308     bool Changed = false;
01309     while (!Worklist.empty())
01310       Changed |= processLoop(Worklist.pop_back_val());
01311 
01312     // Process each loop nest in the function.
01313     return Changed;
01314   }
01315 
01316   bool processLoop(Loop *L) {
01317     assert(L->empty() && "Only process inner loops.");
01318 
01319 #ifndef NDEBUG
01320     const std::string DebugLocStr = getDebugLocString(L);
01321 #endif /* NDEBUG */
01322 
01323     DEBUG(dbgs() << "\nLV: Checking a loop in \""
01324                  << L->getHeader()->getParent()->getName() << "\" from "
01325                  << DebugLocStr << "\n");
01326 
01327     LoopVectorizeHints Hints(L, DisableUnrolling);
01328 
01329     DEBUG(dbgs() << "LV: Loop hints:"
01330                  << " force="
01331                  << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
01332                          ? "disabled"
01333                          : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
01334                                 ? "enabled"
01335                                 : "?")) << " width=" << Hints.getWidth()
01336                  << " unroll=" << Hints.getInterleave() << "\n");
01337 
01338     // Function containing loop
01339     Function *F = L->getHeader()->getParent();
01340 
01341     // Looking at the diagnostic output is the only way to determine if a loop
01342     // was vectorized (other than looking at the IR or machine code), so it
01343     // is important to generate an optimization remark for each loop. Most of
01344     // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
01345     // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
01346     // less verbose reporting vectorized loops and unvectorized loops that may
01347     // benefit from vectorization, respectively.
01348 
01349     if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) {
01350       DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
01351       emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
01352                                      L->getStartLoc(), Hints.emitRemark());
01353       return false;
01354     }
01355 
01356     if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) {
01357       DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
01358       emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F,
01359                                      L->getStartLoc(), Hints.emitRemark());
01360       return false;
01361     }
01362 
01363     if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) {
01364       DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
01365       emitOptimizationRemarkAnalysis(
01366           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
01367           "loop not vectorized: vector width and interleave count are "
01368           "explicitly set to 1");
01369       return false;
01370     }
01371 
01372     // Check the loop for a trip count threshold:
01373     // do not vectorize loops with a tiny trip count.
01374     const unsigned TC = SE->getSmallConstantTripCount(L);
01375     if (TC > 0u && TC < TinyTripCountVectorThreshold) {
01376       DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
01377                    << "This loop is not worth vectorizing.");
01378       if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
01379         DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
01380       else {
01381         DEBUG(dbgs() << "\n");
01382         emitOptimizationRemarkAnalysis(
01383             F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
01384             "vectorization is not beneficial and is not explicitly forced");
01385         return false;
01386       }
01387     }
01388 
01389     // Check if it is legal to vectorize the loop.
01390     LoopVectorizationLegality LVL(L, SE, DL, DT, TLI, AA, F);
01391     if (!LVL.canVectorize()) {
01392       DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
01393       emitMissedWarning(F, L, Hints);
01394       return false;
01395     }
01396 
01397     // Use the cost model.
01398     LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI, AT, F,
01399                                   &Hints);
01400 
01401     // Check the function attributes to find out if this function should be
01402     // optimized for size.
01403     bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
01404                       F->hasFnAttribute(Attribute::OptimizeForSize);
01405 
01406     // Compute the weighted frequency of this loop being executed and see if it
01407     // is less than 20% of the function entry baseline frequency. Note that we
01408     // always have a canonical loop here because we think we *can* vectoriez.
01409     // FIXME: This is hidden behind a flag due to pervasive problems with
01410     // exactly what block frequency models.
01411     if (LoopVectorizeWithBlockFrequency) {
01412       BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
01413       if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
01414           LoopEntryFreq < ColdEntryFreq)
01415         OptForSize = true;
01416     }
01417 
01418     // Check the function attributes to see if implicit floats are allowed.a
01419     // FIXME: This check doesn't seem possibly correct -- what if the loop is
01420     // an integer loop and the vector instructions selected are purely integer
01421     // vector instructions?
01422     if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
01423       DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
01424             "attribute is used.\n");
01425       emitOptimizationRemarkAnalysis(
01426           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
01427           "loop not vectorized due to NoImplicitFloat attribute");
01428       emitMissedWarning(F, L, Hints);
01429       return false;
01430     }
01431 
01432     // Select the optimal vectorization factor.
01433     const LoopVectorizationCostModel::VectorizationFactor VF =
01434         CM.selectVectorizationFactor(OptForSize);
01435 
01436     // Select the unroll factor.
01437     const unsigned UF =
01438         CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost);
01439 
01440     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
01441                  << DebugLocStr << '\n');
01442     DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
01443 
01444     if (VF.Width == 1) {
01445       DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n");
01446 
01447       if (UF == 1) {
01448         emitOptimizationRemarkAnalysis(
01449             F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
01450             "not beneficial to vectorize and user disabled interleaving");
01451         return false;
01452       }
01453       DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
01454 
01455       // Report the unrolling decision.
01456       emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
01457                              Twine("unrolled with interleaving factor " +
01458                                    Twine(UF) +
01459                                    " (vectorization not beneficial)"));
01460 
01461       // We decided not to vectorize, but we may want to unroll.
01462 
01463       InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
01464       Unroller.vectorize(&LVL);
01465     } else {
01466       // If we decided that it is *legal* to vectorize the loop then do it.
01467       InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
01468       LB.vectorize(&LVL);
01469       ++LoopsVectorized;
01470 
01471       // Report the vectorization decision.
01472       emitOptimizationRemark(
01473           F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(),
01474           Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) +
01475               ", unrolling interleave factor: " + Twine(UF) + ")");
01476     }
01477 
01478     // Mark the loop as already vectorized to avoid vectorizing again.
01479     Hints.setAlreadyVectorized();
01480 
01481     DEBUG(verifyFunction(*L->getHeader()->getParent()));
01482     return true;
01483   }
01484 
01485   void getAnalysisUsage(AnalysisUsage &AU) const override {
01486     AU.addRequired<AssumptionTracker>();
01487     AU.addRequiredID(LoopSimplifyID);
01488     AU.addRequiredID(LCSSAID);
01489     AU.addRequired<BlockFrequencyInfo>();
01490     AU.addRequired<DominatorTreeWrapperPass>();
01491     AU.addRequired<LoopInfo>();
01492     AU.addRequired<ScalarEvolution>();
01493     AU.addRequired<TargetTransformInfo>();
01494     AU.addRequired<AliasAnalysis>();
01495     AU.addPreserved<LoopInfo>();
01496     AU.addPreserved<DominatorTreeWrapperPass>();
01497     AU.addPreserved<AliasAnalysis>();
01498   }
01499 
01500 };
01501 
01502 } // end anonymous namespace
01503 
01504 //===----------------------------------------------------------------------===//
01505 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
01506 // LoopVectorizationCostModel.
01507 //===----------------------------------------------------------------------===//
01508 
01509 static Value *stripIntegerCast(Value *V) {
01510   if (CastInst *CI = dyn_cast<CastInst>(V))
01511     if (CI->getOperand(0)->getType()->isIntegerTy())
01512       return CI->getOperand(0);
01513   return V;
01514 }
01515 
01516 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
01517 ///
01518 /// If \p OrigPtr is not null, use it to look up the stride value instead of
01519 /// \p Ptr.
01520 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
01521                                              ValueToValueMap &PtrToStride,
01522                                              Value *Ptr, Value *OrigPtr = nullptr) {
01523 
01524   const SCEV *OrigSCEV = SE->getSCEV(Ptr);
01525 
01526   // If there is an entry in the map return the SCEV of the pointer with the
01527   // symbolic stride replaced by one.
01528   ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
01529   if (SI != PtrToStride.end()) {
01530     Value *StrideVal = SI->second;
01531 
01532     // Strip casts.
01533     StrideVal = stripIntegerCast(StrideVal);
01534 
01535     // Replace symbolic stride by one.
01536     Value *One = ConstantInt::get(StrideVal->getType(), 1);
01537     ValueToValueMap RewriteMap;
01538     RewriteMap[StrideVal] = One;
01539 
01540     const SCEV *ByOne =
01541         SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
01542     DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
01543                  << "\n");
01544     return ByOne;
01545   }
01546 
01547   // Otherwise, just return the SCEV of the original pointer.
01548   return SE->getSCEV(Ptr);
01549 }
01550 
01551 void LoopVectorizationLegality::RuntimePointerCheck::insert(
01552     ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
01553     unsigned ASId, ValueToValueMap &Strides) {
01554   // Get the stride replaced scev.
01555   const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
01556   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
01557   assert(AR && "Invalid addrec expression");
01558   const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
01559   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
01560   Pointers.push_back(Ptr);
01561   Starts.push_back(AR->getStart());
01562   Ends.push_back(ScEnd);
01563   IsWritePtr.push_back(WritePtr);
01564   DependencySetId.push_back(DepSetId);
01565   AliasSetId.push_back(ASId);
01566 }
01567 
01568 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
01569   // We need to place the broadcast of invariant variables outside the loop.
01570   Instruction *Instr = dyn_cast<Instruction>(V);
01571   bool NewInstr =
01572       (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
01573                           Instr->getParent()) != LoopVectorBody.end());
01574   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
01575 
01576   // Place the code for broadcasting invariant variables in the new preheader.
01577   IRBuilder<>::InsertPointGuard Guard(Builder);
01578   if (Invariant)
01579     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
01580 
01581   // Broadcast the scalar into all locations in the vector.
01582   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
01583 
01584   return Shuf;
01585 }
01586 
01587 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
01588                                                  bool Negate) {
01589   assert(Val->getType()->isVectorTy() && "Must be a vector");
01590   assert(Val->getType()->getScalarType()->isIntegerTy() &&
01591          "Elem must be an integer");
01592   // Create the types.
01593   Type *ITy = Val->getType()->getScalarType();
01594   VectorType *Ty = cast<VectorType>(Val->getType());
01595   int VLen = Ty->getNumElements();
01596   SmallVector<Constant*, 8> Indices;
01597 
01598   // Create a vector of consecutive numbers from zero to VF.
01599   for (int i = 0; i < VLen; ++i) {
01600     int64_t Idx = Negate ? (-i) : i;
01601     Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
01602   }
01603 
01604   // Add the consecutive indices to the vector value.
01605   Constant *Cv = ConstantVector::get(Indices);
01606   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
01607   return Builder.CreateAdd(Val, Cv, "induction");
01608 }
01609 
01610 /// \brief Find the operand of the GEP that should be checked for consecutive
01611 /// stores. This ignores trailing indices that have no effect on the final
01612 /// pointer.
01613 static unsigned getGEPInductionOperand(const DataLayout *DL,
01614                                        const GetElementPtrInst *Gep) {
01615   unsigned LastOperand = Gep->getNumOperands() - 1;
01616   unsigned GEPAllocSize = DL->getTypeAllocSize(
01617       cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
01618 
01619   // Walk backwards and try to peel off zeros.
01620   while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
01621     // Find the type we're currently indexing into.
01622     gep_type_iterator GEPTI = gep_type_begin(Gep);
01623     std::advance(GEPTI, LastOperand - 1);
01624 
01625     // If it's a type with the same allocation size as the result of the GEP we
01626     // can peel off the zero index.
01627     if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
01628       break;
01629     --LastOperand;
01630   }
01631 
01632   return LastOperand;
01633 }
01634 
01635 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
01636   assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
01637   // Make sure that the pointer does not point to structs.
01638   if (Ptr->getType()->getPointerElementType()->isAggregateType())
01639     return 0;
01640 
01641   // If this value is a pointer induction variable we know it is consecutive.
01642   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
01643   if (Phi && Inductions.count(Phi)) {
01644     InductionInfo II = Inductions[Phi];
01645     if (IK_PtrInduction == II.IK)
01646       return 1;
01647     else if (IK_ReversePtrInduction == II.IK)
01648       return -1;
01649   }
01650 
01651   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
01652   if (!Gep)
01653     return 0;
01654 
01655   unsigned NumOperands = Gep->getNumOperands();
01656   Value *GpPtr = Gep->getPointerOperand();
01657   // If this GEP value is a consecutive pointer induction variable and all of
01658   // the indices are constant then we know it is consecutive. We can
01659   Phi = dyn_cast<PHINode>(GpPtr);
01660   if (Phi && Inductions.count(Phi)) {
01661 
01662     // Make sure that the pointer does not point to structs.
01663     PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
01664     if (GepPtrType->getElementType()->isAggregateType())
01665       return 0;
01666 
01667     // Make sure that all of the index operands are loop invariant.
01668     for (unsigned i = 1; i < NumOperands; ++i)
01669       if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
01670         return 0;
01671 
01672     InductionInfo II = Inductions[Phi];
01673     if (IK_PtrInduction == II.IK)
01674       return 1;
01675     else if (IK_ReversePtrInduction == II.IK)
01676       return -1;
01677   }
01678 
01679   unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
01680 
01681   // Check that all of the gep indices are uniform except for our induction
01682   // operand.
01683   for (unsigned i = 0; i != NumOperands; ++i)
01684     if (i != InductionOperand &&
01685         !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
01686       return 0;
01687 
01688   // We can emit wide load/stores only if the last non-zero index is the
01689   // induction variable.
01690   const SCEV *Last = nullptr;
01691   if (!Strides.count(Gep))
01692     Last = SE->getSCEV(Gep->getOperand(InductionOperand));
01693   else {
01694     // Because of the multiplication by a stride we can have a s/zext cast.
01695     // We are going to replace this stride by 1 so the cast is safe to ignore.
01696     //
01697     //  %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
01698     //  %0 = trunc i64 %indvars.iv to i32
01699     //  %mul = mul i32 %0, %Stride1
01700     //  %idxprom = zext i32 %mul to i64  << Safe cast.
01701     //  %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
01702     //
01703     Last = replaceSymbolicStrideSCEV(SE, Strides,
01704                                      Gep->getOperand(InductionOperand), Gep);
01705     if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
01706       Last =
01707           (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
01708               ? C->getOperand()
01709               : Last;
01710   }
01711   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
01712     const SCEV *Step = AR->getStepRecurrence(*SE);
01713 
01714     // The memory is consecutive because the last index is consecutive
01715     // and all other indices are loop invariant.
01716     if (Step->isOne())
01717       return 1;
01718     if (Step->isAllOnesValue())
01719       return -1;
01720   }
01721 
01722   return 0;
01723 }
01724 
01725 bool LoopVectorizationLegality::isUniform(Value *V) {
01726   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
01727 }
01728 
01729 InnerLoopVectorizer::VectorParts&
01730 InnerLoopVectorizer::getVectorValue(Value *V) {
01731   assert(V != Induction && "The new induction variable should not be used.");
01732   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
01733 
01734   // If we have a stride that is replaced by one, do it here.
01735   if (Legal->hasStride(V))
01736     V = ConstantInt::get(V->getType(), 1);
01737 
01738   // If we have this scalar in the map, return it.
01739   if (WidenMap.has(V))
01740     return WidenMap.get(V);
01741 
01742   // If this scalar is unknown, assume that it is a constant or that it is
01743   // loop invariant. Broadcast V and save the value for future uses.
01744   Value *B = getBroadcastInstrs(V);
01745   return WidenMap.splat(V, B);
01746 }
01747 
01748 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
01749   assert(Vec->getType()->isVectorTy() && "Invalid type");
01750   SmallVector<Constant*, 8> ShuffleMask;
01751   for (unsigned i = 0; i < VF; ++i)
01752     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
01753 
01754   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
01755                                      ConstantVector::get(ShuffleMask),
01756                                      "reverse");
01757 }
01758 
01759 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
01760   // Attempt to issue a wide load.
01761   LoadInst *LI = dyn_cast<LoadInst>(Instr);
01762   StoreInst *SI = dyn_cast<StoreInst>(Instr);
01763 
01764   assert((LI || SI) && "Invalid Load/Store instruction");
01765 
01766   Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
01767   Type *DataTy = VectorType::get(ScalarDataTy, VF);
01768   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
01769   unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
01770   // An alignment of 0 means target abi alignment. We need to use the scalar's
01771   // target abi alignment in such a case.
01772   if (!Alignment)
01773     Alignment = DL->getABITypeAlignment(ScalarDataTy);
01774   unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
01775   unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
01776   unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
01777 
01778   if (SI && Legal->blockNeedsPredication(SI->getParent()))
01779     return scalarizeInstruction(Instr, true);
01780 
01781   if (ScalarAllocatedSize != VectorElementSize)
01782     return scalarizeInstruction(Instr);
01783 
01784   // If the pointer is loop invariant or if it is non-consecutive,
01785   // scalarize the load.
01786   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
01787   bool Reverse = ConsecutiveStride < 0;
01788   bool UniformLoad = LI && Legal->isUniform(Ptr);
01789   if (!ConsecutiveStride || UniformLoad)
01790     return scalarizeInstruction(Instr);
01791 
01792   Constant *Zero = Builder.getInt32(0);
01793   VectorParts &Entry = WidenMap.get(Instr);
01794 
01795   // Handle consecutive loads/stores.
01796   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
01797   if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
01798     setDebugLocFromInst(Builder, Gep);
01799     Value *PtrOperand = Gep->getPointerOperand();
01800     Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
01801     FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
01802 
01803     // Create the new GEP with the new induction variable.
01804     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
01805     Gep2->setOperand(0, FirstBasePtr);
01806     Gep2->setName("gep.indvar.base");
01807     Ptr = Builder.Insert(Gep2);
01808   } else if (Gep) {
01809     setDebugLocFromInst(Builder, Gep);
01810     assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
01811                                OrigLoop) && "Base ptr must be invariant");
01812 
01813     // The last index does not have to be the induction. It can be
01814     // consecutive and be a function of the index. For example A[I+1];
01815     unsigned NumOperands = Gep->getNumOperands();
01816     unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
01817     // Create the new GEP with the new induction variable.
01818     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
01819 
01820     for (unsigned i = 0; i < NumOperands; ++i) {
01821       Value *GepOperand = Gep->getOperand(i);
01822       Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
01823 
01824       // Update last index or loop invariant instruction anchored in loop.
01825       if (i == InductionOperand ||
01826           (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
01827         assert((i == InductionOperand ||
01828                SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
01829                "Must be last index or loop invariant");
01830 
01831         VectorParts &GEPParts = getVectorValue(GepOperand);
01832         Value *Index = GEPParts[0];
01833         Index = Builder.CreateExtractElement(Index, Zero);
01834         Gep2->setOperand(i, Index);
01835         Gep2->setName("gep.indvar.idx");
01836       }
01837     }
01838     Ptr = Builder.Insert(Gep2);
01839   } else {
01840     // Use the induction element ptr.
01841     assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
01842     setDebugLocFromInst(Builder, Ptr);
01843     VectorParts &PtrVal = getVectorValue(Ptr);
01844     Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
01845   }
01846 
01847   // Handle Stores:
01848   if (SI) {
01849     assert(!Legal->isUniform(SI->getPointerOperand()) &&
01850            "We do not allow storing to uniform addresses");
01851     setDebugLocFromInst(Builder, SI);
01852     // We don't want to update the value in the map as it might be used in
01853     // another expression. So don't use a reference type for "StoredVal".
01854     VectorParts StoredVal = getVectorValue(SI->getValueOperand());
01855 
01856     for (unsigned Part = 0; Part < UF; ++Part) {
01857       // Calculate the pointer for the specific unroll-part.
01858       Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
01859 
01860       if (Reverse) {
01861         // If we store to reverse consecutive memory locations then we need
01862         // to reverse the order of elements in the stored value.
01863         StoredVal[Part] = reverseVector(StoredVal[Part]);
01864         // If the address is consecutive but reversed, then the
01865         // wide store needs to start at the last vector element.
01866         PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
01867         PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
01868       }
01869 
01870       Value *VecPtr = Builder.CreateBitCast(PartPtr,
01871                                             DataTy->getPointerTo(AddressSpace));
01872       StoreInst *NewSI =
01873         Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
01874       propagateMetadata(NewSI, SI);
01875     }
01876     return;
01877   }
01878 
01879   // Handle loads.
01880   assert(LI && "Must have a load instruction");
01881   setDebugLocFromInst(Builder, LI);
01882   for (unsigned Part = 0; Part < UF; ++Part) {
01883     // Calculate the pointer for the specific unroll-part.
01884     Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
01885 
01886     if (Reverse) {
01887       // If the address is consecutive but reversed, then the
01888       // wide store needs to start at the last vector element.
01889       PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
01890       PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
01891     }
01892 
01893     Value *VecPtr = Builder.CreateBitCast(PartPtr,
01894                                           DataTy->getPointerTo(AddressSpace));
01895     LoadInst *NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
01896     propagateMetadata(NewLI, LI);
01897     Entry[Part] = Reverse ? reverseVector(NewLI) :  NewLI;
01898   }
01899 }
01900 
01901 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) {
01902   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
01903   // Holds vector parameters or scalars, in case of uniform vals.
01904   SmallVector<VectorParts, 4> Params;
01905 
01906   setDebugLocFromInst(Builder, Instr);
01907 
01908   // Find all of the vectorized parameters.
01909   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
01910     Value *SrcOp = Instr->getOperand(op);
01911 
01912     // If we are accessing the old induction variable, use the new one.
01913     if (SrcOp == OldInduction) {
01914       Params.push_back(getVectorValue(SrcOp));
01915       continue;
01916     }
01917 
01918     // Try using previously calculated values.
01919     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
01920 
01921     // If the src is an instruction that appeared earlier in the basic block
01922     // then it should already be vectorized.
01923     if (SrcInst && OrigLoop->contains(SrcInst)) {
01924       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
01925       // The parameter is a vector value from earlier.
01926       Params.push_back(WidenMap.get(SrcInst));
01927     } else {
01928       // The parameter is a scalar from outside the loop. Maybe even a constant.
01929       VectorParts Scalars;
01930       Scalars.append(UF, SrcOp);
01931       Params.push_back(Scalars);
01932     }
01933   }
01934 
01935   assert(Params.size() == Instr->getNumOperands() &&
01936          "Invalid number of operands");
01937 
01938   // Does this instruction return a value ?
01939   bool IsVoidRetTy = Instr->getType()->isVoidTy();
01940 
01941   Value *UndefVec = IsVoidRetTy ? nullptr :
01942     UndefValue::get(VectorType::get(Instr->getType(), VF));
01943   // Create a new entry in the WidenMap and initialize it to Undef or Null.
01944   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
01945 
01946   Instruction *InsertPt = Builder.GetInsertPoint();
01947   BasicBlock *IfBlock = Builder.GetInsertBlock();
01948   BasicBlock *CondBlock = nullptr;
01949 
01950   VectorParts Cond;
01951   Loop *VectorLp = nullptr;
01952   if (IfPredicateStore) {
01953     assert(Instr->getParent()->getSinglePredecessor() &&
01954            "Only support single predecessor blocks");
01955     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
01956                           Instr->getParent());
01957     VectorLp = LI->getLoopFor(IfBlock);
01958     assert(VectorLp && "Must have a loop for this block");
01959   }
01960 
01961   // For each vector unroll 'part':
01962   for (unsigned Part = 0; Part < UF; ++Part) {
01963     // For each scalar that we create:
01964     for (unsigned Width = 0; Width < VF; ++Width) {
01965 
01966       // Start if-block.
01967       Value *Cmp = nullptr;
01968       if (IfPredicateStore) {
01969         Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
01970         Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1));
01971         CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
01972         LoopVectorBody.push_back(CondBlock);
01973         VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
01974         // Update Builder with newly created basic block.
01975         Builder.SetInsertPoint(InsertPt);
01976       }
01977 
01978       Instruction *Cloned = Instr->clone();
01979       if (!IsVoidRetTy)
01980         Cloned->setName(Instr->getName() + ".cloned");
01981       // Replace the operands of the cloned instructions with extracted scalars.
01982       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
01983         Value *Op = Params[op][Part];
01984         // Param is a vector. Need to extract the right lane.
01985         if (Op->getType()->isVectorTy())
01986           Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
01987         Cloned->setOperand(op, Op);
01988       }
01989 
01990       // Place the cloned scalar in the new loop.
01991       Builder.Insert(Cloned);
01992 
01993       // If the original scalar returns a value we need to place it in a vector
01994       // so that future users will be able to use it.
01995       if (!IsVoidRetTy)
01996         VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
01997                                                        Builder.getInt32(Width));
01998       // End if-block.
01999       if (IfPredicateStore) {
02000          BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
02001          LoopVectorBody.push_back(NewIfBlock);
02002          VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
02003          Builder.SetInsertPoint(InsertPt);
02004          Instruction *OldBr = IfBlock->getTerminator();
02005          BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
02006          OldBr->eraseFromParent();
02007          IfBlock = NewIfBlock;
02008       }
02009     }
02010   }
02011 }
02012 
02013 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
02014                                  Instruction *Loc) {
02015   if (FirstInst)
02016     return FirstInst;
02017   if (Instruction *I = dyn_cast<Instruction>(V))
02018     return I->getParent() == Loc->getParent() ? I : nullptr;
02019   return nullptr;
02020 }
02021 
02022 std::pair<Instruction *, Instruction *>
02023 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
02024   Instruction *tnullptr = nullptr;
02025   if (!Legal->mustCheckStrides())
02026     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
02027 
02028   IRBuilder<> ChkBuilder(Loc);
02029 
02030   // Emit checks.
02031   Value *Check = nullptr;
02032   Instruction *FirstInst = nullptr;
02033   for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
02034                                          SE = Legal->strides_end();
02035        SI != SE; ++SI) {
02036     Value *Ptr = stripIntegerCast(*SI);
02037     Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
02038                                        "stride.chk");
02039     // Store the first instruction we create.
02040     FirstInst = getFirstInst(FirstInst, C, Loc);
02041     if (Check)
02042       Check = ChkBuilder.CreateOr(Check, C);
02043     else
02044       Check = C;
02045   }
02046 
02047   // We have to do this trickery because the IRBuilder might fold the check to a
02048   // constant expression in which case there is no Instruction anchored in a
02049   // the block.
02050   LLVMContext &Ctx = Loc->getContext();
02051   Instruction *TheCheck =
02052       BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
02053   ChkBuilder.Insert(TheCheck, "stride.not.one");
02054   FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
02055 
02056   return std::make_pair(FirstInst, TheCheck);
02057 }
02058 
02059 std::pair<Instruction *, Instruction *>
02060 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
02061   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
02062   Legal->getRuntimePointerCheck();
02063 
02064   Instruction *tnullptr = nullptr;
02065   if (!PtrRtCheck->Need)
02066     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
02067 
02068   unsigned NumPointers = PtrRtCheck->Pointers.size();
02069   SmallVector<TrackingVH<Value> , 2> Starts;
02070   SmallVector<TrackingVH<Value> , 2> Ends;
02071 
02072   LLVMContext &Ctx = Loc->getContext();
02073   SCEVExpander Exp(*SE, "induction");
02074   Instruction *FirstInst = nullptr;
02075 
02076   for (unsigned i = 0; i < NumPointers; ++i) {
02077     Value *Ptr = PtrRtCheck->Pointers[i];
02078     const SCEV *Sc = SE->getSCEV(Ptr);
02079 
02080     if (SE->isLoopInvariant(Sc, OrigLoop)) {
02081       DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
02082             *Ptr <<"\n");
02083       Starts.push_back(Ptr);
02084       Ends.push_back(Ptr);
02085     } else {
02086       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
02087       unsigned AS = Ptr->getType()->getPointerAddressSpace();
02088 
02089       // Use this type for pointer arithmetic.
02090       Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
02091 
02092       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
02093       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
02094       Starts.push_back(Start);
02095       Ends.push_back(End);
02096     }
02097   }
02098 
02099   IRBuilder<> ChkBuilder(Loc);
02100   // Our instructions might fold to a constant.
02101   Value *MemoryRuntimeCheck = nullptr;
02102   for (unsigned i = 0; i < NumPointers; ++i) {
02103     for (unsigned j = i+1; j < NumPointers; ++j) {
02104       // No need to check if two readonly pointers intersect.
02105       if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
02106         continue;
02107 
02108       // Only need to check pointers between two different dependency sets.
02109       if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
02110        continue;
02111       // Only need to check pointers in the same alias set.
02112       if (PtrRtCheck->AliasSetId[i] != PtrRtCheck->AliasSetId[j])
02113         continue;
02114 
02115       unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
02116       unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
02117 
02118       assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
02119              (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
02120              "Trying to bounds check pointers with different address spaces");
02121 
02122       Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
02123       Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
02124 
02125       Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
02126       Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
02127       Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy1, "bc");
02128       Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy0, "bc");
02129 
02130       Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
02131       FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
02132       Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
02133       FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
02134       Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
02135       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
02136       if (MemoryRuntimeCheck) {
02137         IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
02138                                          "conflict.rdx");
02139         FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
02140       }
02141       MemoryRuntimeCheck = IsConflict;
02142     }
02143   }
02144 
02145   // We have to do this trickery because the IRBuilder might fold the check to a
02146   // constant expression in which case there is no Instruction anchored in a
02147   // the block.
02148   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
02149                                                  ConstantInt::getTrue(Ctx));
02150   ChkBuilder.Insert(Check, "memcheck.conflict");
02151   FirstInst = getFirstInst(FirstInst, Check, Loc);
02152   return std::make_pair(FirstInst, Check);
02153 }
02154 
02155 void InnerLoopVectorizer::createEmptyLoop() {
02156   /*
02157    In this function we generate a new loop. The new loop will contain
02158    the vectorized instructions while the old loop will continue to run the
02159    scalar remainder.
02160 
02161        [ ] <-- Back-edge taken count overflow check.
02162     /   |
02163    /    v
02164   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
02165   |  /  |
02166   | /   v
02167   ||   [ ]     <-- vector pre header.
02168   ||    |
02169   ||    v
02170   ||   [  ] \
02171   ||   [  ]_|   <-- vector loop.
02172   ||    |
02173   | \   v
02174   |   >[ ]   <--- middle-block.
02175   |  /  |
02176   | /   v
02177   -|- >[ ]     <--- new preheader.
02178    |    |
02179    |    v
02180    |   [ ] \
02181    |   [ ]_|   <-- old scalar loop to handle remainder.
02182     \   |
02183      \  v
02184       >[ ]     <-- exit block.
02185    ...
02186    */
02187 
02188   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
02189   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
02190   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
02191   assert(BypassBlock && "Invalid loop structure");
02192   assert(ExitBlock && "Must have an exit block");
02193 
02194   // Some loops have a single integer induction variable, while other loops
02195   // don't. One example is c++ iterators that often have multiple pointer
02196   // induction variables. In the code below we also support a case where we
02197   // don't have a single induction variable.
02198   OldInduction = Legal->getInduction();
02199   Type *IdxTy = Legal->getWidestInductionType();
02200 
02201   // Find the loop boundaries.
02202   const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
02203   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
02204 
02205   // The exit count might have the type of i64 while the phi is i32. This can
02206   // happen if we have an induction variable that is sign extended before the
02207   // compare. The only way that we get a backedge taken count is that the
02208   // induction variable was signed and as such will not overflow. In such a case
02209   // truncation is legal.
02210   if (ExitCount->getType()->getPrimitiveSizeInBits() >
02211       IdxTy->getPrimitiveSizeInBits())
02212     ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
02213 
02214   const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
02215   // Get the total trip count from the count by adding 1.
02216   ExitCount = SE->getAddExpr(BackedgeTakeCount,
02217                              SE->getConstant(BackedgeTakeCount->getType(), 1));
02218 
02219   // Expand the trip count and place the new instructions in the preheader.
02220   // Notice that the pre-header does not change, only the loop body.
02221   SCEVExpander Exp(*SE, "induction");
02222 
02223   // We need to test whether the backedge-taken count is uint##_max. Adding one
02224   // to it will cause overflow and an incorrect loop trip count in the vector
02225   // body. In case of overflow we want to directly jump to the scalar remainder
02226   // loop.
02227   Value *BackedgeCount =
02228       Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(),
02229                         BypassBlock->getTerminator());
02230   if (BackedgeCount->getType()->isPointerTy())
02231     BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy,
02232                                                 "backedge.ptrcnt.to.int",
02233                                                 BypassBlock->getTerminator());
02234   Instruction *CheckBCOverflow =
02235       CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount,
02236                       Constant::getAllOnesValue(BackedgeCount->getType()),
02237                       "backedge.overflow", BypassBlock->getTerminator());
02238 
02239   // The loop index does not have to start at Zero. Find the original start
02240   // value from the induction PHI node. If we don't have an induction variable
02241   // then we know that it starts at zero.
02242   Builder.SetInsertPoint(BypassBlock->getTerminator());
02243   Value *StartIdx = ExtendedIdx = OldInduction ?
02244     Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
02245                        IdxTy):
02246     ConstantInt::get(IdxTy, 0);
02247 
02248   // We need an instruction to anchor the overflow check on. StartIdx needs to
02249   // be defined before the overflow check branch. Because the scalar preheader
02250   // is going to merge the start index and so the overflow branch block needs to
02251   // contain a definition of the start index.
02252   Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd(
02253       StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor",
02254       BypassBlock->getTerminator());
02255 
02256   // Count holds the overall loop count (N).
02257   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
02258                                    BypassBlock->getTerminator());
02259 
02260   LoopBypassBlocks.push_back(BypassBlock);
02261 
02262   // Split the single block loop into the two loop structure described above.
02263   BasicBlock *VectorPH =
02264   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
02265   BasicBlock *VecBody =
02266   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
02267   BasicBlock *MiddleBlock =
02268   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
02269   BasicBlock *ScalarPH =
02270   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
02271 
02272   // Create and register the new vector loop.
02273   Loop* Lp = new Loop();
02274   Loop *ParentLoop = OrigLoop->getParentLoop();
02275 
02276   // Insert the new loop into the loop nest and register the new basic blocks
02277   // before calling any utilities such as SCEV that require valid LoopInfo.
02278   if (ParentLoop) {
02279     ParentLoop->addChildLoop(Lp);
02280     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
02281     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
02282     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
02283   } else {
02284     LI->addTopLevelLoop(Lp);
02285   }
02286   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
02287 
02288   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
02289   // inside the loop.
02290   Builder.SetInsertPoint(VecBody->getFirstNonPHI());
02291 
02292   // Generate the induction variable.
02293   setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
02294   Induction = Builder.CreatePHI(IdxTy, 2, "index");
02295   // The loop step is equal to the vectorization factor (num of SIMD elements)
02296   // times the unroll factor (num of SIMD instructions).
02297   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
02298 
02299   // This is the IR builder that we use to add all of the logic for bypassing
02300   // the new vector loop.
02301   IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
02302   setDebugLocFromInst(BypassBuilder,
02303                       getDebugLocFromInstOrOperands(OldInduction));
02304 
02305   // We may need to extend the index in case there is a type mismatch.
02306   // We know that the count starts at zero and does not overflow.
02307   if (Count->getType() != IdxTy) {
02308     // The exit count can be of pointer type. Convert it to the correct
02309     // integer type.
02310     if (ExitCount->getType()->isPointerTy())
02311       Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
02312     else
02313       Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
02314   }
02315 
02316   // Add the start index to the loop count to get the new end index.
02317   Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
02318 
02319   // Now we need to generate the expression for N - (N % VF), which is
02320   // the part that the vectorized body will execute.
02321   Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
02322   Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
02323   Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
02324                                                      "end.idx.rnd.down");
02325 
02326   // Now, compare the new count to zero. If it is zero skip the vector loop and
02327   // jump to the scalar loop.
02328   Value *Cmp =
02329       BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero");
02330 
02331   BasicBlock *LastBypassBlock = BypassBlock;
02332 
02333   // Generate code to check that the loops trip count that we computed by adding
02334   // one to the backedge-taken count will not overflow.
02335   {
02336     auto PastOverflowCheck =
02337         std::next(BasicBlock::iterator(OverflowCheckAnchor));
02338     BasicBlock *CheckBlock =
02339       LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked");
02340     if (ParentLoop)
02341       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
02342     LoopBypassBlocks.push_back(CheckBlock);
02343     Instruction *OldTerm = LastBypassBlock->getTerminator();
02344     BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm);
02345     OldTerm->eraseFromParent();
02346     LastBypassBlock = CheckBlock;
02347   }
02348 
02349   // Generate the code to check that the strides we assumed to be one are really
02350   // one. We want the new basic block to start at the first instruction in a
02351   // sequence of instructions that form a check.
02352   Instruction *StrideCheck;
02353   Instruction *FirstCheckInst;
02354   std::tie(FirstCheckInst, StrideCheck) =
02355       addStrideCheck(LastBypassBlock->getTerminator());
02356   if (StrideCheck) {
02357     // Create a new block containing the stride check.
02358     BasicBlock *CheckBlock =
02359         LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
02360     if (ParentLoop)
02361       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
02362     LoopBypassBlocks.push_back(CheckBlock);
02363 
02364     // Replace the branch into the memory check block with a conditional branch
02365     // for the "few elements case".
02366     Instruction *OldTerm = LastBypassBlock->getTerminator();
02367     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
02368     OldTerm->eraseFromParent();
02369 
02370     Cmp = StrideCheck;
02371     LastBypassBlock = CheckBlock;
02372   }
02373 
02374   // Generate the code that checks in runtime if arrays overlap. We put the
02375   // checks into a separate block to make the more common case of few elements
02376   // faster.
02377   Instruction *MemRuntimeCheck;
02378   std::tie(FirstCheckInst, MemRuntimeCheck) =
02379       addRuntimeCheck(LastBypassBlock->getTerminator());
02380   if (MemRuntimeCheck) {
02381     // Create a new block containing the memory check.
02382     BasicBlock *CheckBlock =
02383         LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
02384     if (ParentLoop)
02385       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
02386     LoopBypassBlocks.push_back(CheckBlock);
02387 
02388     // Replace the branch into the memory check block with a conditional branch
02389     // for the "few elements case".
02390     Instruction *OldTerm = LastBypassBlock->getTerminator();
02391     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
02392     OldTerm->eraseFromParent();
02393 
02394     Cmp = MemRuntimeCheck;
02395     LastBypassBlock = CheckBlock;
02396   }
02397 
02398   LastBypassBlock->getTerminator()->eraseFromParent();
02399   BranchInst::Create(MiddleBlock, VectorPH, Cmp,
02400                      LastBypassBlock);
02401 
02402   // We are going to resume the execution of the scalar loop.
02403   // Go over all of the induction variables that we found and fix the
02404   // PHIs that are left in the scalar version of the loop.
02405   // The starting values of PHI nodes depend on the counter of the last
02406   // iteration in the vectorized loop.
02407   // If we come from a bypass edge then we need to start from the original
02408   // start value.
02409 
02410   // This variable saves the new starting index for the scalar loop.
02411   PHINode *ResumeIndex = nullptr;
02412   LoopVectorizationLegality::InductionList::iterator I, E;
02413   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
02414   // Set builder to point to last bypass block.
02415   BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
02416   for (I = List->begin(), E = List->end(); I != E; ++I) {
02417     PHINode *OrigPhi = I->first;
02418     LoopVectorizationLegality::InductionInfo II = I->second;
02419 
02420     Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
02421     PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
02422                                          MiddleBlock->getTerminator());
02423     // We might have extended the type of the induction variable but we need a
02424     // truncated version for the scalar loop.
02425     PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
02426       PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
02427                       MiddleBlock->getTerminator()) : nullptr;
02428 
02429     // Create phi nodes to merge from the  backedge-taken check block.
02430     PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val",
02431                                            ScalarPH->getTerminator());
02432     BCResumeVal->addIncoming(ResumeVal, MiddleBlock);
02433 
02434     PHINode *BCTruncResumeVal = nullptr;
02435     if (OrigPhi == OldInduction) {
02436       BCTruncResumeVal =
02437           PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val",
02438                           ScalarPH->getTerminator());
02439       BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock);
02440     }
02441 
02442     Value *EndValue = nullptr;
02443     switch (II.IK) {
02444     case LoopVectorizationLegality::IK_NoInduction:
02445       llvm_unreachable("Unknown induction");
02446     case LoopVectorizationLegality::IK_IntInduction: {
02447       // Handle the integer induction counter.
02448       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
02449 
02450       // We have the canonical induction variable.
02451       if (OrigPhi == OldInduction) {
02452         // Create a truncated version of the resume value for the scalar loop,
02453         // we might have promoted the type to a larger width.
02454         EndValue =
02455           BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
02456         // The new PHI merges the original incoming value, in case of a bypass,
02457         // or the value at the end of the vectorized loop.
02458         for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
02459           TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
02460         TruncResumeVal->addIncoming(EndValue, VecBody);
02461 
02462         BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
02463 
02464         // We know what the end value is.
02465         EndValue = IdxEndRoundDown;
02466         // We also know which PHI node holds it.
02467         ResumeIndex = ResumeVal;
02468         break;
02469       }
02470 
02471       // Not the canonical induction variable - add the vector loop count to the
02472       // start value.
02473       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
02474                                                    II.StartValue->getType(),
02475                                                    "cast.crd");
02476       EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
02477       break;
02478     }
02479     case LoopVectorizationLegality::IK_ReverseIntInduction: {
02480       // Convert the CountRoundDown variable to the PHI size.
02481       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
02482                                                    II.StartValue->getType(),
02483                                                    "cast.crd");
02484       // Handle reverse integer induction counter.
02485       EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
02486       break;
02487     }
02488     case LoopVectorizationLegality::IK_PtrInduction: {
02489       // For pointer induction variables, calculate the offset using
02490       // the end index.
02491       EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
02492                                          "ptr.ind.end");
02493       break;
02494     }
02495     case LoopVectorizationLegality::IK_ReversePtrInduction: {
02496       // The value at the end of the loop for the reverse pointer is calculated
02497       // by creating a GEP with a negative index starting from the start value.
02498       Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
02499       Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
02500                                               "rev.ind.end");
02501       EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
02502                                          "rev.ptr.ind.end");
02503       break;
02504     }
02505     }// end of case
02506 
02507     // The new PHI merges the original incoming value, in case of a bypass,
02508     // or the value at the end of the vectorized loop.
02509     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) {
02510       if (OrigPhi == OldInduction)
02511         ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
02512       else
02513         ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
02514     }
02515     ResumeVal->addIncoming(EndValue, VecBody);
02516 
02517     // Fix the scalar body counter (PHI node).
02518     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
02519 
02520     // The old induction's phi node in the scalar body needs the truncated
02521     // value.
02522     if (OrigPhi == OldInduction) {
02523       BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]);
02524       OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal);
02525     } else {
02526       BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]);
02527       OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
02528     }
02529   }
02530 
02531   // If we are generating a new induction variable then we also need to
02532   // generate the code that calculates the exit value. This value is not
02533   // simply the end of the counter because we may skip the vectorized body
02534   // in case of a runtime check.
02535   if (!OldInduction){
02536     assert(!ResumeIndex && "Unexpected resume value found");
02537     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
02538                                   MiddleBlock->getTerminator());
02539     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
02540       ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
02541     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
02542   }
02543 
02544   // Make sure that we found the index where scalar loop needs to continue.
02545   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
02546          "Invalid resume Index");
02547 
02548   // Add a check in the middle block to see if we have completed
02549   // all of the iterations in the first vector loop.
02550   // If (N - N%VF) == N, then we *don't* need to run the remainder.
02551   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
02552                                 ResumeIndex, "cmp.n",
02553                                 MiddleBlock->getTerminator());
02554 
02555   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
02556   // Remove the old terminator.
02557   MiddleBlock->getTerminator()->eraseFromParent();
02558 
02559   // Create i+1 and fill the PHINode.
02560   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
02561   Induction->addIncoming(StartIdx, VectorPH);
02562   Induction->addIncoming(NextIdx, VecBody);
02563   // Create the compare.
02564   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
02565   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
02566 
02567   // Now we have two terminators. Remove the old one from the block.
02568   VecBody->getTerminator()->eraseFromParent();
02569 
02570   // Get ready to start creating new instructions into the vectorized body.
02571   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
02572 
02573   // Save the state.
02574   LoopVectorPreHeader = VectorPH;
02575   LoopScalarPreHeader = ScalarPH;
02576   LoopMiddleBlock = MiddleBlock;
02577   LoopExitBlock = ExitBlock;
02578   LoopVectorBody.push_back(VecBody);
02579   LoopScalarBody = OldBasicBlock;
02580 
02581   LoopVectorizeHints Hints(Lp, true);
02582   Hints.setAlreadyVectorized();
02583 }
02584 
02585 /// This function returns the identity element (or neutral element) for
02586 /// the operation K.
02587 Constant*
02588 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
02589   switch (K) {
02590   case RK_IntegerXor:
02591   case RK_IntegerAdd:
02592   case RK_IntegerOr:
02593     // Adding, Xoring, Oring zero to a number does not change it.
02594     return ConstantInt::get(Tp, 0);
02595   case RK_IntegerMult:
02596     // Multiplying a number by 1 does not change it.
02597     return ConstantInt::get(Tp, 1);
02598   case RK_IntegerAnd:
02599     // AND-ing a number with an all-1 value does not change it.
02600     return ConstantInt::get(Tp, -1, true);
02601   case  RK_FloatMult:
02602     // Multiplying a number by 1 does not change it.
02603     return ConstantFP::get(Tp, 1.0L);
02604   case  RK_FloatAdd:
02605     // Adding zero to a number does not change it.
02606     return ConstantFP::get(Tp, 0.0L);
02607   default:
02608     llvm_unreachable("Unknown reduction kind");
02609   }
02610 }
02611 
02612 /// This function translates the reduction kind to an LLVM binary operator.
02613 static unsigned
02614 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
02615   switch (Kind) {
02616     case LoopVectorizationLegality::RK_IntegerAdd:
02617       return Instruction::Add;
02618     case LoopVectorizationLegality::RK_IntegerMult:
02619       return Instruction::Mul;
02620     case LoopVectorizationLegality::RK_IntegerOr:
02621       return Instruction::Or;
02622     case LoopVectorizationLegality::RK_IntegerAnd:
02623       return Instruction::And;
02624     case LoopVectorizationLegality::RK_IntegerXor:
02625       return Instruction::Xor;
02626     case LoopVectorizationLegality::RK_FloatMult:
02627       return Instruction::FMul;
02628     case LoopVectorizationLegality::RK_FloatAdd:
02629       return Instruction::FAdd;
02630     case LoopVectorizationLegality::RK_IntegerMinMax:
02631       return Instruction::ICmp;
02632     case LoopVectorizationLegality::RK_FloatMinMax:
02633       return Instruction::FCmp;
02634     default:
02635       llvm_unreachable("Unknown reduction operation");
02636   }
02637 }
02638 
02639 Value *createMinMaxOp(IRBuilder<> &Builder,
02640                       LoopVectorizationLegality::MinMaxReductionKind RK,
02641                       Value *Left,
02642                       Value *Right) {
02643   CmpInst::Predicate P = CmpInst::ICMP_NE;
02644   switch (RK) {
02645   default:
02646     llvm_unreachable("Unknown min/max reduction kind");
02647   case LoopVectorizationLegality::MRK_UIntMin:
02648     P = CmpInst::ICMP_ULT;
02649     break;
02650   case LoopVectorizationLegality::MRK_UIntMax:
02651     P = CmpInst::ICMP_UGT;
02652     break;
02653   case LoopVectorizationLegality::MRK_SIntMin:
02654     P = CmpInst::ICMP_SLT;
02655     break;
02656   case LoopVectorizationLegality::MRK_SIntMax:
02657     P = CmpInst::ICMP_SGT;
02658     break;
02659   case LoopVectorizationLegality::MRK_FloatMin:
02660     P = CmpInst::FCMP_OLT;
02661     break;
02662   case LoopVectorizationLegality::MRK_FloatMax:
02663     P = CmpInst::FCMP_OGT;
02664     break;
02665   }
02666 
02667   Value *Cmp;
02668   if (RK == LoopVectorizationLegality::MRK_FloatMin ||
02669       RK == LoopVectorizationLegality::MRK_FloatMax)
02670     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
02671   else
02672     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
02673 
02674   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
02675   return Select;
02676 }
02677 
02678 namespace {
02679 struct CSEDenseMapInfo {
02680   static bool canHandle(Instruction *I) {
02681     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
02682            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
02683   }
02684   static inline Instruction *getEmptyKey() {
02685     return DenseMapInfo<Instruction *>::getEmptyKey();
02686   }
02687   static inline Instruction *getTombstoneKey() {
02688     return DenseMapInfo<Instruction *>::getTombstoneKey();
02689   }
02690   static unsigned getHashValue(Instruction *I) {
02691     assert(canHandle(I) && "Unknown instruction!");
02692     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
02693                                                            I->value_op_end()));
02694   }
02695   static bool isEqual(Instruction *LHS, Instruction *RHS) {
02696     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
02697         LHS == getTombstoneKey() || RHS == getTombstoneKey())
02698       return LHS == RHS;
02699     return LHS->isIdenticalTo(RHS);
02700   }
02701 };
02702 }
02703 
02704 /// \brief Check whether this block is a predicated block.
02705 /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
02706 /// = ...;  " blocks. We start with one vectorized basic block. For every
02707 /// conditional block we split this vectorized block. Therefore, every second
02708 /// block will be a predicated one.
02709 static bool isPredicatedBlock(unsigned BlockNum) {
02710   return BlockNum % 2;
02711 }
02712 
02713 ///\brief Perform cse of induction variable instructions.
02714 static void cse(SmallVector<BasicBlock *, 4> &BBs) {
02715   // Perform simple cse.
02716   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
02717   for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
02718     BasicBlock *BB = BBs[i];
02719     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
02720       Instruction *In = I++;
02721 
02722       if (!CSEDenseMapInfo::canHandle(In))
02723         continue;
02724 
02725       // Check if we can replace this instruction with any of the
02726       // visited instructions.
02727       if (Instruction *V = CSEMap.lookup(In)) {
02728         In->replaceAllUsesWith(V);
02729         In->eraseFromParent();
02730         continue;
02731       }
02732       // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
02733       // ...;" blocks for predicated stores. Every second block is a predicated
02734       // block.
02735       if (isPredicatedBlock(i))
02736         continue;
02737 
02738       CSEMap[In] = In;
02739     }
02740   }
02741 }
02742 
02743 /// \brief Adds a 'fast' flag to floating point operations.
02744 static Value *addFastMathFlag(Value *V) {
02745   if (isa<FPMathOperator>(V)){
02746     FastMathFlags Flags;
02747     Flags.setUnsafeAlgebra();
02748     cast<Instruction>(V)->setFastMathFlags(Flags);
02749   }
02750   return V;
02751 }
02752 
02753 void InnerLoopVectorizer::vectorizeLoop() {
02754   //===------------------------------------------------===//
02755   //
02756   // Notice: any optimization or new instruction that go
02757   // into the code below should be also be implemented in
02758   // the cost-model.
02759   //
02760   //===------------------------------------------------===//
02761   Constant *Zero = Builder.getInt32(0);
02762 
02763   // In order to support reduction variables we need to be able to vectorize
02764   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
02765   // stages. First, we create a new vector PHI node with no incoming edges.
02766   // We use this value when we vectorize all of the instructions that use the
02767   // PHI. Next, after all of the instructions in the block are complete we
02768   // add the new incoming edges to the PHI. At this point all of the
02769   // instructions in the basic block are vectorized, so we can use them to
02770   // construct the PHI.
02771   PhiVector RdxPHIsToFix;
02772 
02773   // Scan the loop in a topological order to ensure that defs are vectorized
02774   // before users.
02775   LoopBlocksDFS DFS(OrigLoop);
02776   DFS.perform(LI);
02777 
02778   // Vectorize all of the blocks in the original loop.
02779   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
02780        be = DFS.endRPO(); bb != be; ++bb)
02781     vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
02782 
02783   // At this point every instruction in the original loop is widened to
02784   // a vector form. We are almost done. Now, we need to fix the PHI nodes
02785   // that we vectorized. The PHI nodes are currently empty because we did
02786   // not want to introduce cycles. Notice that the remaining PHI nodes
02787   // that we need to fix are reduction variables.
02788 
02789   // Create the 'reduced' values for each of the induction vars.
02790   // The reduced values are the vector values that we scalarize and combine
02791   // after the loop is finished.
02792   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
02793        it != e; ++it) {
02794     PHINode *RdxPhi = *it;
02795     assert(RdxPhi && "Unable to recover vectorized PHI");
02796 
02797     // Find the reduction variable descriptor.
02798     assert(Legal->getReductionVars()->count(RdxPhi) &&
02799            "Unable to find the reduction variable");
02800     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
02801     (*Legal->getReductionVars())[RdxPhi];
02802 
02803     setDebugLocFromInst(Builder, RdxDesc.StartValue);
02804 
02805     // We need to generate a reduction vector from the incoming scalar.
02806     // To do so, we need to generate the 'identity' vector and override
02807     // one of the elements with the incoming scalar reduction. We need
02808     // to do it in the vector-loop preheader.
02809     Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
02810 
02811     // This is the vector-clone of the value that leaves the loop.
02812     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
02813     Type *VecTy = VectorExit[0]->getType();
02814 
02815     // Find the reduction identity variable. Zero for addition, or, xor,
02816     // one for multiplication, -1 for And.
02817     Value *Identity;
02818     Value *VectorStart;
02819     if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
02820         RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
02821       // MinMax reduction have the start value as their identify.
02822       if (VF == 1) {
02823         VectorStart = Identity = RdxDesc.StartValue;
02824       } else {
02825         VectorStart = Identity = Builder.CreateVectorSplat(VF,
02826                                                            RdxDesc.StartValue,
02827                                                            "minmax.ident");
02828       }
02829     } else {
02830       // Handle other reduction kinds:
02831       Constant *Iden =
02832       LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
02833                                                       VecTy->getScalarType());
02834       if (VF == 1) {
02835         Identity = Iden;
02836         // This vector is the Identity vector where the first element is the
02837         // incoming scalar reduction.
02838         VectorStart = RdxDesc.StartValue;
02839       } else {
02840         Identity = ConstantVector::getSplat(VF, Iden);
02841 
02842         // This vector is the Identity vector where the first element is the
02843         // incoming scalar reduction.
02844         VectorStart = Builder.CreateInsertElement(Identity,
02845                                                   RdxDesc.StartValue, Zero);
02846       }
02847     }
02848 
02849     // Fix the vector-loop phi.
02850     // We created the induction variable so we know that the
02851     // preheader is the first entry.
02852     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
02853 
02854     // Reductions do not have to start at zero. They can start with
02855     // any loop invariant values.
02856     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
02857     BasicBlock *Latch = OrigLoop->getLoopLatch();
02858     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
02859     VectorParts &Val = getVectorValue(LoopVal);
02860     for (unsigned part = 0; part < UF; ++part) {
02861       // Make sure to add the reduction stat value only to the
02862       // first unroll part.
02863       Value *StartVal = (part == 0) ? VectorStart : Identity;
02864       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
02865       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
02866                                                   LoopVectorBody.back());
02867     }
02868 
02869     // Before each round, move the insertion point right between
02870     // the PHIs and the values we are going to write.
02871     // This allows us to write both PHINodes and the extractelement
02872     // instructions.
02873     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
02874 
02875     VectorParts RdxParts;
02876     setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
02877     for (unsigned part = 0; part < UF; ++part) {
02878       // This PHINode contains the vectorized reduction variable, or
02879       // the initial value vector, if we bypass the vector loop.
02880       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
02881       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
02882       Value *StartVal = (part == 0) ? VectorStart : Identity;
02883       for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
02884         NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
02885       NewPhi->addIncoming(RdxExitVal[part],
02886                           LoopVectorBody.back());
02887       RdxParts.push_back(NewPhi);
02888     }
02889 
02890     // Reduce all of the unrolled parts into a single vector.
02891     Value *ReducedPartRdx = RdxParts[0];
02892     unsigned Op = getReductionBinOp(RdxDesc.Kind);
02893     setDebugLocFromInst(Builder, ReducedPartRdx);
02894     for (unsigned part = 1; part < UF; ++part) {
02895       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
02896         // Floating point operations had to be 'fast' to enable the reduction.
02897         ReducedPartRdx = addFastMathFlag(
02898             Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
02899                                 ReducedPartRdx, "bin.rdx"));
02900       else
02901         ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
02902                                         ReducedPartRdx, RdxParts[part]);
02903     }
02904 
02905     if (VF > 1) {
02906       // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
02907       // and vector ops, reducing the set of values being computed by half each
02908       // round.
02909       assert(isPowerOf2_32(VF) &&
02910              "Reduction emission only supported for pow2 vectors!");
02911       Value *TmpVec = ReducedPartRdx;
02912       SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
02913       for (unsigned i = VF; i != 1; i >>= 1) {
02914         // Move the upper half of the vector to the lower half.
02915         for (unsigned j = 0; j != i/2; ++j)
02916           ShuffleMask[j] = Builder.getInt32(i/2 + j);
02917 
02918         // Fill the rest of the mask with undef.
02919         std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
02920                   UndefValue::get(Builder.getInt32Ty()));
02921 
02922         Value *Shuf =
02923         Builder.CreateShuffleVector(TmpVec,
02924                                     UndefValue::get(TmpVec->getType()),
02925                                     ConstantVector::get(ShuffleMask),
02926                                     "rdx.shuf");
02927 
02928         if (Op != Instruction::ICmp && Op != Instruction::FCmp)
02929           // Floating point operations had to be 'fast' to enable the reduction.
02930           TmpVec = addFastMathFlag(Builder.CreateBinOp(
02931               (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
02932         else
02933           TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
02934       }
02935 
02936       // The result is in the first element of the vector.
02937       ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
02938                                                     Builder.getInt32(0));
02939     }
02940 
02941     // Create a phi node that merges control-flow from the backedge-taken check
02942     // block and the middle block.
02943     PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx",
02944                                           LoopScalarPreHeader->getTerminator());
02945     BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]);
02946     BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
02947 
02948     // Now, we need to fix the users of the reduction variable
02949     // inside and outside of the scalar remainder loop.
02950     // We know that the loop is in LCSSA form. We need to update the
02951     // PHI nodes in the exit blocks.
02952     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
02953          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
02954       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
02955       if (!LCSSAPhi) break;
02956 
02957       // All PHINodes need to have a single entry edge, or two if
02958       // we already fixed them.
02959       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
02960 
02961       // We found our reduction value exit-PHI. Update it with the
02962       // incoming bypass edge.
02963       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
02964         // Add an edge coming from the bypass.
02965         LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
02966         break;
02967       }
02968     }// end of the LCSSA phi scan.
02969 
02970     // Fix the scalar loop reduction variable with the incoming reduction sum
02971     // from the vector body and from the backedge value.
02972     int IncomingEdgeBlockIdx =
02973     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
02974     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
02975     // Pick the other block.
02976     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
02977     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
02978     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
02979   }// end of for each redux variable.
02980 
02981   fixLCSSAPHIs();
02982 
02983   // Remove redundant induction instructions.
02984   cse(LoopVectorBody);
02985 }
02986 
02987 void InnerLoopVectorizer::fixLCSSAPHIs() {
02988   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
02989        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
02990     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
02991     if (!LCSSAPhi) break;
02992     if (LCSSAPhi->getNumIncomingValues() == 1)
02993       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
02994                             LoopMiddleBlock);
02995   }
02996 } 
02997 
02998 InnerLoopVectorizer::VectorParts
02999 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
03000   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
03001          "Invalid edge");
03002 
03003   // Look for cached value.
03004   std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
03005   EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
03006   if (ECEntryIt != MaskCache.end())
03007     return ECEntryIt->second;
03008 
03009   VectorParts SrcMask = createBlockInMask(Src);
03010 
03011   // The terminator has to be a branch inst!
03012   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
03013   assert(BI && "Unexpected terminator found");
03014 
03015   if (BI->isConditional()) {
03016     VectorParts EdgeMask = getVectorValue(BI->getCondition());
03017 
03018     if (BI->getSuccessor(0) != Dst)
03019       for (unsigned part = 0; part < UF; ++part)
03020         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
03021 
03022     for (unsigned part = 0; part < UF; ++part)
03023       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
03024 
03025     MaskCache[Edge] = EdgeMask;
03026     return EdgeMask;
03027   }
03028 
03029   MaskCache[Edge] = SrcMask;
03030   return SrcMask;
03031 }
03032 
03033 InnerLoopVectorizer::VectorParts
03034 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
03035   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
03036 
03037   // Loop incoming mask is all-one.
03038   if (OrigLoop->getHeader() == BB) {
03039     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
03040     return getVectorValue(C);
03041   }
03042 
03043   // This is the block mask. We OR all incoming edges, and with zero.
03044   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
03045   VectorParts BlockMask = getVectorValue(Zero);
03046 
03047   // For each pred:
03048   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
03049     VectorParts EM = createEdgeMask(*it, BB);
03050     for (unsigned part = 0; part < UF; ++part)
03051       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
03052   }
03053 
03054   return BlockMask;
03055 }
03056 
03057 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
03058                                               InnerLoopVectorizer::VectorParts &Entry,
03059                                               unsigned UF, unsigned VF, PhiVector *PV) {
03060   PHINode* P = cast<PHINode>(PN);
03061   // Handle reduction variables:
03062   if (Legal->getReductionVars()->count(P)) {
03063     for (unsigned part = 0; part < UF; ++part) {
03064       // This is phase one of vectorizing PHIs.
03065       Type *VecTy = (VF == 1) ? PN->getType() :
03066       VectorType::get(PN->getType(), VF);
03067       Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
03068                                     LoopVectorBody.back()-> getFirstInsertionPt());
03069     }
03070     PV->push_back(P);
03071     return;
03072   }
03073 
03074   setDebugLocFromInst(Builder, P);
03075   // Check for PHI nodes that are lowered to vector selects.
03076   if (P->getParent() != OrigLoop->getHeader()) {
03077     // We know that all PHIs in non-header blocks are converted into
03078     // selects, so we don't have to worry about the insertion order and we
03079     // can just use the builder.
03080     // At this point we generate the predication tree. There may be
03081     // duplications since this is a simple recursive scan, but future
03082     // optimizations will clean it up.
03083 
03084     unsigned NumIncoming = P->getNumIncomingValues();
03085 
03086     // Generate a sequence of selects of the form:
03087     // SELECT(Mask3, In3,
03088     //      SELECT(Mask2, In2,
03089     //                   ( ...)))
03090     for (unsigned In = 0; In < NumIncoming; In++) {
03091       VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
03092                                         P->getParent());
03093       VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
03094 
03095       for (unsigned part = 0; part < UF; ++part) {
03096         // We might have single edge PHIs (blocks) - use an identity
03097         // 'select' for the first PHI operand.
03098         if (In == 0)
03099           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
03100                                              In0[part]);
03101         else
03102           // Select between the current value and the previous incoming edge
03103           // based on the incoming mask.
03104           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
03105                                              Entry[part], "predphi");
03106       }
03107     }
03108     return;
03109   }
03110 
03111   // This PHINode must be an induction variable.
03112   // Make sure that we know about it.
03113   assert(Legal->getInductionVars()->count(P) &&
03114          "Not an induction variable");
03115 
03116   LoopVectorizationLegality::InductionInfo II =
03117   Legal->getInductionVars()->lookup(P);
03118 
03119   switch (II.IK) {
03120     case LoopVectorizationLegality::IK_NoInduction:
03121       llvm_unreachable("Unknown induction");
03122     case LoopVectorizationLegality::IK_IntInduction: {
03123       assert(P->getType() == II.StartValue->getType() && "Types must match");
03124       Type *PhiTy = P->getType();
03125       Value *Broadcasted;
03126       if (P == OldInduction) {
03127         // Handle the canonical induction variable. We might have had to
03128         // extend the type.
03129         Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
03130       } else {
03131         // Handle other induction variables that are now based on the
03132         // canonical one.
03133         Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
03134                                                  "normalized.idx");
03135         NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
03136         Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
03137                                         "offset.idx");
03138       }
03139       Broadcasted = getBroadcastInstrs(Broadcasted);
03140       // After broadcasting the induction variable we need to make the vector
03141       // consecutive by adding 0, 1, 2, etc.
03142       for (unsigned part = 0; part < UF; ++part)
03143         Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
03144       return;
03145     }
03146     case LoopVectorizationLegality::IK_ReverseIntInduction:
03147     case LoopVectorizationLegality::IK_PtrInduction:
03148     case LoopVectorizationLegality::IK_ReversePtrInduction:
03149       // Handle reverse integer and pointer inductions.
03150       Value *StartIdx = ExtendedIdx;
03151       // This is the normalized GEP that starts counting at zero.
03152       Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
03153                                                "normalized.idx");
03154 
03155       // Handle the reverse integer induction variable case.
03156       if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
03157         IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
03158         Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
03159                                                "resize.norm.idx");
03160         Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
03161                                                "reverse.idx");
03162 
03163         // This is a new value so do not hoist it out.
03164         Value *Broadcasted = getBroadcastInstrs(ReverseInd);
03165         // After broadcasting the induction variable we need to make the
03166         // vector consecutive by adding  ... -3, -2, -1, 0.
03167         for (unsigned part = 0; part < UF; ++part)
03168           Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
03169                                              true);
03170         return;
03171       }
03172 
03173       // Handle the pointer induction variable case.
03174       assert(P->getType()->isPointerTy() && "Unexpected type.");
03175 
03176       // Is this a reverse induction ptr or a consecutive induction ptr.
03177       bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
03178                       II.IK);
03179 
03180       // This is the vector of results. Notice that we don't generate
03181       // vector geps because scalar geps result in better code.
03182       for (unsigned part = 0; part < UF; ++part) {
03183         if (VF == 1) {
03184           int EltIndex = (part) * (Reverse ? -1 : 1);
03185           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
03186           Value *GlobalIdx;
03187           if (Reverse)
03188             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
03189           else
03190             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
03191 
03192           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
03193                                              "next.gep");
03194           Entry[part] = SclrGep;
03195           continue;
03196         }
03197 
03198         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
03199         for (unsigned int i = 0; i < VF; ++i) {
03200           int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
03201           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
03202           Value *GlobalIdx;
03203           if (!Reverse)
03204             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
03205           else
03206             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
03207 
03208           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
03209                                              "next.gep");
03210           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
03211                                                Builder.getInt32(i),
03212                                                "insert.gep");
03213         }
03214         Entry[part] = VecVal;
03215       }
03216       return;
03217   }
03218 }
03219 
03220 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
03221   // For each instruction in the old loop.
03222   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
03223     VectorParts &Entry = WidenMap.get(it);
03224     switch (it->getOpcode()) {
03225     case Instruction::Br:
03226       // Nothing to do for PHIs and BR, since we already took care of the
03227       // loop control flow instructions.
03228       continue;
03229     case Instruction::PHI:{
03230       // Vectorize PHINodes.
03231       widenPHIInstruction(it, Entry, UF, VF, PV);
03232       continue;
03233     }// End of PHI.
03234 
03235     case Instruction::Add:
03236     case Instruction::FAdd:
03237     case Instruction::Sub:
03238     case Instruction::FSub:
03239     case Instruction::Mul:
03240     case Instruction::FMul:
03241     case Instruction::UDiv:
03242     case Instruction::SDiv:
03243     case Instruction::FDiv:
03244     case Instruction::URem:
03245     case Instruction::SRem:
03246     case Instruction::FRem:
03247     case Instruction::Shl:
03248     case Instruction::LShr:
03249     case Instruction::AShr:
03250     case Instruction::And:
03251     case Instruction::Or:
03252     case Instruction::Xor: {
03253       // Just widen binops.
03254       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
03255       setDebugLocFromInst(Builder, BinOp);
03256       VectorParts &A = getVectorValue(it->getOperand(0));
03257       VectorParts &B = getVectorValue(it->getOperand(1));
03258 
03259       // Use this vector value for all users of the original instruction.
03260       for (unsigned Part = 0; Part < UF; ++Part) {
03261         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
03262 
03263         if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
03264           VecOp->copyIRFlags(BinOp);
03265         
03266         Entry[Part] = V;
03267       }
03268 
03269       propagateMetadata(Entry, it);
03270       break;
03271     }
03272     case Instruction::Select: {
03273       // Widen selects.
03274       // If the selector is loop invariant we can create a select
03275       // instruction with a scalar condition. Otherwise, use vector-select.
03276       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
03277                                                OrigLoop);
03278       setDebugLocFromInst(Builder, it);
03279 
03280       // The condition can be loop invariant  but still defined inside the
03281       // loop. This means that we can't just use the original 'cond' value.
03282       // We have to take the 'vectorized' value and pick the first lane.
03283       // Instcombine will make this a no-op.
03284       VectorParts &Cond = getVectorValue(it->getOperand(0));
03285       VectorParts &Op0  = getVectorValue(it->getOperand(1));
03286       VectorParts &Op1  = getVectorValue(it->getOperand(2));
03287 
03288       Value *ScalarCond = (VF == 1) ? Cond[0] :
03289         Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
03290 
03291       for (unsigned Part = 0; Part < UF; ++Part) {
03292         Entry[Part] = Builder.CreateSelect(
03293           InvariantCond ? ScalarCond : Cond[Part],
03294           Op0[Part],
03295           Op1[Part]);
03296       }
03297 
03298       propagateMetadata(Entry, it);
03299       break;
03300     }
03301 
03302     case Instruction::ICmp:
03303     case Instruction::FCmp: {
03304       // Widen compares. Generate vector compares.
03305       bool FCmp = (it->getOpcode() == Instruction::FCmp);
03306       CmpInst *Cmp = dyn_cast<CmpInst>(it);
03307       setDebugLocFromInst(Builder, it);
03308       VectorParts &A = getVectorValue(it->getOperand(0));
03309       VectorParts &B = getVectorValue(it->getOperand(1));
03310       for (unsigned Part = 0; Part < UF; ++Part) {
03311         Value *C = nullptr;
03312         if (FCmp)
03313           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
03314         else
03315           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
03316         Entry[Part] = C;
03317       }
03318 
03319       propagateMetadata(Entry, it);
03320       break;
03321     }
03322 
03323     case Instruction::Store:
03324     case Instruction::Load:
03325       vectorizeMemoryInstruction(it);
03326         break;
03327     case Instruction::ZExt:
03328     case Instruction::SExt:
03329     case Instruction::FPToUI:
03330     case Instruction::FPToSI:
03331     case Instruction::FPExt:
03332     case Instruction::PtrToInt:
03333     case Instruction::IntToPtr:
03334     case Instruction::SIToFP:
03335     case Instruction::UIToFP:
03336     case Instruction::Trunc:
03337     case Instruction::FPTrunc:
03338     case Instruction::BitCast: {
03339       CastInst *CI = dyn_cast<CastInst>(it);
03340       setDebugLocFromInst(Builder, it);
03341       /// Optimize the special case where the source is the induction
03342       /// variable. Notice that we can only optimize the 'trunc' case
03343       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
03344       /// c. other casts depend on pointer size.
03345       if (CI->getOperand(0) == OldInduction &&
03346           it->getOpcode() == Instruction::Trunc) {
03347         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
03348                                                CI->getType());
03349         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
03350         for (unsigned Part = 0; Part < UF; ++Part)
03351           Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
03352         propagateMetadata(Entry, it);
03353         break;
03354       }
03355       /// Vectorize casts.
03356       Type *DestTy = (VF == 1) ? CI->getType() :
03357                                  VectorType::get(CI->getType(), VF);
03358 
03359       VectorParts &A = getVectorValue(it->getOperand(0));
03360       for (unsigned Part = 0; Part < UF; ++Part)
03361         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
03362       propagateMetadata(Entry, it);
03363       break;
03364     }
03365 
03366     case Instruction::Call: {
03367       // Ignore dbg intrinsics.
03368       if (isa<DbgInfoIntrinsic>(it))
03369         break;
03370       setDebugLocFromInst(Builder, it);
03371 
03372       Module *M = BB->getParent()->getParent();
03373       CallInst *CI = cast<CallInst>(it);
03374       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
03375       assert(ID && "Not an intrinsic call!");
03376       switch (ID) {
03377       case Intrinsic::assume:
03378       case Intrinsic::lifetime_end:
03379       case Intrinsic::lifetime_start:
03380         scalarizeInstruction(it);
03381         break;
03382       default:
03383         bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1);
03384         for (unsigned Part = 0; Part < UF; ++Part) {
03385           SmallVector<Value *, 4> Args;
03386           for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
03387             if (HasScalarOpd && i == 1) {
03388               Args.push_back(CI->getArgOperand(i));
03389               continue;
03390             }
03391             VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
03392             Args.push_back(Arg[Part]);
03393           }
03394           Type *Tys[] = {CI->getType()};
03395           if (VF > 1)
03396             Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
03397 
03398           Function *F = Intrinsic::getDeclaration(M, ID, Tys);
03399           Entry[Part] = Builder.CreateCall(F, Args);
03400         }
03401 
03402         propagateMetadata(Entry, it);
03403         break;
03404       }
03405       break;
03406     }
03407 
03408     default:
03409       // All other instructions are unsupported. Scalarize them.
03410       scalarizeInstruction(it);
03411       break;
03412     }// end of switch.
03413   }// end of for_each instr.
03414 }
03415 
03416 void InnerLoopVectorizer::updateAnalysis() {
03417   // Forget the original basic block.
03418   SE->forgetLoop(OrigLoop);
03419 
03420   // Update the dominator tree information.
03421   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
03422          "Entry does not dominate exit.");
03423 
03424   for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
03425     DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
03426   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
03427 
03428   // Due to if predication of stores we might create a sequence of "if(pred)
03429   // a[i] = ...;  " blocks.
03430   for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) {
03431     if (i == 0)
03432       DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
03433     else if (isPredicatedBlock(i)) {
03434       DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]);
03435     } else {
03436       DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]);
03437     }
03438   }
03439 
03440   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]);
03441   DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
03442   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
03443   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
03444 
03445   DEBUG(DT->verifyDomTree());
03446 }
03447 
03448 /// \brief Check whether it is safe to if-convert this phi node.
03449 ///
03450 /// Phi nodes with constant expressions that can trap are not safe to if
03451 /// convert.
03452 static bool canIfConvertPHINodes(BasicBlock *BB) {
03453   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
03454     PHINode *Phi = dyn_cast<PHINode>(I);
03455     if (!Phi)
03456       return true;
03457     for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
03458       if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
03459         if (C->canTrap())
03460           return false;
03461   }
03462   return true;
03463 }
03464 
03465 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
03466   if (!EnableIfConversion) {
03467     emitAnalysis(Report() << "if-conversion is disabled");
03468     return false;
03469   }
03470 
03471   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
03472 
03473   // A list of pointers that we can safely read and write to.
03474   SmallPtrSet<Value *, 8> SafePointes;
03475 
03476   // Collect safe addresses.
03477   for (Loop::block_iterator BI = TheLoop->block_begin(),
03478          BE = TheLoop->block_end(); BI != BE; ++BI) {
03479     BasicBlock *BB = *BI;
03480 
03481     if (blockNeedsPredication(BB))
03482       continue;
03483 
03484     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
03485       if (LoadInst *LI = dyn_cast<LoadInst>(I))
03486         SafePointes.insert(LI->getPointerOperand());
03487       else if (StoreInst *SI = dyn_cast<StoreInst>(I))
03488         SafePointes.insert(SI->getPointerOperand());
03489     }
03490   }
03491 
03492   // Collect the blocks that need predication.
03493   BasicBlock *Header = TheLoop->getHeader();
03494   for (Loop::block_iterator BI = TheLoop->block_begin(),
03495          BE = TheLoop->block_end(); BI != BE; ++BI) {
03496     BasicBlock *BB = *BI;
03497 
03498     // We don't support switch statements inside loops.
03499     if (!isa<BranchInst>(BB->getTerminator())) {
03500       emitAnalysis(Report(BB->getTerminator())
03501                    << "loop contains a switch statement");
03502       return false;
03503     }
03504 
03505     // We must be able to predicate all blocks that need to be predicated.
03506     if (blockNeedsPredication(BB)) {
03507       if (!blockCanBePredicated(BB, SafePointes)) {
03508         emitAnalysis(Report(BB->getTerminator())
03509                      << "control flow cannot be substituted for a select");
03510         return false;
03511       }
03512     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
03513       emitAnalysis(Report(BB->getTerminator())
03514                    << "control flow cannot be substituted for a select");
03515       return false;
03516     }
03517   }
03518 
03519   // We can if-convert this loop.
03520   return true;
03521 }
03522 
03523 bool LoopVectorizationLegality::canVectorize() {
03524   // We must have a loop in canonical form. Loops with indirectbr in them cannot
03525   // be canonicalized.
03526   if (!TheLoop->getLoopPreheader()) {
03527     emitAnalysis(
03528         Report() << "loop control flow is not understood by vectorizer");
03529     return false;
03530   }
03531 
03532   // We can only vectorize innermost loops.
03533   if (TheLoop->getSubLoopsVector().size()) {
03534     emitAnalysis(Report() << "loop is not the innermost loop");
03535     return false;
03536   }
03537 
03538   // We must have a single backedge.
03539   if (TheLoop->getNumBackEdges() != 1) {
03540     emitAnalysis(
03541         Report() << "loop control flow is not understood by vectorizer");
03542     return false;
03543   }
03544 
03545   // We must have a single exiting block.
03546   if (!TheLoop->getExitingBlock()) {
03547     emitAnalysis(
03548         Report() << "loop control flow is not understood by vectorizer");
03549     return false;
03550   }
03551 
03552   // We need to have a loop header.
03553   DEBUG(dbgs() << "LV: Found a loop: " <<
03554         TheLoop->getHeader()->getName() << '\n');
03555 
03556   // Check if we can if-convert non-single-bb loops.
03557   unsigned NumBlocks = TheLoop->getNumBlocks();
03558   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
03559     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
03560     return false;
03561   }
03562 
03563   // ScalarEvolution needs to be able to find the exit count.
03564   const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
03565   if (ExitCount == SE->getCouldNotCompute()) {
03566     emitAnalysis(Report() << "could not determine number of loop iterations");
03567     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
03568     return false;
03569   }
03570 
03571   // Check if we can vectorize the instructions and CFG in this loop.
03572   if (!canVectorizeInstrs()) {
03573     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
03574     return false;
03575   }
03576 
03577   // Go over each instruction and look at memory deps.
03578   if (!canVectorizeMemory()) {
03579     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
03580     return false;
03581   }
03582 
03583   // Collect all of the variables that remain uniform after vectorization.
03584   collectLoopUniforms();
03585 
03586   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
03587         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
03588         <<"!\n");
03589 
03590   // Okay! We can vectorize. At this point we don't have any other mem analysis
03591   // which may limit our maximum vectorization factor, so just return true with
03592   // no restrictions.
03593   return true;
03594 }
03595 
03596 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
03597   if (Ty->isPointerTy())
03598     return DL.getIntPtrType(Ty);
03599 
03600   // It is possible that char's or short's overflow when we ask for the loop's
03601   // trip count, work around this by changing the type size.
03602   if (Ty->getScalarSizeInBits() < 32)
03603     return Type::getInt32Ty(Ty->getContext());
03604 
03605   return Ty;
03606 }
03607 
03608 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
03609   Ty0 = convertPointerToIntegerType(DL, Ty0);
03610   Ty1 = convertPointerToIntegerType(DL, Ty1);
03611   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
03612     return Ty0;
03613   return Ty1;
03614 }
03615 
03616 /// \brief Check that the instruction has outside loop users and is not an
03617 /// identified reduction variable.
03618 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
03619                                SmallPtrSetImpl<Value *> &Reductions) {
03620   // Reduction instructions are allowed to have exit users. All other
03621   // instructions must not have external users.
03622   if (!Reductions.count(Inst))
03623     //Check that all of the users of the loop are inside the BB.
03624     for (User *U : Inst->users()) {
03625       Instruction *UI = cast<Instruction>(U);
03626       // This user may be a reduction exit value.
03627       if (!TheLoop->contains(UI)) {
03628         DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
03629         return true;
03630       }
03631     }
03632   return false;
03633 }
03634 
03635 bool LoopVectorizationLegality::canVectorizeInstrs() {
03636   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
03637   BasicBlock *Header = TheLoop->getHeader();
03638 
03639   // Look for the attribute signaling the absence of NaNs.
03640   Function &F = *Header->getParent();
03641   if (F.hasFnAttribute("no-nans-fp-math"))
03642     HasFunNoNaNAttr = F.getAttributes().getAttribute(
03643       AttributeSet::FunctionIndex,
03644       "no-nans-fp-math").getValueAsString() == "true";
03645 
03646   // For each block in the loop.
03647   for (Loop::block_iterator bb = TheLoop->block_begin(),
03648        be = TheLoop->block_end(); bb != be; ++bb) {
03649 
03650     // Scan the instructions in the block and look for hazards.
03651     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
03652          ++it) {
03653 
03654       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
03655         Type *PhiTy = Phi->getType();
03656         // Check that this PHI type is allowed.
03657         if (!PhiTy->isIntegerTy() &&
03658             !PhiTy->isFloatingPointTy() &&
03659             !PhiTy->isPointerTy()) {
03660           emitAnalysis(Report(it)
03661                        << "loop control flow is not understood by vectorizer");
03662           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
03663           return false;
03664         }
03665 
03666         // If this PHINode is not in the header block, then we know that we
03667         // can convert it to select during if-conversion. No need to check if
03668         // the PHIs in this block are induction or reduction variables.
03669         if (*bb != Header) {
03670           // Check that this instruction has no outside users or is an
03671           // identified reduction value with an outside user.
03672           if (!hasOutsideLoopUser(TheLoop, it, AllowedExit))
03673             continue;
03674           emitAnalysis(Report(it) << "value could not be identified as "
03675                                      "an induction or reduction variable");
03676           return false;
03677         }
03678 
03679         // We only allow if-converted PHIs with more than two incoming values.
03680         if (Phi->getNumIncomingValues() != 2) {
03681           emitAnalysis(Report(it)
03682                        << "control flow not understood by vectorizer");
03683           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
03684           return false;
03685         }
03686 
03687         // This is the value coming from the preheader.
03688         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
03689         // Check if this is an induction variable.
03690         InductionKind IK = isInductionVariable(Phi);
03691 
03692         if (IK_NoInduction != IK) {
03693           // Get the widest type.
03694           if (!WidestIndTy)
03695             WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
03696           else
03697             WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
03698 
03699           // Int inductions are special because we only allow one IV.
03700           if (IK == IK_IntInduction) {
03701             // Use the phi node with the widest type as induction. Use the last
03702             // one if there are multiple (no good reason for doing this other
03703             // than it is expedient).
03704             if (!Induction || PhiTy == WidestIndTy)
03705               Induction = Phi;
03706           }
03707 
03708           DEBUG(dbgs() << "LV: Found an induction variable.\n");
03709           Inductions[Phi] = InductionInfo(StartValue, IK);
03710 
03711           // Until we explicitly handle the case of an induction variable with
03712           // an outside loop user we have to give up vectorizing this loop.
03713           if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
03714             emitAnalysis(Report(it) << "use of induction value outside of the "
03715                                        "loop is not handled by vectorizer");
03716             return false;
03717           }
03718 
03719           continue;
03720         }
03721 
03722         if (AddReductionVar(Phi, RK_IntegerAdd)) {
03723           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
03724           continue;
03725         }
03726         if (AddReductionVar(Phi, RK_IntegerMult)) {
03727           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
03728           continue;
03729         }
03730         if (AddReductionVar(Phi, RK_IntegerOr)) {
03731           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
03732           continue;
03733         }
03734         if (AddReductionVar(Phi, RK_IntegerAnd)) {
03735           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
03736           continue;
03737         }
03738         if (AddReductionVar(Phi, RK_IntegerXor)) {
03739           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
03740           continue;
03741         }
03742         if (AddReductionVar(Phi, RK_IntegerMinMax)) {
03743           DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
03744           continue;
03745         }
03746         if (AddReductionVar(Phi, RK_FloatMult)) {
03747           DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
03748           continue;
03749         }
03750         if (AddReductionVar(Phi, RK_FloatAdd)) {
03751           DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
03752           continue;
03753         }
03754         if (AddReductionVar(Phi, RK_FloatMinMax)) {
03755           DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
03756                 "\n");
03757           continue;
03758         }
03759 
03760         emitAnalysis(Report(it) << "value that could not be identified as "
03761                                    "reduction is used outside the loop");
03762         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
03763         return false;
03764       }// end of PHI handling
03765 
03766       // We still don't handle functions. However, we can ignore dbg intrinsic
03767       // calls and we do handle certain intrinsic and libm functions.
03768       CallInst *CI = dyn_cast<CallInst>(it);
03769       if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
03770         emitAnalysis(Report(it) << "call instruction cannot be vectorized");
03771         DEBUG(dbgs() << "LV: Found a call site.\n");
03772         return false;
03773       }
03774 
03775       // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
03776       // second argument is the same (i.e. loop invariant)
03777       if (CI &&
03778           hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) {
03779         if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) {
03780           emitAnalysis(Report(it)
03781                        << "intrinsic instruction cannot be vectorized");
03782           DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
03783           return false;
03784         }
03785       }
03786 
03787       // Check that the instruction return type is vectorizable.
03788       // Also, we can't vectorize extractelement instructions.
03789       if ((!VectorType::isValidElementType(it->getType()) &&
03790            !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
03791         emitAnalysis(Report(it)
03792                      << "instruction return type cannot be vectorized");
03793         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
03794         return false;
03795       }
03796 
03797       // Check that the stored type is vectorizable.
03798       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
03799         Type *T = ST->getValueOperand()->getType();
03800         if (!VectorType::isValidElementType(T)) {
03801           emitAnalysis(Report(ST) << "store instruction cannot be vectorized");
03802           return false;
03803         }
03804         if (EnableMemAccessVersioning)
03805           collectStridedAcccess(ST);
03806       }
03807 
03808       if (EnableMemAccessVersioning)
03809         if (LoadInst *LI = dyn_cast<LoadInst>(it))
03810           collectStridedAcccess(LI);
03811 
03812       // Reduction instructions are allowed to have exit users.
03813       // All other instructions must not have external users.
03814       if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) {
03815         emitAnalysis(Report(it) << "value cannot be used outside the loop");
03816         return false;
03817       }
03818 
03819     } // next instr.
03820 
03821   }
03822 
03823   if (!Induction) {
03824     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
03825     if (Inductions.empty()) {
03826       emitAnalysis(Report()
03827                    << "loop induction variable could not be identified");
03828       return false;
03829     }
03830   }
03831 
03832   return true;
03833 }
03834 
03835 ///\brief Remove GEPs whose indices but the last one are loop invariant and
03836 /// return the induction operand of the gep pointer.
03837 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
03838                                  const DataLayout *DL, Loop *Lp) {
03839   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
03840   if (!GEP)
03841     return Ptr;
03842 
03843   unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
03844 
03845   // Check that all of the gep indices are uniform except for our induction
03846   // operand.
03847   for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
03848     if (i != InductionOperand &&
03849         !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
03850       return Ptr;
03851   return GEP->getOperand(InductionOperand);
03852 }
03853 
03854 ///\brief Look for a cast use of the passed value.
03855 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
03856   Value *UniqueCast = nullptr;
03857   for (User *U : Ptr->users()) {
03858     CastInst *CI = dyn_cast<CastInst>(U);
03859     if (CI && CI->getType() == Ty) {
03860       if (!UniqueCast)
03861         UniqueCast = CI;
03862       else
03863         return nullptr;
03864     }
03865   }
03866   return UniqueCast;
03867 }
03868 
03869 ///\brief Get the stride of a pointer access in a loop.
03870 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
03871 /// pointer to the Value, or null otherwise.
03872 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
03873                                    const DataLayout *DL, Loop *Lp) {
03874   const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
03875   if (!PtrTy || PtrTy->isAggregateType())
03876     return nullptr;
03877 
03878   // Try to remove a gep instruction to make the pointer (actually index at this
03879   // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
03880   // pointer, otherwise, we are analyzing the index.
03881   Value *OrigPtr = Ptr;
03882 
03883   // The size of the pointer access.
03884   int64_t PtrAccessSize = 1;
03885 
03886   Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
03887   const SCEV *V = SE->getSCEV(Ptr);
03888 
03889   if (Ptr != OrigPtr)
03890     // Strip off casts.
03891     while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
03892       V = C->getOperand();
03893 
03894   const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
03895   if (!S)
03896     return nullptr;
03897 
03898   V = S->getStepRecurrence(*SE);
03899   if (!V)
03900     return nullptr;
03901 
03902   // Strip off the size of access multiplication if we are still analyzing the
03903   // pointer.
03904   if (OrigPtr == Ptr) {
03905     DL->getTypeAllocSize(PtrTy->getElementType());
03906     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
03907       if (M->getOperand(0)->getSCEVType() != scConstant)
03908         return nullptr;
03909 
03910       const APInt &APStepVal =
03911           cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
03912 
03913       // Huge step value - give up.
03914       if (APStepVal.getBitWidth() > 64)
03915         return nullptr;
03916 
03917       int64_t StepVal = APStepVal.getSExtValue();
03918       if (PtrAccessSize != StepVal)
03919         return nullptr;
03920       V = M->getOperand(1);
03921     }
03922   }
03923 
03924   // Strip off casts.
03925   Type *StripedOffRecurrenceCast = nullptr;
03926   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
03927     StripedOffRecurrenceCast = C->getType();
03928     V = C->getOperand();
03929   }
03930 
03931   // Look for the loop invariant symbolic value.
03932   const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
03933   if (!U)
03934     return nullptr;
03935 
03936   Value *Stride = U->getValue();
03937   if (!Lp->isLoopInvariant(Stride))
03938     return nullptr;
03939 
03940   // If we have stripped off the recurrence cast we have to make sure that we
03941   // return the value that is used in this loop so that we can replace it later.
03942   if (StripedOffRecurrenceCast)
03943     Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
03944 
03945   return Stride;
03946 }
03947 
03948 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
03949   Value *Ptr = nullptr;
03950   if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
03951     Ptr = LI->getPointerOperand();
03952   else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
03953     Ptr = SI->getPointerOperand();
03954   else
03955     return;
03956 
03957   Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
03958   if (!Stride)
03959     return;
03960 
03961   DEBUG(dbgs() << "LV: Found a strided access that we can version");
03962   DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
03963   Strides[Ptr] = Stride;
03964   StrideSet.insert(Stride);
03965 }
03966 
03967 void LoopVectorizationLegality::collectLoopUniforms() {
03968   // We now know that the loop is vectorizable!
03969   // Collect variables that will remain uniform after vectorization.
03970   std::vector<Value*> Worklist;
03971   BasicBlock *Latch = TheLoop->getLoopLatch();
03972 
03973   // Start with the conditional branch and walk up the block.
03974   Worklist.push_back(Latch->getTerminator()->getOperand(0));
03975 
03976   // Also add all consecutive pointer values; these values will be uniform
03977   // after vectorization (and subsequent cleanup) and, until revectorization is
03978   // supported, all dependencies must also be uniform.
03979   for (Loop::block_iterator B = TheLoop->block_begin(),
03980        BE = TheLoop->block_end(); B != BE; ++B)
03981     for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
03982          I != IE; ++I)
03983       if (I->getType()->isPointerTy() && isConsecutivePtr(I))
03984         Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
03985 
03986   while (Worklist.size()) {
03987     Instruction *I = dyn_cast<Instruction>(Worklist.back());
03988     Worklist.pop_back();
03989 
03990     // Look at instructions inside this loop.
03991     // Stop when reaching PHI nodes.
03992     // TODO: we need to follow values all over the loop, not only in this block.
03993     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
03994       continue;
03995 
03996     // This is a known uniform.
03997     Uniforms.insert(I);
03998 
03999     // Insert all operands.
04000     Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
04001   }
04002 }
04003 
04004 namespace {
04005 /// \brief Analyses memory accesses in a loop.
04006 ///
04007 /// Checks whether run time pointer checks are needed and builds sets for data
04008 /// dependence checking.
04009 class AccessAnalysis {
04010 public:
04011   /// \brief Read or write access location.
04012   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
04013   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
04014 
04015   /// \brief Set of potential dependent memory accesses.
04016   typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
04017 
04018   AccessAnalysis(const DataLayout *Dl, AliasAnalysis *AA, DepCandidates &DA) :
04019     DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
04020 
04021   /// \brief Register a load  and whether it is only read from.
04022   void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
04023     Value *Ptr = const_cast<Value*>(Loc.Ptr);
04024     AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
04025     Accesses.insert(MemAccessInfo(Ptr, false));
04026     if (IsReadOnly)
04027       ReadOnlyPtr.insert(Ptr);
04028   }
04029 
04030   /// \brief Register a store.
04031   void addStore(AliasAnalysis::Location &Loc) {
04032     Value *Ptr = const_cast<Value*>(Loc.Ptr);
04033     AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
04034     Accesses.insert(MemAccessInfo(Ptr, true));
04035   }
04036 
04037   /// \brief Check whether we can check the pointers at runtime for
04038   /// non-intersection.
04039   bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
04040                        unsigned &NumComparisons, ScalarEvolution *SE,
04041                        Loop *TheLoop, ValueToValueMap &Strides,
04042                        bool ShouldCheckStride = false);
04043 
04044   /// \brief Goes over all memory accesses, checks whether a RT check is needed
04045   /// and builds sets of dependent accesses.
04046   void buildDependenceSets() {
04047     processMemAccesses();
04048   }
04049 
04050   bool isRTCheckNeeded() { return IsRTCheckNeeded; }
04051 
04052   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
04053   void resetDepChecks() { CheckDeps.clear(); }
04054 
04055   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
04056 
04057 private:
04058   typedef SetVector<MemAccessInfo> PtrAccessSet;
04059 
04060   /// \brief Go over all memory access and check whether runtime pointer checks
04061   /// are needed /// and build sets of dependency check candidates.
04062   void processMemAccesses();
04063 
04064   /// Set of all accesses.
04065   PtrAccessSet Accesses;
04066 
04067   /// Set of accesses that need a further dependence check.
04068   MemAccessInfoSet CheckDeps;
04069 
04070   /// Set of pointers that are read only.
04071   SmallPtrSet<Value*, 16> ReadOnlyPtr;
04072 
04073   const DataLayout *DL;
04074 
04075   /// An alias set tracker to partition the access set by underlying object and
04076   //intrinsic property (such as TBAA metadata).
04077   AliasSetTracker AST;
04078 
04079   /// Sets of potentially dependent accesses - members of one set share an
04080   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
04081   /// dependence check.
04082   DepCandidates &DepCands;
04083 
04084   bool IsRTCheckNeeded;
04085 };
04086 
04087 } // end anonymous namespace
04088 
04089 /// \brief Check whether a pointer can participate in a runtime bounds check.
04090 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
04091                                 Value *Ptr) {
04092   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
04093   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
04094   if (!AR)
04095     return false;
04096 
04097   return AR->isAffine();
04098 }
04099 
04100 /// \brief Check the stride of the pointer and ensure that it does not wrap in
04101 /// the address space.
04102 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
04103                         const Loop *Lp, ValueToValueMap &StridesMap);
04104 
04105 bool AccessAnalysis::canCheckPtrAtRT(
04106     LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
04107     unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
04108     ValueToValueMap &StridesMap, bool ShouldCheckStride) {
04109   // Find pointers with computable bounds. We are going to use this information
04110   // to place a runtime bound check.
04111   bool CanDoRT = true;
04112 
04113   bool IsDepCheckNeeded = isDependencyCheckNeeded();
04114   NumComparisons = 0;
04115 
04116   // We assign a consecutive id to access from different alias sets.
04117   // Accesses between different groups doesn't need to be checked.
04118   unsigned ASId = 1;
04119   for (auto &AS : AST) {
04120     unsigned NumReadPtrChecks = 0;
04121     unsigned NumWritePtrChecks = 0;
04122 
04123     // We assign consecutive id to access from different dependence sets.
04124     // Accesses within the same set don't need a runtime check.
04125     unsigned RunningDepId = 1;
04126     DenseMap<Value *, unsigned> DepSetId;
04127 
04128     for (auto A : AS) {
04129       Value *Ptr = A.getValue();
04130       bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
04131       MemAccessInfo Access(Ptr, IsWrite);
04132 
04133       if (IsWrite)
04134         ++NumWritePtrChecks;
04135       else
04136         ++NumReadPtrChecks;
04137 
04138       if (hasComputableBounds(SE, StridesMap, Ptr) &&
04139           // When we run after a failing dependency check we have to make sure we
04140           // don't have wrapping pointers.
04141           (!ShouldCheckStride ||
04142            isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
04143         // The id of the dependence set.
04144         unsigned DepId;
04145 
04146         if (IsDepCheckNeeded) {
04147           Value *Leader = DepCands.getLeaderValue(Access).getPointer();
04148           unsigned &LeaderId = DepSetId[Leader];
04149           if (!LeaderId)
04150             LeaderId = RunningDepId++;
04151           DepId = LeaderId;
04152         } else
04153           // Each access has its own dependence set.
04154           DepId = RunningDepId++;
04155 
04156         RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
04157 
04158         DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
04159       } else {
04160         CanDoRT = false;
04161       }
04162     }
04163 
04164     if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
04165       NumComparisons += 0; // Only one dependence set.
04166     else {
04167       NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
04168                                               NumWritePtrChecks - 1));
04169     }
04170 
04171     ++ASId;
04172   }
04173 
04174   // If the pointers that we would use for the bounds comparison have different
04175   // address spaces, assume the values aren't directly comparable, so we can't
04176   // use them for the runtime check. We also have to assume they could
04177   // overlap. In the future there should be metadata for whether address spaces
04178   // are disjoint.
04179   unsigned NumPointers = RtCheck.Pointers.size();
04180   for (unsigned i = 0; i < NumPointers; ++i) {
04181     for (unsigned j = i + 1; j < NumPointers; ++j) {
04182       // Only need to check pointers between two different dependency sets.
04183       if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
04184        continue;
04185       // Only need to check pointers in the same alias set.
04186       if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
04187         continue;
04188 
04189       Value *PtrI = RtCheck.Pointers[i];
04190       Value *PtrJ = RtCheck.Pointers[j];
04191 
04192       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
04193       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
04194       if (ASi != ASj) {
04195         DEBUG(dbgs() << "LV: Runtime check would require comparison between"
04196                        " different address spaces\n");
04197         return false;
04198       }
04199     }
04200   }
04201 
04202   return CanDoRT;
04203 }
04204 
04205 void AccessAnalysis::processMemAccesses() {
04206   // We process the set twice: first we process read-write pointers, last we
04207   // process read-only pointers. This allows us to skip dependence tests for
04208   // read-only pointers.
04209 
04210   DEBUG(dbgs() << "LV: Processing memory accesses...\n");
04211   DEBUG(dbgs() << "  AST: "; AST.dump());
04212   DEBUG(dbgs() << "LV:   Accesses:\n");
04213   DEBUG({
04214     for (auto A : Accesses)
04215       dbgs() << "\t" << *A.getPointer() << " (" <<
04216                 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
04217                                          "read-only" : "read")) << ")\n";
04218   });
04219 
04220   // The AliasSetTracker has nicely partitioned our pointers by metadata
04221   // compatibility and potential for underlying-object overlap. As a result, we
04222   // only need to check for potential pointer dependencies within each alias
04223   // set.
04224   for (auto &AS : AST) {
04225     // Note that both the alias-set tracker and the alias sets themselves used
04226     // linked lists internally and so the iteration order here is deterministic
04227     // (matching the original instruction order within each set).
04228 
04229     bool SetHasWrite = false;
04230 
04231     // Map of pointers to last access encountered.
04232     typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
04233     UnderlyingObjToAccessMap ObjToLastAccess;
04234 
04235     // Set of access to check after all writes have been processed.
04236     PtrAccessSet DeferredAccesses;
04237 
04238     // Iterate over each alias set twice, once to process read/write pointers,
04239     // and then to process read-only pointers.
04240     for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
04241       bool UseDeferred = SetIteration > 0;
04242       PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
04243 
04244       for (auto A : AS) {
04245         Value *Ptr = A.getValue();
04246         bool IsWrite = S.count(MemAccessInfo(Ptr, true));
04247 
04248         // If we're using the deferred access set, then it contains only reads.
04249         bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
04250         if (UseDeferred && !IsReadOnlyPtr)
04251           continue;
04252         // Otherwise, the pointer must be in the PtrAccessSet, either as a read
04253         // or a write.
04254         assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
04255                  S.count(MemAccessInfo(Ptr, false))) &&
04256                "Alias-set pointer not in the access set?");
04257 
04258         MemAccessInfo Access(Ptr, IsWrite);
04259         DepCands.insert(Access);
04260 
04261         // Memorize read-only pointers for later processing and skip them in the
04262         // first round (they need to be checked after we have seen all write
04263         // pointers). Note: we also mark pointer that are not consecutive as
04264         // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need
04265         // the second check for "!IsWrite".
04266         if (!UseDeferred && IsReadOnlyPtr) {
04267           DeferredAccesses.insert(Access);
04268           continue;
04269         }
04270 
04271         // If this is a write - check other reads and writes for conflicts.  If
04272         // this is a read only check other writes for conflicts (but only if
04273         // there is no other write to the ptr - this is an optimization to
04274         // catch "a[i] = a[i] + " without having to do a dependence check).
04275         if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
04276           CheckDeps.insert(Access);
04277           IsRTCheckNeeded = true;
04278         }
04279 
04280         if (IsWrite)
04281           SetHasWrite = true;
04282 
04283   // Create sets of pointers connected by a shared alias set and
04284   // underlying object.
04285         typedef SmallVector<Value*, 16> ValueVector;
04286         ValueVector TempObjects;
04287         GetUnderlyingObjects(Ptr, TempObjects, DL);
04288         for (Value *UnderlyingObj : TempObjects) {
04289           UnderlyingObjToAccessMap::iterator Prev =
04290             ObjToLastAccess.find(UnderlyingObj);
04291           if (Prev != ObjToLastAccess.end())
04292             DepCands.unionSets(Access, Prev->second);
04293 
04294           ObjToLastAccess[UnderlyingObj] = Access;
04295         }
04296       }
04297     }
04298   }
04299 }
04300 
04301 namespace {
04302 /// \brief Checks memory dependences among accesses to the same underlying
04303 /// object to determine whether there vectorization is legal or not (and at
04304 /// which vectorization factor).
04305 ///
04306 /// This class works under the assumption that we already checked that memory
04307 /// locations with different underlying pointers are "must-not alias".
04308 /// We use the ScalarEvolution framework to symbolically evalutate access
04309 /// functions pairs. Since we currently don't restructure the loop we can rely
04310 /// on the program order of memory accesses to determine their safety.
04311 /// At the moment we will only deem accesses as safe for:
04312 ///  * A negative constant distance assuming program order.
04313 ///
04314 ///      Safe: tmp = a[i + 1];     OR     a[i + 1] = x;
04315 ///            a[i] = tmp;                y = a[i];
04316 ///
04317 ///   The latter case is safe because later checks guarantuee that there can't
04318 ///   be a cycle through a phi node (that is, we check that "x" and "y" is not
04319 ///   the same variable: a header phi can only be an induction or a reduction, a
04320 ///   reduction can't have a memory sink, an induction can't have a memory
04321 ///   source). This is important and must not be violated (or we have to
04322 ///   resort to checking for cycles through memory).
04323 ///
04324 ///  * A positive constant distance assuming program order that is bigger
04325 ///    than the biggest memory access.
04326 ///
04327 ///     tmp = a[i]        OR              b[i] = x
04328 ///     a[i+2] = tmp                      y = b[i+2];
04329 ///
04330 ///     Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
04331 ///
04332 ///  * Zero distances and all accesses have the same size.
04333 ///
04334 class MemoryDepChecker {
04335 public:
04336   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
04337   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
04338 
04339   MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L)
04340       : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
04341         ShouldRetryWithRuntimeCheck(false) {}
04342 
04343   /// \brief Register the location (instructions are given increasing numbers)
04344   /// of a write access.
04345   void addAccess(StoreInst *SI) {
04346     Value *Ptr = SI->getPointerOperand();
04347     Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
04348     InstMap.push_back(SI);
04349     ++AccessIdx;
04350   }
04351 
04352   /// \brief Register the location (instructions are given increasing numbers)
04353   /// of a write access.
04354   void addAccess(LoadInst *LI) {
04355     Value *Ptr = LI->getPointerOperand();
04356     Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
04357     InstMap.push_back(LI);
04358     ++AccessIdx;
04359   }
04360 
04361   /// \brief Check whether the dependencies between the accesses are safe.
04362   ///
04363   /// Only checks sets with elements in \p CheckDeps.
04364   bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
04365                    MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
04366 
04367   /// \brief The maximum number of bytes of a vector register we can vectorize
04368   /// the accesses safely with.
04369   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
04370 
04371   /// \brief In same cases when the dependency check fails we can still
04372   /// vectorize the loop with a dynamic array access check.
04373   bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
04374 
04375 private:
04376   ScalarEvolution *SE;
04377   const DataLayout *DL;
04378   const Loop *InnermostLoop;
04379 
04380   /// \brief Maps access locations (ptr, read/write) to program order.
04381   DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
04382 
04383   /// \brief Memory access instructions in program order.
04384   SmallVector<Instruction *, 16> InstMap;
04385 
04386   /// \brief The program order index to be used for the next instruction.
04387   unsigned AccessIdx;
04388 
04389   // We can access this many bytes in parallel safely.
04390   unsigned MaxSafeDepDistBytes;
04391 
04392   /// \brief If we see a non-constant dependence distance we can still try to
04393   /// vectorize this loop with runtime checks.
04394   bool ShouldRetryWithRuntimeCheck;
04395 
04396   /// \brief Check whether there is a plausible dependence between the two
04397   /// accesses.
04398   ///
04399   /// Access \p A must happen before \p B in program order. The two indices
04400   /// identify the index into the program order map.
04401   ///
04402   /// This function checks  whether there is a plausible dependence (or the
04403   /// absence of such can't be proved) between the two accesses. If there is a
04404   /// plausible dependence but the dependence distance is bigger than one
04405   /// element access it records this distance in \p MaxSafeDepDistBytes (if this
04406   /// distance is smaller than any other distance encountered so far).
04407   /// Otherwise, this function returns true signaling a possible dependence.
04408   bool isDependent(const MemAccessInfo &A, unsigned AIdx,
04409                    const MemAccessInfo &B, unsigned BIdx,
04410                    ValueToValueMap &Strides);
04411 
04412   /// \brief Check whether the data dependence could prevent store-load
04413   /// forwarding.
04414   bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
04415 };
04416 
04417 } // end anonymous namespace
04418 
04419 static bool isInBoundsGep(Value *Ptr) {
04420   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
04421     return GEP->isInBounds();
04422   return false;
04423 }
04424 
04425 /// \brief Check whether the access through \p Ptr has a constant stride.
04426 static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr,
04427                         const Loop *Lp, ValueToValueMap &StridesMap) {
04428   const Type *Ty = Ptr->getType();
04429   assert(Ty->isPointerTy() && "Unexpected non-ptr");
04430 
04431   // Make sure that the pointer does not point to aggregate types.
04432   const PointerType *PtrTy = cast<PointerType>(Ty);
04433   if (PtrTy->getElementType()->isAggregateType()) {
04434     DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
04435           "\n");
04436     return 0;
04437   }
04438 
04439   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
04440 
04441   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
04442   if (!AR) {
04443     DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
04444           << *Ptr << " SCEV: " << *PtrScev << "\n");
04445     return 0;
04446   }
04447 
04448   // The accesss function must stride over the innermost loop.
04449   if (Lp != AR->getLoop()) {
04450     DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
04451           *Ptr << " SCEV: " << *PtrScev << "\n");
04452   }
04453 
04454   // The address calculation must not wrap. Otherwise, a dependence could be
04455   // inverted.
04456   // An inbounds getelementptr that is a AddRec with a unit stride
04457   // cannot wrap per definition. The unit stride requirement is checked later.
04458   // An getelementptr without an inbounds attribute and unit stride would have
04459   // to access the pointer value "0" which is undefined behavior in address
04460   // space 0, therefore we can also vectorize this case.
04461   bool IsInBoundsGEP = isInBoundsGep(Ptr);
04462   bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
04463   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
04464   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
04465     DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
04466           << *Ptr << " SCEV: " << *PtrScev << "\n");
04467     return 0;
04468   }
04469 
04470   // Check the step is constant.
04471   const SCEV *Step = AR->getStepRecurrence(*SE);
04472 
04473   // Calculate the pointer stride and check if it is consecutive.
04474   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
04475   if (!C) {
04476     DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
04477           " SCEV: " << *PtrScev << "\n");
04478     return 0;
04479   }
04480 
04481   int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
04482   const APInt &APStepVal = C->getValue()->getValue();
04483 
04484   // Huge step value - give up.
04485   if (APStepVal.getBitWidth() > 64)
04486     return 0;
04487 
04488   int64_t StepVal = APStepVal.getSExtValue();
04489 
04490   // Strided access.
04491   int64_t Stride = StepVal / Size;
04492   int64_t Rem = StepVal % Size;
04493   if (Rem)
04494     return 0;
04495 
04496   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
04497   // know we can't "wrap around the address space". In case of address space
04498   // zero we know that this won't happen without triggering undefined behavior.
04499   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
04500       Stride != 1 && Stride != -1)
04501     return 0;
04502 
04503   return Stride;
04504 }
04505 
04506 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
04507                                                     unsigned TypeByteSize) {
04508   // If loads occur at a distance that is not a multiple of a feasible vector
04509   // factor store-load forwarding does not take place.
04510   // Positive dependences might cause troubles because vectorizing them might
04511   // prevent store-load forwarding making vectorized code run a lot slower.
04512   //   a[i] = a[i-3] ^ a[i-8];
04513   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
04514   //   hence on your typical architecture store-load forwarding does not take
04515   //   place. Vectorizing in such cases does not make sense.
04516   // Store-load forwarding distance.
04517   const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
04518   // Maximum vector factor.
04519   unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
04520   if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
04521     MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
04522 
04523   for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
04524        vf *= 2) {
04525     if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
04526       MaxVFWithoutSLForwardIssues = (vf >>=1);
04527       break;
04528     }
04529   }
04530 
04531   if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
04532     DEBUG(dbgs() << "LV: Distance " << Distance <<
04533           " that could cause a store-load forwarding conflict\n");
04534     return true;
04535   }
04536 
04537   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
04538       MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
04539     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
04540   return false;
04541 }
04542 
04543 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
04544                                    const MemAccessInfo &B, unsigned BIdx,
04545                                    ValueToValueMap &Strides) {
04546   assert (AIdx < BIdx && "Must pass arguments in program order");
04547 
04548   Value *APtr = A.getPointer();
04549   Value *BPtr = B.getPointer();
04550   bool AIsWrite = A.getInt();
04551   bool BIsWrite = B.getInt();
04552 
04553   // Two reads are independent.
04554   if (!AIsWrite && !BIsWrite)
04555     return false;
04556 
04557   // We cannot check pointers in different address spaces.
04558   if (APtr->getType()->getPointerAddressSpace() !=
04559       BPtr->getType()->getPointerAddressSpace())
04560     return true;
04561 
04562   const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
04563   const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
04564 
04565   int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
04566   int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
04567 
04568   const SCEV *Src = AScev;
04569   const SCEV *Sink = BScev;
04570 
04571   // If the induction step is negative we have to invert source and sink of the
04572   // dependence.
04573   if (StrideAPtr < 0) {
04574     //Src = BScev;
04575     //Sink = AScev;
04576     std::swap(APtr, BPtr);
04577     std::swap(Src, Sink);
04578     std::swap(AIsWrite, BIsWrite);
04579     std::swap(AIdx, BIdx);
04580     std::swap(StrideAPtr, StrideBPtr);
04581   }
04582 
04583   const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
04584 
04585   DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
04586         << "(Induction step: " << StrideAPtr <<  ")\n");
04587   DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
04588         << *InstMap[BIdx] << ": " << *Dist << "\n");
04589 
04590   // Need consecutive accesses. We don't want to vectorize
04591   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
04592   // the address space.
04593   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
04594     DEBUG(dbgs() << "Non-consecutive pointer access\n");
04595     return true;
04596   }
04597 
04598   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
04599   if (!C) {
04600     DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
04601     ShouldRetryWithRuntimeCheck = true;
04602     return true;
04603   }
04604 
04605   Type *ATy = APtr->getType()->getPointerElementType();
04606   Type *BTy = BPtr->getType()->getPointerElementType();
04607   unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
04608 
04609   // Negative distances are not plausible dependencies.
04610   const APInt &Val = C->getValue()->getValue();
04611   if (Val.isNegative()) {
04612     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
04613     if (IsTrueDataDependence &&
04614         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
04615          ATy != BTy))
04616       return true;
04617 
04618     DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
04619     return false;
04620   }
04621 
04622   // Write to the same location with the same size.
04623   // Could be improved to assert type sizes are the same (i32 == float, etc).
04624   if (Val == 0) {
04625     if (ATy == BTy)
04626       return false;
04627     DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
04628     return true;
04629   }
04630 
04631   assert(Val.isStrictlyPositive() && "Expect a positive value");
04632 
04633   // Positive distance bigger than max vectorization factor.
04634   if (ATy != BTy) {
04635     DEBUG(dbgs() <<
04636           "LV: ReadWrite-Write positive dependency with different types\n");
04637     return false;
04638   }
04639 
04640   unsigned Distance = (unsigned) Val.getZExtValue();
04641 
04642   // Bail out early if passed-in parameters make vectorization not feasible.
04643   unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
04644   unsigned ForcedUnroll = VectorizationInterleave ? VectorizationInterleave : 1;
04645 
04646   // The distance must be bigger than the size needed for a vectorized version
04647   // of the operation and the size of the vectorized operation must not be
04648   // bigger than the currrent maximum size.
04649   if (Distance < 2*TypeByteSize ||
04650       2*TypeByteSize > MaxSafeDepDistBytes ||
04651       Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
04652     DEBUG(dbgs() << "LV: Failure because of Positive distance "
04653         << Val.getSExtValue() << '\n');
04654     return true;
04655   }
04656 
04657   MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
04658     Distance : MaxSafeDepDistBytes;
04659 
04660   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
04661   if (IsTrueDataDependence &&
04662       couldPreventStoreLoadForward(Distance, TypeByteSize))
04663      return true;
04664 
04665   DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
04666         " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
04667 
04668   return false;
04669 }
04670 
04671 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
04672                                    MemAccessInfoSet &CheckDeps,
04673                                    ValueToValueMap &Strides) {
04674 
04675   MaxSafeDepDistBytes = -1U;
04676   while (!CheckDeps.empty()) {
04677     MemAccessInfo CurAccess = *CheckDeps.begin();
04678 
04679     // Get the relevant memory access set.
04680     EquivalenceClasses<MemAccessInfo>::iterator I =
04681       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
04682 
04683     // Check accesses within this set.
04684     EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
04685     AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
04686 
04687     // Check every access pair.
04688     while (AI != AE) {
04689       CheckDeps.erase(*AI);
04690       EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
04691       while (OI != AE) {
04692         // Check every accessing instruction pair in program order.
04693         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
04694              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
04695           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
04696                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
04697             if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
04698               return false;
04699             if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
04700               return false;
04701           }
04702         ++OI;
04703       }
04704       AI++;
04705     }
04706   }
04707   return true;
04708 }
04709 
04710 bool LoopVectorizationLegality::canVectorizeMemory() {
04711 
04712   typedef SmallVector<Value*, 16> ValueVector;
04713   typedef SmallPtrSet<Value*, 16> ValueSet;
04714 
04715   // Holds the Load and Store *instructions*.
04716   ValueVector Loads;
04717   ValueVector Stores;
04718 
04719   // Holds all the different accesses in the loop.
04720   unsigned NumReads = 0;
04721   unsigned NumReadWrites = 0;
04722 
04723   PtrRtCheck.Pointers.clear();
04724   PtrRtCheck.Need = false;
04725 
04726   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
04727   MemoryDepChecker DepChecker(SE, DL, TheLoop);
04728 
04729   // For each block.
04730   for (Loop::block_iterator bb = TheLoop->block_begin(),
04731        be = TheLoop->block_end(); bb != be; ++bb) {
04732 
04733     // Scan the BB and collect legal loads and stores.
04734     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
04735          ++it) {
04736 
04737       // If this is a load, save it. If this instruction can read from memory
04738       // but is not a load, then we quit. Notice that we don't handle function
04739       // calls that read or write.
04740       if (it->mayReadFromMemory()) {
04741         // Many math library functions read the rounding mode. We will only
04742         // vectorize a loop if it contains known function calls that don't set
04743         // the flag. Therefore, it is safe to ignore this read from memory.
04744         CallInst *Call = dyn_cast<CallInst>(it);
04745         if (Call && getIntrinsicIDForCall(Call, TLI))
04746           continue;
04747 
04748         LoadInst *Ld = dyn_cast<LoadInst>(it);
04749         if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
04750           emitAnalysis(Report(Ld)
04751                        << "read with atomic ordering or volatile read");
04752           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
04753           return false;
04754         }
04755         NumLoads++;
04756         Loads.push_back(Ld);
04757         DepChecker.addAccess(Ld);
04758         continue;
04759       }
04760 
04761       // Save 'store' instructions. Abort if other instructions write to memory.
04762       if (it->mayWriteToMemory()) {
04763         StoreInst *St = dyn_cast<StoreInst>(it);
04764         if (!St) {
04765           emitAnalysis(Report(it) << "instruction cannot be vectorized");
04766           return false;
04767         }
04768         if (!St->isSimple() && !IsAnnotatedParallel) {
04769           emitAnalysis(Report(St)
04770                        << "write with atomic ordering or volatile write");
04771           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
04772           return false;
04773         }
04774         NumStores++;
04775         Stores.push_back(St);
04776         DepChecker.addAccess(St);
04777       }
04778     } // Next instr.
04779   } // Next block.
04780 
04781   // Now we have two lists that hold the loads and the stores.
04782   // Next, we find the pointers that they use.
04783 
04784   // Check if we see any stores. If there are no stores, then we don't
04785   // care if the pointers are *restrict*.
04786   if (!Stores.size()) {
04787     DEBUG(dbgs() << "LV: Found a read-only loop!\n");
04788     return true;
04789   }
04790 
04791   AccessAnalysis::DepCandidates DependentAccesses;
04792   AccessAnalysis Accesses(DL, AA, DependentAccesses);
04793 
04794   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
04795   // multiple times on the same object. If the ptr is accessed twice, once
04796   // for read and once for write, it will only appear once (on the write
04797   // list). This is okay, since we are going to check for conflicts between
04798   // writes and between reads and writes, but not between reads and reads.
04799   ValueSet Seen;
04800 
04801   ValueVector::iterator I, IE;
04802   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
04803     StoreInst *ST = cast<StoreInst>(*I);
04804     Value* Ptr = ST->getPointerOperand();
04805 
04806     if (isUniform(Ptr)) {
04807       emitAnalysis(
04808           Report(ST)
04809           << "write to a loop invariant address could not be vectorized");
04810       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
04811       return false;
04812     }
04813 
04814     // If we did *not* see this pointer before, insert it to  the read-write
04815     // list. At this phase it is only a 'write' list.
04816     if (Seen.insert(Ptr)) {
04817       ++NumReadWrites;
04818 
04819       AliasAnalysis::Location Loc = AA->getLocation(ST);
04820       // The TBAA metadata could have a control dependency on the predication
04821       // condition, so we cannot rely on it when determining whether or not we
04822       // need runtime pointer checks.
04823       if (blockNeedsPredication(ST->getParent()))
04824         Loc.AATags.TBAA = nullptr;
04825 
04826       Accesses.addStore(Loc);
04827     }
04828   }
04829 
04830   if (IsAnnotatedParallel) {
04831     DEBUG(dbgs()
04832           << "LV: A loop annotated parallel, ignore memory dependency "
04833           << "checks.\n");
04834     return true;
04835   }
04836 
04837   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
04838     LoadInst *LD = cast<LoadInst>(*I);
04839     Value* Ptr = LD->getPointerOperand();
04840     // If we did *not* see this pointer before, insert it to the
04841     // read list. If we *did* see it before, then it is already in
04842     // the read-write list. This allows us to vectorize expressions
04843     // such as A[i] += x;  Because the address of A[i] is a read-write
04844     // pointer. This only works if the index of A[i] is consecutive.
04845     // If the address of i is unknown (for example A[B[i]]) then we may
04846     // read a few words, modify, and write a few words, and some of the
04847     // words may be written to the same address.
04848     bool IsReadOnlyPtr = false;
04849     if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
04850       ++NumReads;
04851       IsReadOnlyPtr = true;
04852     }
04853 
04854     AliasAnalysis::Location Loc = AA->getLocation(LD);
04855     // The TBAA metadata could have a control dependency on the predication
04856     // condition, so we cannot rely on it when determining whether or not we
04857     // need runtime pointer checks.
04858     if (blockNeedsPredication(LD->getParent()))
04859       Loc.AATags.TBAA = nullptr;
04860 
04861     Accesses.addLoad(Loc, IsReadOnlyPtr);
04862   }
04863 
04864   // If we write (or read-write) to a single destination and there are no
04865   // other reads in this loop then is it safe to vectorize.
04866   if (NumReadWrites == 1 && NumReads == 0) {
04867     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
04868     return true;
04869   }
04870 
04871   // Build dependence sets and check whether we need a runtime pointer bounds
04872   // check.
04873   Accesses.buildDependenceSets();
04874   bool NeedRTCheck = Accesses.isRTCheckNeeded();
04875 
04876   // Find pointers with computable bounds. We are going to use this information
04877   // to place a runtime bound check.
04878   unsigned NumComparisons = 0;
04879   bool CanDoRT = false;
04880   if (NeedRTCheck)
04881     CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
04882                                        Strides);
04883 
04884   DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
04885         " pointer comparisons.\n");
04886 
04887   // If we only have one set of dependences to check pointers among we don't
04888   // need a runtime check.
04889   if (NumComparisons == 0 && NeedRTCheck)
04890     NeedRTCheck = false;
04891 
04892   // Check that we did not collect too many pointers or found an unsizeable
04893   // pointer.
04894   if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
04895     PtrRtCheck.reset();
04896     CanDoRT = false;
04897   }
04898 
04899   if (CanDoRT) {
04900     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
04901   }
04902 
04903   if (NeedRTCheck && !CanDoRT) {
04904     emitAnalysis(Report() << "cannot identify array bounds");
04905     DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
04906           "the array bounds.\n");
04907     PtrRtCheck.reset();
04908     return false;
04909   }
04910 
04911   PtrRtCheck.Need = NeedRTCheck;
04912 
04913   bool CanVecMem = true;
04914   if (Accesses.isDependencyCheckNeeded()) {
04915     DEBUG(dbgs() << "LV: Checking memory dependencies\n");
04916     CanVecMem = DepChecker.areDepsSafe(
04917         DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
04918     MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
04919 
04920     if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
04921       DEBUG(dbgs() << "LV: Retrying with memory checks\n");
04922       NeedRTCheck = true;
04923 
04924       // Clear the dependency checks. We assume they are not needed.
04925       Accesses.resetDepChecks();
04926 
04927       PtrRtCheck.reset();
04928       PtrRtCheck.Need = true;
04929 
04930       CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
04931                                          TheLoop, Strides, true);
04932       // Check that we did not collect too many pointers or found an unsizeable
04933       // pointer.
04934       if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
04935         if (!CanDoRT && NumComparisons > 0)
04936           emitAnalysis(Report()
04937                        << "cannot check memory dependencies at runtime");
04938         else
04939           emitAnalysis(Report()
04940                        << NumComparisons << " exceeds limit of "
04941                        << RuntimeMemoryCheckThreshold
04942                        << " dependent memory operations checked at runtime");
04943         DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
04944         PtrRtCheck.reset();
04945         return false;
04946       }
04947 
04948       CanVecMem = true;
04949     }
04950   }
04951 
04952   if (!CanVecMem)
04953     emitAnalysis(Report() << "unsafe dependent memory operations in loop");
04954 
04955   DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
04956         " need a runtime memory check.\n");
04957 
04958   return CanVecMem;
04959 }
04960 
04961 static bool hasMultipleUsesOf(Instruction *I,
04962                               SmallPtrSetImpl<Instruction *> &Insts) {
04963   unsigned NumUses = 0;
04964   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
04965     if (Insts.count(dyn_cast<Instruction>(*Use)))
04966       ++NumUses;
04967     if (NumUses > 1)
04968       return true;
04969   }
04970 
04971   return false;
04972 }
04973 
04974 static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set) {
04975   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
04976     if (!Set.count(dyn_cast<Instruction>(*Use)))
04977       return false;
04978   return true;
04979 }
04980 
04981 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
04982                                                 ReductionKind Kind) {
04983   if (Phi->getNumIncomingValues() != 2)
04984     return false;
04985 
04986   // Reduction variables are only found in the loop header block.
04987   if (Phi->getParent() != TheLoop->getHeader())
04988     return false;
04989 
04990   // Obtain the reduction start value from the value that comes from the loop
04991   // preheader.
04992   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
04993 
04994   // ExitInstruction is the single value which is used outside the loop.
04995   // We only allow for a single reduction value to be used outside the loop.
04996   // This includes users of the reduction, variables (which form a cycle
04997   // which ends in the phi node).
04998   Instruction *ExitInstruction = nullptr;
04999   // Indicates that we found a reduction operation in our scan.
05000   bool FoundReduxOp = false;
05001 
05002   // We start with the PHI node and scan for all of the users of this
05003   // instruction. All users must be instructions that can be used as reduction
05004   // variables (such as ADD). We must have a single out-of-block user. The cycle
05005   // must include the original PHI.
05006   bool FoundStartPHI = false;
05007 
05008   // To recognize min/max patterns formed by a icmp select sequence, we store
05009   // the number of instruction we saw from the recognized min/max pattern,
05010   //  to make sure we only see exactly the two instructions.
05011   unsigned NumCmpSelectPatternInst = 0;
05012   ReductionInstDesc ReduxDesc(false, nullptr);
05013 
05014   SmallPtrSet<Instruction *, 8> VisitedInsts;
05015   SmallVector<Instruction *, 8> Worklist;
05016   Worklist.push_back(Phi);
05017   VisitedInsts.insert(Phi);
05018 
05019   // A value in the reduction can be used:
05020   //  - By the reduction:
05021   //      - Reduction operation:
05022   //        - One use of reduction value (safe).
05023   //        - Multiple use of reduction value (not safe).
05024   //      - PHI:
05025   //        - All uses of the PHI must be the reduction (safe).
05026   //        - Otherwise, not safe.
05027   //  - By one instruction outside of the loop (safe).
05028   //  - By further instructions outside of the loop (not safe).
05029   //  - By an instruction that is not part of the reduction (not safe).
05030   //    This is either:
05031   //      * An instruction type other than PHI or the reduction operation.
05032   //      * A PHI in the header other than the initial PHI.
05033   while (!Worklist.empty()) {
05034     Instruction *Cur = Worklist.back();
05035     Worklist.pop_back();
05036 
05037     // No Users.
05038     // If the instruction has no users then this is a broken chain and can't be
05039     // a reduction variable.
05040     if (Cur->use_empty())
05041       return false;
05042 
05043     bool IsAPhi = isa<PHINode>(Cur);
05044 
05045     // A header PHI use other than the original PHI.
05046     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
05047       return false;
05048 
05049     // Reductions of instructions such as Div, and Sub is only possible if the
05050     // LHS is the reduction variable.
05051     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
05052         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
05053         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
05054       return false;
05055 
05056     // Any reduction instruction must be of one of the allowed kinds.
05057     ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
05058     if (!ReduxDesc.IsReduction)
05059       return false;
05060 
05061     // A reduction operation must only have one use of the reduction value.
05062     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
05063         hasMultipleUsesOf(Cur, VisitedInsts))
05064       return false;
05065 
05066     // All inputs to a PHI node must be a reduction value.
05067     if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
05068       return false;
05069 
05070     if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
05071                                      isa<SelectInst>(Cur)))
05072       ++NumCmpSelectPatternInst;
05073     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
05074                                    isa<SelectInst>(Cur)))
05075       ++NumCmpSelectPatternInst;
05076 
05077     // Check  whether we found a reduction operator.
05078     FoundReduxOp |= !IsAPhi;
05079 
05080     // Process users of current instruction. Push non-PHI nodes after PHI nodes
05081     // onto the stack. This way we are going to have seen all inputs to PHI
05082     // nodes once we get to them.
05083     SmallVector<Instruction *, 8> NonPHIs;
05084     SmallVector<Instruction *, 8> PHIs;
05085     for (User *U : Cur->users()) {
05086       Instruction *UI = cast<Instruction>(U);
05087 
05088       // Check if we found the exit user.
05089       BasicBlock *Parent = UI->getParent();
05090       if (!TheLoop->contains(Parent)) {
05091         // Exit if you find multiple outside users or if the header phi node is
05092         // being used. In this case the user uses the value of the previous
05093         // iteration, in which case we would loose "VF-1" iterations of the
05094         // reduction operation if we vectorize.
05095         if (ExitInstruction != nullptr || Cur == Phi)
05096           return false;
05097 
05098         // The instruction used by an outside user must be the last instruction
05099         // before we feed back to the reduction phi. Otherwise, we loose VF-1
05100         // operations on the value.
05101         if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
05102          return false;
05103 
05104         ExitInstruction = Cur;
05105         continue;
05106       }
05107 
05108       // Process instructions only once (termination). Each reduction cycle
05109       // value must only be used once, except by phi nodes and min/max
05110       // reductions which are represented as a cmp followed by a select.
05111       ReductionInstDesc IgnoredVal(false, nullptr);
05112       if (VisitedInsts.insert(UI)) {
05113         if (isa<PHINode>(UI))
05114           PHIs.push_back(UI);
05115         else
05116           NonPHIs.push_back(UI);
05117       } else if (!isa<PHINode>(UI) &&
05118                  ((!isa<FCmpInst>(UI) &&
05119                    !isa<ICmpInst>(UI) &&
05120                    !isa<SelectInst>(UI)) ||
05121                   !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction))
05122         return false;
05123 
05124       // Remember that we completed the cycle.
05125       if (UI == Phi)
05126         FoundStartPHI = true;
05127     }
05128     Worklist.append(PHIs.begin(), PHIs.end());
05129     Worklist.append(NonPHIs.begin(), NonPHIs.end());
05130   }
05131 
05132   // This means we have seen one but not the other instruction of the
05133   // pattern or more than just a select and cmp.
05134   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
05135       NumCmpSelectPatternInst != 2)
05136     return false;
05137 
05138   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
05139     return false;
05140 
05141   // We found a reduction var if we have reached the original phi node and we
05142   // only have a single instruction with out-of-loop users.
05143 
05144   // This instruction is allowed to have out-of-loop users.
05145   AllowedExit.insert(ExitInstruction);
05146 
05147   // Save the description of this reduction variable.
05148   ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
05149                          ReduxDesc.MinMaxKind);
05150   Reductions[Phi] = RD;
05151   // We've ended the cycle. This is a reduction variable if we have an
05152   // outside user and it has a binary op.
05153 
05154   return true;
05155 }
05156 
05157 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
05158 /// pattern corresponding to a min(X, Y) or max(X, Y).
05159 LoopVectorizationLegality::ReductionInstDesc
05160 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
05161                                                     ReductionInstDesc &Prev) {
05162 
05163   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
05164          "Expect a select instruction");
05165   Instruction *Cmp = nullptr;
05166   SelectInst *Select = nullptr;
05167 
05168   // We must handle the select(cmp()) as a single instruction. Advance to the
05169   // select.
05170   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
05171     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
05172       return ReductionInstDesc(false, I);
05173     return ReductionInstDesc(Select, Prev.MinMaxKind);
05174   }
05175 
05176   // Only handle single use cases for now.
05177   if (!(Select = dyn_cast<SelectInst>(I)))
05178     return ReductionInstDesc(false, I);
05179   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
05180       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
05181     return ReductionInstDesc(false, I);
05182   if (!Cmp->hasOneUse())
05183     return ReductionInstDesc(false, I);
05184 
05185   Value *CmpLeft;
05186   Value *CmpRight;
05187 
05188   // Look for a min/max pattern.
05189   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
05190     return ReductionInstDesc(Select, MRK_UIntMin);
05191   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
05192     return ReductionInstDesc(Select, MRK_UIntMax);
05193   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
05194     return ReductionInstDesc(Select, MRK_SIntMax);
05195   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
05196     return ReductionInstDesc(Select, MRK_SIntMin);
05197   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
05198     return ReductionInstDesc(Select, MRK_FloatMin);
05199   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
05200     return ReductionInstDesc(Select, MRK_FloatMax);
05201   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
05202     return ReductionInstDesc(Select, MRK_FloatMin);
05203   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
05204     return ReductionInstDesc(Select, MRK_FloatMax);
05205 
05206   return ReductionInstDesc(false, I);
05207 }
05208 
05209 LoopVectorizationLegality::ReductionInstDesc
05210 LoopVectorizationLegality::isReductionInstr(Instruction *I,
05211                                             ReductionKind Kind,
05212                                             ReductionInstDesc &Prev) {
05213   bool FP = I->getType()->isFloatingPointTy();
05214   bool FastMath = FP && I->hasUnsafeAlgebra();
05215   switch (I->getOpcode()) {
05216   default:
05217     return ReductionInstDesc(false, I);
05218   case Instruction::PHI:
05219       if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
05220                  Kind != RK_FloatMinMax))
05221         return ReductionInstDesc(false, I);
05222     return ReductionInstDesc(I, Prev.MinMaxKind);
05223   case Instruction::Sub:
05224   case Instruction::Add:
05225     return ReductionInstDesc(Kind == RK_IntegerAdd, I);
05226   case Instruction::Mul:
05227     return ReductionInstDesc(Kind == RK_IntegerMult, I);
05228   case Instruction::And:
05229     return ReductionInstDesc(Kind == RK_IntegerAnd, I);
05230   case Instruction::Or:
05231     return ReductionInstDesc(Kind == RK_IntegerOr, I);
05232   case Instruction::Xor:
05233     return ReductionInstDesc(Kind == RK_IntegerXor, I);
05234   case Instruction::FMul:
05235     return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
05236   case Instruction::FSub:
05237   case Instruction::FAdd:
05238     return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
05239   case Instruction::FCmp:
05240   case Instruction::ICmp:
05241   case Instruction::Select:
05242     if (Kind != RK_IntegerMinMax &&
05243         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
05244       return ReductionInstDesc(false, I);
05245     return isMinMaxSelectCmpPattern(I, Prev);
05246   }
05247 }
05248 
05249 LoopVectorizationLegality::InductionKind
05250 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
05251   Type *PhiTy = Phi->getType();
05252   // We only handle integer and pointer inductions variables.
05253   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
05254     return IK_NoInduction;
05255 
05256   // Check that the PHI is consecutive.
05257   const SCEV *PhiScev = SE->getSCEV(Phi);
05258   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
05259   if (!AR) {
05260     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
05261     return IK_NoInduction;
05262   }
05263   const SCEV *Step = AR->getStepRecurrence(*SE);
05264 
05265   // Integer inductions need to have a stride of one.
05266   if (PhiTy->isIntegerTy()) {
05267     if (Step->isOne())
05268       return IK_IntInduction;
05269     if (Step->isAllOnesValue())
05270       return IK_ReverseIntInduction;
05271     return IK_NoInduction;
05272   }
05273 
05274   // Calculate the pointer stride and check if it is consecutive.
05275   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
05276   if (!C)
05277     return IK_NoInduction;
05278 
05279   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
05280   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
05281   if (C->getValue()->equalsInt(Size))
05282     return IK_PtrInduction;
05283   else if (C->getValue()->equalsInt(0 - Size))
05284     return IK_ReversePtrInduction;
05285 
05286   return IK_NoInduction;
05287 }
05288 
05289 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
05290   Value *In0 = const_cast<Value*>(V);
05291   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
05292   if (!PN)
05293     return false;
05294 
05295   return Inductions.count(PN);
05296 }
05297 
05298 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
05299   assert(TheLoop->contains(BB) && "Unknown block used");
05300 
05301   // Blocks that do not dominate the latch need predication.
05302   BasicBlock* Latch = TheLoop->getLoopLatch();
05303   return !DT->dominates(BB, Latch);
05304 }
05305 
05306 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
05307                                            SmallPtrSetImpl<Value *> &SafePtrs) {
05308   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
05309     // We might be able to hoist the load.
05310     if (it->mayReadFromMemory()) {
05311       LoadInst *LI = dyn_cast<LoadInst>(it);
05312       if (!LI || !SafePtrs.count(LI->getPointerOperand()))
05313         return false;
05314     }
05315 
05316     // We don't predicate stores at the moment.
05317     if (it->mayWriteToMemory()) {
05318       StoreInst *SI = dyn_cast<StoreInst>(it);
05319       // We only support predication of stores in basic blocks with one
05320       // predecessor.
05321       if (!SI || ++NumPredStores > NumberOfStoresToPredicate ||
05322           !SafePtrs.count(SI->getPointerOperand()) ||
05323           !SI->getParent()->getSinglePredecessor())
05324         return false;
05325     }
05326     if (it->mayThrow())
05327       return false;
05328 
05329     // Check that we don't have a constant expression that can trap as operand.
05330     for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
05331          OI != OE; ++OI) {
05332       if (Constant *C = dyn_cast<Constant>(*OI))
05333         if (C->canTrap())
05334           return false;
05335     }
05336 
05337     // The instructions below can trap.
05338     switch (it->getOpcode()) {
05339     default: continue;
05340     case Instruction::UDiv:
05341     case Instruction::SDiv:
05342     case Instruction::URem:
05343     case Instruction::SRem:
05344              return false;
05345     }
05346   }
05347 
05348   return true;
05349 }
05350 
05351 LoopVectorizationCostModel::VectorizationFactor
05352 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
05353   // Width 1 means no vectorize
05354   VectorizationFactor Factor = { 1U, 0U };
05355   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
05356     emitAnalysis(Report() << "runtime pointer checks needed. Enable vectorization of this loop with '#pragma clang loop vectorize(enable)' when compiling with -Os");
05357     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
05358     return Factor;
05359   }
05360 
05361   if (!EnableCondStoresVectorization && Legal->NumPredStores) {
05362     emitAnalysis(Report() << "store that is conditionally executed prevents vectorization");
05363     DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
05364     return Factor;
05365   }
05366 
05367   // Find the trip count.
05368   unsigned TC = SE->getSmallConstantTripCount(TheLoop);
05369   DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
05370 
05371   unsigned WidestType = getWidestType();
05372   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
05373   unsigned MaxSafeDepDist = -1U;
05374   if (Legal->getMaxSafeDepDistBytes() != -1U)
05375     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
05376   WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
05377                     WidestRegister : MaxSafeDepDist);
05378   unsigned MaxVectorSize = WidestRegister / WidestType;
05379   DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
05380   DEBUG(dbgs() << "LV: The Widest register is: "
05381           << WidestRegister << " bits.\n");
05382 
05383   if (MaxVectorSize == 0) {
05384     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
05385     MaxVectorSize = 1;
05386   }
05387 
05388   assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
05389          " into one vector!");
05390 
05391   unsigned VF = MaxVectorSize;
05392 
05393   // If we optimize the program for size, avoid creating the tail loop.
05394   if (OptForSize) {
05395     // If we are unable to calculate the trip count then don't try to vectorize.
05396     if (TC < 2) {
05397       emitAnalysis(Report() << "unable to calculate the loop count due to complex control flow");
05398       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
05399       return Factor;
05400     }
05401 
05402     // Find the maximum SIMD width that can fit within the trip count.
05403     VF = TC % MaxVectorSize;
05404 
05405     if (VF == 0)
05406       VF = MaxVectorSize;
05407 
05408     // If the trip count that we found modulo the vectorization factor is not
05409     // zero then we require a tail.
05410     if (VF < 2) {
05411       emitAnalysis(Report() << "cannot optimize for size and vectorize at the same time. Enable vectorization of this loop with '#pragma clang loop vectorize(enable)' when compiling with -Os"); 
05412       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
05413       return Factor;
05414     }
05415   }
05416 
05417   int UserVF = Hints->getWidth();
05418   if (UserVF != 0) {
05419     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
05420     DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
05421 
05422     Factor.Width = UserVF;
05423     return Factor;
05424   }
05425 
05426   float Cost = expectedCost(1);
05427 #ifndef NDEBUG
05428   const float ScalarCost = Cost;
05429 #endif /* NDEBUG */
05430   unsigned Width = 1;
05431   DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
05432 
05433   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
05434   // Ignore scalar width, because the user explicitly wants vectorization.
05435   if (ForceVectorization && VF > 1) {
05436     Width = 2;
05437     Cost = expectedCost(Width) / (float)Width;
05438   }
05439 
05440   for (unsigned i=2; i <= VF; i*=2) {
05441     // Notice that the vector loop needs to be executed less times, so
05442     // we need to divide the cost of the vector loops by the width of
05443     // the vector elements.
05444     float VectorCost = expectedCost(i) / (float)i;
05445     DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
05446           (int)VectorCost << ".\n");
05447     if (VectorCost < Cost) {
05448       Cost = VectorCost;
05449       Width = i;
05450     }
05451   }
05452 
05453   DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
05454         << "LV: Vectorization seems to be not beneficial, "
05455         << "but was forced by a user.\n");
05456   DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
05457   Factor.Width = Width;
05458   Factor.Cost = Width * Cost;
05459   return Factor;
05460 }
05461 
05462 unsigned LoopVectorizationCostModel::getWidestType() {
05463   unsigned MaxWidth = 8;
05464 
05465   // For each block.
05466   for (Loop::block_iterator bb = TheLoop->block_begin(),
05467        be = TheLoop->block_end(); bb != be; ++bb) {
05468     BasicBlock *BB = *bb;
05469 
05470     // For each instruction in the loop.
05471     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
05472       Type *T = it->getType();
05473 
05474       // Ignore ephemeral values.
05475       if (EphValues.count(it))
05476         continue;
05477 
05478       // Only examine Loads, Stores and PHINodes.
05479       if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
05480         continue;
05481 
05482       // Examine PHI nodes that are reduction variables.
05483       if (PHINode *PN = dyn_cast<PHINode>(it))
05484         if (!Legal->getReductionVars()->count(PN))
05485           continue;
05486 
05487       // Examine the stored values.
05488       if (StoreInst *ST = dyn_cast<StoreInst>(it))
05489         T = ST->getValueOperand()->getType();
05490 
05491       // Ignore loaded pointer types and stored pointer types that are not
05492       // consecutive. However, we do want to take consecutive stores/loads of
05493       // pointer vectors into account.
05494       if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
05495         continue;
05496 
05497       MaxWidth = std::max(MaxWidth,
05498                           (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
05499     }
05500   }
05501 
05502   return MaxWidth;
05503 }
05504 
05505 unsigned
05506 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
05507                                                unsigned VF,
05508                                                unsigned LoopCost) {
05509 
05510   // -- The unroll heuristics --
05511   // We unroll the loop in order to expose ILP and reduce the loop overhead.
05512   // There are many micro-architectural considerations that we can't predict
05513   // at this level. For example, frontend pressure (on decode or fetch) due to
05514   // code size, or the number and capabilities of the execution ports.
05515   //
05516   // We use the following heuristics to select the unroll factor:
05517   // 1. If the code has reductions, then we unroll in order to break the cross
05518   // iteration dependency.
05519   // 2. If the loop is really small, then we unroll in order to reduce the loop
05520   // overhead.
05521   // 3. We don't unroll if we think that we will spill registers to memory due
05522   // to the increased register pressure.
05523 
05524   // Use the user preference, unless 'auto' is selected.
05525   int UserUF = Hints->getInterleave();
05526   if (UserUF != 0)
05527     return UserUF;
05528 
05529   // When we optimize for size, we don't unroll.
05530   if (OptForSize)
05531     return 1;
05532 
05533   // We used the distance for the unroll factor.
05534   if (Legal->getMaxSafeDepDistBytes() != -1U)
05535     return 1;
05536 
05537   // Do not unroll loops with a relatively small trip count.
05538   unsigned TC = SE->getSmallConstantTripCount(TheLoop);
05539   if (TC > 1 && TC < TinyTripCountUnrollThreshold)
05540     return 1;
05541 
05542   unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
05543   DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
05544         " registers\n");
05545 
05546   if (VF == 1) {
05547     if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
05548       TargetNumRegisters = ForceTargetNumScalarRegs;
05549   } else {
05550     if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
05551       TargetNumRegisters = ForceTargetNumVectorRegs;
05552   }
05553 
05554   LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
05555   // We divide by these constants so assume that we have at least one
05556   // instruction that uses at least one register.
05557   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
05558   R.NumInstructions = std::max(R.NumInstructions, 1U);
05559 
05560   // We calculate the unroll factor using the following formula.
05561   // Subtract the number of loop invariants from the number of available
05562   // registers. These registers are used by all of the unrolled instances.
05563   // Next, divide the remaining registers by the number of registers that is
05564   // required by the loop, in order to estimate how many parallel instances
05565   // fit without causing spills. All of this is rounded down if necessary to be
05566   // a power of two. We want power of two unroll factors to simplify any
05567   // addressing operations or alignment considerations.
05568   unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
05569                               R.MaxLocalUsers);
05570 
05571   // Don't count the induction variable as unrolled.
05572   if (EnableIndVarRegisterHeur)
05573     UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
05574                        std::max(1U, (R.MaxLocalUsers - 1)));
05575 
05576   // Clamp the unroll factor ranges to reasonable factors.
05577   unsigned MaxInterleaveSize = TTI.getMaxInterleaveFactor();
05578 
05579   // Check if the user has overridden the unroll max.
05580   if (VF == 1) {
05581     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
05582       MaxInterleaveSize = ForceTargetMaxScalarInterleaveFactor;
05583   } else {
05584     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
05585       MaxInterleaveSize = ForceTargetMaxVectorInterleaveFactor;
05586   }
05587 
05588   // If we did not calculate the cost for VF (because the user selected the VF)
05589   // then we calculate the cost of VF here.
05590   if (LoopCost == 0)
05591     LoopCost = expectedCost(VF);
05592 
05593   // Clamp the calculated UF to be between the 1 and the max unroll factor
05594   // that the target allows.
05595   if (UF > MaxInterleaveSize)
05596     UF = MaxInterleaveSize;
05597   else if (UF < 1)
05598     UF = 1;
05599 
05600   // Unroll if we vectorized this loop and there is a reduction that could
05601   // benefit from unrolling.
05602   if (VF > 1 && Legal->getReductionVars()->size()) {
05603     DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
05604     return UF;
05605   }
05606 
05607   // Note that if we've already vectorized the loop we will have done the
05608   // runtime check and so unrolling won't require further checks.
05609   bool UnrollingRequiresRuntimePointerCheck =
05610       (VF == 1 && Legal->getRuntimePointerCheck()->Need);
05611 
05612   // We want to unroll small loops in order to reduce the loop overhead and
05613   // potentially expose ILP opportunities.
05614   DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
05615   if (!UnrollingRequiresRuntimePointerCheck &&
05616       LoopCost < SmallLoopCost) {
05617     // We assume that the cost overhead is 1 and we use the cost model
05618     // to estimate the cost of the loop and unroll until the cost of the
05619     // loop overhead is about 5% of the cost of the loop.
05620     unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
05621 
05622     // Unroll until store/load ports (estimated by max unroll factor) are
05623     // saturated.
05624     unsigned StoresUF = UF / (Legal->NumStores ? Legal->NumStores : 1);
05625     unsigned LoadsUF = UF /  (Legal->NumLoads ? Legal->NumLoads : 1);
05626 
05627     // If we have a scalar reduction (vector reductions are already dealt with
05628     // by this point), we can increase the critical path length if the loop
05629     // we're unrolling is inside another loop. Limit, by default to 2, so the
05630     // critical path only gets increased by one reduction operation.
05631     if (Legal->getReductionVars()->size() &&
05632         TheLoop->getLoopDepth() > 1) {
05633       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionUF);
05634       SmallUF = std::min(SmallUF, F);
05635       StoresUF = std::min(StoresUF, F);
05636       LoadsUF = std::min(LoadsUF, F);
05637     }
05638 
05639     if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) {
05640       DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n");
05641       return std::max(StoresUF, LoadsUF);
05642     }
05643 
05644     DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
05645     return SmallUF;
05646   }
05647 
05648   DEBUG(dbgs() << "LV: Not Unrolling.\n");
05649   return 1;
05650 }
05651 
05652 LoopVectorizationCostModel::RegisterUsage
05653 LoopVectorizationCostModel::calculateRegisterUsage() {
05654   // This function calculates the register usage by measuring the highest number
05655   // of values that are alive at a single location. Obviously, this is a very
05656   // rough estimation. We scan the loop in a topological order in order and
05657   // assign a number to each instruction. We use RPO to ensure that defs are
05658   // met before their users. We assume that each instruction that has in-loop
05659   // users starts an interval. We record every time that an in-loop value is
05660   // used, so we have a list of the first and last occurrences of each
05661   // instruction. Next, we transpose this data structure into a multi map that
05662   // holds the list of intervals that *end* at a specific location. This multi
05663   // map allows us to perform a linear search. We scan the instructions linearly
05664   // and record each time that a new interval starts, by placing it in a set.
05665   // If we find this value in the multi-map then we remove it from the set.
05666   // The max register usage is the maximum size of the set.
05667   // We also search for instructions that are defined outside the loop, but are
05668   // used inside the loop. We need this number separately from the max-interval
05669   // usage number because when we unroll, loop-invariant values do not take
05670   // more register.
05671   LoopBlocksDFS DFS(TheLoop);
05672   DFS.perform(LI);
05673 
05674   RegisterUsage R;
05675   R.NumInstructions = 0;
05676 
05677   // Each 'key' in the map opens a new interval. The values
05678   // of the map are the index of the 'last seen' usage of the
05679   // instruction that is the key.
05680   typedef DenseMap<Instruction*, unsigned> IntervalMap;
05681   // Maps instruction to its index.
05682   DenseMap<unsigned, Instruction*> IdxToInstr;
05683   // Marks the end of each interval.
05684   IntervalMap EndPoint;
05685   // Saves the list of instruction indices that are used in the loop.
05686   SmallSet<Instruction*, 8> Ends;
05687   // Saves the list of values that are used in the loop but are
05688   // defined outside the loop, such as arguments and constants.
05689   SmallPtrSet<Value*, 8> LoopInvariants;
05690 
05691   unsigned Index = 0;
05692   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
05693        be = DFS.endRPO(); bb != be; ++bb) {
05694     R.NumInstructions += (*bb)->size();
05695     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
05696          ++it) {
05697       Instruction *I = it;
05698       IdxToInstr[Index++] = I;
05699 
05700       // Save the end location of each USE.
05701       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
05702         Value *U = I->getOperand(i);
05703         Instruction *Instr = dyn_cast<Instruction>(U);
05704 
05705         // Ignore non-instruction values such as arguments, constants, etc.
05706         if (!Instr) continue;
05707 
05708         // If this instruction is outside the loop then record it and continue.
05709         if (!TheLoop->contains(Instr)) {
05710           LoopInvariants.insert(Instr);
05711           continue;
05712         }
05713 
05714         // Overwrite previous end points.
05715         EndPoint[Instr] = Index;
05716         Ends.insert(Instr);
05717       }
05718     }
05719   }
05720 
05721   // Saves the list of intervals that end with the index in 'key'.
05722   typedef SmallVector<Instruction*, 2> InstrList;
05723   DenseMap<unsigned, InstrList> TransposeEnds;
05724 
05725   // Transpose the EndPoints to a list of values that end at each index.
05726   for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
05727        it != e; ++it)
05728     TransposeEnds[it->second].push_back(it->first);
05729 
05730   SmallSet<Instruction*, 8> OpenIntervals;
05731   unsigned MaxUsage = 0;
05732 
05733 
05734   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
05735   for (unsigned int i = 0; i < Index; ++i) {
05736     Instruction *I = IdxToInstr[i];
05737     // Ignore instructions that are never used within the loop.
05738     if (!Ends.count(I)) continue;
05739 
05740     // Ignore ephemeral values.
05741     if (EphValues.count(I))
05742       continue;
05743 
05744     // Remove all of the instructions that end at this location.
05745     InstrList &List = TransposeEnds[i];
05746     for (unsigned int j=0, e = List.size(); j < e; ++j)
05747       OpenIntervals.erase(List[j]);
05748 
05749     // Count the number of live interals.
05750     MaxUsage = std::max(MaxUsage, OpenIntervals.size());
05751 
05752     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
05753           OpenIntervals.size() << '\n');
05754 
05755     // Add the current instruction to the list of open intervals.
05756     OpenIntervals.insert(I);
05757   }
05758 
05759   unsigned Invariant = LoopInvariants.size();
05760   DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
05761   DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
05762   DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
05763 
05764   R.LoopInvariantRegs = Invariant;
05765   R.MaxLocalUsers = MaxUsage;
05766   return R;
05767 }
05768 
05769 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
05770   unsigned Cost = 0;
05771 
05772   // For each block.
05773   for (Loop::block_iterator bb = TheLoop->block_begin(),
05774        be = TheLoop->block_end(); bb != be; ++bb) {
05775     unsigned BlockCost = 0;
05776     BasicBlock *BB = *bb;
05777 
05778     // For each instruction in the old loop.
05779     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
05780       // Skip dbg intrinsics.
05781       if (isa<DbgInfoIntrinsic>(it))
05782         continue;
05783 
05784       // Ignore ephemeral values.
05785       if (EphValues.count(it))
05786         continue;
05787 
05788       unsigned C = getInstructionCost(it, VF);
05789 
05790       // Check if we should override the cost.
05791       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
05792         C = ForceTargetInstructionCost;
05793 
05794       BlockCost += C;
05795       DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
05796             VF << " For instruction: " << *it << '\n');
05797     }
05798 
05799     // We assume that if-converted blocks have a 50% chance of being executed.
05800     // When the code is scalar then some of the blocks are avoided due to CF.
05801     // When the code is vectorized we execute all code paths.
05802     if (VF == 1 && Legal->blockNeedsPredication(*bb))
05803       BlockCost /= 2;
05804 
05805     Cost += BlockCost;
05806   }
05807 
05808   return Cost;
05809 }
05810 
05811 /// \brief Check whether the address computation for a non-consecutive memory
05812 /// access looks like an unlikely candidate for being merged into the indexing
05813 /// mode.
05814 ///
05815 /// We look for a GEP which has one index that is an induction variable and all
05816 /// other indices are loop invariant. If the stride of this access is also
05817 /// within a small bound we decide that this address computation can likely be
05818 /// merged into the addressing mode.
05819 /// In all other cases, we identify the address computation as complex.
05820 static bool isLikelyComplexAddressComputation(Value *Ptr,
05821                                               LoopVectorizationLegality *Legal,
05822                                               ScalarEvolution *SE,
05823                                               const Loop *TheLoop) {
05824   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
05825   if (!Gep)
05826     return true;
05827 
05828   // We are looking for a gep with all loop invariant indices except for one
05829   // which should be an induction variable.
05830   unsigned NumOperands = Gep->getNumOperands();
05831   for (unsigned i = 1; i < NumOperands; ++i) {
05832     Value *Opd = Gep->getOperand(i);
05833     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
05834         !Legal->isInductionVariable(Opd))
05835       return true;
05836   }
05837 
05838   // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
05839   // can likely be merged into the address computation.
05840   unsigned MaxMergeDistance = 64;
05841 
05842   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
05843   if (!AddRec)
05844     return true;
05845 
05846   // Check the step is constant.
05847   const SCEV *Step = AddRec->getStepRecurrence(*SE);
05848   // Calculate the pointer stride and check if it is consecutive.
05849   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
05850   if (!C)
05851     return true;
05852 
05853   const APInt &APStepVal = C->getValue()->getValue();
05854 
05855   // Huge step value - give up.
05856   if (APStepVal.getBitWidth() > 64)
05857     return true;
05858 
05859   int64_t StepVal = APStepVal.getSExtValue();
05860 
05861   return StepVal > MaxMergeDistance;
05862 }
05863 
05864 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
05865   if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
05866     return true;
05867   return false;
05868 }
05869 
05870 unsigned
05871 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
05872   // If we know that this instruction will remain uniform, check the cost of
05873   // the scalar version.
05874   if (Legal->isUniformAfterVectorization(I))
05875     VF = 1;
05876 
05877   Type *RetTy = I->getType();
05878   Type *VectorTy = ToVectorTy(RetTy, VF);
05879 
05880   // TODO: We need to estimate the cost of intrinsic calls.
05881   switch (I->getOpcode()) {
05882   case Instruction::GetElementPtr:
05883     // We mark this instruction as zero-cost because the cost of GEPs in
05884     // vectorized code depends on whether the corresponding memory instruction
05885     // is scalarized or not. Therefore, we handle GEPs with the memory
05886     // instruction cost.
05887     return 0;
05888   case Instruction::Br: {
05889     return TTI.getCFInstrCost(I->getOpcode());
05890   }
05891   case Instruction::PHI:
05892     //TODO: IF-converted IFs become selects.
05893     return 0;
05894   case Instruction::Add:
05895   case Instruction::FAdd:
05896   case Instruction::Sub:
05897   case Instruction::FSub:
05898   case Instruction::Mul:
05899   case Instruction::FMul:
05900   case Instruction::UDiv:
05901   case Instruction::SDiv:
05902   case Instruction::FDiv:
05903   case Instruction::URem:
05904   case Instruction::SRem:
05905   case Instruction::FRem:
05906   case Instruction::Shl:
05907   case Instruction::LShr:
05908   case Instruction::AShr:
05909   case Instruction::And:
05910   case Instruction::Or:
05911   case Instruction::Xor: {
05912     // Since we will replace the stride by 1 the multiplication should go away.
05913     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
05914       return 0;
05915     // Certain instructions can be cheaper to vectorize if they have a constant
05916     // second vector operand. One example of this are shifts on x86.
05917     TargetTransformInfo::OperandValueKind Op1VK =
05918       TargetTransformInfo::OK_AnyValue;
05919     TargetTransformInfo::OperandValueKind Op2VK =
05920       TargetTransformInfo::OK_AnyValue;
05921     TargetTransformInfo::OperandValueProperties Op1VP =
05922         TargetTransformInfo::OP_None;
05923     TargetTransformInfo::OperandValueProperties Op2VP =
05924         TargetTransformInfo::OP_None;
05925     Value *Op2 = I->getOperand(1);
05926 
05927     // Check for a splat of a constant or for a non uniform vector of constants.
05928     if (isa<ConstantInt>(Op2)) {
05929       ConstantInt *CInt = cast<ConstantInt>(Op2);
05930       if (CInt && CInt->getValue().isPowerOf2())
05931         Op2VP = TargetTransformInfo::OP_PowerOf2;
05932       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
05933     } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
05934       Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
05935       Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
05936       if (SplatValue) {
05937         ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
05938         if (CInt && CInt->getValue().isPowerOf2())
05939           Op2VP = TargetTransformInfo::OP_PowerOf2;
05940         Op2VK = TargetTransformInfo::OK_UniformConstantValue;
05941       }
05942     }
05943 
05944     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
05945                                       Op1VP, Op2VP);
05946   }
05947   case Instruction::Select: {
05948     SelectInst *SI = cast<SelectInst>(I);
05949     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
05950     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
05951     Type *CondTy = SI->getCondition()->getType();
05952     if (!ScalarCond)
05953       CondTy = VectorType::get(CondTy, VF);
05954 
05955     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
05956   }
05957   case Instruction::ICmp:
05958   case Instruction::FCmp: {
05959     Type *ValTy = I->getOperand(0)->getType();
05960     VectorTy = ToVectorTy(ValTy, VF);
05961     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
05962   }
05963   case Instruction::Store:
05964   case Instruction::Load: {
05965     StoreInst *SI = dyn_cast<StoreInst>(I);
05966     LoadInst *LI = dyn_cast<LoadInst>(I);
05967     Type *ValTy = (SI ? SI->getValueOperand()->getType() :
05968                    LI->getType());
05969     VectorTy = ToVectorTy(ValTy, VF);
05970 
05971     unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
05972     unsigned AS = SI ? SI->getPointerAddressSpace() :
05973       LI->getPointerAddressSpace();
05974     Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
05975     // We add the cost of address computation here instead of with the gep
05976     // instruction because only here we know whether the operation is
05977     // scalarized.
05978     if (VF == 1)
05979       return TTI.getAddressComputationCost(VectorTy) +
05980         TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
05981 
05982     // Scalarized loads/stores.
05983     int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
05984     bool Reverse = ConsecutiveStride < 0;
05985     unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
05986     unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
05987     if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
05988       bool IsComplexComputation =
05989         isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
05990       unsigned Cost = 0;
05991       // The cost of extracting from the value vector and pointer vector.
05992       Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
05993       for (unsigned i = 0; i < VF; ++i) {
05994         //  The cost of extracting the pointer operand.
05995         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
05996         // In case of STORE, the cost of ExtractElement from the vector.
05997         // In case of LOAD, the cost of InsertElement into the returned
05998         // vector.
05999         Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
06000                                             Instruction::InsertElement,
06001                                             VectorTy, i);
06002       }
06003 
06004       // The cost of the scalar loads/stores.
06005       Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
06006       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
06007                                        Alignment, AS);
06008       return Cost;
06009     }
06010 
06011     // Wide load/stores.
06012     unsigned Cost = TTI.getAddressComputationCost(VectorTy);
06013     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
06014 
06015     if (Reverse)
06016       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
06017                                   VectorTy, 0);
06018     return Cost;
06019   }
06020   case Instruction::ZExt:
06021   case Instruction::SExt:
06022   case Instruction::FPToUI:
06023   case Instruction::FPToSI:
06024   case Instruction::FPExt:
06025   case Instruction::PtrToInt:
06026   case Instruction::IntToPtr:
06027   case Instruction::SIToFP:
06028   case Instruction::UIToFP:
06029   case Instruction::Trunc:
06030   case Instruction::FPTrunc:
06031   case Instruction::BitCast: {
06032     // We optimize the truncation of induction variable.
06033     // The cost of these is the same as the scalar operation.
06034     if (I->getOpcode() == Instruction::Trunc &&
06035         Legal->isInductionVariable(I->getOperand(0)))
06036       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
06037                                   I->getOperand(0)->getType());
06038 
06039     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
06040     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
06041   }
06042   case Instruction::Call: {
06043     CallInst *CI = cast<CallInst>(I);
06044     Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
06045     assert(ID && "Not an intrinsic call!");
06046     Type *RetTy = ToVectorTy(CI->getType(), VF);
06047     SmallVector<Type*, 4> Tys;
06048     for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
06049       Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
06050     return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
06051   }
06052   default: {
06053     // We are scalarizing the instruction. Return the cost of the scalar
06054     // instruction, plus the cost of insert and extract into vector
06055     // elements, times the vector width.
06056     unsigned Cost = 0;
06057 
06058     if (!RetTy->isVoidTy() && VF != 1) {
06059       unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
06060                                                 VectorTy);
06061       unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
06062                                                 VectorTy);
06063 
06064       // The cost of inserting the results plus extracting each one of the
06065       // operands.
06066       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
06067     }
06068 
06069     // The cost of executing VF copies of the scalar instruction. This opcode
06070     // is unknown. Assume that it is the same as 'mul'.
06071     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
06072     return Cost;
06073   }
06074   }// end of switch.
06075 }
06076 
06077 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
06078   if (Scalar->isVoidTy() || VF == 1)
06079     return Scalar;
06080   return VectorType::get(Scalar, VF);
06081 }
06082 
06083 char LoopVectorize::ID = 0;
06084 static const char lv_name[] = "Loop Vectorization";
06085 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
06086 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
06087 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
06088 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
06089 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
06090 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
06091 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
06092 INITIALIZE_PASS_DEPENDENCY(LCSSA)
06093 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
06094 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
06095 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
06096 
06097 namespace llvm {
06098   Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
06099     return new LoopVectorize(NoUnrolling, AlwaysVectorize);
06100   }
06101 }
06102 
06103 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
06104   // Check for a store.
06105   if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
06106     return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
06107 
06108   // Check for a load.
06109   if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
06110     return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
06111 
06112   return false;
06113 }
06114 
06115 
06116 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
06117                                              bool IfPredicateStore) {
06118   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
06119   // Holds vector parameters or scalars, in case of uniform vals.
06120   SmallVector<VectorParts, 4> Params;
06121 
06122   setDebugLocFromInst(Builder, Instr);
06123 
06124   // Find all of the vectorized parameters.
06125   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
06126     Value *SrcOp = Instr->getOperand(op);
06127 
06128     // If we are accessing the old induction variable, use the new one.
06129     if (SrcOp == OldInduction) {
06130       Params.push_back(getVectorValue(SrcOp));
06131       continue;
06132     }
06133 
06134     // Try using previously calculated values.
06135     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
06136 
06137     // If the src is an instruction that appeared earlier in the basic block
06138     // then it should already be vectorized.
06139     if (SrcInst && OrigLoop->contains(SrcInst)) {
06140       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
06141       // The parameter is a vector value from earlier.
06142       Params.push_back(WidenMap.get(SrcInst));
06143     } else {
06144       // The parameter is a scalar from outside the loop. Maybe even a constant.
06145       VectorParts Scalars;
06146       Scalars.append(UF, SrcOp);
06147       Params.push_back(Scalars);
06148     }
06149   }
06150 
06151   assert(Params.size() == Instr->getNumOperands() &&
06152          "Invalid number of operands");
06153 
06154   // Does this instruction return a value ?
06155   bool IsVoidRetTy = Instr->getType()->isVoidTy();
06156 
06157   Value *UndefVec = IsVoidRetTy ? nullptr :
06158   UndefValue::get(Instr->getType());
06159   // Create a new entry in the WidenMap and initialize it to Undef or Null.
06160   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
06161 
06162   Instruction *InsertPt = Builder.GetInsertPoint();
06163   BasicBlock *IfBlock = Builder.GetInsertBlock();
06164   BasicBlock *CondBlock = nullptr;
06165 
06166   VectorParts Cond;
06167   Loop *VectorLp = nullptr;
06168   if (IfPredicateStore) {
06169     assert(Instr->getParent()->getSinglePredecessor() &&
06170            "Only support single predecessor blocks");
06171     Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
06172                           Instr->getParent());
06173     VectorLp = LI->getLoopFor(IfBlock);
06174     assert(VectorLp && "Must have a loop for this block");
06175   }
06176 
06177   // For each vector unroll 'part':
06178   for (unsigned Part = 0; Part < UF; ++Part) {
06179     // For each scalar that we create:
06180 
06181     // Start an "if (pred) a[i] = ..." block.
06182     Value *Cmp = nullptr;
06183     if (IfPredicateStore) {
06184       if (Cond[Part]->getType()->isVectorTy())
06185         Cond[Part] =
06186             Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
06187       Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
06188                                ConstantInt::get(Cond[Part]->getType(), 1));
06189       CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
06190       LoopVectorBody.push_back(CondBlock);
06191       VectorLp->addBasicBlockToLoop(CondBlock, LI->getBase());
06192       // Update Builder with newly created basic block.
06193       Builder.SetInsertPoint(InsertPt);
06194     }
06195 
06196     Instruction *Cloned = Instr->clone();
06197       if (!IsVoidRetTy)
06198         Cloned->setName(Instr->getName() + ".cloned");
06199       // Replace the operands of the cloned instructions with extracted scalars.
06200       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
06201         Value *Op = Params[op][Part];
06202         Cloned->setOperand(op, Op);
06203       }
06204 
06205       // Place the cloned scalar in the new loop.
06206       Builder.Insert(Cloned);
06207 
06208       // If the original scalar returns a value we need to place it in a vector
06209       // so that future users will be able to use it.
06210       if (!IsVoidRetTy)
06211         VecResults[Part] = Cloned;
06212 
06213     // End if-block.
06214       if (IfPredicateStore) {
06215         BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
06216         LoopVectorBody.push_back(NewIfBlock);
06217         VectorLp->addBasicBlockToLoop(NewIfBlock, LI->getBase());
06218         Builder.SetInsertPoint(InsertPt);
06219         Instruction *OldBr = IfBlock->getTerminator();
06220         BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
06221         OldBr->eraseFromParent();
06222         IfBlock = NewIfBlock;
06223       }
06224   }
06225 }
06226 
06227 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
06228   StoreInst *SI = dyn_cast<StoreInst>(Instr);
06229   bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
06230 
06231   return scalarizeInstruction(Instr, IfPredicateStore);
06232 }
06233 
06234 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
06235   return Vec;
06236 }
06237 
06238 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
06239   return V;
06240 }
06241 
06242 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
06243                                                bool Negate) {
06244   // When unrolling and the VF is 1, we only need to add a simple scalar.
06245   Type *ITy = Val->getType();
06246   assert(!ITy->isVectorTy() && "Val must be a scalar");
06247   Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
06248   return Builder.CreateAdd(Val, C, "induction");
06249 }