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