LLVM API Documentation

BBVectorize.cpp
Go to the documentation of this file.
00001 //===- BBVectorize.cpp - A Basic-Block 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 file implements a basic-block vectorization pass. The algorithm was
00011 // inspired by that used by the Vienna MAP Vectorizor by Franchetti and Kral,
00012 // et al. It works by looking for chains of pairable operations and then
00013 // pairing them.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #define BBV_NAME "bb-vectorize"
00018 #include "llvm/Transforms/Vectorize.h"
00019 #include "llvm/ADT/DenseMap.h"
00020 #include "llvm/ADT/DenseSet.h"
00021 #include "llvm/ADT/STLExtras.h"
00022 #include "llvm/ADT/SmallSet.h"
00023 #include "llvm/ADT/SmallVector.h"
00024 #include "llvm/ADT/Statistic.h"
00025 #include "llvm/ADT/StringExtras.h"
00026 #include "llvm/Analysis/AliasAnalysis.h"
00027 #include "llvm/Analysis/AliasSetTracker.h"
00028 #include "llvm/Analysis/ScalarEvolution.h"
00029 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
00030 #include "llvm/Analysis/TargetTransformInfo.h"
00031 #include "llvm/Analysis/ValueTracking.h"
00032 #include "llvm/IR/Constants.h"
00033 #include "llvm/IR/DataLayout.h"
00034 #include "llvm/IR/DerivedTypes.h"
00035 #include "llvm/IR/Dominators.h"
00036 #include "llvm/IR/Function.h"
00037 #include "llvm/IR/Instructions.h"
00038 #include "llvm/IR/IntrinsicInst.h"
00039 #include "llvm/IR/Intrinsics.h"
00040 #include "llvm/IR/LLVMContext.h"
00041 #include "llvm/IR/Metadata.h"
00042 #include "llvm/IR/Type.h"
00043 #include "llvm/IR/ValueHandle.h"
00044 #include "llvm/Pass.h"
00045 #include "llvm/Support/CommandLine.h"
00046 #include "llvm/Support/Debug.h"
00047 #include "llvm/Support/raw_ostream.h"
00048 #include "llvm/Transforms/Utils/Local.h"
00049 #include <algorithm>
00050 using namespace llvm;
00051 
00052 #define DEBUG_TYPE BBV_NAME
00053 
00054 static cl::opt<bool>
00055 IgnoreTargetInfo("bb-vectorize-ignore-target-info",  cl::init(false),
00056   cl::Hidden, cl::desc("Ignore target information"));
00057 
00058 static cl::opt<unsigned>
00059 ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
00060   cl::desc("The required chain depth for vectorization"));
00061 
00062 static cl::opt<bool>
00063 UseChainDepthWithTI("bb-vectorize-use-chain-depth",  cl::init(false),
00064   cl::Hidden, cl::desc("Use the chain depth requirement with"
00065                        " target information"));
00066 
00067 static cl::opt<unsigned>
00068 SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
00069   cl::desc("The maximum search distance for instruction pairs"));
00070 
00071 static cl::opt<bool>
00072 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
00073   cl::desc("Replicating one element to a pair breaks the chain"));
00074 
00075 static cl::opt<unsigned>
00076 VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
00077   cl::desc("The size of the native vector registers"));
00078 
00079 static cl::opt<unsigned>
00080 MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
00081   cl::desc("The maximum number of pairing iterations"));
00082 
00083 static cl::opt<bool>
00084 Pow2LenOnly("bb-vectorize-pow2-len-only", cl::init(false), cl::Hidden,
00085   cl::desc("Don't try to form non-2^n-length vectors"));
00086 
00087 static cl::opt<unsigned>
00088 MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
00089   cl::desc("The maximum number of pairable instructions per group"));
00090 
00091 static cl::opt<unsigned>
00092 MaxPairs("bb-vectorize-max-pairs-per-group", cl::init(3000), cl::Hidden,
00093   cl::desc("The maximum number of candidate instruction pairs per group"));
00094 
00095 static cl::opt<unsigned>
00096 MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
00097   cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
00098                        " a full cycle check"));
00099 
00100 static cl::opt<bool>
00101 NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
00102   cl::desc("Don't try to vectorize boolean (i1) values"));
00103 
00104 static cl::opt<bool>
00105 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
00106   cl::desc("Don't try to vectorize integer values"));
00107 
00108 static cl::opt<bool>
00109 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
00110   cl::desc("Don't try to vectorize floating-point values"));
00111 
00112 // FIXME: This should default to false once pointer vector support works.
00113 static cl::opt<bool>
00114 NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
00115   cl::desc("Don't try to vectorize pointer values"));
00116 
00117 static cl::opt<bool>
00118 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
00119   cl::desc("Don't try to vectorize casting (conversion) operations"));
00120 
00121 static cl::opt<bool>
00122 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
00123   cl::desc("Don't try to vectorize floating-point math intrinsics"));
00124 
00125 static cl::opt<bool>
00126 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
00127   cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
00128 
00129 static cl::opt<bool>
00130 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
00131   cl::desc("Don't try to vectorize select instructions"));
00132 
00133 static cl::opt<bool>
00134 NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
00135   cl::desc("Don't try to vectorize comparison instructions"));
00136 
00137 static cl::opt<bool>
00138 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
00139   cl::desc("Don't try to vectorize getelementptr instructions"));
00140 
00141 static cl::opt<bool>
00142 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
00143   cl::desc("Don't try to vectorize loads and stores"));
00144 
00145 static cl::opt<bool>
00146 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
00147   cl::desc("Only generate aligned loads and stores"));
00148 
00149 static cl::opt<bool>
00150 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
00151   cl::init(false), cl::Hidden,
00152   cl::desc("Don't boost the chain-depth contribution of loads and stores"));
00153 
00154 static cl::opt<bool>
00155 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
00156   cl::desc("Use a fast instruction dependency analysis"));
00157 
00158 #ifndef NDEBUG
00159 static cl::opt<bool>
00160 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
00161   cl::init(false), cl::Hidden,
00162   cl::desc("When debugging is enabled, output information on the"
00163            " instruction-examination process"));
00164 static cl::opt<bool>
00165 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
00166   cl::init(false), cl::Hidden,
00167   cl::desc("When debugging is enabled, output information on the"
00168            " candidate-selection process"));
00169 static cl::opt<bool>
00170 DebugPairSelection("bb-vectorize-debug-pair-selection",
00171   cl::init(false), cl::Hidden,
00172   cl::desc("When debugging is enabled, output information on the"
00173            " pair-selection process"));
00174 static cl::opt<bool>
00175 DebugCycleCheck("bb-vectorize-debug-cycle-check",
00176   cl::init(false), cl::Hidden,
00177   cl::desc("When debugging is enabled, output information on the"
00178            " cycle-checking process"));
00179 
00180 static cl::opt<bool>
00181 PrintAfterEveryPair("bb-vectorize-debug-print-after-every-pair",
00182   cl::init(false), cl::Hidden,
00183   cl::desc("When debugging is enabled, dump the basic block after"
00184            " every pair is fused"));
00185 #endif
00186 
00187 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
00188 
00189 namespace {
00190   struct BBVectorize : public BasicBlockPass {
00191     static char ID; // Pass identification, replacement for typeid
00192 
00193     const VectorizeConfig Config;
00194 
00195     BBVectorize(const VectorizeConfig &C = VectorizeConfig())
00196       : BasicBlockPass(ID), Config(C) {
00197       initializeBBVectorizePass(*PassRegistry::getPassRegistry());
00198     }
00199 
00200     BBVectorize(Pass *P, const VectorizeConfig &C)
00201       : BasicBlockPass(ID), Config(C) {
00202       AA = &P->getAnalysis<AliasAnalysis>();
00203       DT = &P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00204       SE = &P->getAnalysis<ScalarEvolution>();
00205       DataLayoutPass *DLP = P->getAnalysisIfAvailable<DataLayoutPass>();
00206       DL = DLP ? &DLP->getDataLayout() : 0;
00207       TTI = IgnoreTargetInfo ? 0 : &P->getAnalysis<TargetTransformInfo>();
00208     }
00209 
00210     typedef std::pair<Value *, Value *> ValuePair;
00211     typedef std::pair<ValuePair, int> ValuePairWithCost;
00212     typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
00213     typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
00214     typedef std::pair<VPPair, unsigned> VPPairWithType;
00215 
00216     AliasAnalysis *AA;
00217     DominatorTree *DT;
00218     ScalarEvolution *SE;
00219     const DataLayout *DL;
00220     const TargetTransformInfo *TTI;
00221 
00222     // FIXME: const correct?
00223 
00224     bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
00225 
00226     bool getCandidatePairs(BasicBlock &BB,
00227                        BasicBlock::iterator &Start,
00228                        DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00229                        DenseSet<ValuePair> &FixedOrderPairs,
00230                        DenseMap<ValuePair, int> &CandidatePairCostSavings,
00231                        std::vector<Value *> &PairableInsts, bool NonPow2Len);
00232 
00233     // FIXME: The current implementation does not account for pairs that
00234     // are connected in multiple ways. For example:
00235     //   C1 = A1 / A2; C2 = A2 / A1 (which may be both direct and a swap)
00236     enum PairConnectionType {
00237       PairConnectionDirect,
00238       PairConnectionSwap,
00239       PairConnectionSplat
00240     };
00241 
00242     void computeConnectedPairs(
00243              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00244              DenseSet<ValuePair> &CandidatePairsSet,
00245              std::vector<Value *> &PairableInsts,
00246              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00247              DenseMap<VPPair, unsigned> &PairConnectionTypes);
00248 
00249     void buildDepMap(BasicBlock &BB,
00250              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00251              std::vector<Value *> &PairableInsts,
00252              DenseSet<ValuePair> &PairableInstUsers);
00253 
00254     void choosePairs(DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00255              DenseSet<ValuePair> &CandidatePairsSet,
00256              DenseMap<ValuePair, int> &CandidatePairCostSavings,
00257              std::vector<Value *> &PairableInsts,
00258              DenseSet<ValuePair> &FixedOrderPairs,
00259              DenseMap<VPPair, unsigned> &PairConnectionTypes,
00260              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00261              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
00262              DenseSet<ValuePair> &PairableInstUsers,
00263              DenseMap<Value *, Value *>& ChosenPairs);
00264 
00265     void fuseChosenPairs(BasicBlock &BB,
00266              std::vector<Value *> &PairableInsts,
00267              DenseMap<Value *, Value *>& ChosenPairs,
00268              DenseSet<ValuePair> &FixedOrderPairs,
00269              DenseMap<VPPair, unsigned> &PairConnectionTypes,
00270              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00271              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps);
00272 
00273 
00274     bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
00275 
00276     bool areInstsCompatible(Instruction *I, Instruction *J,
00277                        bool IsSimpleLoadStore, bool NonPow2Len,
00278                        int &CostSavings, int &FixedOrder);
00279 
00280     bool trackUsesOfI(DenseSet<Value *> &Users,
00281                       AliasSetTracker &WriteSet, Instruction *I,
00282                       Instruction *J, bool UpdateUsers = true,
00283                       DenseSet<ValuePair> *LoadMoveSetPairs = 0);
00284 
00285   void computePairsConnectedTo(
00286              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00287              DenseSet<ValuePair> &CandidatePairsSet,
00288              std::vector<Value *> &PairableInsts,
00289              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00290              DenseMap<VPPair, unsigned> &PairConnectionTypes,
00291              ValuePair P);
00292 
00293     bool pairsConflict(ValuePair P, ValuePair Q,
00294              DenseSet<ValuePair> &PairableInstUsers,
00295              DenseMap<ValuePair, std::vector<ValuePair> >
00296                *PairableInstUserMap = 0,
00297              DenseSet<VPPair> *PairableInstUserPairSet = 0);
00298 
00299     bool pairWillFormCycle(ValuePair P,
00300              DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUsers,
00301              DenseSet<ValuePair> &CurrentPairs);
00302 
00303     void pruneDAGFor(
00304              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00305              std::vector<Value *> &PairableInsts,
00306              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00307              DenseSet<ValuePair> &PairableInstUsers,
00308              DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
00309              DenseSet<VPPair> &PairableInstUserPairSet,
00310              DenseMap<Value *, Value *> &ChosenPairs,
00311              DenseMap<ValuePair, size_t> &DAG,
00312              DenseSet<ValuePair> &PrunedDAG, ValuePair J,
00313              bool UseCycleCheck);
00314 
00315     void buildInitialDAGFor(
00316              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00317              DenseSet<ValuePair> &CandidatePairsSet,
00318              std::vector<Value *> &PairableInsts,
00319              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00320              DenseSet<ValuePair> &PairableInstUsers,
00321              DenseMap<Value *, Value *> &ChosenPairs,
00322              DenseMap<ValuePair, size_t> &DAG, ValuePair J);
00323 
00324     void findBestDAGFor(
00325              DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
00326              DenseSet<ValuePair> &CandidatePairsSet,
00327              DenseMap<ValuePair, int> &CandidatePairCostSavings,
00328              std::vector<Value *> &PairableInsts,
00329              DenseSet<ValuePair> &FixedOrderPairs,
00330              DenseMap<VPPair, unsigned> &PairConnectionTypes,
00331              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
00332              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
00333              DenseSet<ValuePair> &PairableInstUsers,
00334              DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
00335              DenseSet<VPPair> &PairableInstUserPairSet,
00336              DenseMap<Value *, Value *> &ChosenPairs,
00337              DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
00338              int &BestEffSize, Value *II, std::vector<Value *>&JJ,
00339              bool UseCycleCheck);
00340 
00341     Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
00342                      Instruction *J, unsigned o);
00343 
00344     void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
00345                      unsigned MaskOffset, unsigned NumInElem,
00346                      unsigned NumInElem1, unsigned IdxOffset,
00347                      std::vector<Constant*> &Mask);
00348 
00349     Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
00350                      Instruction *J);
00351 
00352     bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
00353                        unsigned o, Value *&LOp, unsigned numElemL,
00354                        Type *ArgTypeL, Type *ArgTypeR, bool IBeforeJ,
00355                        unsigned IdxOff = 0);
00356 
00357     Value *getReplacementInput(LLVMContext& Context, Instruction *I,
00358                      Instruction *J, unsigned o, bool IBeforeJ);
00359 
00360     void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
00361                      Instruction *J, SmallVectorImpl<Value *> &ReplacedOperands,
00362                      bool IBeforeJ);
00363 
00364     void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
00365                      Instruction *J, Instruction *K,
00366                      Instruction *&InsertionPt, Instruction *&K1,
00367                      Instruction *&K2);
00368 
00369     void collectPairLoadMoveSet(BasicBlock &BB,
00370                      DenseMap<Value *, Value *> &ChosenPairs,
00371                      DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
00372                      DenseSet<ValuePair> &LoadMoveSetPairs,
00373                      Instruction *I);
00374 
00375     void collectLoadMoveSet(BasicBlock &BB,
00376                      std::vector<Value *> &PairableInsts,
00377                      DenseMap<Value *, Value *> &ChosenPairs,
00378                      DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
00379                      DenseSet<ValuePair> &LoadMoveSetPairs);
00380 
00381     bool canMoveUsesOfIAfterJ(BasicBlock &BB,
00382                      DenseSet<ValuePair> &LoadMoveSetPairs,
00383                      Instruction *I, Instruction *J);
00384 
00385     void moveUsesOfIAfterJ(BasicBlock &BB,
00386                      DenseSet<ValuePair> &LoadMoveSetPairs,
00387                      Instruction *&InsertionPt,
00388                      Instruction *I, Instruction *J);
00389 
00390     void combineMetadata(Instruction *K, const Instruction *J);
00391 
00392     bool vectorizeBB(BasicBlock &BB) {
00393       if (skipOptnoneFunction(BB))
00394         return false;
00395       if (!DT->isReachableFromEntry(&BB)) {
00396         DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
00397               " in " << BB.getParent()->getName() << "\n");
00398         return false;
00399       }
00400 
00401       DEBUG(if (TTI) dbgs() << "BBV: using target information\n");
00402 
00403       bool changed = false;
00404       // Iterate a sufficient number of times to merge types of size 1 bit,
00405       // then 2 bits, then 4, etc. up to half of the target vector width of the
00406       // target vector register.
00407       unsigned n = 1;
00408       for (unsigned v = 2;
00409            (TTI || v <= Config.VectorBits) &&
00410            (!Config.MaxIter || n <= Config.MaxIter);
00411            v *= 2, ++n) {
00412         DEBUG(dbgs() << "BBV: fusing loop #" << n <<
00413               " for " << BB.getName() << " in " <<
00414               BB.getParent()->getName() << "...\n");
00415         if (vectorizePairs(BB))
00416           changed = true;
00417         else
00418           break;
00419       }
00420 
00421       if (changed && !Pow2LenOnly) {
00422         ++n;
00423         for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
00424           DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
00425                 n << " for " << BB.getName() << " in " <<
00426                 BB.getParent()->getName() << "...\n");
00427           if (!vectorizePairs(BB, true)) break;
00428         }
00429       }
00430 
00431       DEBUG(dbgs() << "BBV: done!\n");
00432       return changed;
00433     }
00434 
00435     bool runOnBasicBlock(BasicBlock &BB) override {
00436       // OptimizeNone check deferred to vectorizeBB().
00437 
00438       AA = &getAnalysis<AliasAnalysis>();
00439       DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00440       SE = &getAnalysis<ScalarEvolution>();
00441       DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
00442       DL = DLP ? &DLP->getDataLayout() : 0;
00443       TTI = IgnoreTargetInfo ? 0 : &getAnalysis<TargetTransformInfo>();
00444 
00445       return vectorizeBB(BB);
00446     }
00447 
00448     void getAnalysisUsage(AnalysisUsage &AU) const override {
00449       BasicBlockPass::getAnalysisUsage(AU);
00450       AU.addRequired<AliasAnalysis>();
00451       AU.addRequired<DominatorTreeWrapperPass>();
00452       AU.addRequired<ScalarEvolution>();
00453       AU.addRequired<TargetTransformInfo>();
00454       AU.addPreserved<AliasAnalysis>();
00455       AU.addPreserved<DominatorTreeWrapperPass>();
00456       AU.addPreserved<ScalarEvolution>();
00457       AU.setPreservesCFG();
00458     }
00459 
00460     static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
00461       assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
00462              "Cannot form vector from incompatible scalar types");
00463       Type *STy = ElemTy->getScalarType();
00464 
00465       unsigned numElem;
00466       if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
00467         numElem = VTy->getNumElements();
00468       } else {
00469         numElem = 1;
00470       }
00471 
00472       if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
00473         numElem += VTy->getNumElements();
00474       } else {
00475         numElem += 1;
00476       }
00477 
00478       return VectorType::get(STy, numElem);
00479     }
00480 
00481     static inline void getInstructionTypes(Instruction *I,
00482                                            Type *&T1, Type *&T2) {
00483       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00484         // For stores, it is the value type, not the pointer type that matters
00485         // because the value is what will come from a vector register.
00486   
00487         Value *IVal = SI->getValueOperand();
00488         T1 = IVal->getType();
00489       } else {
00490         T1 = I->getType();
00491       }
00492   
00493       if (CastInst *CI = dyn_cast<CastInst>(I))
00494         T2 = CI->getSrcTy();
00495       else
00496         T2 = T1;
00497 
00498       if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
00499         T2 = SI->getCondition()->getType();
00500       } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
00501         T2 = SI->getOperand(0)->getType();
00502       } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
00503         T2 = CI->getOperand(0)->getType();
00504       }
00505     }
00506 
00507     // Returns the weight associated with the provided value. A chain of
00508     // candidate pairs has a length given by the sum of the weights of its
00509     // members (one weight per pair; the weight of each member of the pair
00510     // is assumed to be the same). This length is then compared to the
00511     // chain-length threshold to determine if a given chain is significant
00512     // enough to be vectorized. The length is also used in comparing
00513     // candidate chains where longer chains are considered to be better.
00514     // Note: when this function returns 0, the resulting instructions are
00515     // not actually fused.
00516     inline size_t getDepthFactor(Value *V) {
00517       // InsertElement and ExtractElement have a depth factor of zero. This is
00518       // for two reasons: First, they cannot be usefully fused. Second, because
00519       // the pass generates a lot of these, they can confuse the simple metric
00520       // used to compare the dags in the next iteration. Thus, giving them a
00521       // weight of zero allows the pass to essentially ignore them in
00522       // subsequent iterations when looking for vectorization opportunities
00523       // while still tracking dependency chains that flow through those
00524       // instructions.
00525       if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
00526         return 0;
00527 
00528       // Give a load or store half of the required depth so that load/store
00529       // pairs will vectorize.
00530       if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
00531         return Config.ReqChainDepth/2;
00532 
00533       return 1;
00534     }
00535 
00536     // Returns the cost of the provided instruction using TTI.
00537     // This does not handle loads and stores.
00538     unsigned getInstrCost(unsigned Opcode, Type *T1, Type *T2,
00539                           TargetTransformInfo::OperandValueKind Op1VK = 
00540                               TargetTransformInfo::OK_AnyValue,
00541                           TargetTransformInfo::OperandValueKind Op2VK =
00542                               TargetTransformInfo::OK_AnyValue) {
00543       switch (Opcode) {
00544       default: break;
00545       case Instruction::GetElementPtr:
00546         // We mark this instruction as zero-cost because scalar GEPs are usually
00547         // lowered to the instruction addressing mode. At the moment we don't
00548         // generate vector GEPs.
00549         return 0;
00550       case Instruction::Br:
00551         return TTI->getCFInstrCost(Opcode);
00552       case Instruction::PHI:
00553         return 0;
00554       case Instruction::Add:
00555       case Instruction::FAdd:
00556       case Instruction::Sub:
00557       case Instruction::FSub:
00558       case Instruction::Mul:
00559       case Instruction::FMul:
00560       case Instruction::UDiv:
00561       case Instruction::SDiv:
00562       case Instruction::FDiv:
00563       case Instruction::URem:
00564       case Instruction::SRem:
00565       case Instruction::FRem:
00566       case Instruction::Shl:
00567       case Instruction::LShr:
00568       case Instruction::AShr:
00569       case Instruction::And:
00570       case Instruction::Or:
00571       case Instruction::Xor:
00572         return TTI->getArithmeticInstrCost(Opcode, T1, Op1VK, Op2VK);
00573       case Instruction::Select:
00574       case Instruction::ICmp:
00575       case Instruction::FCmp:
00576         return TTI->getCmpSelInstrCost(Opcode, T1, T2);
00577       case Instruction::ZExt:
00578       case Instruction::SExt:
00579       case Instruction::FPToUI:
00580       case Instruction::FPToSI:
00581       case Instruction::FPExt:
00582       case Instruction::PtrToInt:
00583       case Instruction::IntToPtr:
00584       case Instruction::SIToFP:
00585       case Instruction::UIToFP:
00586       case Instruction::Trunc:
00587       case Instruction::FPTrunc:
00588       case Instruction::BitCast:
00589       case Instruction::ShuffleVector:
00590         return TTI->getCastInstrCost(Opcode, T1, T2);
00591       }
00592 
00593       return 1;
00594     }
00595 
00596     // This determines the relative offset of two loads or stores, returning
00597     // true if the offset could be determined to be some constant value.
00598     // For example, if OffsetInElmts == 1, then J accesses the memory directly
00599     // after I; if OffsetInElmts == -1 then I accesses the memory
00600     // directly after J.
00601     bool getPairPtrInfo(Instruction *I, Instruction *J,
00602         Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
00603         unsigned &IAddressSpace, unsigned &JAddressSpace,
00604         int64_t &OffsetInElmts, bool ComputeOffset = true) {
00605       OffsetInElmts = 0;
00606       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00607         LoadInst *LJ = cast<LoadInst>(J);
00608         IPtr = LI->getPointerOperand();
00609         JPtr = LJ->getPointerOperand();
00610         IAlignment = LI->getAlignment();
00611         JAlignment = LJ->getAlignment();
00612         IAddressSpace = LI->getPointerAddressSpace();
00613         JAddressSpace = LJ->getPointerAddressSpace();
00614       } else {
00615         StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
00616         IPtr = SI->getPointerOperand();
00617         JPtr = SJ->getPointerOperand();
00618         IAlignment = SI->getAlignment();
00619         JAlignment = SJ->getAlignment();
00620         IAddressSpace = SI->getPointerAddressSpace();
00621         JAddressSpace = SJ->getPointerAddressSpace();
00622       }
00623 
00624       if (!ComputeOffset)
00625         return true;
00626 
00627       const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
00628       const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
00629 
00630       // If this is a trivial offset, then we'll get something like
00631       // 1*sizeof(type). With target data, which we need anyway, this will get
00632       // constant folded into a number.
00633       const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
00634       if (const SCEVConstant *ConstOffSCEV =
00635             dyn_cast<SCEVConstant>(OffsetSCEV)) {
00636         ConstantInt *IntOff = ConstOffSCEV->getValue();
00637         int64_t Offset = IntOff->getSExtValue();
00638 
00639         Type *VTy = IPtr->getType()->getPointerElementType();
00640         int64_t VTyTSS = (int64_t) DL->getTypeStoreSize(VTy);
00641 
00642         Type *VTy2 = JPtr->getType()->getPointerElementType();
00643         if (VTy != VTy2 && Offset < 0) {
00644           int64_t VTy2TSS = (int64_t) DL->getTypeStoreSize(VTy2);
00645           OffsetInElmts = Offset/VTy2TSS;
00646           return (abs64(Offset) % VTy2TSS) == 0;
00647         }
00648 
00649         OffsetInElmts = Offset/VTyTSS;
00650         return (abs64(Offset) % VTyTSS) == 0;
00651       }
00652 
00653       return false;
00654     }
00655 
00656     // Returns true if the provided CallInst represents an intrinsic that can
00657     // be vectorized.
00658     bool isVectorizableIntrinsic(CallInst* I) {
00659       Function *F = I->getCalledFunction();
00660       if (!F) return false;
00661 
00662       Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
00663       if (!IID) return false;
00664 
00665       switch(IID) {
00666       default:
00667         return false;
00668       case Intrinsic::sqrt:
00669       case Intrinsic::powi:
00670       case Intrinsic::sin:
00671       case Intrinsic::cos:
00672       case Intrinsic::log:
00673       case Intrinsic::log2:
00674       case Intrinsic::log10:
00675       case Intrinsic::exp:
00676       case Intrinsic::exp2:
00677       case Intrinsic::pow:
00678       case Intrinsic::round:
00679       case Intrinsic::copysign:
00680       case Intrinsic::ceil:
00681       case Intrinsic::nearbyint:
00682       case Intrinsic::rint:
00683       case Intrinsic::trunc:
00684       case Intrinsic::floor:
00685       case Intrinsic::fabs:
00686         return Config.VectorizeMath;
00687       case Intrinsic::fma:
00688       case Intrinsic::fmuladd:
00689         return Config.VectorizeFMA;
00690       }
00691     }
00692 
00693     bool isPureIEChain(InsertElementInst *IE) {
00694       InsertElementInst *IENext = IE;
00695       do {
00696         if (!isa<UndefValue>(IENext->getOperand(0)) &&
00697             !isa<InsertElementInst>(IENext->getOperand(0))) {
00698           return false;
00699         }
00700       } while ((IENext =
00701                  dyn_cast<InsertElementInst>(IENext->getOperand(0))));
00702 
00703       return true;
00704     }
00705   };
00706 
00707   // This function implements one vectorization iteration on the provided
00708   // basic block. It returns true if the block is changed.
00709   bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
00710     bool ShouldContinue;
00711     BasicBlock::iterator Start = BB.getFirstInsertionPt();
00712 
00713     std::vector<Value *> AllPairableInsts;
00714     DenseMap<Value *, Value *> AllChosenPairs;
00715     DenseSet<ValuePair> AllFixedOrderPairs;
00716     DenseMap<VPPair, unsigned> AllPairConnectionTypes;
00717     DenseMap<ValuePair, std::vector<ValuePair> > AllConnectedPairs,
00718                                                  AllConnectedPairDeps;
00719 
00720     do {
00721       std::vector<Value *> PairableInsts;
00722       DenseMap<Value *, std::vector<Value *> > CandidatePairs;
00723       DenseSet<ValuePair> FixedOrderPairs;
00724       DenseMap<ValuePair, int> CandidatePairCostSavings;
00725       ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
00726                                          FixedOrderPairs,
00727                                          CandidatePairCostSavings,
00728                                          PairableInsts, NonPow2Len);
00729       if (PairableInsts.empty()) continue;
00730 
00731       // Build the candidate pair set for faster lookups.
00732       DenseSet<ValuePair> CandidatePairsSet;
00733       for (DenseMap<Value *, std::vector<Value *> >::iterator I =
00734            CandidatePairs.begin(), E = CandidatePairs.end(); I != E; ++I)
00735         for (std::vector<Value *>::iterator J = I->second.begin(),
00736              JE = I->second.end(); J != JE; ++J)
00737           CandidatePairsSet.insert(ValuePair(I->first, *J));
00738 
00739       // Now we have a map of all of the pairable instructions and we need to
00740       // select the best possible pairing. A good pairing is one such that the
00741       // users of the pair are also paired. This defines a (directed) forest
00742       // over the pairs such that two pairs are connected iff the second pair
00743       // uses the first.
00744 
00745       // Note that it only matters that both members of the second pair use some
00746       // element of the first pair (to allow for splatting).
00747 
00748       DenseMap<ValuePair, std::vector<ValuePair> > ConnectedPairs,
00749                                                    ConnectedPairDeps;
00750       DenseMap<VPPair, unsigned> PairConnectionTypes;
00751       computeConnectedPairs(CandidatePairs, CandidatePairsSet,
00752                             PairableInsts, ConnectedPairs, PairConnectionTypes);
00753       if (ConnectedPairs.empty()) continue;
00754 
00755       for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
00756            I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
00757            I != IE; ++I)
00758         for (std::vector<ValuePair>::iterator J = I->second.begin(),
00759              JE = I->second.end(); J != JE; ++J)
00760           ConnectedPairDeps[*J].push_back(I->first);
00761 
00762       // Build the pairable-instruction dependency map
00763       DenseSet<ValuePair> PairableInstUsers;
00764       buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
00765 
00766       // There is now a graph of the connected pairs. For each variable, pick
00767       // the pairing with the largest dag meeting the depth requirement on at
00768       // least one branch. Then select all pairings that are part of that dag
00769       // and remove them from the list of available pairings and pairable
00770       // variables.
00771 
00772       DenseMap<Value *, Value *> ChosenPairs;
00773       choosePairs(CandidatePairs, CandidatePairsSet,
00774         CandidatePairCostSavings,
00775         PairableInsts, FixedOrderPairs, PairConnectionTypes,
00776         ConnectedPairs, ConnectedPairDeps,
00777         PairableInstUsers, ChosenPairs);
00778 
00779       if (ChosenPairs.empty()) continue;
00780       AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
00781                               PairableInsts.end());
00782       AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
00783 
00784       // Only for the chosen pairs, propagate information on fixed-order pairs,
00785       // pair connections, and their types to the data structures used by the
00786       // pair fusion procedures.
00787       for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
00788            IE = ChosenPairs.end(); I != IE; ++I) {
00789         if (FixedOrderPairs.count(*I))
00790           AllFixedOrderPairs.insert(*I);
00791         else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
00792           AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
00793 
00794         for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
00795              J != IE; ++J) {
00796           DenseMap<VPPair, unsigned>::iterator K =
00797             PairConnectionTypes.find(VPPair(*I, *J));
00798           if (K != PairConnectionTypes.end()) {
00799             AllPairConnectionTypes.insert(*K);
00800           } else {
00801             K = PairConnectionTypes.find(VPPair(*J, *I));
00802             if (K != PairConnectionTypes.end())
00803               AllPairConnectionTypes.insert(*K);
00804           }
00805         }
00806       }
00807 
00808       for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
00809            I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
00810            I != IE; ++I)
00811         for (std::vector<ValuePair>::iterator J = I->second.begin(),
00812           JE = I->second.end(); J != JE; ++J)
00813           if (AllPairConnectionTypes.count(VPPair(I->first, *J))) {
00814             AllConnectedPairs[I->first].push_back(*J);
00815             AllConnectedPairDeps[*J].push_back(I->first);
00816           }
00817     } while (ShouldContinue);
00818 
00819     if (AllChosenPairs.empty()) return false;
00820     NumFusedOps += AllChosenPairs.size();
00821 
00822     // A set of pairs has now been selected. It is now necessary to replace the
00823     // paired instructions with vector instructions. For this procedure each
00824     // operand must be replaced with a vector operand. This vector is formed
00825     // by using build_vector on the old operands. The replaced values are then
00826     // replaced with a vector_extract on the result.  Subsequent optimization
00827     // passes should coalesce the build/extract combinations.
00828 
00829     fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
00830                     AllPairConnectionTypes,
00831                     AllConnectedPairs, AllConnectedPairDeps);
00832 
00833     // It is important to cleanup here so that future iterations of this
00834     // function have less work to do.
00835     (void) SimplifyInstructionsInBlock(&BB, DL, AA->getTargetLibraryInfo());
00836     return true;
00837   }
00838 
00839   // This function returns true if the provided instruction is capable of being
00840   // fused into a vector instruction. This determination is based only on the
00841   // type and other attributes of the instruction.
00842   bool BBVectorize::isInstVectorizable(Instruction *I,
00843                                          bool &IsSimpleLoadStore) {
00844     IsSimpleLoadStore = false;
00845 
00846     if (CallInst *C = dyn_cast<CallInst>(I)) {
00847       if (!isVectorizableIntrinsic(C))
00848         return false;
00849     } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
00850       // Vectorize simple loads if possbile:
00851       IsSimpleLoadStore = L->isSimple();
00852       if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
00853         return false;
00854     } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
00855       // Vectorize simple stores if possbile:
00856       IsSimpleLoadStore = S->isSimple();
00857       if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
00858         return false;
00859     } else if (CastInst *C = dyn_cast<CastInst>(I)) {
00860       // We can vectorize casts, but not casts of pointer types, etc.
00861       if (!Config.VectorizeCasts)
00862         return false;
00863 
00864       Type *SrcTy = C->getSrcTy();
00865       if (!SrcTy->isSingleValueType())
00866         return false;
00867 
00868       Type *DestTy = C->getDestTy();
00869       if (!DestTy->isSingleValueType())
00870         return false;
00871     } else if (isa<SelectInst>(I)) {
00872       if (!Config.VectorizeSelect)
00873         return false;
00874     } else if (isa<CmpInst>(I)) {
00875       if (!Config.VectorizeCmp)
00876         return false;
00877     } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
00878       if (!Config.VectorizeGEP)
00879         return false;
00880 
00881       // Currently, vector GEPs exist only with one index.
00882       if (G->getNumIndices() != 1)
00883         return false;
00884     } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
00885         isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
00886       return false;
00887     }
00888 
00889     // We can't vectorize memory operations without target data
00890     if (DL == 0 && IsSimpleLoadStore)
00891       return false;
00892 
00893     Type *T1, *T2;
00894     getInstructionTypes(I, T1, T2);
00895 
00896     // Not every type can be vectorized...
00897     if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
00898         !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
00899       return false;
00900 
00901     if (T1->getScalarSizeInBits() == 1) {
00902       if (!Config.VectorizeBools)
00903         return false;
00904     } else {
00905       if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
00906         return false;
00907     }
00908 
00909     if (T2->getScalarSizeInBits() == 1) {
00910       if (!Config.VectorizeBools)
00911         return false;
00912     } else {
00913       if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
00914         return false;
00915     }
00916 
00917     if (!Config.VectorizeFloats
00918         && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
00919       return false;
00920 
00921     // Don't vectorize target-specific types.
00922     if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
00923       return false;
00924     if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
00925       return false;
00926 
00927     if ((!Config.VectorizePointers || DL == 0) &&
00928         (T1->getScalarType()->isPointerTy() ||
00929          T2->getScalarType()->isPointerTy()))
00930       return false;
00931 
00932     if (!TTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
00933                  T2->getPrimitiveSizeInBits() >= Config.VectorBits))
00934       return false;
00935 
00936     return true;
00937   }
00938 
00939   // This function returns true if the two provided instructions are compatible
00940   // (meaning that they can be fused into a vector instruction). This assumes
00941   // that I has already been determined to be vectorizable and that J is not
00942   // in the use dag of I.
00943   bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
00944                        bool IsSimpleLoadStore, bool NonPow2Len,
00945                        int &CostSavings, int &FixedOrder) {
00946     DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
00947                      " <-> " << *J << "\n");
00948 
00949     CostSavings = 0;
00950     FixedOrder = 0;
00951 
00952     // Loads and stores can be merged if they have different alignments,
00953     // but are otherwise the same.
00954     if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
00955                       (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
00956       return false;
00957 
00958     Type *IT1, *IT2, *JT1, *JT2;
00959     getInstructionTypes(I, IT1, IT2);
00960     getInstructionTypes(J, JT1, JT2);
00961     unsigned MaxTypeBits = std::max(
00962       IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
00963       IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
00964     if (!TTI && MaxTypeBits > Config.VectorBits)
00965       return false;
00966 
00967     // FIXME: handle addsub-type operations!
00968 
00969     if (IsSimpleLoadStore) {
00970       Value *IPtr, *JPtr;
00971       unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
00972       int64_t OffsetInElmts = 0;
00973       if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
00974             IAddressSpace, JAddressSpace,
00975             OffsetInElmts) && abs64(OffsetInElmts) == 1) {
00976         FixedOrder = (int) OffsetInElmts;
00977         unsigned BottomAlignment = IAlignment;
00978         if (OffsetInElmts < 0) BottomAlignment = JAlignment;
00979 
00980         Type *aTypeI = isa<StoreInst>(I) ?
00981           cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
00982         Type *aTypeJ = isa<StoreInst>(J) ?
00983           cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
00984         Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
00985 
00986         if (Config.AlignedOnly) {
00987           // An aligned load or store is possible only if the instruction
00988           // with the lower offset has an alignment suitable for the
00989           // vector type.
00990 
00991           unsigned VecAlignment = DL->getPrefTypeAlignment(VType);
00992           if (BottomAlignment < VecAlignment)
00993             return false;
00994         }
00995 
00996         if (TTI) {
00997           unsigned ICost = TTI->getMemoryOpCost(I->getOpcode(), aTypeI,
00998                                                 IAlignment, IAddressSpace);
00999           unsigned JCost = TTI->getMemoryOpCost(J->getOpcode(), aTypeJ,
01000                                                 JAlignment, JAddressSpace);
01001           unsigned VCost = TTI->getMemoryOpCost(I->getOpcode(), VType,
01002                                                 BottomAlignment,
01003                                                 IAddressSpace);
01004 
01005           ICost += TTI->getAddressComputationCost(aTypeI);
01006           JCost += TTI->getAddressComputationCost(aTypeJ);
01007           VCost += TTI->getAddressComputationCost(VType);
01008 
01009           if (VCost > ICost + JCost)
01010             return false;
01011 
01012           // We don't want to fuse to a type that will be split, even
01013           // if the two input types will also be split and there is no other
01014           // associated cost.
01015           unsigned VParts = TTI->getNumberOfParts(VType);
01016           if (VParts > 1)
01017             return false;
01018           else if (!VParts && VCost == ICost + JCost)
01019             return false;
01020 
01021           CostSavings = ICost + JCost - VCost;
01022         }
01023       } else {
01024         return false;
01025       }
01026     } else if (TTI) {
01027       unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
01028       unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
01029       Type *VT1 = getVecTypeForPair(IT1, JT1),
01030            *VT2 = getVecTypeForPair(IT2, JT2);
01031       TargetTransformInfo::OperandValueKind Op1VK =
01032           TargetTransformInfo::OK_AnyValue;
01033       TargetTransformInfo::OperandValueKind Op2VK =
01034           TargetTransformInfo::OK_AnyValue;
01035 
01036       // On some targets (example X86) the cost of a vector shift may vary
01037       // depending on whether the second operand is a Uniform or
01038       // NonUniform Constant.
01039       switch (I->getOpcode()) {
01040       default : break;
01041       case Instruction::Shl:
01042       case Instruction::LShr:
01043       case Instruction::AShr:
01044 
01045         // If both I and J are scalar shifts by constant, then the
01046         // merged vector shift count would be either a constant splat value
01047         // or a non-uniform vector of constants.
01048         if (ConstantInt *CII = dyn_cast<ConstantInt>(I->getOperand(1))) {
01049           if (ConstantInt *CIJ = dyn_cast<ConstantInt>(J->getOperand(1)))
01050             Op2VK = CII == CIJ ? TargetTransformInfo::OK_UniformConstantValue :
01051                                TargetTransformInfo::OK_NonUniformConstantValue;
01052         } else {
01053           // Check for a splat of a constant or for a non uniform vector
01054           // of constants.
01055           Value *IOp = I->getOperand(1);
01056           Value *JOp = J->getOperand(1);
01057           if ((isa<ConstantVector>(IOp) || isa<ConstantDataVector>(IOp)) &&
01058               (isa<ConstantVector>(JOp) || isa<ConstantDataVector>(JOp))) {
01059             Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
01060             Constant *SplatValue = cast<Constant>(IOp)->getSplatValue();
01061             if (SplatValue != NULL &&
01062                 SplatValue == cast<Constant>(JOp)->getSplatValue())
01063               Op2VK = TargetTransformInfo::OK_UniformConstantValue;
01064           }
01065         }
01066       }
01067 
01068       // Note that this procedure is incorrect for insert and extract element
01069       // instructions (because combining these often results in a shuffle),
01070       // but this cost is ignored (because insert and extract element
01071       // instructions are assigned a zero depth factor and are not really
01072       // fused in general).
01073       unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2, Op1VK, Op2VK);
01074 
01075       if (VCost > ICost + JCost)
01076         return false;
01077 
01078       // We don't want to fuse to a type that will be split, even
01079       // if the two input types will also be split and there is no other
01080       // associated cost.
01081       unsigned VParts1 = TTI->getNumberOfParts(VT1),
01082                VParts2 = TTI->getNumberOfParts(VT2);
01083       if (VParts1 > 1 || VParts2 > 1)
01084         return false;
01085       else if ((!VParts1 || !VParts2) && VCost == ICost + JCost)
01086         return false;
01087 
01088       CostSavings = ICost + JCost - VCost;
01089     }
01090 
01091     // The powi intrinsic is special because only the first argument is
01092     // vectorized, the second arguments must be equal.
01093     CallInst *CI = dyn_cast<CallInst>(I);
01094     Function *FI;
01095     if (CI && (FI = CI->getCalledFunction())) {
01096       Intrinsic::ID IID = (Intrinsic::ID) FI->getIntrinsicID();
01097       if (IID == Intrinsic::powi) {
01098         Value *A1I = CI->getArgOperand(1),
01099               *A1J = cast<CallInst>(J)->getArgOperand(1);
01100         const SCEV *A1ISCEV = SE->getSCEV(A1I),
01101                    *A1JSCEV = SE->getSCEV(A1J);
01102         return (A1ISCEV == A1JSCEV);
01103       }
01104 
01105       if (IID && TTI) {
01106         SmallVector<Type*, 4> Tys;
01107         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
01108           Tys.push_back(CI->getArgOperand(i)->getType());
01109         unsigned ICost = TTI->getIntrinsicInstrCost(IID, IT1, Tys);
01110 
01111         Tys.clear();
01112         CallInst *CJ = cast<CallInst>(J);
01113         for (unsigned i = 0, ie = CJ->getNumArgOperands(); i != ie; ++i)
01114           Tys.push_back(CJ->getArgOperand(i)->getType());
01115         unsigned JCost = TTI->getIntrinsicInstrCost(IID, JT1, Tys);
01116 
01117         Tys.clear();
01118         assert(CI->getNumArgOperands() == CJ->getNumArgOperands() &&
01119                "Intrinsic argument counts differ");
01120         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
01121           if (IID == Intrinsic::powi && i == 1)
01122             Tys.push_back(CI->getArgOperand(i)->getType());
01123           else
01124             Tys.push_back(getVecTypeForPair(CI->getArgOperand(i)->getType(),
01125                                             CJ->getArgOperand(i)->getType()));
01126         }
01127 
01128         Type *RetTy = getVecTypeForPair(IT1, JT1);
01129         unsigned VCost = TTI->getIntrinsicInstrCost(IID, RetTy, Tys);
01130 
01131         if (VCost > ICost + JCost)
01132           return false;
01133 
01134         // We don't want to fuse to a type that will be split, even
01135         // if the two input types will also be split and there is no other
01136         // associated cost.
01137         unsigned RetParts = TTI->getNumberOfParts(RetTy);
01138         if (RetParts > 1)
01139           return false;
01140         else if (!RetParts && VCost == ICost + JCost)
01141           return false;
01142 
01143         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
01144           if (!Tys[i]->isVectorTy())
01145             continue;
01146 
01147           unsigned NumParts = TTI->getNumberOfParts(Tys[i]);
01148           if (NumParts > 1)
01149             return false;
01150           else if (!NumParts && VCost == ICost + JCost)
01151             return false;
01152         }
01153 
01154         CostSavings = ICost + JCost - VCost;
01155       }
01156     }
01157 
01158     return true;
01159   }
01160 
01161   // Figure out whether or not J uses I and update the users and write-set
01162   // structures associated with I. Specifically, Users represents the set of
01163   // instructions that depend on I. WriteSet represents the set
01164   // of memory locations that are dependent on I. If UpdateUsers is true,
01165   // and J uses I, then Users is updated to contain J and WriteSet is updated
01166   // to contain any memory locations to which J writes. The function returns
01167   // true if J uses I. By default, alias analysis is used to determine
01168   // whether J reads from memory that overlaps with a location in WriteSet.
01169   // If LoadMoveSet is not null, then it is a previously-computed map
01170   // where the key is the memory-based user instruction and the value is
01171   // the instruction to be compared with I. So, if LoadMoveSet is provided,
01172   // then the alias analysis is not used. This is necessary because this
01173   // function is called during the process of moving instructions during
01174   // vectorization and the results of the alias analysis are not stable during
01175   // that process.
01176   bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
01177                        AliasSetTracker &WriteSet, Instruction *I,
01178                        Instruction *J, bool UpdateUsers,
01179                        DenseSet<ValuePair> *LoadMoveSetPairs) {
01180     bool UsesI = false;
01181 
01182     // This instruction may already be marked as a user due, for example, to
01183     // being a member of a selected pair.
01184     if (Users.count(J))
01185       UsesI = true;
01186 
01187     if (!UsesI)
01188       for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
01189            JU != JE; ++JU) {
01190         Value *V = *JU;
01191         if (I == V || Users.count(V)) {
01192           UsesI = true;
01193           break;
01194         }
01195       }
01196     if (!UsesI && J->mayReadFromMemory()) {
01197       if (LoadMoveSetPairs) {
01198         UsesI = LoadMoveSetPairs->count(ValuePair(J, I));
01199       } else {
01200         for (AliasSetTracker::iterator W = WriteSet.begin(),
01201              WE = WriteSet.end(); W != WE; ++W) {
01202           if (W->aliasesUnknownInst(J, *AA)) {
01203             UsesI = true;
01204             break;
01205           }
01206         }
01207       }
01208     }
01209 
01210     if (UsesI && UpdateUsers) {
01211       if (J->mayWriteToMemory()) WriteSet.add(J);
01212       Users.insert(J);
01213     }
01214 
01215     return UsesI;
01216   }
01217 
01218   // This function iterates over all instruction pairs in the provided
01219   // basic block and collects all candidate pairs for vectorization.
01220   bool BBVectorize::getCandidatePairs(BasicBlock &BB,
01221                        BasicBlock::iterator &Start,
01222                        DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01223                        DenseSet<ValuePair> &FixedOrderPairs,
01224                        DenseMap<ValuePair, int> &CandidatePairCostSavings,
01225                        std::vector<Value *> &PairableInsts, bool NonPow2Len) {
01226     size_t TotalPairs = 0;
01227     BasicBlock::iterator E = BB.end();
01228     if (Start == E) return false;
01229 
01230     bool ShouldContinue = false, IAfterStart = false;
01231     for (BasicBlock::iterator I = Start++; I != E; ++I) {
01232       if (I == Start) IAfterStart = true;
01233 
01234       bool IsSimpleLoadStore;
01235       if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
01236 
01237       // Look for an instruction with which to pair instruction *I...
01238       DenseSet<Value *> Users;
01239       AliasSetTracker WriteSet(*AA);
01240       if (I->mayWriteToMemory()) WriteSet.add(I);
01241 
01242       bool JAfterStart = IAfterStart;
01243       BasicBlock::iterator J = std::next(I);
01244       for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
01245         if (J == Start) JAfterStart = true;
01246 
01247         // Determine if J uses I, if so, exit the loop.
01248         bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
01249         if (Config.FastDep) {
01250           // Note: For this heuristic to be effective, independent operations
01251           // must tend to be intermixed. This is likely to be true from some
01252           // kinds of grouped loop unrolling (but not the generic LLVM pass),
01253           // but otherwise may require some kind of reordering pass.
01254 
01255           // When using fast dependency analysis,
01256           // stop searching after first use:
01257           if (UsesI) break;
01258         } else {
01259           if (UsesI) continue;
01260         }
01261 
01262         // J does not use I, and comes before the first use of I, so it can be
01263         // merged with I if the instructions are compatible.
01264         int CostSavings, FixedOrder;
01265         if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
01266             CostSavings, FixedOrder)) continue;
01267 
01268         // J is a candidate for merging with I.
01269         if (!PairableInsts.size() ||
01270              PairableInsts[PairableInsts.size()-1] != I) {
01271           PairableInsts.push_back(I);
01272         }
01273 
01274         CandidatePairs[I].push_back(J);
01275         ++TotalPairs;
01276         if (TTI)
01277           CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
01278                                                             CostSavings));
01279 
01280         if (FixedOrder == 1)
01281           FixedOrderPairs.insert(ValuePair(I, J));
01282         else if (FixedOrder == -1)
01283           FixedOrderPairs.insert(ValuePair(J, I));
01284 
01285         // The next call to this function must start after the last instruction
01286         // selected during this invocation.
01287         if (JAfterStart) {
01288           Start = std::next(J);
01289           IAfterStart = JAfterStart = false;
01290         }
01291 
01292         DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
01293                      << *I << " <-> " << *J << " (cost savings: " <<
01294                      CostSavings << ")\n");
01295 
01296         // If we have already found too many pairs, break here and this function
01297         // will be called again starting after the last instruction selected
01298         // during this invocation.
01299         if (PairableInsts.size() >= Config.MaxInsts ||
01300             TotalPairs >= Config.MaxPairs) {
01301           ShouldContinue = true;
01302           break;
01303         }
01304       }
01305 
01306       if (ShouldContinue)
01307         break;
01308     }
01309 
01310     DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
01311            << " instructions with candidate pairs\n");
01312 
01313     return ShouldContinue;
01314   }
01315 
01316   // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
01317   // it looks for pairs such that both members have an input which is an
01318   // output of PI or PJ.
01319   void BBVectorize::computePairsConnectedTo(
01320                   DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01321                   DenseSet<ValuePair> &CandidatePairsSet,
01322                   std::vector<Value *> &PairableInsts,
01323                   DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
01324                   DenseMap<VPPair, unsigned> &PairConnectionTypes,
01325                   ValuePair P) {
01326     StoreInst *SI, *SJ;
01327 
01328     // For each possible pairing for this variable, look at the uses of
01329     // the first value...
01330     for (Value::user_iterator I = P.first->user_begin(),
01331                               E = P.first->user_end();
01332          I != E; ++I) {
01333       User *UI = *I;
01334       if (isa<LoadInst>(UI)) {
01335         // A pair cannot be connected to a load because the load only takes one
01336         // operand (the address) and it is a scalar even after vectorization.
01337         continue;
01338       } else if ((SI = dyn_cast<StoreInst>(UI)) &&
01339                  P.first == SI->getPointerOperand()) {
01340         // Similarly, a pair cannot be connected to a store through its
01341         // pointer operand.
01342         continue;
01343       }
01344 
01345       // For each use of the first variable, look for uses of the second
01346       // variable...
01347       for (User *UJ : P.second->users()) {
01348         if ((SJ = dyn_cast<StoreInst>(UJ)) &&
01349             P.second == SJ->getPointerOperand())
01350           continue;
01351 
01352         // Look for <I, J>:
01353         if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
01354           VPPair VP(P, ValuePair(UI, UJ));
01355           ConnectedPairs[VP.first].push_back(VP.second);
01356           PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
01357         }
01358 
01359         // Look for <J, I>:
01360         if (CandidatePairsSet.count(ValuePair(UJ, UI))) {
01361           VPPair VP(P, ValuePair(UJ, UI));
01362           ConnectedPairs[VP.first].push_back(VP.second);
01363           PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
01364         }
01365       }
01366 
01367       if (Config.SplatBreaksChain) continue;
01368       // Look for cases where just the first value in the pair is used by
01369       // both members of another pair (splatting).
01370       for (Value::user_iterator J = P.first->user_begin(); J != E; ++J) {
01371         User *UJ = *J;
01372         if ((SJ = dyn_cast<StoreInst>(UJ)) &&
01373             P.first == SJ->getPointerOperand())
01374           continue;
01375 
01376         if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
01377           VPPair VP(P, ValuePair(UI, UJ));
01378           ConnectedPairs[VP.first].push_back(VP.second);
01379           PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
01380         }
01381       }
01382     }
01383 
01384     if (Config.SplatBreaksChain) return;
01385     // Look for cases where just the second value in the pair is used by
01386     // both members of another pair (splatting).
01387     for (Value::user_iterator I = P.second->user_begin(),
01388                               E = P.second->user_end();
01389          I != E; ++I) {
01390       User *UI = *I;
01391       if (isa<LoadInst>(UI))
01392         continue;
01393       else if ((SI = dyn_cast<StoreInst>(UI)) &&
01394                P.second == SI->getPointerOperand())
01395         continue;
01396 
01397       for (Value::user_iterator J = P.second->user_begin(); J != E; ++J) {
01398         User *UJ = *J;
01399         if ((SJ = dyn_cast<StoreInst>(UJ)) &&
01400             P.second == SJ->getPointerOperand())
01401           continue;
01402 
01403         if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
01404           VPPair VP(P, ValuePair(UI, UJ));
01405           ConnectedPairs[VP.first].push_back(VP.second);
01406           PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
01407         }
01408       }
01409     }
01410   }
01411 
01412   // This function figures out which pairs are connected.  Two pairs are
01413   // connected if some output of the first pair forms an input to both members
01414   // of the second pair.
01415   void BBVectorize::computeConnectedPairs(
01416                   DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01417                   DenseSet<ValuePair> &CandidatePairsSet,
01418                   std::vector<Value *> &PairableInsts,
01419                   DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
01420                   DenseMap<VPPair, unsigned> &PairConnectionTypes) {
01421     for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
01422          PE = PairableInsts.end(); PI != PE; ++PI) {
01423       DenseMap<Value *, std::vector<Value *> >::iterator PP =
01424         CandidatePairs.find(*PI);
01425       if (PP == CandidatePairs.end())
01426         continue;
01427 
01428       for (std::vector<Value *>::iterator P = PP->second.begin(),
01429            E = PP->second.end(); P != E; ++P)
01430         computePairsConnectedTo(CandidatePairs, CandidatePairsSet,
01431                                 PairableInsts, ConnectedPairs,
01432                                 PairConnectionTypes, ValuePair(*PI, *P));
01433     }
01434 
01435     DEBUG(size_t TotalPairs = 0;
01436           for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator I =
01437                ConnectedPairs.begin(), IE = ConnectedPairs.end(); I != IE; ++I)
01438             TotalPairs += I->second.size();
01439           dbgs() << "BBV: found " << TotalPairs
01440                  << " pair connections.\n");
01441   }
01442 
01443   // This function builds a set of use tuples such that <A, B> is in the set
01444   // if B is in the use dag of A. If B is in the use dag of A, then B
01445   // depends on the output of A.
01446   void BBVectorize::buildDepMap(
01447                       BasicBlock &BB,
01448                       DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01449                       std::vector<Value *> &PairableInsts,
01450                       DenseSet<ValuePair> &PairableInstUsers) {
01451     DenseSet<Value *> IsInPair;
01452     for (DenseMap<Value *, std::vector<Value *> >::iterator C =
01453          CandidatePairs.begin(), E = CandidatePairs.end(); C != E; ++C) {
01454       IsInPair.insert(C->first);
01455       IsInPair.insert(C->second.begin(), C->second.end());
01456     }
01457 
01458     // Iterate through the basic block, recording all users of each
01459     // pairable instruction.
01460 
01461     BasicBlock::iterator E = BB.end(), EL =
01462       BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
01463     for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
01464       if (IsInPair.find(I) == IsInPair.end()) continue;
01465 
01466       DenseSet<Value *> Users;
01467       AliasSetTracker WriteSet(*AA);
01468       if (I->mayWriteToMemory()) WriteSet.add(I);
01469 
01470       for (BasicBlock::iterator J = std::next(I); J != E; ++J) {
01471         (void) trackUsesOfI(Users, WriteSet, I, J);
01472 
01473         if (J == EL)
01474           break;
01475       }
01476 
01477       for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
01478            U != E; ++U) {
01479         if (IsInPair.find(*U) == IsInPair.end()) continue;
01480         PairableInstUsers.insert(ValuePair(I, *U));
01481       }
01482 
01483       if (I == EL)
01484         break;
01485     }
01486   }
01487 
01488   // Returns true if an input to pair P is an output of pair Q and also an
01489   // input of pair Q is an output of pair P. If this is the case, then these
01490   // two pairs cannot be simultaneously fused.
01491   bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
01492              DenseSet<ValuePair> &PairableInstUsers,
01493              DenseMap<ValuePair, std::vector<ValuePair> > *PairableInstUserMap,
01494              DenseSet<VPPair> *PairableInstUserPairSet) {
01495     // Two pairs are in conflict if they are mutual Users of eachother.
01496     bool QUsesP = PairableInstUsers.count(ValuePair(P.first,  Q.first))  ||
01497                   PairableInstUsers.count(ValuePair(P.first,  Q.second)) ||
01498                   PairableInstUsers.count(ValuePair(P.second, Q.first))  ||
01499                   PairableInstUsers.count(ValuePair(P.second, Q.second));
01500     bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first,  P.first))  ||
01501                   PairableInstUsers.count(ValuePair(Q.first,  P.second)) ||
01502                   PairableInstUsers.count(ValuePair(Q.second, P.first))  ||
01503                   PairableInstUsers.count(ValuePair(Q.second, P.second));
01504     if (PairableInstUserMap) {
01505       // FIXME: The expensive part of the cycle check is not so much the cycle
01506       // check itself but this edge insertion procedure. This needs some
01507       // profiling and probably a different data structure.
01508       if (PUsesQ) {
01509         if (PairableInstUserPairSet->insert(VPPair(Q, P)).second)
01510           (*PairableInstUserMap)[Q].push_back(P);
01511       }
01512       if (QUsesP) {
01513         if (PairableInstUserPairSet->insert(VPPair(P, Q)).second)
01514           (*PairableInstUserMap)[P].push_back(Q);
01515       }
01516     }
01517 
01518     return (QUsesP && PUsesQ);
01519   }
01520 
01521   // This function walks the use graph of current pairs to see if, starting
01522   // from P, the walk returns to P.
01523   bool BBVectorize::pairWillFormCycle(ValuePair P,
01524              DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
01525              DenseSet<ValuePair> &CurrentPairs) {
01526     DEBUG(if (DebugCycleCheck)
01527             dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
01528                    << *P.second << "\n");
01529     // A lookup table of visisted pairs is kept because the PairableInstUserMap
01530     // contains non-direct associations.
01531     DenseSet<ValuePair> Visited;
01532     SmallVector<ValuePair, 32> Q;
01533     // General depth-first post-order traversal:
01534     Q.push_back(P);
01535     do {
01536       ValuePair QTop = Q.pop_back_val();
01537       Visited.insert(QTop);
01538 
01539       DEBUG(if (DebugCycleCheck)
01540               dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
01541                      << *QTop.second << "\n");
01542       DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
01543         PairableInstUserMap.find(QTop);
01544       if (QQ == PairableInstUserMap.end())
01545         continue;
01546 
01547       for (std::vector<ValuePair>::iterator C = QQ->second.begin(),
01548            CE = QQ->second.end(); C != CE; ++C) {
01549         if (*C == P) {
01550           DEBUG(dbgs()
01551                  << "BBV: rejected to prevent non-trivial cycle formation: "
01552                  << QTop.first << " <-> " << C->second << "\n");
01553           return true;
01554         }
01555 
01556         if (CurrentPairs.count(*C) && !Visited.count(*C))
01557           Q.push_back(*C);
01558       }
01559     } while (!Q.empty());
01560 
01561     return false;
01562   }
01563 
01564   // This function builds the initial dag of connected pairs with the
01565   // pair J at the root.
01566   void BBVectorize::buildInitialDAGFor(
01567                   DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01568                   DenseSet<ValuePair> &CandidatePairsSet,
01569                   std::vector<Value *> &PairableInsts,
01570                   DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
01571                   DenseSet<ValuePair> &PairableInstUsers,
01572                   DenseMap<Value *, Value *> &ChosenPairs,
01573                   DenseMap<ValuePair, size_t> &DAG, ValuePair J) {
01574     // Each of these pairs is viewed as the root node of a DAG. The DAG
01575     // is then walked (depth-first). As this happens, we keep track of
01576     // the pairs that compose the DAG and the maximum depth of the DAG.
01577     SmallVector<ValuePairWithDepth, 32> Q;
01578     // General depth-first post-order traversal:
01579     Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
01580     do {
01581       ValuePairWithDepth QTop = Q.back();
01582 
01583       // Push each child onto the queue:
01584       bool MoreChildren = false;
01585       size_t MaxChildDepth = QTop.second;
01586       DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
01587         ConnectedPairs.find(QTop.first);
01588       if (QQ != ConnectedPairs.end())
01589         for (std::vector<ValuePair>::iterator k = QQ->second.begin(),
01590              ke = QQ->second.end(); k != ke; ++k) {
01591           // Make sure that this child pair is still a candidate:
01592           if (CandidatePairsSet.count(*k)) {
01593             DenseMap<ValuePair, size_t>::iterator C = DAG.find(*k);
01594             if (C == DAG.end()) {
01595               size_t d = getDepthFactor(k->first);
01596               Q.push_back(ValuePairWithDepth(*k, QTop.second+d));
01597               MoreChildren = true;
01598             } else {
01599               MaxChildDepth = std::max(MaxChildDepth, C->second);
01600             }
01601           }
01602         }
01603 
01604       if (!MoreChildren) {
01605         // Record the current pair as part of the DAG:
01606         DAG.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
01607         Q.pop_back();
01608       }
01609     } while (!Q.empty());
01610   }
01611 
01612   // Given some initial dag, prune it by removing conflicting pairs (pairs
01613   // that cannot be simultaneously chosen for vectorization).
01614   void BBVectorize::pruneDAGFor(
01615               DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01616               std::vector<Value *> &PairableInsts,
01617               DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
01618               DenseSet<ValuePair> &PairableInstUsers,
01619               DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
01620               DenseSet<VPPair> &PairableInstUserPairSet,
01621               DenseMap<Value *, Value *> &ChosenPairs,
01622               DenseMap<ValuePair, size_t> &DAG,
01623               DenseSet<ValuePair> &PrunedDAG, ValuePair J,
01624               bool UseCycleCheck) {
01625     SmallVector<ValuePairWithDepth, 32> Q;
01626     // General depth-first post-order traversal:
01627     Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
01628     do {
01629       ValuePairWithDepth QTop = Q.pop_back_val();
01630       PrunedDAG.insert(QTop.first);
01631 
01632       // Visit each child, pruning as necessary...
01633       SmallVector<ValuePairWithDepth, 8> BestChildren;
01634       DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
01635         ConnectedPairs.find(QTop.first);
01636       if (QQ == ConnectedPairs.end())
01637         continue;
01638 
01639       for (std::vector<ValuePair>::iterator K = QQ->second.begin(),
01640            KE = QQ->second.end(); K != KE; ++K) {
01641         DenseMap<ValuePair, size_t>::iterator C = DAG.find(*K);
01642         if (C == DAG.end()) continue;
01643 
01644         // This child is in the DAG, now we need to make sure it is the
01645         // best of any conflicting children. There could be multiple
01646         // conflicting children, so first, determine if we're keeping
01647         // this child, then delete conflicting children as necessary.
01648 
01649         // It is also necessary to guard against pairing-induced
01650         // dependencies. Consider instructions a .. x .. y .. b
01651         // such that (a,b) are to be fused and (x,y) are to be fused
01652         // but a is an input to x and b is an output from y. This
01653         // means that y cannot be moved after b but x must be moved
01654         // after b for (a,b) to be fused. In other words, after
01655         // fusing (a,b) we have y .. a/b .. x where y is an input
01656         // to a/b and x is an output to a/b: x and y can no longer
01657         // be legally fused. To prevent this condition, we must
01658         // make sure that a child pair added to the DAG is not
01659         // both an input and output of an already-selected pair.
01660 
01661         // Pairing-induced dependencies can also form from more complicated
01662         // cycles. The pair vs. pair conflicts are easy to check, and so
01663         // that is done explicitly for "fast rejection", and because for
01664         // child vs. child conflicts, we may prefer to keep the current
01665         // pair in preference to the already-selected child.
01666         DenseSet<ValuePair> CurrentPairs;
01667 
01668         bool CanAdd = true;
01669         for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
01670               = BestChildren.begin(), E2 = BestChildren.end();
01671              C2 != E2; ++C2) {
01672           if (C2->first.first == C->first.first ||
01673               C2->first.first == C->first.second ||
01674               C2->first.second == C->first.first ||
01675               C2->first.second == C->first.second ||
01676               pairsConflict(C2->first, C->first, PairableInstUsers,
01677                             UseCycleCheck ? &PairableInstUserMap : 0,
01678                             UseCycleCheck ? &PairableInstUserPairSet : 0)) {
01679             if (C2->second >= C->second) {
01680               CanAdd = false;
01681               break;
01682             }
01683 
01684             CurrentPairs.insert(C2->first);
01685           }
01686         }
01687         if (!CanAdd) continue;
01688 
01689         // Even worse, this child could conflict with another node already
01690         // selected for the DAG. If that is the case, ignore this child.
01691         for (DenseSet<ValuePair>::iterator T = PrunedDAG.begin(),
01692              E2 = PrunedDAG.end(); T != E2; ++T) {
01693           if (T->first == C->first.first ||
01694               T->first == C->first.second ||
01695               T->second == C->first.first ||
01696               T->second == C->first.second ||
01697               pairsConflict(*T, C->first, PairableInstUsers,
01698                             UseCycleCheck ? &PairableInstUserMap : 0,
01699                             UseCycleCheck ? &PairableInstUserPairSet : 0)) {
01700             CanAdd = false;
01701             break;
01702           }
01703 
01704           CurrentPairs.insert(*T);
01705         }
01706         if (!CanAdd) continue;
01707 
01708         // And check the queue too...
01709         for (SmallVectorImpl<ValuePairWithDepth>::iterator C2 = Q.begin(),
01710              E2 = Q.end(); C2 != E2; ++C2) {
01711           if (C2->first.first == C->first.first ||
01712               C2->first.first == C->first.second ||
01713               C2->first.second == C->first.first ||
01714               C2->first.second == C->first.second ||
01715               pairsConflict(C2->first, C->first, PairableInstUsers,
01716                             UseCycleCheck ? &PairableInstUserMap : 0,
01717                             UseCycleCheck ? &PairableInstUserPairSet : 0)) {
01718             CanAdd = false;
01719             break;
01720           }
01721 
01722           CurrentPairs.insert(C2->first);
01723         }
01724         if (!CanAdd) continue;
01725 
01726         // Last but not least, check for a conflict with any of the
01727         // already-chosen pairs.
01728         for (DenseMap<Value *, Value *>::iterator C2 =
01729               ChosenPairs.begin(), E2 = ChosenPairs.end();
01730              C2 != E2; ++C2) {
01731           if (pairsConflict(*C2, C->first, PairableInstUsers,
01732                             UseCycleCheck ? &PairableInstUserMap : 0,
01733                             UseCycleCheck ? &PairableInstUserPairSet : 0)) {
01734             CanAdd = false;
01735             break;
01736           }
01737 
01738           CurrentPairs.insert(*C2);
01739         }
01740         if (!CanAdd) continue;
01741 
01742         // To check for non-trivial cycles formed by the addition of the
01743         // current pair we've formed a list of all relevant pairs, now use a
01744         // graph walk to check for a cycle. We start from the current pair and
01745         // walk the use dag to see if we again reach the current pair. If we
01746         // do, then the current pair is rejected.
01747 
01748         // FIXME: It may be more efficient to use a topological-ordering
01749         // algorithm to improve the cycle check. This should be investigated.
01750         if (UseCycleCheck &&
01751             pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
01752           continue;
01753 
01754         // This child can be added, but we may have chosen it in preference
01755         // to an already-selected child. Check for this here, and if a
01756         // conflict is found, then remove the previously-selected child
01757         // before adding this one in its place.
01758         for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
01759               = BestChildren.begin(); C2 != BestChildren.end();) {
01760           if (C2->first.first == C->first.first ||
01761               C2->first.first == C->first.second ||
01762               C2->first.second == C->first.first ||
01763               C2->first.second == C->first.second ||
01764               pairsConflict(C2->first, C->first, PairableInstUsers))
01765             C2 = BestChildren.erase(C2);
01766           else
01767             ++C2;
01768         }
01769 
01770         BestChildren.push_back(ValuePairWithDepth(C->first, C->second));
01771       }
01772 
01773       for (SmallVectorImpl<ValuePairWithDepth>::iterator C
01774             = BestChildren.begin(), E2 = BestChildren.end();
01775            C != E2; ++C) {
01776         size_t DepthF = getDepthFactor(C->first.first);
01777         Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
01778       }
01779     } while (!Q.empty());
01780   }
01781 
01782   // This function finds the best dag of mututally-compatible connected
01783   // pairs, given the choice of root pairs as an iterator range.
01784   void BBVectorize::findBestDAGFor(
01785               DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
01786               DenseSet<ValuePair> &CandidatePairsSet,
01787               DenseMap<ValuePair, int> &CandidatePairCostSavings,
01788               std::vector<Value *> &PairableInsts,
01789               DenseSet<ValuePair> &FixedOrderPairs,
01790               DenseMap<VPPair, unsigned> &PairConnectionTypes,
01791               DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
01792               DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
01793               DenseSet<ValuePair> &PairableInstUsers,
01794               DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
01795               DenseSet<VPPair> &PairableInstUserPairSet,
01796               DenseMap<Value *, Value *> &ChosenPairs,
01797               DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
01798               int &BestEffSize, Value *II, std::vector<Value *>&JJ,
01799               bool UseCycleCheck) {
01800     for (std::vector<Value *>::iterator J = JJ.begin(), JE = JJ.end();
01801          J != JE; ++J) {
01802       ValuePair IJ(II, *J);
01803       if (!CandidatePairsSet.count(IJ))
01804         continue;
01805 
01806       // Before going any further, make sure that this pair does not
01807       // conflict with any already-selected pairs (see comment below
01808       // near the DAG pruning for more details).
01809       DenseSet<ValuePair> ChosenPairSet;
01810       bool DoesConflict = false;
01811       for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
01812            E = ChosenPairs.end(); C != E; ++C) {
01813         if (pairsConflict(*C, IJ, PairableInstUsers,
01814                           UseCycleCheck ? &PairableInstUserMap : 0,
01815                           UseCycleCheck ? &PairableInstUserPairSet : 0)) {
01816           DoesConflict = true;
01817           break;
01818         }
01819 
01820         ChosenPairSet.insert(*C);
01821       }
01822       if (DoesConflict) continue;
01823 
01824       if (UseCycleCheck &&
01825           pairWillFormCycle(IJ, PairableInstUserMap, ChosenPairSet))
01826         continue;
01827 
01828       DenseMap<ValuePair, size_t> DAG;
01829       buildInitialDAGFor(CandidatePairs, CandidatePairsSet,
01830                           PairableInsts, ConnectedPairs,
01831                           PairableInstUsers, ChosenPairs, DAG, IJ);
01832 
01833       // Because we'll keep the child with the largest depth, the largest
01834       // depth is still the same in the unpruned DAG.
01835       size_t MaxDepth = DAG.lookup(IJ);
01836 
01837       DEBUG(if (DebugPairSelection) dbgs() << "BBV: found DAG for pair {"
01838                    << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
01839                    MaxDepth << " and size " << DAG.size() << "\n");
01840 
01841       // At this point the DAG has been constructed, but, may contain
01842       // contradictory children (meaning that different children of
01843       // some dag node may be attempting to fuse the same instruction).
01844       // So now we walk the dag again, in the case of a conflict,
01845       // keep only the child with the largest depth. To break a tie,
01846       // favor the first child.
01847 
01848       DenseSet<ValuePair> PrunedDAG;
01849       pruneDAGFor(CandidatePairs, PairableInsts, ConnectedPairs,
01850                    PairableInstUsers, PairableInstUserMap,
01851                    PairableInstUserPairSet,
01852                    ChosenPairs, DAG, PrunedDAG, IJ, UseCycleCheck);
01853 
01854       int EffSize = 0;
01855       if (TTI) {
01856         DenseSet<Value *> PrunedDAGInstrs;
01857         for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
01858              E = PrunedDAG.end(); S != E; ++S) {
01859           PrunedDAGInstrs.insert(S->first);
01860           PrunedDAGInstrs.insert(S->second);
01861         }
01862 
01863         // The set of pairs that have already contributed to the total cost.
01864         DenseSet<ValuePair> IncomingPairs;
01865 
01866         // If the cost model were perfect, this might not be necessary; but we
01867         // need to make sure that we don't get stuck vectorizing our own
01868         // shuffle chains.
01869         bool HasNontrivialInsts = false;
01870 
01871         // The node weights represent the cost savings associated with
01872         // fusing the pair of instructions.
01873         for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
01874              E = PrunedDAG.end(); S != E; ++S) {
01875           if (!isa<ShuffleVectorInst>(S->first) &&
01876               !isa<InsertElementInst>(S->first) &&
01877               !isa<ExtractElementInst>(S->first))
01878             HasNontrivialInsts = true;
01879 
01880           bool FlipOrder = false;
01881 
01882           if (getDepthFactor(S->first)) {
01883             int ESContrib = CandidatePairCostSavings.find(*S)->second;
01884             DEBUG(if (DebugPairSelection) dbgs() << "\tweight {"
01885                    << *S->first << " <-> " << *S->second << "} = " <<
01886                    ESContrib << "\n");
01887             EffSize += ESContrib;
01888           }
01889 
01890           // The edge weights contribute in a negative sense: they represent
01891           // the cost of shuffles.
01892           DenseMap<ValuePair, std::vector<ValuePair> >::iterator SS =
01893             ConnectedPairDeps.find(*S);
01894           if (SS != ConnectedPairDeps.end()) {
01895             unsigned NumDepsDirect = 0, NumDepsSwap = 0;
01896             for (std::vector<ValuePair>::iterator T = SS->second.begin(),
01897                  TE = SS->second.end(); T != TE; ++T) {
01898               VPPair Q(*S, *T);
01899               if (!PrunedDAG.count(Q.second))
01900                 continue;
01901               DenseMap<VPPair, unsigned>::iterator R =
01902                 PairConnectionTypes.find(VPPair(Q.second, Q.first));
01903               assert(R != PairConnectionTypes.end() &&
01904                      "Cannot find pair connection type");
01905               if (R->second == PairConnectionDirect)
01906                 ++NumDepsDirect;
01907               else if (R->second == PairConnectionSwap)
01908                 ++NumDepsSwap;
01909             }
01910 
01911             // If there are more swaps than direct connections, then
01912             // the pair order will be flipped during fusion. So the real
01913             // number of swaps is the minimum number.
01914             FlipOrder = !FixedOrderPairs.count(*S) &&
01915               ((NumDepsSwap > NumDepsDirect) ||
01916                 FixedOrderPairs.count(ValuePair(S->second, S->first)));
01917 
01918             for (std::vector<ValuePair>::iterator T = SS->second.begin(),
01919                  TE = SS->second.end(); T != TE; ++T) {
01920               VPPair Q(*S, *T);
01921               if (!PrunedDAG.count(Q.second))
01922                 continue;
01923               DenseMap<VPPair, unsigned>::iterator R =
01924                 PairConnectionTypes.find(VPPair(Q.second, Q.first));
01925               assert(R != PairConnectionTypes.end() &&
01926                      "Cannot find pair connection type");
01927               Type *Ty1 = Q.second.first->getType(),
01928                    *Ty2 = Q.second.second->getType();
01929               Type *VTy = getVecTypeForPair(Ty1, Ty2);
01930               if ((R->second == PairConnectionDirect && FlipOrder) ||
01931                   (R->second == PairConnectionSwap && !FlipOrder)  ||
01932                   R->second == PairConnectionSplat) {
01933                 int ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
01934                                                    VTy, VTy);
01935 
01936                 if (VTy->getVectorNumElements() == 2) {
01937                   if (R->second == PairConnectionSplat)
01938                     ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
01939                       TargetTransformInfo::SK_Broadcast, VTy));
01940                   else
01941                     ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
01942                       TargetTransformInfo::SK_Reverse, VTy));
01943                 }
01944 
01945                 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
01946                   *Q.second.first << " <-> " << *Q.second.second <<
01947                     "} -> {" <<
01948                   *S->first << " <-> " << *S->second << "} = " <<
01949                    ESContrib << "\n");
01950                 EffSize -= ESContrib;
01951               }
01952             }
01953           }
01954 
01955           // Compute the cost of outgoing edges. We assume that edges outgoing
01956           // to shuffles, inserts or extracts can be merged, and so contribute
01957           // no additional cost.
01958           if (!S->first->getType()->isVoidTy()) {
01959             Type *Ty1 = S->first->getType(),
01960                  *Ty2 = S->second->getType();
01961             Type *VTy = getVecTypeForPair(Ty1, Ty2);
01962 
01963             bool NeedsExtraction = false;
01964             for (User *U : S->first->users()) {
01965               if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
01966                 // Shuffle can be folded if it has no other input
01967                 if (isa<UndefValue>(SI->getOperand(1)))
01968                   continue;
01969               }
01970               if (isa<ExtractElementInst>(U))
01971                 continue;
01972               if (PrunedDAGInstrs.count(U))
01973                 continue;
01974               NeedsExtraction = true;
01975               break;
01976             }
01977 
01978             if (NeedsExtraction) {
01979               int ESContrib;
01980               if (Ty1->isVectorTy()) {
01981                 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
01982                                                Ty1, VTy);
01983                 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
01984                   TargetTransformInfo::SK_ExtractSubvector, VTy, 0, Ty1));
01985               } else
01986                 ESContrib = (int) TTI->getVectorInstrCost(
01987                                     Instruction::ExtractElement, VTy, 0);
01988 
01989               DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
01990                 *S->first << "} = " << ESContrib << "\n");
01991               EffSize -= ESContrib;
01992             }
01993 
01994             NeedsExtraction = false;
01995             for (User *U : S->second->users()) {
01996               if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
01997                 // Shuffle can be folded if it has no other input
01998                 if (isa<UndefValue>(SI->getOperand(1)))
01999                   continue;
02000               }
02001               if (isa<ExtractElementInst>(U))
02002                 continue;
02003               if (PrunedDAGInstrs.count(U))
02004                 continue;
02005               NeedsExtraction = true;
02006               break;
02007             }
02008 
02009             if (NeedsExtraction) {
02010               int ESContrib;
02011               if (Ty2->isVectorTy()) {
02012                 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
02013                                                Ty2, VTy);
02014                 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
02015                   TargetTransformInfo::SK_ExtractSubvector, VTy,
02016                   Ty1->isVectorTy() ? Ty1->getVectorNumElements() : 1, Ty2));
02017               } else
02018                 ESContrib = (int) TTI->getVectorInstrCost(
02019                                     Instruction::ExtractElement, VTy, 1);
02020               DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
02021                 *S->second << "} = " << ESContrib << "\n");
02022               EffSize -= ESContrib;
02023             }
02024           }
02025 
02026           // Compute the cost of incoming edges.
02027           if (!isa<LoadInst>(S->first) && !isa<StoreInst>(S->first)) {
02028             Instruction *S1 = cast<Instruction>(S->first),
02029                         *S2 = cast<Instruction>(S->second);
02030             for (unsigned o = 0; o < S1->getNumOperands(); ++o) {
02031               Value *O1 = S1->getOperand(o), *O2 = S2->getOperand(o);
02032 
02033               // Combining constants into vector constants (or small vector
02034               // constants into larger ones are assumed free).
02035               if (isa<Constant>(O1) && isa<Constant>(O2))
02036                 continue;
02037 
02038               if (FlipOrder)
02039                 std::swap(O1, O2);
02040 
02041               ValuePair VP  = ValuePair(O1, O2);
02042               ValuePair VPR = ValuePair(O2, O1);
02043 
02044               // Internal edges are not handled here.
02045               if (PrunedDAG.count(VP) || PrunedDAG.count(VPR))
02046                 continue;
02047 
02048               Type *Ty1 = O1->getType(),
02049                    *Ty2 = O2->getType();
02050               Type *VTy = getVecTypeForPair(Ty1, Ty2);
02051 
02052               // Combining vector operations of the same type is also assumed
02053               // folded with other operations.
02054               if (Ty1 == Ty2) {
02055                 // If both are insert elements, then both can be widened.
02056                 InsertElementInst *IEO1 = dyn_cast<InsertElementInst>(O1),
02057                                   *IEO2 = dyn_cast<InsertElementInst>(O2);
02058                 if (IEO1 && IEO2 && isPureIEChain(IEO1) && isPureIEChain(IEO2))
02059                   continue;
02060                 // If both are extract elements, and both have the same input
02061                 // type, then they can be replaced with a shuffle
02062                 ExtractElementInst *EIO1 = dyn_cast<ExtractElementInst>(O1),
02063                                    *EIO2 = dyn_cast<ExtractElementInst>(O2);
02064                 if (EIO1 && EIO2 &&
02065                     EIO1->getOperand(0)->getType() ==
02066                       EIO2->getOperand(0)->getType())
02067                   continue;
02068                 // If both are a shuffle with equal operand types and only two
02069                 // unqiue operands, then they can be replaced with a single
02070                 // shuffle
02071                 ShuffleVectorInst *SIO1 = dyn_cast<ShuffleVectorInst>(O1),
02072                                   *SIO2 = dyn_cast<ShuffleVectorInst>(O2);
02073                 if (SIO1 && SIO2 &&
02074                     SIO1->getOperand(0)->getType() ==
02075                       SIO2->getOperand(0)->getType()) {
02076                   SmallSet<Value *, 4> SIOps;
02077                   SIOps.insert(SIO1->getOperand(0));
02078                   SIOps.insert(SIO1->getOperand(1));
02079                   SIOps.insert(SIO2->getOperand(0));
02080                   SIOps.insert(SIO2->getOperand(1));
02081                   if (SIOps.size() <= 2)
02082                     continue;
02083                 }
02084               }
02085 
02086               int ESContrib;
02087               // This pair has already been formed.
02088               if (IncomingPairs.count(VP)) {
02089                 continue;
02090               } else if (IncomingPairs.count(VPR)) {
02091                 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
02092                                                VTy, VTy);
02093 
02094                 if (VTy->getVectorNumElements() == 2)
02095                   ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
02096                     TargetTransformInfo::SK_Reverse, VTy));
02097               } else if (!Ty1->isVectorTy() && !Ty2->isVectorTy()) {
02098                 ESContrib = (int) TTI->getVectorInstrCost(
02099                                     Instruction::InsertElement, VTy, 0);
02100                 ESContrib += (int) TTI->getVectorInstrCost(
02101                                      Instruction::InsertElement, VTy, 1);
02102               } else if (!Ty1->isVectorTy()) {
02103                 // O1 needs to be inserted into a vector of size O2, and then
02104                 // both need to be shuffled together.
02105                 ESContrib = (int) TTI->getVectorInstrCost(
02106                                     Instruction::InsertElement, Ty2, 0);
02107                 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
02108                                                 VTy, Ty2);
02109               } else if (!Ty2->isVectorTy()) {
02110                 // O2 needs to be inserted into a vector of size O1, and then
02111                 // both need to be shuffled together.
02112                 ESContrib = (int) TTI->getVectorInstrCost(
02113                                     Instruction::InsertElement, Ty1, 0);
02114                 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
02115                                                 VTy, Ty1);
02116               } else {
02117                 Type *TyBig = Ty1, *TySmall = Ty2;
02118                 if (Ty2->getVectorNumElements() > Ty1->getVectorNumElements())
02119                   std::swap(TyBig, TySmall);
02120 
02121                 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
02122                                                VTy, TyBig);
02123                 if (TyBig != TySmall)
02124                   ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
02125                                                   TyBig, TySmall);
02126               }
02127 
02128               DEBUG(if (DebugPairSelection) dbgs() << "\tcost {"
02129                      << *O1 << " <-> " << *O2 << "} = " <<
02130                      ESContrib << "\n");
02131               EffSize -= ESContrib;
02132               IncomingPairs.insert(VP);
02133             }
02134           }
02135         }
02136 
02137         if (!HasNontrivialInsts) {
02138           DEBUG(if (DebugPairSelection) dbgs() <<
02139                 "\tNo non-trivial instructions in DAG;"
02140                 " override to zero effective size\n");
02141           EffSize = 0;
02142         }
02143       } else {
02144         for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
02145              E = PrunedDAG.end(); S != E; ++S)
02146           EffSize += (int) getDepthFactor(S->first);
02147       }
02148 
02149       DEBUG(if (DebugPairSelection)
02150              dbgs() << "BBV: found pruned DAG for pair {"
02151              << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
02152              MaxDepth << " and size " << PrunedDAG.size() <<
02153             " (effective size: " << EffSize << ")\n");
02154       if (((TTI && !UseChainDepthWithTI) ||
02155             MaxDepth >= Config.ReqChainDepth) &&
02156           EffSize > 0 && EffSize > BestEffSize) {
02157         BestMaxDepth = MaxDepth;
02158         BestEffSize = EffSize;
02159         BestDAG = PrunedDAG;
02160       }
02161     }
02162   }
02163 
02164   // Given the list of candidate pairs, this function selects those
02165   // that will be fused into vector instructions.
02166   void BBVectorize::choosePairs(
02167                 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
02168                 DenseSet<ValuePair> &CandidatePairsSet,
02169                 DenseMap<ValuePair, int> &CandidatePairCostSavings,
02170                 std::vector<Value *> &PairableInsts,
02171                 DenseSet<ValuePair> &FixedOrderPairs,
02172                 DenseMap<VPPair, unsigned> &PairConnectionTypes,
02173                 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
02174                 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
02175                 DenseSet<ValuePair> &PairableInstUsers,
02176                 DenseMap<Value *, Value *>& ChosenPairs) {
02177     bool UseCycleCheck =
02178      CandidatePairsSet.size() <= Config.MaxCandPairsForCycleCheck;
02179 
02180     DenseMap<Value *, std::vector<Value *> > CandidatePairs2;
02181     for (DenseSet<ValuePair>::iterator I = CandidatePairsSet.begin(),
02182          E = CandidatePairsSet.end(); I != E; ++I) {
02183       std::vector<Value *> &JJ = CandidatePairs2[I->second];
02184       if (JJ.empty()) JJ.reserve(32);
02185       JJ.push_back(I->first);
02186     }
02187 
02188     DenseMap<ValuePair, std::vector<ValuePair> > PairableInstUserMap;
02189     DenseSet<VPPair> PairableInstUserPairSet;
02190     for (std::vector<Value *>::iterator I = PairableInsts.begin(),
02191          E = PairableInsts.end(); I != E; ++I) {
02192       // The number of possible pairings for this variable:
02193       size_t NumChoices = CandidatePairs.lookup(*I).size();
02194       if (!NumChoices) continue;
02195 
02196       std::vector<Value *> &JJ = CandidatePairs[*I];
02197 
02198       // The best pair to choose and its dag:
02199       size_t BestMaxDepth = 0;
02200       int BestEffSize = 0;
02201       DenseSet<ValuePair> BestDAG;
02202       findBestDAGFor(CandidatePairs, CandidatePairsSet,
02203                       CandidatePairCostSavings,
02204                       PairableInsts, FixedOrderPairs, PairConnectionTypes,
02205                       ConnectedPairs, ConnectedPairDeps,
02206                       PairableInstUsers, PairableInstUserMap,
02207                       PairableInstUserPairSet, ChosenPairs,
02208                       BestDAG, BestMaxDepth, BestEffSize, *I, JJ,
02209                       UseCycleCheck);
02210 
02211       if (BestDAG.empty())
02212         continue;
02213 
02214       // A dag has been chosen (or not) at this point. If no dag was
02215       // chosen, then this instruction, I, cannot be paired (and is no longer
02216       // considered).
02217 
02218       DEBUG(dbgs() << "BBV: selected pairs in the best DAG for: "
02219                    << *cast<Instruction>(*I) << "\n");
02220 
02221       for (DenseSet<ValuePair>::iterator S = BestDAG.begin(),
02222            SE2 = BestDAG.end(); S != SE2; ++S) {
02223         // Insert the members of this dag into the list of chosen pairs.
02224         ChosenPairs.insert(ValuePair(S->first, S->second));
02225         DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
02226                *S->second << "\n");
02227 
02228         // Remove all candidate pairs that have values in the chosen dag.
02229         std::vector<Value *> &KK = CandidatePairs[S->first];
02230         for (std::vector<Value *>::iterator K = KK.begin(), KE = KK.end();
02231              K != KE; ++K) {
02232           if (*K == S->second)
02233             continue;
02234 
02235           CandidatePairsSet.erase(ValuePair(S->first, *K));
02236         }
02237 
02238         std::vector<Value *> &LL = CandidatePairs2[S->second];
02239         for (std::vector<Value *>::iterator L = LL.begin(), LE = LL.end();
02240              L != LE; ++L) {
02241           if (*L == S->first)
02242             continue;
02243 
02244           CandidatePairsSet.erase(ValuePair(*L, S->second));
02245         }
02246 
02247         std::vector<Value *> &MM = CandidatePairs[S->second];
02248         for (std::vector<Value *>::iterator M = MM.begin(), ME = MM.end();
02249              M != ME; ++M) {
02250           assert(*M != S->first && "Flipped pair in candidate list?");
02251           CandidatePairsSet.erase(ValuePair(S->second, *M));
02252         }
02253 
02254         std::vector<Value *> &NN = CandidatePairs2[S->first];
02255         for (std::vector<Value *>::iterator N = NN.begin(), NE = NN.end();
02256              N != NE; ++N) {
02257           assert(*N != S->second && "Flipped pair in candidate list?");
02258           CandidatePairsSet.erase(ValuePair(*N, S->first));
02259         }
02260       }
02261     }
02262 
02263     DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
02264   }
02265 
02266   std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
02267                      unsigned n = 0) {
02268     if (!I->hasName())
02269       return "";
02270 
02271     return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
02272              (n > 0 ? "." + utostr(n) : "")).str();
02273   }
02274 
02275   // Returns the value that is to be used as the pointer input to the vector
02276   // instruction that fuses I with J.
02277   Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
02278                      Instruction *I, Instruction *J, unsigned o) {
02279     Value *IPtr, *JPtr;
02280     unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
02281     int64_t OffsetInElmts;
02282 
02283     // Note: the analysis might fail here, that is why the pair order has
02284     // been precomputed (OffsetInElmts must be unused here).
02285     (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
02286                           IAddressSpace, JAddressSpace,
02287                           OffsetInElmts, false);
02288 
02289     // The pointer value is taken to be the one with the lowest offset.
02290     Value *VPtr = IPtr;
02291 
02292     Type *ArgTypeI = IPtr->getType()->getPointerElementType();
02293     Type *ArgTypeJ = JPtr->getType()->getPointerElementType();
02294     Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
02295     Type *VArgPtrType
02296       = PointerType::get(VArgType,
02297                          IPtr->getType()->getPointerAddressSpace());
02298     return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
02299                         /* insert before */ I);
02300   }
02301 
02302   void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
02303                      unsigned MaskOffset, unsigned NumInElem,
02304                      unsigned NumInElem1, unsigned IdxOffset,
02305                      std::vector<Constant*> &Mask) {
02306     unsigned NumElem1 = J->getType()->getVectorNumElements();
02307     for (unsigned v = 0; v < NumElem1; ++v) {
02308       int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
02309       if (m < 0) {
02310         Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
02311       } else {
02312         unsigned mm = m + (int) IdxOffset;
02313         if (m >= (int) NumInElem1)
02314           mm += (int) NumInElem;
02315 
02316         Mask[v+MaskOffset] =
02317           ConstantInt::get(Type::getInt32Ty(Context), mm);
02318       }
02319     }
02320   }
02321 
02322   // Returns the value that is to be used as the vector-shuffle mask to the
02323   // vector instruction that fuses I with J.
02324   Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
02325                      Instruction *I, Instruction *J) {
02326     // This is the shuffle mask. We need to append the second
02327     // mask to the first, and the numbers need to be adjusted.
02328 
02329     Type *ArgTypeI = I->getType();
02330     Type *ArgTypeJ = J->getType();
02331     Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
02332 
02333     unsigned NumElemI = ArgTypeI->getVectorNumElements();
02334 
02335     // Get the total number of elements in the fused vector type.
02336     // By definition, this must equal the number of elements in
02337     // the final mask.
02338     unsigned NumElem = VArgType->getVectorNumElements();
02339     std::vector<Constant*> Mask(NumElem);
02340 
02341     Type *OpTypeI = I->getOperand(0)->getType();
02342     unsigned NumInElemI = OpTypeI->getVectorNumElements();
02343     Type *OpTypeJ = J->getOperand(0)->getType();
02344     unsigned NumInElemJ = OpTypeJ->getVectorNumElements();
02345 
02346     // The fused vector will be:
02347     // -----------------------------------------------------
02348     // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
02349     // -----------------------------------------------------
02350     // from which we'll extract NumElem total elements (where the first NumElemI
02351     // of them come from the mask in I and the remainder come from the mask
02352     // in J.
02353 
02354     // For the mask from the first pair...
02355     fillNewShuffleMask(Context, I, 0,        NumInElemJ, NumInElemI,
02356                        0,          Mask);
02357 
02358     // For the mask from the second pair...
02359     fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
02360                        NumInElemI, Mask);
02361 
02362     return ConstantVector::get(Mask);
02363   }
02364 
02365   bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
02366                                   Instruction *J, unsigned o, Value *&LOp,
02367                                   unsigned numElemL,
02368                                   Type *ArgTypeL, Type *ArgTypeH,
02369                                   bool IBeforeJ, unsigned IdxOff) {
02370     bool ExpandedIEChain = false;
02371     if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
02372       // If we have a pure insertelement chain, then this can be rewritten
02373       // into a chain that directly builds the larger type.
02374       if (isPureIEChain(LIE)) {
02375         SmallVector<Value *, 8> VectElemts(numElemL,
02376           UndefValue::get(ArgTypeL->getScalarType()));
02377         InsertElementInst *LIENext = LIE;
02378         do {
02379           unsigned Idx =
02380             cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
02381           VectElemts[Idx] = LIENext->getOperand(1);
02382         } while ((LIENext =
02383                    dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
02384 
02385         LIENext = 0;
02386         Value *LIEPrev = UndefValue::get(ArgTypeH);
02387         for (unsigned i = 0; i < numElemL; ++i) {
02388           if (isa<UndefValue>(VectElemts[i])) continue;
02389           LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
02390                              ConstantInt::get(Type::getInt32Ty(Context),
02391                                               i + IdxOff),
02392                              getReplacementName(IBeforeJ ? I : J,
02393                                                 true, o, i+1));
02394           LIENext->insertBefore(IBeforeJ ? J : I);
02395           LIEPrev = LIENext;
02396         }
02397 
02398         LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
02399         ExpandedIEChain = true;
02400       }
02401     }
02402 
02403     return ExpandedIEChain;
02404   }
02405 
02406   static unsigned getNumScalarElements(Type *Ty) {
02407     if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
02408       return VecTy->getNumElements();
02409     return 1;
02410   }
02411 
02412   // Returns the value to be used as the specified operand of the vector
02413   // instruction that fuses I with J.
02414   Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
02415                      Instruction *J, unsigned o, bool IBeforeJ) {
02416     Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
02417     Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
02418 
02419     // Compute the fused vector type for this operand
02420     Type *ArgTypeI = I->getOperand(o)->getType();
02421     Type *ArgTypeJ = J->getOperand(o)->getType();
02422     VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
02423 
02424     Instruction *L = I, *H = J;
02425     Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
02426 
02427     unsigned numElemL = getNumScalarElements(ArgTypeL);
02428     unsigned numElemH = getNumScalarElements(ArgTypeH);
02429 
02430     Value *LOp = L->getOperand(o);
02431     Value *HOp = H->getOperand(o);
02432     unsigned numElem = VArgType->getNumElements();
02433 
02434     // First, we check if we can reuse the "original" vector outputs (if these
02435     // exist). We might need a shuffle.
02436     ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
02437     ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
02438     ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
02439     ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
02440 
02441     // FIXME: If we're fusing shuffle instructions, then we can't apply this
02442     // optimization. The input vectors to the shuffle might be a different
02443     // length from the shuffle outputs. Unfortunately, the replacement
02444     // shuffle mask has already been formed, and the mask entries are sensitive
02445     // to the sizes of the inputs.
02446     bool IsSizeChangeShuffle =
02447       isa<ShuffleVectorInst>(L) &&
02448         (LOp->getType() != L->getType() || HOp->getType() != H->getType());
02449 
02450     if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
02451       // We can have at most two unique vector inputs.
02452       bool CanUseInputs = true;
02453       Value *I1, *I2 = 0;
02454       if (LEE) {
02455         I1 = LEE->getOperand(0);
02456       } else {
02457         I1 = LSV->getOperand(0);
02458         I2 = LSV->getOperand(1);
02459         if (I2 == I1 || isa<UndefValue>(I2))
02460           I2 = 0;
02461       }
02462   
02463       if (HEE) {
02464         Value *I3 = HEE->getOperand(0);
02465         if (!I2 && I3 != I1)
02466           I2 = I3;
02467         else if (I3 != I1 && I3 != I2)
02468           CanUseInputs = false;
02469       } else {
02470         Value *I3 = HSV->getOperand(0);
02471         if (!I2 && I3 != I1)
02472           I2 = I3;
02473         else if (I3 != I1 && I3 != I2)
02474           CanUseInputs = false;
02475 
02476         if (CanUseInputs) {
02477           Value *I4 = HSV->getOperand(1);
02478           if (!isa<UndefValue>(I4)) {
02479             if (!I2 && I4 != I1)
02480               I2 = I4;
02481             else if (I4 != I1 && I4 != I2)
02482               CanUseInputs = false;
02483           }
02484         }
02485       }
02486 
02487       if (CanUseInputs) {
02488         unsigned LOpElem =
02489           cast<Instruction>(LOp)->getOperand(0)->getType()
02490             ->getVectorNumElements();
02491 
02492         unsigned HOpElem =
02493           cast<Instruction>(HOp)->getOperand(0)->getType()
02494             ->getVectorNumElements();
02495 
02496         // We have one or two input vectors. We need to map each index of the
02497         // operands to the index of the original vector.
02498         SmallVector<std::pair<int, int>, 8>  II(numElem);
02499         for (unsigned i = 0; i < numElemL; ++i) {
02500           int Idx, INum;
02501           if (LEE) {
02502             Idx =
02503               cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
02504             INum = LEE->getOperand(0) == I1 ? 0 : 1;
02505           } else {
02506             Idx = LSV->getMaskValue(i);
02507             if (Idx < (int) LOpElem) {
02508               INum = LSV->getOperand(0) == I1 ? 0 : 1;
02509             } else {
02510               Idx -= LOpElem;
02511               INum = LSV->getOperand(1) == I1 ? 0 : 1;
02512             }
02513           }
02514 
02515           II[i] = std::pair<int, int>(Idx, INum);
02516         }
02517         for (unsigned i = 0; i < numElemH; ++i) {
02518           int Idx, INum;
02519           if (HEE) {
02520             Idx =
02521               cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
02522             INum = HEE->getOperand(0) == I1 ? 0 : 1;
02523           } else {
02524             Idx = HSV->getMaskValue(i);
02525             if (Idx < (int) HOpElem) {
02526               INum = HSV->getOperand(0) == I1 ? 0 : 1;
02527             } else {
02528               Idx -= HOpElem;
02529               INum = HSV->getOperand(1) == I1 ? 0 : 1;
02530             }
02531           }
02532 
02533           II[i + numElemL] = std::pair<int, int>(Idx, INum);
02534         }
02535 
02536         // We now have an array which tells us from which index of which
02537         // input vector each element of the operand comes.
02538         VectorType *I1T = cast<VectorType>(I1->getType());
02539         unsigned I1Elem = I1T->getNumElements();
02540 
02541         if (!I2) {
02542           // In this case there is only one underlying vector input. Check for
02543           // the trivial case where we can use the input directly.
02544           if (I1Elem == numElem) {
02545             bool ElemInOrder = true;
02546             for (unsigned i = 0; i < numElem; ++i) {
02547               if (II[i].first != (int) i && II[i].first != -1) {
02548                 ElemInOrder = false;
02549                 break;
02550               }
02551             }
02552 
02553             if (ElemInOrder)
02554               return I1;
02555           }
02556 
02557           // A shuffle is needed.
02558           std::vector<Constant *> Mask(numElem);
02559           for (unsigned i = 0; i < numElem; ++i) {
02560             int Idx = II[i].first;
02561             if (Idx == -1)
02562               Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
02563             else
02564               Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
02565           }
02566 
02567           Instruction *S =
02568             new ShuffleVectorInst(I1, UndefValue::get(I1T),
02569                                   ConstantVector::get(Mask),
02570                                   getReplacementName(IBeforeJ ? I : J,
02571                                                      true, o));
02572           S->insertBefore(IBeforeJ ? J : I);
02573           return S;
02574         }
02575 
02576         VectorType *I2T = cast<VectorType>(I2->getType());
02577         unsigned I2Elem = I2T->getNumElements();
02578 
02579         // This input comes from two distinct vectors. The first step is to
02580         // make sure that both vectors are the same length. If not, the
02581         // smaller one will need to grow before they can be shuffled together.
02582         if (I1Elem < I2Elem) {
02583           std::vector<Constant *> Mask(I2Elem);
02584           unsigned v = 0;
02585           for (; v < I1Elem; ++v)
02586             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
02587           for (; v < I2Elem; ++v)
02588             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
02589 
02590           Instruction *NewI1 =
02591             new ShuffleVectorInst(I1, UndefValue::get(I1T),
02592                                   ConstantVector::get(Mask),
02593                                   getReplacementName(IBeforeJ ? I : J,
02594                                                      true, o, 1));
02595           NewI1->insertBefore(IBeforeJ ? J : I);
02596           I1 = NewI1;
02597           I1T = I2T;
02598           I1Elem = I2Elem;
02599         } else if (I1Elem > I2Elem) {
02600           std::vector<Constant *> Mask(I1Elem);
02601           unsigned v = 0;
02602           for (; v < I2Elem; ++v)
02603             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
02604           for (; v < I1Elem; ++v)
02605             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
02606 
02607           Instruction *NewI2 =
02608             new ShuffleVectorInst(I2, UndefValue::get(I2T),
02609                                   ConstantVector::get(Mask),
02610                                   getReplacementName(IBeforeJ ? I : J,
02611                                                      true, o, 1));
02612           NewI2->insertBefore(IBeforeJ ? J : I);
02613           I2 = NewI2;
02614           I2T = I1T;
02615           I2Elem = I1Elem;
02616         }
02617 
02618         // Now that both I1 and I2 are the same length we can shuffle them
02619         // together (and use the result).
02620         std::vector<Constant *> Mask(numElem);
02621         for (unsigned v = 0; v < numElem; ++v) {
02622           if (II[v].first == -1) {
02623             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
02624           } else {
02625             int Idx = II[v].first + II[v].second * I1Elem;
02626             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
02627           }
02628         }
02629 
02630         Instruction *NewOp =
02631           new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
02632                                 getReplacementName(IBeforeJ ? I : J, true, o));
02633         NewOp->insertBefore(IBeforeJ ? J : I);
02634         return NewOp;
02635       }
02636     }
02637 
02638     Type *ArgType = ArgTypeL;
02639     if (numElemL < numElemH) {
02640       if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
02641                                          ArgTypeL, VArgType, IBeforeJ, 1)) {
02642         // This is another short-circuit case: we're combining a scalar into
02643         // a vector that is formed by an IE chain. We've just expanded the IE
02644         // chain, now insert the scalar and we're done.
02645 
02646         Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
02647                            getReplacementName(IBeforeJ ? I : J, true, o));
02648         S->insertBefore(IBeforeJ ? J : I);
02649         return S;
02650       } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
02651                                 ArgTypeH, IBeforeJ)) {
02652         // The two vector inputs to the shuffle must be the same length,
02653         // so extend the smaller vector to be the same length as the larger one.
02654         Instruction *NLOp;
02655         if (numElemL > 1) {
02656   
02657           std::vector<Constant *> Mask(numElemH);
02658           unsigned v = 0;
02659           for (; v < numElemL; ++v)
02660             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
02661           for (; v < numElemH; ++v)
02662             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
02663     
02664           NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
02665                                        ConstantVector::get(Mask),
02666                                        getReplacementName(IBeforeJ ? I : J,
02667                                                           true, o, 1));
02668         } else {
02669           NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
02670                                            getReplacementName(IBeforeJ ? I : J,
02671                                                               true, o, 1));
02672         }
02673   
02674         NLOp->insertBefore(IBeforeJ ? J : I);
02675         LOp = NLOp;
02676       }
02677 
02678       ArgType = ArgTypeH;
02679     } else if (numElemL > numElemH) {
02680       if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
02681                                          ArgTypeH, VArgType, IBeforeJ)) {
02682         Instruction *S =
02683           InsertElementInst::Create(LOp, HOp, 
02684                                     ConstantInt::get(Type::getInt32Ty(Context),
02685                                                      numElemL),
02686                                     getReplacementName(IBeforeJ ? I : J,
02687                                                        true, o));
02688         S->insertBefore(IBeforeJ ? J : I);
02689         return S;
02690       } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
02691                                 ArgTypeL, IBeforeJ)) {
02692         Instruction *NHOp;
02693         if (numElemH > 1) {
02694           std::vector<Constant *> Mask(numElemL);
02695           unsigned v = 0;
02696           for (; v < numElemH; ++v)
02697             Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
02698           for (; v < numElemL; ++v)
02699             Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
02700     
02701           NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
02702                                        ConstantVector::get(Mask),
02703                                        getReplacementName(IBeforeJ ? I : J,
02704                                                           true, o, 1));
02705         } else {
02706           NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
02707                                            getReplacementName(IBeforeJ ? I : J,
02708                                                               true, o, 1));
02709         }
02710 
02711         NHOp->insertBefore(IBeforeJ ? J : I);
02712         HOp = NHOp;
02713       }
02714     }
02715 
02716     if (ArgType->isVectorTy()) {
02717       unsigned numElem = VArgType->getVectorNumElements();
02718       std::vector<Constant*> Mask(numElem);
02719       for (unsigned v = 0; v < numElem; ++v) {
02720         unsigned Idx = v;
02721         // If the low vector was expanded, we need to skip the extra
02722         // undefined entries.
02723         if (v >= numElemL && numElemH > numElemL)
02724           Idx += (numElemH - numElemL);
02725         Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
02726       }
02727 
02728       Instruction *BV = new ShuffleVectorInst(LOp, HOp,
02729                           ConstantVector::get(Mask),
02730                           getReplacementName(IBeforeJ ? I : J, true, o));
02731       BV->insertBefore(IBeforeJ ? J : I);
02732       return BV;
02733     }
02734 
02735     Instruction *BV1 = InsertElementInst::Create(
02736                                           UndefValue::get(VArgType), LOp, CV0,
02737                                           getReplacementName(IBeforeJ ? I : J,
02738                                                              true, o, 1));
02739     BV1->insertBefore(IBeforeJ ? J : I);
02740     Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
02741                                           getReplacementName(IBeforeJ ? I : J,
02742                                                              true, o, 2));
02743     BV2->insertBefore(IBeforeJ ? J : I);
02744     return BV2;
02745   }
02746 
02747   // This function creates an array of values that will be used as the inputs
02748   // to the vector instruction that fuses I with J.
02749   void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
02750                      Instruction *I, Instruction *J,
02751                      SmallVectorImpl<Value *> &ReplacedOperands,
02752                      bool IBeforeJ) {
02753     unsigned NumOperands = I->getNumOperands();
02754 
02755     for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
02756       // Iterate backward so that we look at the store pointer
02757       // first and know whether or not we need to flip the inputs.
02758 
02759       if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
02760         // This is the pointer for a load/store instruction.
02761         ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
02762         continue;
02763       } else if (isa<CallInst>(I)) {
02764         Function *F = cast<CallInst>(I)->getCalledFunction();
02765         Intrinsic::ID IID = (Intrinsic::ID) F->getIntrinsicID();
02766         if (o == NumOperands-1) {
02767           BasicBlock &BB = *I->getParent();
02768 
02769           Module *M = BB.getParent()->getParent();
02770           Type *ArgTypeI = I->getType();
02771           Type *ArgTypeJ = J->getType();
02772           Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
02773 
02774           ReplacedOperands[o] = Intrinsic::getDeclaration(M, IID, VArgType);
02775           continue;
02776         } else if (IID == Intrinsic::powi && o == 1) {
02777           // The second argument of powi is a single integer and we've already
02778           // checked that both arguments are equal. As a result, we just keep
02779           // I's second argument.
02780           ReplacedOperands[o] = I->getOperand(o);
02781           continue;
02782         }
02783       } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
02784         ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
02785         continue;
02786       }
02787 
02788       ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
02789     }
02790   }
02791 
02792   // This function creates two values that represent the outputs of the
02793   // original I and J instructions. These are generally vector shuffles
02794   // or extracts. In many cases, these will end up being unused and, thus,
02795   // eliminated by later passes.
02796   void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
02797                      Instruction *J, Instruction *K,
02798                      Instruction *&InsertionPt,
02799                      Instruction *&K1, Instruction *&K2) {
02800     if (isa<StoreInst>(I)) {
02801       AA->replaceWithNewValue(I, K);
02802       AA->replaceWithNewValue(J, K);
02803     } else {
02804       Type *IType = I->getType();
02805       Type *JType = J->getType();
02806 
02807       VectorType *VType = getVecTypeForPair(IType, JType);
02808       unsigned numElem = VType->getNumElements();
02809 
02810       unsigned numElemI = getNumScalarElements(IType);
02811       unsigned numElemJ = getNumScalarElements(JType);
02812 
02813       if (IType->isVectorTy()) {
02814         std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
02815         for (unsigned v = 0; v < numElemI; ++v) {
02816           Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
02817           Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
02818         }
02819 
02820         K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
02821                                    ConstantVector::get( Mask1),
02822                                    getReplacementName(K, false, 1));
02823       } else {
02824         Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
02825         K1 = ExtractElementInst::Create(K, CV0,
02826                                           getReplacementName(K, false, 1));
02827       }
02828 
02829       if (JType->isVectorTy()) {
02830         std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
02831         for (unsigned v = 0; v < numElemJ; ++v) {
02832           Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
02833           Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
02834         }
02835 
02836         K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
02837                                    ConstantVector::get( Mask2),
02838                                    getReplacementName(K, false, 2));
02839       } else {
02840         Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
02841         K2 = ExtractElementInst::Create(K, CV1,
02842                                           getReplacementName(K, false, 2));
02843       }
02844 
02845       K1->insertAfter(K);
02846       K2->insertAfter(K1);
02847       InsertionPt = K2;
02848     }
02849   }
02850 
02851   // Move all uses of the function I (including pairing-induced uses) after J.
02852   bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
02853                      DenseSet<ValuePair> &LoadMoveSetPairs,
02854                      Instruction *I, Instruction *J) {
02855     // Skip to the first instruction past I.
02856     BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
02857 
02858     DenseSet<Value *> Users;
02859     AliasSetTracker WriteSet(*AA);
02860     if (I->mayWriteToMemory()) WriteSet.add(I);
02861 
02862     for (; cast<Instruction>(L) != J; ++L)
02863       (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
02864 
02865     assert(cast<Instruction>(L) == J &&
02866       "Tracking has not proceeded far enough to check for dependencies");
02867     // If J is now in the use set of I, then trackUsesOfI will return true
02868     // and we have a dependency cycle (and the fusing operation must abort).
02869     return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSetPairs);
02870   }
02871 
02872   // Move all uses of the function I (including pairing-induced uses) after J.
02873   void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
02874                      DenseSet<ValuePair> &LoadMoveSetPairs,
02875                      Instruction *&InsertionPt,
02876                      Instruction *I, Instruction *J) {
02877     // Skip to the first instruction past I.
02878     BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
02879 
02880     DenseSet<Value *> Users;
02881     AliasSetTracker WriteSet(*AA);
02882     if (I->mayWriteToMemory()) WriteSet.add(I);
02883 
02884     for (; cast<Instruction>(L) != J;) {
02885       if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
02886         // Move this instruction
02887         Instruction *InstToMove = L; ++L;
02888 
02889         DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
02890                         " to after " << *InsertionPt << "\n");
02891         InstToMove->removeFromParent();
02892         InstToMove->insertAfter(InsertionPt);
02893         InsertionPt = InstToMove;
02894       } else {
02895         ++L;
02896       }
02897     }
02898   }
02899 
02900   // Collect all load instruction that are in the move set of a given first
02901   // pair member.  These loads depend on the first instruction, I, and so need
02902   // to be moved after J (the second instruction) when the pair is fused.
02903   void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
02904                      DenseMap<Value *, Value *> &ChosenPairs,
02905                      DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
02906                      DenseSet<ValuePair> &LoadMoveSetPairs,
02907                      Instruction *I) {
02908     // Skip to the first instruction past I.
02909     BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
02910 
02911     DenseSet<Value *> Users;
02912     AliasSetTracker WriteSet(*AA);
02913     if (I->mayWriteToMemory()) WriteSet.add(I);
02914 
02915     // Note: We cannot end the loop when we reach J because J could be moved
02916     // farther down the use chain by another instruction pairing. Also, J
02917     // could be before I if this is an inverted input.
02918     for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
02919       if (trackUsesOfI(Users, WriteSet, I, L)) {
02920         if (L->mayReadFromMemory()) {
02921           LoadMoveSet[L].push_back(I);
02922           LoadMoveSetPairs.insert(ValuePair(L, I));
02923         }
02924       }
02925     }
02926   }
02927 
02928   // In cases where both load/stores and the computation of their pointers
02929   // are chosen for vectorization, we can end up in a situation where the
02930   // aliasing analysis starts returning different query results as the
02931   // process of fusing instruction pairs continues. Because the algorithm
02932   // relies on finding the same use dags here as were found earlier, we'll
02933   // need to precompute the necessary aliasing information here and then
02934   // manually update it during the fusion process.
02935   void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
02936                      std::vector<Value *> &PairableInsts,
02937                      DenseMap<Value *, Value *> &ChosenPairs,
02938                      DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
02939                      DenseSet<ValuePair> &LoadMoveSetPairs) {
02940     for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
02941          PIE = PairableInsts.end(); PI != PIE; ++PI) {
02942       DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
02943       if (P == ChosenPairs.end()) continue;
02944 
02945       Instruction *I = cast<Instruction>(P->first);
02946       collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet,
02947                              LoadMoveSetPairs, I);
02948     }
02949   }
02950 
02951   // When the first instruction in each pair is cloned, it will inherit its
02952   // parent's metadata. This metadata must be combined with that of the other
02953   // instruction in a safe way.
02954   void BBVectorize::combineMetadata(Instruction *K, const Instruction *J) {
02955     SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
02956     K->getAllMetadataOtherThanDebugLoc(Metadata);
02957     for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
02958       unsigned Kind = Metadata[i].first;
02959       MDNode *JMD = J->getMetadata(Kind);
02960       MDNode *KMD = Metadata[i].second;
02961 
02962       switch (Kind) {
02963       default:
02964         K->setMetadata(Kind, 0); // Remove unknown metadata
02965         break;
02966       case LLVMContext::MD_tbaa:
02967         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
02968         break;
02969       case LLVMContext::MD_fpmath:
02970         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
02971         break;
02972       }
02973     }
02974   }
02975 
02976   // This function fuses the chosen instruction pairs into vector instructions,
02977   // taking care preserve any needed scalar outputs and, then, it reorders the
02978   // remaining instructions as needed (users of the first member of the pair
02979   // need to be moved to after the location of the second member of the pair
02980   // because the vector instruction is inserted in the location of the pair's
02981   // second member).
02982   void BBVectorize::fuseChosenPairs(BasicBlock &BB,
02983              std::vector<Value *> &PairableInsts,
02984              DenseMap<Value *, Value *> &ChosenPairs,
02985              DenseSet<ValuePair> &FixedOrderPairs,
02986              DenseMap<VPPair, unsigned> &PairConnectionTypes,
02987              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
02988              DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps) {
02989     LLVMContext& Context = BB.getContext();
02990 
02991     // During the vectorization process, the order of the pairs to be fused
02992     // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
02993     // list. After a pair is fused, the flipped pair is removed from the list.
02994     DenseSet<ValuePair> FlippedPairs;
02995     for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
02996          E = ChosenPairs.end(); P != E; ++P)
02997       FlippedPairs.insert(ValuePair(P->second, P->first));
02998     for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
02999          E = FlippedPairs.end(); P != E; ++P)
03000       ChosenPairs.insert(*P);
03001 
03002     DenseMap<Value *, std::vector<Value *> > LoadMoveSet;
03003     DenseSet<ValuePair> LoadMoveSetPairs;
03004     collectLoadMoveSet(BB, PairableInsts, ChosenPairs,
03005                        LoadMoveSet, LoadMoveSetPairs);
03006 
03007     DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
03008 
03009     for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
03010       DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
03011       if (P == ChosenPairs.end()) {
03012         ++PI;
03013         continue;
03014       }
03015 
03016       if (getDepthFactor(P->first) == 0) {
03017         // These instructions are not really fused, but are tracked as though
03018         // they are. Any case in which it would be interesting to fuse them
03019         // will be taken care of by InstCombine.
03020         --NumFusedOps;
03021         ++PI;
03022         continue;
03023       }
03024 
03025       Instruction *I = cast<Instruction>(P->first),
03026         *J = cast<Instruction>(P->second);
03027 
03028       DEBUG(dbgs() << "BBV: fusing: " << *I <<
03029              " <-> " << *J << "\n");
03030 
03031       // Remove the pair and flipped pair from the list.
03032       DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
03033       assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
03034       ChosenPairs.erase(FP);
03035       ChosenPairs.erase(P);
03036 
03037       if (!canMoveUsesOfIAfterJ(BB, LoadMoveSetPairs, I, J)) {
03038         DEBUG(dbgs() << "BBV: fusion of: " << *I <<
03039                " <-> " << *J <<
03040                " aborted because of non-trivial dependency cycle\n");
03041         --NumFusedOps;
03042         ++PI;
03043         continue;
03044       }
03045 
03046       // If the pair must have the other order, then flip it.
03047       bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
03048       if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
03049         // This pair does not have a fixed order, and so we might want to
03050         // flip it if that will yield fewer shuffles. We count the number
03051         // of dependencies connected via swaps, and those directly connected,
03052         // and flip the order if the number of swaps is greater.
03053         bool OrigOrder = true;
03054         DenseMap<ValuePair, std::vector<ValuePair> >::iterator IJ =
03055           ConnectedPairDeps.find(ValuePair(I, J));
03056         if (IJ == ConnectedPairDeps.end()) {
03057           IJ = ConnectedPairDeps.find(ValuePair(J, I));
03058           OrigOrder = false;
03059         }
03060 
03061         if (IJ != ConnectedPairDeps.end()) {
03062           unsigned NumDepsDirect = 0, NumDepsSwap = 0;
03063           for (std::vector<ValuePair>::iterator T = IJ->second.begin(),
03064                TE = IJ->second.end(); T != TE; ++T) {
03065             VPPair Q(IJ->first, *T);
03066             DenseMap<VPPair, unsigned>::iterator R =
03067               PairConnectionTypes.find(VPPair(Q.second, Q.first));
03068             assert(R != PairConnectionTypes.end() &&
03069                    "Cannot find pair connection type");
03070             if (R->second == PairConnectionDirect)
03071               ++NumDepsDirect;
03072             else if (R->second == PairConnectionSwap)
03073               ++NumDepsSwap;
03074           }
03075 
03076           if (!OrigOrder)
03077             std::swap(NumDepsDirect, NumDepsSwap);
03078 
03079           if (NumDepsSwap > NumDepsDirect) {
03080             FlipPairOrder = true;
03081             DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
03082                             " <-> " << *J << "\n");
03083           }
03084         }
03085       }
03086 
03087       Instruction *L = I, *H = J;
03088       if (FlipPairOrder)
03089         std::swap(H, L);
03090 
03091       // If the pair being fused uses the opposite order from that in the pair
03092       // connection map, then we need to flip the types.
03093       DenseMap<ValuePair, std::vector<ValuePair> >::iterator HL =
03094         ConnectedPairs.find(ValuePair(H, L));
03095       if (HL != ConnectedPairs.end())
03096         for (std::vector<ValuePair>::iterator T = HL->second.begin(),
03097              TE = HL->second.end(); T != TE; ++T) {
03098           VPPair Q(HL->first, *T);
03099           DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(Q);
03100           assert(R != PairConnectionTypes.end() &&
03101                  "Cannot find pair connection type");
03102           if (R->second == PairConnectionDirect)
03103             R->second = PairConnectionSwap;
03104           else if (R->second == PairConnectionSwap)
03105             R->second = PairConnectionDirect;
03106         }
03107 
03108       bool LBeforeH = !FlipPairOrder;
03109       unsigned NumOperands = I->getNumOperands();
03110       SmallVector<Value *, 3> ReplacedOperands(NumOperands);
03111       getReplacementInputsForPair(Context, L, H, ReplacedOperands,
03112                                   LBeforeH);
03113 
03114       // Make a copy of the original operation, change its type to the vector
03115       // type and replace its operands with the vector operands.
03116       Instruction *K = L->clone();
03117       if (L->hasName())
03118         K->takeName(L);
03119       else if (H->hasName())
03120         K->takeName(H);
03121 
03122       if (!isa<StoreInst>(K))
03123         K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
03124 
03125       combineMetadata(K, H);
03126       K->intersectOptionalDataWith(H);
03127 
03128       for (unsigned o = 0; o < NumOperands; ++o)
03129         K->setOperand(o, ReplacedOperands[o]);
03130 
03131       K->insertAfter(J);
03132 
03133       // Instruction insertion point:
03134       Instruction *InsertionPt = K;
03135       Instruction *K1 = 0, *K2 = 0;
03136       replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
03137 
03138       // The use dag of the first original instruction must be moved to after
03139       // the location of the second instruction. The entire use dag of the
03140       // first instruction is disjoint from the input dag of the second
03141       // (by definition), and so commutes with it.
03142 
03143       moveUsesOfIAfterJ(BB, LoadMoveSetPairs, InsertionPt, I, J);
03144 
03145       if (!isa<StoreInst>(I)) {
03146         L->replaceAllUsesWith(K1);
03147         H->replaceAllUsesWith(K2);
03148         AA->replaceWithNewValue(L, K1);
03149         AA->replaceWithNewValue(H, K2);
03150       }
03151 
03152       // Instructions that may read from memory may be in the load move set.
03153       // Once an instruction is fused, we no longer need its move set, and so
03154       // the values of the map never need to be updated. However, when a load
03155       // is fused, we need to merge the entries from both instructions in the
03156       // pair in case those instructions were in the move set of some other
03157       // yet-to-be-fused pair. The loads in question are the keys of the map.
03158       if (I->mayReadFromMemory()) {
03159         std::vector<ValuePair> NewSetMembers;
03160         DenseMap<Value *, std::vector<Value *> >::iterator II =
03161           LoadMoveSet.find(I);
03162         if (II != LoadMoveSet.end())
03163           for (std::vector<Value *>::iterator N = II->second.begin(),
03164                NE = II->second.end(); N != NE; ++N)
03165             NewSetMembers.push_back(ValuePair(K, *N));
03166         DenseMap<Value *, std::vector<Value *> >::iterator JJ =
03167           LoadMoveSet.find(J);
03168         if (JJ != LoadMoveSet.end())
03169           for (std::vector<Value *>::iterator N = JJ->second.begin(),
03170                NE = JJ->second.end(); N != NE; ++N)
03171             NewSetMembers.push_back(ValuePair(K, *N));
03172         for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
03173              AE = NewSetMembers.end(); A != AE; ++A) {
03174           LoadMoveSet[A->first].push_back(A->second);
03175           LoadMoveSetPairs.insert(*A);
03176         }
03177       }
03178 
03179       // Before removing I, set the iterator to the next instruction.
03180       PI = std::next(BasicBlock::iterator(I));
03181       if (cast<Instruction>(PI) == J)
03182         ++PI;
03183 
03184       SE->forgetValue(I);
03185       SE->forgetValue(J);
03186       I->eraseFromParent();
03187       J->eraseFromParent();
03188 
03189       DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
03190                                                BB << "\n");
03191     }
03192 
03193     DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
03194   }
03195 }
03196 
03197 char BBVectorize::ID = 0;
03198 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
03199 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
03200 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
03201 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
03202 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
03203 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
03204 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
03205 
03206 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
03207   return new BBVectorize(C);
03208 }
03209 
03210 bool
03211 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
03212   BBVectorize BBVectorizer(P, C);
03213   return BBVectorizer.vectorizeBB(BB);
03214 }
03215 
03216 //===----------------------------------------------------------------------===//
03217 VectorizeConfig::VectorizeConfig() {
03218   VectorBits = ::VectorBits;
03219   VectorizeBools = !::NoBools;
03220   VectorizeInts = !::NoInts;
03221   VectorizeFloats = !::NoFloats;
03222   VectorizePointers = !::NoPointers;
03223   VectorizeCasts = !::NoCasts;
03224   VectorizeMath = !::NoMath;
03225   VectorizeFMA = !::NoFMA;
03226   VectorizeSelect = !::NoSelect;
03227   VectorizeCmp = !::NoCmp;
03228   VectorizeGEP = !::NoGEP;
03229   VectorizeMemOps = !::NoMemOps;
03230   AlignedOnly = ::AlignedOnly;
03231   ReqChainDepth= ::ReqChainDepth;
03232   SearchLimit = ::SearchLimit;
03233   MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
03234   SplatBreaksChain = ::SplatBreaksChain;
03235   MaxInsts = ::MaxInsts;
03236   MaxPairs = ::MaxPairs;
03237   MaxIter = ::MaxIter;
03238   Pow2LenOnly = ::Pow2LenOnly;
03239   NoMemOpBoost = ::NoMemOpBoost;
03240   FastDep = ::FastDep;
03241 }