BBVectorize.cpp revision 86ccc55c82651f91fd6a312c5f6a4b511bcd1aec
1//===- BBVectorize.cpp - A Basic-Block Vectorizer -------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a basic-block vectorization pass. The algorithm was
11// inspired by that used by the Vienna MAP Vectorizor by Franchetti and Kral,
12// et al. It works by looking for chains of pairable operations and then
13// pairing them.
14//
15//===----------------------------------------------------------------------===//
16
17#define BBV_NAME "bb-vectorize"
18#define DEBUG_TYPE BBV_NAME
19#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
22#include "llvm/Instructions.h"
23#include "llvm/IntrinsicInst.h"
24#include "llvm/Intrinsics.h"
25#include "llvm/LLVMContext.h"
26#include "llvm/Metadata.h"
27#include "llvm/Pass.h"
28#include "llvm/Type.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/StringExtras.h"
35#include "llvm/Analysis/AliasAnalysis.h"
36#include "llvm/Analysis/AliasSetTracker.h"
37#include "llvm/Analysis/Dominators.h"
38#include "llvm/Analysis/ScalarEvolution.h"
39#include "llvm/Analysis/ScalarEvolutionExpressions.h"
40#include "llvm/Analysis/ValueTracking.h"
41#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/Debug.h"
43#include "llvm/Support/raw_ostream.h"
44#include "llvm/Support/ValueHandle.h"
45#include "llvm/DataLayout.h"
46#include "llvm/TargetTransformInfo.h"
47#include "llvm/Transforms/Utils/Local.h"
48#include "llvm/Transforms/Vectorize.h"
49#include <algorithm>
50#include <map>
51using namespace llvm;
52
53static cl::opt<bool>
54IgnoreTargetInfo("bb-vectorize-ignore-target-info",  cl::init(false),
55  cl::Hidden, cl::desc("Ignore target information"));
56
57static cl::opt<unsigned>
58ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
59  cl::desc("The required chain depth for vectorization"));
60
61static cl::opt<unsigned>
62SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
63  cl::desc("The maximum search distance for instruction pairs"));
64
65static cl::opt<bool>
66SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
67  cl::desc("Replicating one element to a pair breaks the chain"));
68
69static cl::opt<unsigned>
70VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
71  cl::desc("The size of the native vector registers"));
72
73static cl::opt<unsigned>
74MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
75  cl::desc("The maximum number of pairing iterations"));
76
77static cl::opt<bool>
78Pow2LenOnly("bb-vectorize-pow2-len-only", cl::init(false), cl::Hidden,
79  cl::desc("Don't try to form non-2^n-length vectors"));
80
81static cl::opt<unsigned>
82MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
83  cl::desc("The maximum number of pairable instructions per group"));
84
85static cl::opt<unsigned>
86MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
87  cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
88                       " a full cycle check"));
89
90static cl::opt<bool>
91NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
92  cl::desc("Don't try to vectorize boolean (i1) values"));
93
94static cl::opt<bool>
95NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
96  cl::desc("Don't try to vectorize integer values"));
97
98static cl::opt<bool>
99NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
100  cl::desc("Don't try to vectorize floating-point values"));
101
102// FIXME: This should default to false once pointer vector support works.
103static cl::opt<bool>
104NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
105  cl::desc("Don't try to vectorize pointer values"));
106
107static cl::opt<bool>
108NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
109  cl::desc("Don't try to vectorize casting (conversion) operations"));
110
111static cl::opt<bool>
112NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
113  cl::desc("Don't try to vectorize floating-point math intrinsics"));
114
115static cl::opt<bool>
116NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
117  cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
118
119static cl::opt<bool>
120NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
121  cl::desc("Don't try to vectorize select instructions"));
122
123static cl::opt<bool>
124NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
125  cl::desc("Don't try to vectorize comparison instructions"));
126
127static cl::opt<bool>
128NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
129  cl::desc("Don't try to vectorize getelementptr instructions"));
130
131static cl::opt<bool>
132NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
133  cl::desc("Don't try to vectorize loads and stores"));
134
135static cl::opt<bool>
136AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
137  cl::desc("Only generate aligned loads and stores"));
138
139static cl::opt<bool>
140NoMemOpBoost("bb-vectorize-no-mem-op-boost",
141  cl::init(false), cl::Hidden,
142  cl::desc("Don't boost the chain-depth contribution of loads and stores"));
143
144static cl::opt<bool>
145FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
146  cl::desc("Use a fast instruction dependency analysis"));
147
148#ifndef NDEBUG
149static cl::opt<bool>
150DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
151  cl::init(false), cl::Hidden,
152  cl::desc("When debugging is enabled, output information on the"
153           " instruction-examination process"));
154static cl::opt<bool>
155DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
156  cl::init(false), cl::Hidden,
157  cl::desc("When debugging is enabled, output information on the"
158           " candidate-selection process"));
159static cl::opt<bool>
160DebugPairSelection("bb-vectorize-debug-pair-selection",
161  cl::init(false), cl::Hidden,
162  cl::desc("When debugging is enabled, output information on the"
163           " pair-selection process"));
164static cl::opt<bool>
165DebugCycleCheck("bb-vectorize-debug-cycle-check",
166  cl::init(false), cl::Hidden,
167  cl::desc("When debugging is enabled, output information on the"
168           " cycle-checking process"));
169
170static cl::opt<bool>
171PrintAfterEveryPair("bb-vectorize-debug-print-after-every-pair",
172  cl::init(false), cl::Hidden,
173  cl::desc("When debugging is enabled, dump the basic block after"
174           " every pair is fused"));
175#endif
176
177STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
178
179namespace {
180  struct BBVectorize : public BasicBlockPass {
181    static char ID; // Pass identification, replacement for typeid
182
183    const VectorizeConfig Config;
184
185    BBVectorize(const VectorizeConfig &C = VectorizeConfig())
186      : BasicBlockPass(ID), Config(C) {
187      initializeBBVectorizePass(*PassRegistry::getPassRegistry());
188    }
189
190    BBVectorize(Pass *P, const VectorizeConfig &C)
191      : BasicBlockPass(ID), Config(C) {
192      AA = &P->getAnalysis<AliasAnalysis>();
193      DT = &P->getAnalysis<DominatorTree>();
194      SE = &P->getAnalysis<ScalarEvolution>();
195      TD = P->getAnalysisIfAvailable<DataLayout>();
196      TTI = IgnoreTargetInfo ? 0 :
197        P->getAnalysisIfAvailable<TargetTransformInfo>();
198      VTTI = TTI ? TTI->getVectorTargetTransformInfo() : 0;
199    }
200
201    typedef std::pair<Value *, Value *> ValuePair;
202    typedef std::pair<ValuePair, int> ValuePairWithCost;
203    typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
204    typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
205    typedef std::pair<VPPair, unsigned> VPPairWithType;
206    typedef std::pair<std::multimap<Value *, Value *>::iterator,
207              std::multimap<Value *, Value *>::iterator> VPIteratorPair;
208    typedef std::pair<std::multimap<ValuePair, ValuePair>::iterator,
209              std::multimap<ValuePair, ValuePair>::iterator>
210                VPPIteratorPair;
211
212    AliasAnalysis *AA;
213    DominatorTree *DT;
214    ScalarEvolution *SE;
215    DataLayout *TD;
216    TargetTransformInfo *TTI;
217    const VectorTargetTransformInfo *VTTI;
218
219    // FIXME: const correct?
220
221    bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
222
223    bool getCandidatePairs(BasicBlock &BB,
224                       BasicBlock::iterator &Start,
225                       std::multimap<Value *, Value *> &CandidatePairs,
226                       DenseSet<ValuePair> &FixedOrderPairs,
227                       DenseMap<ValuePair, int> &CandidatePairCostSavings,
228                       std::vector<Value *> &PairableInsts, bool NonPow2Len);
229
230    enum PairConnectionType {
231      PairConnectionDirect,
232      PairConnectionSwap,
233      PairConnectionSplat
234    };
235
236    void computeConnectedPairs(std::multimap<Value *, Value *> &CandidatePairs,
237                       std::vector<Value *> &PairableInsts,
238                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
239                       DenseMap<VPPair, unsigned> &PairConnectionTypes);
240
241    void buildDepMap(BasicBlock &BB,
242                       std::multimap<Value *, Value *> &CandidatePairs,
243                       std::vector<Value *> &PairableInsts,
244                       DenseSet<ValuePair> &PairableInstUsers);
245
246    void choosePairs(std::multimap<Value *, Value *> &CandidatePairs,
247                        DenseMap<ValuePair, int> &CandidatePairCostSavings,
248                        std::vector<Value *> &PairableInsts,
249                        DenseSet<ValuePair> &FixedOrderPairs,
250                        DenseMap<VPPair, unsigned> &PairConnectionTypes,
251                        std::multimap<ValuePair, ValuePair> &ConnectedPairs,
252                        std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
253                        DenseSet<ValuePair> &PairableInstUsers,
254                        DenseMap<Value *, Value *>& ChosenPairs);
255
256    void fuseChosenPairs(BasicBlock &BB,
257                     std::vector<Value *> &PairableInsts,
258                     DenseMap<Value *, Value *>& ChosenPairs,
259                     DenseSet<ValuePair> &FixedOrderPairs,
260                     DenseMap<VPPair, unsigned> &PairConnectionTypes,
261                     std::multimap<ValuePair, ValuePair> &ConnectedPairs,
262                     std::multimap<ValuePair, ValuePair> &ConnectedPairDeps);
263
264
265    bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
266
267    bool areInstsCompatible(Instruction *I, Instruction *J,
268                       bool IsSimpleLoadStore, bool NonPow2Len,
269                       int &CostSavings, int &FixedOrder);
270
271    bool trackUsesOfI(DenseSet<Value *> &Users,
272                      AliasSetTracker &WriteSet, Instruction *I,
273                      Instruction *J, bool UpdateUsers = true,
274                      std::multimap<Value *, Value *> *LoadMoveSet = 0);
275
276    void computePairsConnectedTo(
277                      std::multimap<Value *, Value *> &CandidatePairs,
278                      std::vector<Value *> &PairableInsts,
279                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
280                      DenseMap<VPPair, unsigned> &PairConnectionTypes,
281                      ValuePair P);
282
283    bool pairsConflict(ValuePair P, ValuePair Q,
284                 DenseSet<ValuePair> &PairableInstUsers,
285                 std::multimap<ValuePair, ValuePair> *PairableInstUserMap = 0);
286
287    bool pairWillFormCycle(ValuePair P,
288                       std::multimap<ValuePair, ValuePair> &PairableInstUsers,
289                       DenseSet<ValuePair> &CurrentPairs);
290
291    void pruneTreeFor(
292                      std::multimap<Value *, Value *> &CandidatePairs,
293                      std::vector<Value *> &PairableInsts,
294                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
295                      DenseSet<ValuePair> &PairableInstUsers,
296                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
297                      DenseMap<Value *, Value *> &ChosenPairs,
298                      DenseMap<ValuePair, size_t> &Tree,
299                      DenseSet<ValuePair> &PrunedTree, ValuePair J,
300                      bool UseCycleCheck);
301
302    void buildInitialTreeFor(
303                      std::multimap<Value *, Value *> &CandidatePairs,
304                      std::vector<Value *> &PairableInsts,
305                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
306                      DenseSet<ValuePair> &PairableInstUsers,
307                      DenseMap<Value *, Value *> &ChosenPairs,
308                      DenseMap<ValuePair, size_t> &Tree, ValuePair J);
309
310    void findBestTreeFor(
311                      std::multimap<Value *, Value *> &CandidatePairs,
312                      DenseMap<ValuePair, int> &CandidatePairCostSavings,
313                      std::vector<Value *> &PairableInsts,
314                      DenseSet<ValuePair> &FixedOrderPairs,
315                      DenseMap<VPPair, unsigned> &PairConnectionTypes,
316                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
317                      std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
318                      DenseSet<ValuePair> &PairableInstUsers,
319                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
320                      DenseMap<Value *, Value *> &ChosenPairs,
321                      DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
322                      int &BestEffSize, VPIteratorPair ChoiceRange,
323                      bool UseCycleCheck);
324
325    Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
326                     Instruction *J, unsigned o);
327
328    void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
329                     unsigned MaskOffset, unsigned NumInElem,
330                     unsigned NumInElem1, unsigned IdxOffset,
331                     std::vector<Constant*> &Mask);
332
333    Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
334                     Instruction *J);
335
336    bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
337                       unsigned o, Value *&LOp, unsigned numElemL,
338                       Type *ArgTypeL, Type *ArgTypeR, bool IBeforeJ,
339                       unsigned IdxOff = 0);
340
341    Value *getReplacementInput(LLVMContext& Context, Instruction *I,
342                     Instruction *J, unsigned o, bool IBeforeJ);
343
344    void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
345                     Instruction *J, SmallVector<Value *, 3> &ReplacedOperands,
346                     bool IBeforeJ);
347
348    void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
349                     Instruction *J, Instruction *K,
350                     Instruction *&InsertionPt, Instruction *&K1,
351                     Instruction *&K2);
352
353    void collectPairLoadMoveSet(BasicBlock &BB,
354                     DenseMap<Value *, Value *> &ChosenPairs,
355                     std::multimap<Value *, Value *> &LoadMoveSet,
356                     Instruction *I);
357
358    void collectLoadMoveSet(BasicBlock &BB,
359                     std::vector<Value *> &PairableInsts,
360                     DenseMap<Value *, Value *> &ChosenPairs,
361                     std::multimap<Value *, Value *> &LoadMoveSet);
362
363    bool canMoveUsesOfIAfterJ(BasicBlock &BB,
364                     std::multimap<Value *, Value *> &LoadMoveSet,
365                     Instruction *I, Instruction *J);
366
367    void moveUsesOfIAfterJ(BasicBlock &BB,
368                     std::multimap<Value *, Value *> &LoadMoveSet,
369                     Instruction *&InsertionPt,
370                     Instruction *I, Instruction *J);
371
372    void combineMetadata(Instruction *K, const Instruction *J);
373
374    bool vectorizeBB(BasicBlock &BB) {
375      if (!DT->isReachableFromEntry(&BB)) {
376        DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
377              " in " << BB.getParent()->getName() << "\n");
378        return false;
379      }
380
381      DEBUG(if (VTTI) dbgs() << "BBV: using target information\n");
382
383      bool changed = false;
384      // Iterate a sufficient number of times to merge types of size 1 bit,
385      // then 2 bits, then 4, etc. up to half of the target vector width of the
386      // target vector register.
387      unsigned n = 1;
388      for (unsigned v = 2;
389           (VTTI || v <= Config.VectorBits) &&
390           (!Config.MaxIter || n <= Config.MaxIter);
391           v *= 2, ++n) {
392        DEBUG(dbgs() << "BBV: fusing loop #" << n <<
393              " for " << BB.getName() << " in " <<
394              BB.getParent()->getName() << "...\n");
395        if (vectorizePairs(BB))
396          changed = true;
397        else
398          break;
399      }
400
401      if (changed && !Pow2LenOnly) {
402        ++n;
403        for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
404          DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
405                n << " for " << BB.getName() << " in " <<
406                BB.getParent()->getName() << "...\n");
407          if (!vectorizePairs(BB, true)) break;
408        }
409      }
410
411      DEBUG(dbgs() << "BBV: done!\n");
412      return changed;
413    }
414
415    virtual bool runOnBasicBlock(BasicBlock &BB) {
416      AA = &getAnalysis<AliasAnalysis>();
417      DT = &getAnalysis<DominatorTree>();
418      SE = &getAnalysis<ScalarEvolution>();
419      TD = getAnalysisIfAvailable<DataLayout>();
420      TTI = IgnoreTargetInfo ? 0 :
421        getAnalysisIfAvailable<TargetTransformInfo>();
422      VTTI = TTI ? TTI->getVectorTargetTransformInfo() : 0;
423
424      return vectorizeBB(BB);
425    }
426
427    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
428      BasicBlockPass::getAnalysisUsage(AU);
429      AU.addRequired<AliasAnalysis>();
430      AU.addRequired<DominatorTree>();
431      AU.addRequired<ScalarEvolution>();
432      AU.addPreserved<AliasAnalysis>();
433      AU.addPreserved<DominatorTree>();
434      AU.addPreserved<ScalarEvolution>();
435      AU.setPreservesCFG();
436    }
437
438    static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
439      assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
440             "Cannot form vector from incompatible scalar types");
441      Type *STy = ElemTy->getScalarType();
442
443      unsigned numElem;
444      if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
445        numElem = VTy->getNumElements();
446      } else {
447        numElem = 1;
448      }
449
450      if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
451        numElem += VTy->getNumElements();
452      } else {
453        numElem += 1;
454      }
455
456      return VectorType::get(STy, numElem);
457    }
458
459    static inline void getInstructionTypes(Instruction *I,
460                                           Type *&T1, Type *&T2) {
461      if (isa<StoreInst>(I)) {
462        // For stores, it is the value type, not the pointer type that matters
463        // because the value is what will come from a vector register.
464
465        Value *IVal = cast<StoreInst>(I)->getValueOperand();
466        T1 = IVal->getType();
467      } else {
468        T1 = I->getType();
469      }
470
471      if (I->isCast())
472        T2 = cast<CastInst>(I)->getSrcTy();
473      else
474        T2 = T1;
475
476      if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
477        T2 = SI->getCondition()->getType();
478      }
479    }
480
481    // Returns the weight associated with the provided value. A chain of
482    // candidate pairs has a length given by the sum of the weights of its
483    // members (one weight per pair; the weight of each member of the pair
484    // is assumed to be the same). This length is then compared to the
485    // chain-length threshold to determine if a given chain is significant
486    // enough to be vectorized. The length is also used in comparing
487    // candidate chains where longer chains are considered to be better.
488    // Note: when this function returns 0, the resulting instructions are
489    // not actually fused.
490    inline size_t getDepthFactor(Value *V) {
491      // InsertElement and ExtractElement have a depth factor of zero. This is
492      // for two reasons: First, they cannot be usefully fused. Second, because
493      // the pass generates a lot of these, they can confuse the simple metric
494      // used to compare the trees in the next iteration. Thus, giving them a
495      // weight of zero allows the pass to essentially ignore them in
496      // subsequent iterations when looking for vectorization opportunities
497      // while still tracking dependency chains that flow through those
498      // instructions.
499      if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
500        return 0;
501
502      // Give a load or store half of the required depth so that load/store
503      // pairs will vectorize.
504      if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
505        return Config.ReqChainDepth/2;
506
507      return 1;
508    }
509
510    // Returns the cost of the provided instruction using VTTI.
511    // This does not handle loads and stores.
512    unsigned getInstrCost(unsigned Opcode, Type *T1, Type *T2) {
513      switch (Opcode) {
514      default: break;
515      case Instruction::GetElementPtr:
516        // We mark this instruction as zero-cost because scalar GEPs are usually
517        // lowered to the intruction addressing mode. At the moment we don't
518        // generate vector GEPs.
519        return 0;
520      case Instruction::Br:
521        return VTTI->getCFInstrCost(Opcode);
522      case Instruction::PHI:
523        return 0;
524      case Instruction::Add:
525      case Instruction::FAdd:
526      case Instruction::Sub:
527      case Instruction::FSub:
528      case Instruction::Mul:
529      case Instruction::FMul:
530      case Instruction::UDiv:
531      case Instruction::SDiv:
532      case Instruction::FDiv:
533      case Instruction::URem:
534      case Instruction::SRem:
535      case Instruction::FRem:
536      case Instruction::Shl:
537      case Instruction::LShr:
538      case Instruction::AShr:
539      case Instruction::And:
540      case Instruction::Or:
541      case Instruction::Xor:
542        return VTTI->getArithmeticInstrCost(Opcode, T1);
543      case Instruction::Select:
544      case Instruction::ICmp:
545      case Instruction::FCmp:
546        return VTTI->getCmpSelInstrCost(Opcode, T1, T2);
547      case Instruction::ZExt:
548      case Instruction::SExt:
549      case Instruction::FPToUI:
550      case Instruction::FPToSI:
551      case Instruction::FPExt:
552      case Instruction::PtrToInt:
553      case Instruction::IntToPtr:
554      case Instruction::SIToFP:
555      case Instruction::UIToFP:
556      case Instruction::Trunc:
557      case Instruction::FPTrunc:
558      case Instruction::BitCast:
559      case Instruction::ShuffleVector:
560        return VTTI->getCastInstrCost(Opcode, T1, T2);
561      }
562
563      return 1;
564    }
565
566    // This determines the relative offset of two loads or stores, returning
567    // true if the offset could be determined to be some constant value.
568    // For example, if OffsetInElmts == 1, then J accesses the memory directly
569    // after I; if OffsetInElmts == -1 then I accesses the memory
570    // directly after J.
571    bool getPairPtrInfo(Instruction *I, Instruction *J,
572        Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
573        unsigned &IAddressSpace, unsigned &JAddressSpace,
574        int64_t &OffsetInElmts, bool ComputeOffset = true) {
575      OffsetInElmts = 0;
576      if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
577        LoadInst *LJ = cast<LoadInst>(J);
578        IPtr = LI->getPointerOperand();
579        JPtr = LJ->getPointerOperand();
580        IAlignment = LI->getAlignment();
581        JAlignment = LJ->getAlignment();
582        IAddressSpace = LI->getPointerAddressSpace();
583        JAddressSpace = LJ->getPointerAddressSpace();
584      } else {
585        StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
586        IPtr = SI->getPointerOperand();
587        JPtr = SJ->getPointerOperand();
588        IAlignment = SI->getAlignment();
589        JAlignment = SJ->getAlignment();
590        IAddressSpace = SI->getPointerAddressSpace();
591        JAddressSpace = SJ->getPointerAddressSpace();
592      }
593
594      if (!ComputeOffset)
595        return true;
596
597      const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
598      const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
599
600      // If this is a trivial offset, then we'll get something like
601      // 1*sizeof(type). With target data, which we need anyway, this will get
602      // constant folded into a number.
603      const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
604      if (const SCEVConstant *ConstOffSCEV =
605            dyn_cast<SCEVConstant>(OffsetSCEV)) {
606        ConstantInt *IntOff = ConstOffSCEV->getValue();
607        int64_t Offset = IntOff->getSExtValue();
608
609        Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
610        int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
611
612        Type *VTy2 = cast<PointerType>(JPtr->getType())->getElementType();
613        if (VTy != VTy2 && Offset < 0) {
614          int64_t VTy2TSS = (int64_t) TD->getTypeStoreSize(VTy2);
615          OffsetInElmts = Offset/VTy2TSS;
616          return (abs64(Offset) % VTy2TSS) == 0;
617        }
618
619        OffsetInElmts = Offset/VTyTSS;
620        return (abs64(Offset) % VTyTSS) == 0;
621      }
622
623      return false;
624    }
625
626    // Returns true if the provided CallInst represents an intrinsic that can
627    // be vectorized.
628    bool isVectorizableIntrinsic(CallInst* I) {
629      Function *F = I->getCalledFunction();
630      if (!F) return false;
631
632      unsigned IID = F->getIntrinsicID();
633      if (!IID) return false;
634
635      switch(IID) {
636      default:
637        return false;
638      case Intrinsic::sqrt:
639      case Intrinsic::powi:
640      case Intrinsic::sin:
641      case Intrinsic::cos:
642      case Intrinsic::log:
643      case Intrinsic::log2:
644      case Intrinsic::log10:
645      case Intrinsic::exp:
646      case Intrinsic::exp2:
647      case Intrinsic::pow:
648        return Config.VectorizeMath;
649      case Intrinsic::fma:
650        return Config.VectorizeFMA;
651      }
652    }
653
654    // Returns true if J is the second element in some pair referenced by
655    // some multimap pair iterator pair.
656    template <typename V>
657    bool isSecondInIteratorPair(V J, std::pair<
658           typename std::multimap<V, V>::iterator,
659           typename std::multimap<V, V>::iterator> PairRange) {
660      for (typename std::multimap<V, V>::iterator K = PairRange.first;
661           K != PairRange.second; ++K)
662        if (K->second == J) return true;
663
664      return false;
665    }
666  };
667
668  // This function implements one vectorization iteration on the provided
669  // basic block. It returns true if the block is changed.
670  bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
671    bool ShouldContinue;
672    BasicBlock::iterator Start = BB.getFirstInsertionPt();
673
674    std::vector<Value *> AllPairableInsts;
675    DenseMap<Value *, Value *> AllChosenPairs;
676    DenseSet<ValuePair> AllFixedOrderPairs;
677    DenseMap<VPPair, unsigned> AllPairConnectionTypes;
678    std::multimap<ValuePair, ValuePair> AllConnectedPairs, AllConnectedPairDeps;
679
680    do {
681      std::vector<Value *> PairableInsts;
682      std::multimap<Value *, Value *> CandidatePairs;
683      DenseSet<ValuePair> FixedOrderPairs;
684      DenseMap<ValuePair, int> CandidatePairCostSavings;
685      ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
686                                         FixedOrderPairs,
687                                         CandidatePairCostSavings,
688                                         PairableInsts, NonPow2Len);
689      if (PairableInsts.empty()) continue;
690
691      // Now we have a map of all of the pairable instructions and we need to
692      // select the best possible pairing. A good pairing is one such that the
693      // users of the pair are also paired. This defines a (directed) forest
694      // over the pairs such that two pairs are connected iff the second pair
695      // uses the first.
696
697      // Note that it only matters that both members of the second pair use some
698      // element of the first pair (to allow for splatting).
699
700      std::multimap<ValuePair, ValuePair> ConnectedPairs, ConnectedPairDeps;
701      DenseMap<VPPair, unsigned> PairConnectionTypes;
702      computeConnectedPairs(CandidatePairs, PairableInsts, ConnectedPairs,
703                            PairConnectionTypes);
704      if (ConnectedPairs.empty()) continue;
705
706      for (std::multimap<ValuePair, ValuePair>::iterator
707           I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
708           I != IE; ++I) {
709        ConnectedPairDeps.insert(VPPair(I->second, I->first));
710      }
711
712      // Build the pairable-instruction dependency map
713      DenseSet<ValuePair> PairableInstUsers;
714      buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
715
716      // There is now a graph of the connected pairs. For each variable, pick
717      // the pairing with the largest tree meeting the depth requirement on at
718      // least one branch. Then select all pairings that are part of that tree
719      // and remove them from the list of available pairings and pairable
720      // variables.
721
722      DenseMap<Value *, Value *> ChosenPairs;
723      choosePairs(CandidatePairs, CandidatePairCostSavings,
724        PairableInsts, FixedOrderPairs, PairConnectionTypes,
725        ConnectedPairs, ConnectedPairDeps,
726        PairableInstUsers, ChosenPairs);
727
728      if (ChosenPairs.empty()) continue;
729      AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
730                              PairableInsts.end());
731      AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
732
733      // Only for the chosen pairs, propagate information on fixed-order pairs,
734      // pair connections, and their types to the data structures used by the
735      // pair fusion procedures.
736      for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
737           IE = ChosenPairs.end(); I != IE; ++I) {
738        if (FixedOrderPairs.count(*I))
739          AllFixedOrderPairs.insert(*I);
740        else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
741          AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
742
743        for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
744             J != IE; ++J) {
745          DenseMap<VPPair, unsigned>::iterator K =
746            PairConnectionTypes.find(VPPair(*I, *J));
747          if (K != PairConnectionTypes.end()) {
748            AllPairConnectionTypes.insert(*K);
749          } else {
750            K = PairConnectionTypes.find(VPPair(*J, *I));
751            if (K != PairConnectionTypes.end())
752              AllPairConnectionTypes.insert(*K);
753          }
754        }
755      }
756
757      for (std::multimap<ValuePair, ValuePair>::iterator
758           I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
759           I != IE; ++I) {
760        if (AllPairConnectionTypes.count(*I)) {
761          AllConnectedPairs.insert(*I);
762          AllConnectedPairDeps.insert(VPPair(I->second, I->first));
763        }
764      }
765    } while (ShouldContinue);
766
767    if (AllChosenPairs.empty()) return false;
768    NumFusedOps += AllChosenPairs.size();
769
770    // A set of pairs has now been selected. It is now necessary to replace the
771    // paired instructions with vector instructions. For this procedure each
772    // operand must be replaced with a vector operand. This vector is formed
773    // by using build_vector on the old operands. The replaced values are then
774    // replaced with a vector_extract on the result.  Subsequent optimization
775    // passes should coalesce the build/extract combinations.
776
777    fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
778                    AllPairConnectionTypes,
779                    AllConnectedPairs, AllConnectedPairDeps);
780
781    // It is important to cleanup here so that future iterations of this
782    // function have less work to do.
783    (void) SimplifyInstructionsInBlock(&BB, TD, AA->getTargetLibraryInfo());
784    return true;
785  }
786
787  // This function returns true if the provided instruction is capable of being
788  // fused into a vector instruction. This determination is based only on the
789  // type and other attributes of the instruction.
790  bool BBVectorize::isInstVectorizable(Instruction *I,
791                                         bool &IsSimpleLoadStore) {
792    IsSimpleLoadStore = false;
793
794    if (CallInst *C = dyn_cast<CallInst>(I)) {
795      if (!isVectorizableIntrinsic(C))
796        return false;
797    } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
798      // Vectorize simple loads if possbile:
799      IsSimpleLoadStore = L->isSimple();
800      if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
801        return false;
802    } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
803      // Vectorize simple stores if possbile:
804      IsSimpleLoadStore = S->isSimple();
805      if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
806        return false;
807    } else if (CastInst *C = dyn_cast<CastInst>(I)) {
808      // We can vectorize casts, but not casts of pointer types, etc.
809      if (!Config.VectorizeCasts)
810        return false;
811
812      Type *SrcTy = C->getSrcTy();
813      if (!SrcTy->isSingleValueType())
814        return false;
815
816      Type *DestTy = C->getDestTy();
817      if (!DestTy->isSingleValueType())
818        return false;
819    } else if (isa<SelectInst>(I)) {
820      if (!Config.VectorizeSelect)
821        return false;
822    } else if (isa<CmpInst>(I)) {
823      if (!Config.VectorizeCmp)
824        return false;
825    } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
826      if (!Config.VectorizeGEP)
827        return false;
828
829      // Currently, vector GEPs exist only with one index.
830      if (G->getNumIndices() != 1)
831        return false;
832    } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
833        isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
834      return false;
835    }
836
837    // We can't vectorize memory operations without target data
838    if (TD == 0 && IsSimpleLoadStore)
839      return false;
840
841    Type *T1, *T2;
842    getInstructionTypes(I, T1, T2);
843
844    // Not every type can be vectorized...
845    if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
846        !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
847      return false;
848
849    if (T1->getScalarSizeInBits() == 1) {
850      if (!Config.VectorizeBools)
851        return false;
852    } else {
853      if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
854        return false;
855    }
856
857    if (T2->getScalarSizeInBits() == 1) {
858      if (!Config.VectorizeBools)
859        return false;
860    } else {
861      if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
862        return false;
863    }
864
865    if (!Config.VectorizeFloats
866        && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
867      return false;
868
869    // Don't vectorize target-specific types.
870    if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
871      return false;
872    if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
873      return false;
874
875    if ((!Config.VectorizePointers || TD == 0) &&
876        (T1->getScalarType()->isPointerTy() ||
877         T2->getScalarType()->isPointerTy()))
878      return false;
879
880    if (!VTTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
881                  T2->getPrimitiveSizeInBits() >= Config.VectorBits))
882      return false;
883
884    return true;
885  }
886
887  // This function returns true if the two provided instructions are compatible
888  // (meaning that they can be fused into a vector instruction). This assumes
889  // that I has already been determined to be vectorizable and that J is not
890  // in the use tree of I.
891  bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
892                       bool IsSimpleLoadStore, bool NonPow2Len,
893                       int &CostSavings, int &FixedOrder) {
894    DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
895                     " <-> " << *J << "\n");
896
897    CostSavings = 0;
898    FixedOrder = 0;
899
900    // Loads and stores can be merged if they have different alignments,
901    // but are otherwise the same.
902    if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
903                      (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
904      return false;
905
906    Type *IT1, *IT2, *JT1, *JT2;
907    getInstructionTypes(I, IT1, IT2);
908    getInstructionTypes(J, JT1, JT2);
909    unsigned MaxTypeBits = std::max(
910      IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
911      IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
912    if (!VTTI && MaxTypeBits > Config.VectorBits)
913      return false;
914
915    // FIXME: handle addsub-type operations!
916
917    if (IsSimpleLoadStore) {
918      Value *IPtr, *JPtr;
919      unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
920      int64_t OffsetInElmts = 0;
921      if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
922            IAddressSpace, JAddressSpace,
923            OffsetInElmts) && abs64(OffsetInElmts) == 1) {
924        FixedOrder = (int) OffsetInElmts;
925        unsigned BottomAlignment = IAlignment;
926        if (OffsetInElmts < 0) BottomAlignment = JAlignment;
927
928        Type *aTypeI = isa<StoreInst>(I) ?
929          cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
930        Type *aTypeJ = isa<StoreInst>(J) ?
931          cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
932        Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
933
934        if (Config.AlignedOnly) {
935          // An aligned load or store is possible only if the instruction
936          // with the lower offset has an alignment suitable for the
937          // vector type.
938
939          unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
940          if (BottomAlignment < VecAlignment)
941            return false;
942        }
943
944        if (VTTI) {
945          unsigned ICost = VTTI->getMemoryOpCost(I->getOpcode(), I->getType(),
946                                                 IAlignment, IAddressSpace);
947          unsigned JCost = VTTI->getMemoryOpCost(J->getOpcode(), J->getType(),
948                                                 JAlignment, JAddressSpace);
949          unsigned VCost = VTTI->getMemoryOpCost(I->getOpcode(), VType,
950                                                 BottomAlignment,
951                                                 IAddressSpace);
952          if (VCost > ICost + JCost)
953            return false;
954
955          // We don't want to fuse to a type that will be split, even
956          // if the two input types will also be split and there is no other
957          // associated cost.
958          unsigned VParts = VTTI->getNumberOfParts(VType);
959          if (VParts > 1)
960            return false;
961          else if (!VParts && VCost == ICost + JCost)
962            return false;
963
964          CostSavings = ICost + JCost - VCost;
965        }
966      } else {
967        return false;
968      }
969    } else if (VTTI) {
970      unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
971      unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
972      Type *VT1 = getVecTypeForPair(IT1, JT1),
973           *VT2 = getVecTypeForPair(IT2, JT2);
974      unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2);
975
976      if (VCost > ICost + JCost)
977        return false;
978
979      // We don't want to fuse to a type that will be split, even
980      // if the two input types will also be split and there is no other
981      // associated cost.
982      unsigned VParts = VTTI->getNumberOfParts(VT1);
983      if (VParts > 1)
984        return false;
985      else if (!VParts && VCost == ICost + JCost)
986        return false;
987
988      CostSavings = ICost + JCost - VCost;
989    }
990
991    // The powi intrinsic is special because only the first argument is
992    // vectorized, the second arguments must be equal.
993    CallInst *CI = dyn_cast<CallInst>(I);
994    Function *FI;
995    if (CI && (FI = CI->getCalledFunction()) &&
996        FI->getIntrinsicID() == Intrinsic::powi) {
997
998      Value *A1I = CI->getArgOperand(1),
999            *A1J = cast<CallInst>(J)->getArgOperand(1);
1000      const SCEV *A1ISCEV = SE->getSCEV(A1I),
1001                 *A1JSCEV = SE->getSCEV(A1J);
1002      return (A1ISCEV == A1JSCEV);
1003    }
1004
1005    return true;
1006  }
1007
1008  // Figure out whether or not J uses I and update the users and write-set
1009  // structures associated with I. Specifically, Users represents the set of
1010  // instructions that depend on I. WriteSet represents the set
1011  // of memory locations that are dependent on I. If UpdateUsers is true,
1012  // and J uses I, then Users is updated to contain J and WriteSet is updated
1013  // to contain any memory locations to which J writes. The function returns
1014  // true if J uses I. By default, alias analysis is used to determine
1015  // whether J reads from memory that overlaps with a location in WriteSet.
1016  // If LoadMoveSet is not null, then it is a previously-computed multimap
1017  // where the key is the memory-based user instruction and the value is
1018  // the instruction to be compared with I. So, if LoadMoveSet is provided,
1019  // then the alias analysis is not used. This is necessary because this
1020  // function is called during the process of moving instructions during
1021  // vectorization and the results of the alias analysis are not stable during
1022  // that process.
1023  bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
1024                       AliasSetTracker &WriteSet, Instruction *I,
1025                       Instruction *J, bool UpdateUsers,
1026                       std::multimap<Value *, Value *> *LoadMoveSet) {
1027    bool UsesI = false;
1028
1029    // This instruction may already be marked as a user due, for example, to
1030    // being a member of a selected pair.
1031    if (Users.count(J))
1032      UsesI = true;
1033
1034    if (!UsesI)
1035      for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
1036           JU != JE; ++JU) {
1037        Value *V = *JU;
1038        if (I == V || Users.count(V)) {
1039          UsesI = true;
1040          break;
1041        }
1042      }
1043    if (!UsesI && J->mayReadFromMemory()) {
1044      if (LoadMoveSet) {
1045        VPIteratorPair JPairRange = LoadMoveSet->equal_range(J);
1046        UsesI = isSecondInIteratorPair<Value*>(I, JPairRange);
1047      } else {
1048        for (AliasSetTracker::iterator W = WriteSet.begin(),
1049             WE = WriteSet.end(); W != WE; ++W) {
1050          if (W->aliasesUnknownInst(J, *AA)) {
1051            UsesI = true;
1052            break;
1053          }
1054        }
1055      }
1056    }
1057
1058    if (UsesI && UpdateUsers) {
1059      if (J->mayWriteToMemory()) WriteSet.add(J);
1060      Users.insert(J);
1061    }
1062
1063    return UsesI;
1064  }
1065
1066  // This function iterates over all instruction pairs in the provided
1067  // basic block and collects all candidate pairs for vectorization.
1068  bool BBVectorize::getCandidatePairs(BasicBlock &BB,
1069                       BasicBlock::iterator &Start,
1070                       std::multimap<Value *, Value *> &CandidatePairs,
1071                       DenseSet<ValuePair> &FixedOrderPairs,
1072                       DenseMap<ValuePair, int> &CandidatePairCostSavings,
1073                       std::vector<Value *> &PairableInsts, bool NonPow2Len) {
1074    BasicBlock::iterator E = BB.end();
1075    if (Start == E) return false;
1076
1077    bool ShouldContinue = false, IAfterStart = false;
1078    for (BasicBlock::iterator I = Start++; I != E; ++I) {
1079      if (I == Start) IAfterStart = true;
1080
1081      bool IsSimpleLoadStore;
1082      if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
1083
1084      // Look for an instruction with which to pair instruction *I...
1085      DenseSet<Value *> Users;
1086      AliasSetTracker WriteSet(*AA);
1087      bool JAfterStart = IAfterStart;
1088      BasicBlock::iterator J = llvm::next(I);
1089      for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
1090        if (J == Start) JAfterStart = true;
1091
1092        // Determine if J uses I, if so, exit the loop.
1093        bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
1094        if (Config.FastDep) {
1095          // Note: For this heuristic to be effective, independent operations
1096          // must tend to be intermixed. This is likely to be true from some
1097          // kinds of grouped loop unrolling (but not the generic LLVM pass),
1098          // but otherwise may require some kind of reordering pass.
1099
1100          // When using fast dependency analysis,
1101          // stop searching after first use:
1102          if (UsesI) break;
1103        } else {
1104          if (UsesI) continue;
1105        }
1106
1107        // J does not use I, and comes before the first use of I, so it can be
1108        // merged with I if the instructions are compatible.
1109        int CostSavings, FixedOrder;
1110        if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
1111            CostSavings, FixedOrder)) continue;
1112
1113        // J is a candidate for merging with I.
1114        if (!PairableInsts.size() ||
1115             PairableInsts[PairableInsts.size()-1] != I) {
1116          PairableInsts.push_back(I);
1117        }
1118
1119        CandidatePairs.insert(ValuePair(I, J));
1120        if (VTTI)
1121          CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
1122                                                            CostSavings));
1123
1124        if (FixedOrder == 1)
1125          FixedOrderPairs.insert(ValuePair(I, J));
1126        else if (FixedOrder == -1)
1127          FixedOrderPairs.insert(ValuePair(J, I));
1128
1129        // The next call to this function must start after the last instruction
1130        // selected during this invocation.
1131        if (JAfterStart) {
1132          Start = llvm::next(J);
1133          IAfterStart = JAfterStart = false;
1134        }
1135
1136        DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
1137                     << *I << " <-> " << *J << " (cost savings: " <<
1138                     CostSavings << ")\n");
1139
1140        // If we have already found too many pairs, break here and this function
1141        // will be called again starting after the last instruction selected
1142        // during this invocation.
1143        if (PairableInsts.size() >= Config.MaxInsts) {
1144          ShouldContinue = true;
1145          break;
1146        }
1147      }
1148
1149      if (ShouldContinue)
1150        break;
1151    }
1152
1153    DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
1154           << " instructions with candidate pairs\n");
1155
1156    return ShouldContinue;
1157  }
1158
1159  // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
1160  // it looks for pairs such that both members have an input which is an
1161  // output of PI or PJ.
1162  void BBVectorize::computePairsConnectedTo(
1163                      std::multimap<Value *, Value *> &CandidatePairs,
1164                      std::vector<Value *> &PairableInsts,
1165                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1166                      DenseMap<VPPair, unsigned> &PairConnectionTypes,
1167                      ValuePair P) {
1168    StoreInst *SI, *SJ;
1169
1170    // For each possible pairing for this variable, look at the uses of
1171    // the first value...
1172    for (Value::use_iterator I = P.first->use_begin(),
1173         E = P.first->use_end(); I != E; ++I) {
1174      if (isa<LoadInst>(*I)) {
1175        // A pair cannot be connected to a load because the load only takes one
1176        // operand (the address) and it is a scalar even after vectorization.
1177        continue;
1178      } else if ((SI = dyn_cast<StoreInst>(*I)) &&
1179                 P.first == SI->getPointerOperand()) {
1180        // Similarly, a pair cannot be connected to a store through its
1181        // pointer operand.
1182        continue;
1183      }
1184
1185      VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
1186
1187      // For each use of the first variable, look for uses of the second
1188      // variable...
1189      for (Value::use_iterator J = P.second->use_begin(),
1190           E2 = P.second->use_end(); J != E2; ++J) {
1191        if ((SJ = dyn_cast<StoreInst>(*J)) &&
1192            P.second == SJ->getPointerOperand())
1193          continue;
1194
1195        VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
1196
1197        // Look for <I, J>:
1198        if (isSecondInIteratorPair<Value*>(*J, IPairRange)) {
1199          VPPair VP(P, ValuePair(*I, *J));
1200          ConnectedPairs.insert(VP);
1201          PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
1202        }
1203
1204        // Look for <J, I>:
1205        if (isSecondInIteratorPair<Value*>(*I, JPairRange)) {
1206          VPPair VP(P, ValuePair(*J, *I));
1207          ConnectedPairs.insert(VP);
1208          PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
1209        }
1210      }
1211
1212      if (Config.SplatBreaksChain) continue;
1213      // Look for cases where just the first value in the pair is used by
1214      // both members of another pair (splatting).
1215      for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
1216        if ((SJ = dyn_cast<StoreInst>(*J)) &&
1217            P.first == SJ->getPointerOperand())
1218          continue;
1219
1220        if (isSecondInIteratorPair<Value*>(*J, IPairRange)) {
1221          VPPair VP(P, ValuePair(*I, *J));
1222          ConnectedPairs.insert(VP);
1223          PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1224        }
1225      }
1226    }
1227
1228    if (Config.SplatBreaksChain) return;
1229    // Look for cases where just the second value in the pair is used by
1230    // both members of another pair (splatting).
1231    for (Value::use_iterator I = P.second->use_begin(),
1232         E = P.second->use_end(); I != E; ++I) {
1233      if (isa<LoadInst>(*I))
1234        continue;
1235      else if ((SI = dyn_cast<StoreInst>(*I)) &&
1236               P.second == SI->getPointerOperand())
1237        continue;
1238
1239      VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
1240
1241      for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
1242        if ((SJ = dyn_cast<StoreInst>(*J)) &&
1243            P.second == SJ->getPointerOperand())
1244          continue;
1245
1246        if (isSecondInIteratorPair<Value*>(*J, IPairRange)) {
1247          VPPair VP(P, ValuePair(*I, *J));
1248          ConnectedPairs.insert(VP);
1249          PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1250        }
1251      }
1252    }
1253  }
1254
1255  // This function figures out which pairs are connected.  Two pairs are
1256  // connected if some output of the first pair forms an input to both members
1257  // of the second pair.
1258  void BBVectorize::computeConnectedPairs(
1259                      std::multimap<Value *, Value *> &CandidatePairs,
1260                      std::vector<Value *> &PairableInsts,
1261                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1262                      DenseMap<VPPair, unsigned> &PairConnectionTypes) {
1263
1264    for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1265         PE = PairableInsts.end(); PI != PE; ++PI) {
1266      VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
1267
1268      for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
1269           P != choiceRange.second; ++P)
1270        computePairsConnectedTo(CandidatePairs, PairableInsts,
1271                                ConnectedPairs, PairConnectionTypes, *P);
1272    }
1273
1274    DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
1275                 << " pair connections.\n");
1276  }
1277
1278  // This function builds a set of use tuples such that <A, B> is in the set
1279  // if B is in the use tree of A. If B is in the use tree of A, then B
1280  // depends on the output of A.
1281  void BBVectorize::buildDepMap(
1282                      BasicBlock &BB,
1283                      std::multimap<Value *, Value *> &CandidatePairs,
1284                      std::vector<Value *> &PairableInsts,
1285                      DenseSet<ValuePair> &PairableInstUsers) {
1286    DenseSet<Value *> IsInPair;
1287    for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
1288         E = CandidatePairs.end(); C != E; ++C) {
1289      IsInPair.insert(C->first);
1290      IsInPair.insert(C->second);
1291    }
1292
1293    // Iterate through the basic block, recording all Users of each
1294    // pairable instruction.
1295
1296    BasicBlock::iterator E = BB.end();
1297    for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1298      if (IsInPair.find(I) == IsInPair.end()) continue;
1299
1300      DenseSet<Value *> Users;
1301      AliasSetTracker WriteSet(*AA);
1302      for (BasicBlock::iterator J = llvm::next(I); J != E; ++J)
1303        (void) trackUsesOfI(Users, WriteSet, I, J);
1304
1305      for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1306           U != E; ++U)
1307        PairableInstUsers.insert(ValuePair(I, *U));
1308    }
1309  }
1310
1311  // Returns true if an input to pair P is an output of pair Q and also an
1312  // input of pair Q is an output of pair P. If this is the case, then these
1313  // two pairs cannot be simultaneously fused.
1314  bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1315                     DenseSet<ValuePair> &PairableInstUsers,
1316                     std::multimap<ValuePair, ValuePair> *PairableInstUserMap) {
1317    // Two pairs are in conflict if they are mutual Users of eachother.
1318    bool QUsesP = PairableInstUsers.count(ValuePair(P.first,  Q.first))  ||
1319                  PairableInstUsers.count(ValuePair(P.first,  Q.second)) ||
1320                  PairableInstUsers.count(ValuePair(P.second, Q.first))  ||
1321                  PairableInstUsers.count(ValuePair(P.second, Q.second));
1322    bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first,  P.first))  ||
1323                  PairableInstUsers.count(ValuePair(Q.first,  P.second)) ||
1324                  PairableInstUsers.count(ValuePair(Q.second, P.first))  ||
1325                  PairableInstUsers.count(ValuePair(Q.second, P.second));
1326    if (PairableInstUserMap) {
1327      // FIXME: The expensive part of the cycle check is not so much the cycle
1328      // check itself but this edge insertion procedure. This needs some
1329      // profiling and probably a different data structure (same is true of
1330      // most uses of std::multimap).
1331      if (PUsesQ) {
1332        VPPIteratorPair QPairRange = PairableInstUserMap->equal_range(Q);
1333        if (!isSecondInIteratorPair(P, QPairRange))
1334          PairableInstUserMap->insert(VPPair(Q, P));
1335      }
1336      if (QUsesP) {
1337        VPPIteratorPair PPairRange = PairableInstUserMap->equal_range(P);
1338        if (!isSecondInIteratorPair(Q, PPairRange))
1339          PairableInstUserMap->insert(VPPair(P, Q));
1340      }
1341    }
1342
1343    return (QUsesP && PUsesQ);
1344  }
1345
1346  // This function walks the use graph of current pairs to see if, starting
1347  // from P, the walk returns to P.
1348  bool BBVectorize::pairWillFormCycle(ValuePair P,
1349                       std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1350                       DenseSet<ValuePair> &CurrentPairs) {
1351    DEBUG(if (DebugCycleCheck)
1352            dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1353                   << *P.second << "\n");
1354    // A lookup table of visisted pairs is kept because the PairableInstUserMap
1355    // contains non-direct associations.
1356    DenseSet<ValuePair> Visited;
1357    SmallVector<ValuePair, 32> Q;
1358    // General depth-first post-order traversal:
1359    Q.push_back(P);
1360    do {
1361      ValuePair QTop = Q.pop_back_val();
1362      Visited.insert(QTop);
1363
1364      DEBUG(if (DebugCycleCheck)
1365              dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1366                     << *QTop.second << "\n");
1367      VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
1368      for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
1369           C != QPairRange.second; ++C) {
1370        if (C->second == P) {
1371          DEBUG(dbgs()
1372                 << "BBV: rejected to prevent non-trivial cycle formation: "
1373                 << *C->first.first << " <-> " << *C->first.second << "\n");
1374          return true;
1375        }
1376
1377        if (CurrentPairs.count(C->second) && !Visited.count(C->second))
1378          Q.push_back(C->second);
1379      }
1380    } while (!Q.empty());
1381
1382    return false;
1383  }
1384
1385  // This function builds the initial tree of connected pairs with the
1386  // pair J at the root.
1387  void BBVectorize::buildInitialTreeFor(
1388                      std::multimap<Value *, Value *> &CandidatePairs,
1389                      std::vector<Value *> &PairableInsts,
1390                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1391                      DenseSet<ValuePair> &PairableInstUsers,
1392                      DenseMap<Value *, Value *> &ChosenPairs,
1393                      DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
1394    // Each of these pairs is viewed as the root node of a Tree. The Tree
1395    // is then walked (depth-first). As this happens, we keep track of
1396    // the pairs that compose the Tree and the maximum depth of the Tree.
1397    SmallVector<ValuePairWithDepth, 32> Q;
1398    // General depth-first post-order traversal:
1399    Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1400    do {
1401      ValuePairWithDepth QTop = Q.back();
1402
1403      // Push each child onto the queue:
1404      bool MoreChildren = false;
1405      size_t MaxChildDepth = QTop.second;
1406      VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
1407      for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
1408           k != qtRange.second; ++k) {
1409        // Make sure that this child pair is still a candidate:
1410        bool IsStillCand = false;
1411        VPIteratorPair checkRange =
1412          CandidatePairs.equal_range(k->second.first);
1413        for (std::multimap<Value *, Value *>::iterator m = checkRange.first;
1414             m != checkRange.second; ++m) {
1415          if (m->second == k->second.second) {
1416            IsStillCand = true;
1417            break;
1418          }
1419        }
1420
1421        if (IsStillCand) {
1422          DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
1423          if (C == Tree.end()) {
1424            size_t d = getDepthFactor(k->second.first);
1425            Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
1426            MoreChildren = true;
1427          } else {
1428            MaxChildDepth = std::max(MaxChildDepth, C->second);
1429          }
1430        }
1431      }
1432
1433      if (!MoreChildren) {
1434        // Record the current pair as part of the Tree:
1435        Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1436        Q.pop_back();
1437      }
1438    } while (!Q.empty());
1439  }
1440
1441  // Given some initial tree, prune it by removing conflicting pairs (pairs
1442  // that cannot be simultaneously chosen for vectorization).
1443  void BBVectorize::pruneTreeFor(
1444                      std::multimap<Value *, Value *> &CandidatePairs,
1445                      std::vector<Value *> &PairableInsts,
1446                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1447                      DenseSet<ValuePair> &PairableInstUsers,
1448                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1449                      DenseMap<Value *, Value *> &ChosenPairs,
1450                      DenseMap<ValuePair, size_t> &Tree,
1451                      DenseSet<ValuePair> &PrunedTree, ValuePair J,
1452                      bool UseCycleCheck) {
1453    SmallVector<ValuePairWithDepth, 32> Q;
1454    // General depth-first post-order traversal:
1455    Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1456    do {
1457      ValuePairWithDepth QTop = Q.pop_back_val();
1458      PrunedTree.insert(QTop.first);
1459
1460      // Visit each child, pruning as necessary...
1461      DenseMap<ValuePair, size_t> BestChildren;
1462      VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
1463      for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
1464           K != QTopRange.second; ++K) {
1465        DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
1466        if (C == Tree.end()) continue;
1467
1468        // This child is in the Tree, now we need to make sure it is the
1469        // best of any conflicting children. There could be multiple
1470        // conflicting children, so first, determine if we're keeping
1471        // this child, then delete conflicting children as necessary.
1472
1473        // It is also necessary to guard against pairing-induced
1474        // dependencies. Consider instructions a .. x .. y .. b
1475        // such that (a,b) are to be fused and (x,y) are to be fused
1476        // but a is an input to x and b is an output from y. This
1477        // means that y cannot be moved after b but x must be moved
1478        // after b for (a,b) to be fused. In other words, after
1479        // fusing (a,b) we have y .. a/b .. x where y is an input
1480        // to a/b and x is an output to a/b: x and y can no longer
1481        // be legally fused. To prevent this condition, we must
1482        // make sure that a child pair added to the Tree is not
1483        // both an input and output of an already-selected pair.
1484
1485        // Pairing-induced dependencies can also form from more complicated
1486        // cycles. The pair vs. pair conflicts are easy to check, and so
1487        // that is done explicitly for "fast rejection", and because for
1488        // child vs. child conflicts, we may prefer to keep the current
1489        // pair in preference to the already-selected child.
1490        DenseSet<ValuePair> CurrentPairs;
1491
1492        bool CanAdd = true;
1493        for (DenseMap<ValuePair, size_t>::iterator C2
1494              = BestChildren.begin(), E2 = BestChildren.end();
1495             C2 != E2; ++C2) {
1496          if (C2->first.first == C->first.first ||
1497              C2->first.first == C->first.second ||
1498              C2->first.second == C->first.first ||
1499              C2->first.second == C->first.second ||
1500              pairsConflict(C2->first, C->first, PairableInstUsers,
1501                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1502            if (C2->second >= C->second) {
1503              CanAdd = false;
1504              break;
1505            }
1506
1507            CurrentPairs.insert(C2->first);
1508          }
1509        }
1510        if (!CanAdd) continue;
1511
1512        // Even worse, this child could conflict with another node already
1513        // selected for the Tree. If that is the case, ignore this child.
1514        for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1515             E2 = PrunedTree.end(); T != E2; ++T) {
1516          if (T->first == C->first.first ||
1517              T->first == C->first.second ||
1518              T->second == C->first.first ||
1519              T->second == C->first.second ||
1520              pairsConflict(*T, C->first, PairableInstUsers,
1521                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1522            CanAdd = false;
1523            break;
1524          }
1525
1526          CurrentPairs.insert(*T);
1527        }
1528        if (!CanAdd) continue;
1529
1530        // And check the queue too...
1531        for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1532             E2 = Q.end(); C2 != E2; ++C2) {
1533          if (C2->first.first == C->first.first ||
1534              C2->first.first == C->first.second ||
1535              C2->first.second == C->first.first ||
1536              C2->first.second == C->first.second ||
1537              pairsConflict(C2->first, C->first, PairableInstUsers,
1538                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1539            CanAdd = false;
1540            break;
1541          }
1542
1543          CurrentPairs.insert(C2->first);
1544        }
1545        if (!CanAdd) continue;
1546
1547        // Last but not least, check for a conflict with any of the
1548        // already-chosen pairs.
1549        for (DenseMap<Value *, Value *>::iterator C2 =
1550              ChosenPairs.begin(), E2 = ChosenPairs.end();
1551             C2 != E2; ++C2) {
1552          if (pairsConflict(*C2, C->first, PairableInstUsers,
1553                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1554            CanAdd = false;
1555            break;
1556          }
1557
1558          CurrentPairs.insert(*C2);
1559        }
1560        if (!CanAdd) continue;
1561
1562        // To check for non-trivial cycles formed by the addition of the
1563        // current pair we've formed a list of all relevant pairs, now use a
1564        // graph walk to check for a cycle. We start from the current pair and
1565        // walk the use tree to see if we again reach the current pair. If we
1566        // do, then the current pair is rejected.
1567
1568        // FIXME: It may be more efficient to use a topological-ordering
1569        // algorithm to improve the cycle check. This should be investigated.
1570        if (UseCycleCheck &&
1571            pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1572          continue;
1573
1574        // This child can be added, but we may have chosen it in preference
1575        // to an already-selected child. Check for this here, and if a
1576        // conflict is found, then remove the previously-selected child
1577        // before adding this one in its place.
1578        for (DenseMap<ValuePair, size_t>::iterator C2
1579              = BestChildren.begin(); C2 != BestChildren.end();) {
1580          if (C2->first.first == C->first.first ||
1581              C2->first.first == C->first.second ||
1582              C2->first.second == C->first.first ||
1583              C2->first.second == C->first.second ||
1584              pairsConflict(C2->first, C->first, PairableInstUsers))
1585            BestChildren.erase(C2++);
1586          else
1587            ++C2;
1588        }
1589
1590        BestChildren.insert(ValuePairWithDepth(C->first, C->second));
1591      }
1592
1593      for (DenseMap<ValuePair, size_t>::iterator C
1594            = BestChildren.begin(), E2 = BestChildren.end();
1595           C != E2; ++C) {
1596        size_t DepthF = getDepthFactor(C->first.first);
1597        Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1598      }
1599    } while (!Q.empty());
1600  }
1601
1602  // This function finds the best tree of mututally-compatible connected
1603  // pairs, given the choice of root pairs as an iterator range.
1604  void BBVectorize::findBestTreeFor(
1605                      std::multimap<Value *, Value *> &CandidatePairs,
1606                      DenseMap<ValuePair, int> &CandidatePairCostSavings,
1607                      std::vector<Value *> &PairableInsts,
1608                      DenseSet<ValuePair> &FixedOrderPairs,
1609                      DenseMap<VPPair, unsigned> &PairConnectionTypes,
1610                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1611                      std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
1612                      DenseSet<ValuePair> &PairableInstUsers,
1613                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1614                      DenseMap<Value *, Value *> &ChosenPairs,
1615                      DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1616                      int &BestEffSize, VPIteratorPair ChoiceRange,
1617                      bool UseCycleCheck) {
1618    for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
1619         J != ChoiceRange.second; ++J) {
1620
1621      // Before going any further, make sure that this pair does not
1622      // conflict with any already-selected pairs (see comment below
1623      // near the Tree pruning for more details).
1624      DenseSet<ValuePair> ChosenPairSet;
1625      bool DoesConflict = false;
1626      for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1627           E = ChosenPairs.end(); C != E; ++C) {
1628        if (pairsConflict(*C, *J, PairableInstUsers,
1629                          UseCycleCheck ? &PairableInstUserMap : 0)) {
1630          DoesConflict = true;
1631          break;
1632        }
1633
1634        ChosenPairSet.insert(*C);
1635      }
1636      if (DoesConflict) continue;
1637
1638      if (UseCycleCheck &&
1639          pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1640        continue;
1641
1642      DenseMap<ValuePair, size_t> Tree;
1643      buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1644                          PairableInstUsers, ChosenPairs, Tree, *J);
1645
1646      // Because we'll keep the child with the largest depth, the largest
1647      // depth is still the same in the unpruned Tree.
1648      size_t MaxDepth = Tree.lookup(*J);
1649
1650      DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1651                   << *J->first << " <-> " << *J->second << "} of depth " <<
1652                   MaxDepth << " and size " << Tree.size() << "\n");
1653
1654      // At this point the Tree has been constructed, but, may contain
1655      // contradictory children (meaning that different children of
1656      // some tree node may be attempting to fuse the same instruction).
1657      // So now we walk the tree again, in the case of a conflict,
1658      // keep only the child with the largest depth. To break a tie,
1659      // favor the first child.
1660
1661      DenseSet<ValuePair> PrunedTree;
1662      pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1663                   PairableInstUsers, PairableInstUserMap, ChosenPairs, Tree,
1664                   PrunedTree, *J, UseCycleCheck);
1665
1666      int EffSize = 0;
1667      if (VTTI) {
1668        // The node weights represent the cost savings associated with
1669        // fusing the pair of instructions.
1670        for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1671             E = PrunedTree.end(); S != E; ++S) {
1672          if (getDepthFactor(S->first))
1673            EffSize += CandidatePairCostSavings.find(*S)->second;
1674
1675        // The edge weights contribute in a negative sense: they represent
1676        // the cost of shuffles.
1677          VPPIteratorPair IP = ConnectedPairDeps.equal_range(*S);
1678          if (IP.first != ConnectedPairDeps.end()) {
1679            unsigned NumDepsDirect = 0, NumDepsSwap = 0;
1680            for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
1681                 Q != IP.second; ++Q) {
1682              DenseMap<VPPair, unsigned>::iterator R =
1683                PairConnectionTypes.find(VPPair(Q->second, Q->first));
1684              assert(R != PairConnectionTypes.end() &&
1685                     "Cannot find pair connection type");
1686              if (R->second == PairConnectionDirect)
1687                ++NumDepsDirect;
1688              else if (R->second == PairConnectionSwap)
1689                ++NumDepsSwap;
1690            }
1691
1692            // If there are more swaps than direct connections, then
1693            // the pair order will be flipped during fusion. So the real
1694            // number of swaps is the minimum number.
1695            bool FlipOrder = !FixedOrderPairs.count(*S) &&
1696              ((NumDepsSwap > NumDepsDirect) ||
1697                FixedOrderPairs.count(ValuePair(S->second, S->first)));
1698
1699            for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
1700                 Q != IP.second; ++Q) {
1701              DenseMap<VPPair, unsigned>::iterator R =
1702                PairConnectionTypes.find(VPPair(Q->second, Q->first));
1703              assert(R != PairConnectionTypes.end() &&
1704                     "Cannot find pair connection type");
1705              Type *Ty1 = Q->second.first->getType(),
1706                   *Ty2 = Q->second.second->getType();
1707              Type *VTy = getVecTypeForPair(Ty1, Ty2);
1708              if ((R->second == PairConnectionDirect && FlipOrder) ||
1709                  (R->second == PairConnectionSwap && !FlipOrder)  ||
1710                  R->second == PairConnectionSplat)
1711                EffSize -= (int) getInstrCost(Instruction::ShuffleVector,
1712                                              VTy, VTy);
1713            }
1714          }
1715        }
1716      } else {
1717        for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1718             E = PrunedTree.end(); S != E; ++S)
1719          EffSize += (int) getDepthFactor(S->first);
1720      }
1721
1722      DEBUG(if (DebugPairSelection)
1723             dbgs() << "BBV: found pruned Tree for pair {"
1724             << *J->first << " <-> " << *J->second << "} of depth " <<
1725             MaxDepth << " and size " << PrunedTree.size() <<
1726            " (effective size: " << EffSize << ")\n");
1727      if (MaxDepth >= Config.ReqChainDepth &&
1728          EffSize > 0 && EffSize > BestEffSize) {
1729        BestMaxDepth = MaxDepth;
1730        BestEffSize = EffSize;
1731        BestTree = PrunedTree;
1732      }
1733    }
1734  }
1735
1736  // Given the list of candidate pairs, this function selects those
1737  // that will be fused into vector instructions.
1738  void BBVectorize::choosePairs(
1739                      std::multimap<Value *, Value *> &CandidatePairs,
1740                      DenseMap<ValuePair, int> &CandidatePairCostSavings,
1741                      std::vector<Value *> &PairableInsts,
1742                      DenseSet<ValuePair> &FixedOrderPairs,
1743                      DenseMap<VPPair, unsigned> &PairConnectionTypes,
1744                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1745                      std::multimap<ValuePair, ValuePair> &ConnectedPairDeps,
1746                      DenseSet<ValuePair> &PairableInstUsers,
1747                      DenseMap<Value *, Value *>& ChosenPairs) {
1748    bool UseCycleCheck =
1749     CandidatePairs.size() <= Config.MaxCandPairsForCycleCheck;
1750    std::multimap<ValuePair, ValuePair> PairableInstUserMap;
1751    for (std::vector<Value *>::iterator I = PairableInsts.begin(),
1752         E = PairableInsts.end(); I != E; ++I) {
1753      // The number of possible pairings for this variable:
1754      size_t NumChoices = CandidatePairs.count(*I);
1755      if (!NumChoices) continue;
1756
1757      VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
1758
1759      // The best pair to choose and its tree:
1760      size_t BestMaxDepth = 0;
1761      int BestEffSize = 0;
1762      DenseSet<ValuePair> BestTree;
1763      findBestTreeFor(CandidatePairs, CandidatePairCostSavings,
1764                      PairableInsts, FixedOrderPairs, PairConnectionTypes,
1765                      ConnectedPairs, ConnectedPairDeps,
1766                      PairableInstUsers, PairableInstUserMap, ChosenPairs,
1767                      BestTree, BestMaxDepth, BestEffSize, ChoiceRange,
1768                      UseCycleCheck);
1769
1770      // A tree has been chosen (or not) at this point. If no tree was
1771      // chosen, then this instruction, I, cannot be paired (and is no longer
1772      // considered).
1773
1774      DEBUG(if (BestTree.size() > 0)
1775              dbgs() << "BBV: selected pairs in the best tree for: "
1776                     << *cast<Instruction>(*I) << "\n");
1777
1778      for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
1779           SE2 = BestTree.end(); S != SE2; ++S) {
1780        // Insert the members of this tree into the list of chosen pairs.
1781        ChosenPairs.insert(ValuePair(S->first, S->second));
1782        DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
1783               *S->second << "\n");
1784
1785        // Remove all candidate pairs that have values in the chosen tree.
1786        for (std::multimap<Value *, Value *>::iterator K =
1787               CandidatePairs.begin(); K != CandidatePairs.end();) {
1788          if (K->first == S->first || K->second == S->first ||
1789              K->second == S->second || K->first == S->second) {
1790            // Don't remove the actual pair chosen so that it can be used
1791            // in subsequent tree selections.
1792            if (!(K->first == S->first && K->second == S->second))
1793              CandidatePairs.erase(K++);
1794            else
1795              ++K;
1796          } else {
1797            ++K;
1798          }
1799        }
1800      }
1801    }
1802
1803    DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
1804  }
1805
1806  std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
1807                     unsigned n = 0) {
1808    if (!I->hasName())
1809      return "";
1810
1811    return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
1812             (n > 0 ? "." + utostr(n) : "")).str();
1813  }
1814
1815  // Returns the value that is to be used as the pointer input to the vector
1816  // instruction that fuses I with J.
1817  Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
1818                     Instruction *I, Instruction *J, unsigned o) {
1819    Value *IPtr, *JPtr;
1820    unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
1821    int64_t OffsetInElmts;
1822
1823    // Note: the analysis might fail here, that is why the pair order has
1824    // been precomputed (OffsetInElmts must be unused here).
1825    (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
1826                          IAddressSpace, JAddressSpace,
1827                          OffsetInElmts, false);
1828
1829    // The pointer value is taken to be the one with the lowest offset.
1830    Value *VPtr = IPtr;
1831
1832    Type *ArgTypeI = cast<PointerType>(IPtr->getType())->getElementType();
1833    Type *ArgTypeJ = cast<PointerType>(JPtr->getType())->getElementType();
1834    Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
1835    Type *VArgPtrType = PointerType::get(VArgType,
1836      cast<PointerType>(IPtr->getType())->getAddressSpace());
1837    return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
1838                        /* insert before */ I);
1839  }
1840
1841  void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
1842                     unsigned MaskOffset, unsigned NumInElem,
1843                     unsigned NumInElem1, unsigned IdxOffset,
1844                     std::vector<Constant*> &Mask) {
1845    unsigned NumElem1 = cast<VectorType>(J->getType())->getNumElements();
1846    for (unsigned v = 0; v < NumElem1; ++v) {
1847      int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
1848      if (m < 0) {
1849        Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
1850      } else {
1851        unsigned mm = m + (int) IdxOffset;
1852        if (m >= (int) NumInElem1)
1853          mm += (int) NumInElem;
1854
1855        Mask[v+MaskOffset] =
1856          ConstantInt::get(Type::getInt32Ty(Context), mm);
1857      }
1858    }
1859  }
1860
1861  // Returns the value that is to be used as the vector-shuffle mask to the
1862  // vector instruction that fuses I with J.
1863  Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
1864                     Instruction *I, Instruction *J) {
1865    // This is the shuffle mask. We need to append the second
1866    // mask to the first, and the numbers need to be adjusted.
1867
1868    Type *ArgTypeI = I->getType();
1869    Type *ArgTypeJ = J->getType();
1870    Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
1871
1872    unsigned NumElemI = cast<VectorType>(ArgTypeI)->getNumElements();
1873
1874    // Get the total number of elements in the fused vector type.
1875    // By definition, this must equal the number of elements in
1876    // the final mask.
1877    unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
1878    std::vector<Constant*> Mask(NumElem);
1879
1880    Type *OpTypeI = I->getOperand(0)->getType();
1881    unsigned NumInElemI = cast<VectorType>(OpTypeI)->getNumElements();
1882    Type *OpTypeJ = J->getOperand(0)->getType();
1883    unsigned NumInElemJ = cast<VectorType>(OpTypeJ)->getNumElements();
1884
1885    // The fused vector will be:
1886    // -----------------------------------------------------
1887    // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
1888    // -----------------------------------------------------
1889    // from which we'll extract NumElem total elements (where the first NumElemI
1890    // of them come from the mask in I and the remainder come from the mask
1891    // in J.
1892
1893    // For the mask from the first pair...
1894    fillNewShuffleMask(Context, I, 0,        NumInElemJ, NumInElemI,
1895                       0,          Mask);
1896
1897    // For the mask from the second pair...
1898    fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
1899                       NumInElemI, Mask);
1900
1901    return ConstantVector::get(Mask);
1902  }
1903
1904  bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
1905                                  Instruction *J, unsigned o, Value *&LOp,
1906                                  unsigned numElemL,
1907                                  Type *ArgTypeL, Type *ArgTypeH,
1908                                  bool IBeforeJ, unsigned IdxOff) {
1909    bool ExpandedIEChain = false;
1910    if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
1911      // If we have a pure insertelement chain, then this can be rewritten
1912      // into a chain that directly builds the larger type.
1913      bool PureChain = true;
1914      InsertElementInst *LIENext = LIE;
1915      do {
1916        if (!isa<UndefValue>(LIENext->getOperand(0)) &&
1917            !isa<InsertElementInst>(LIENext->getOperand(0))) {
1918          PureChain = false;
1919          break;
1920        }
1921      } while ((LIENext =
1922                 dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
1923
1924      if (PureChain) {
1925        SmallVector<Value *, 8> VectElemts(numElemL,
1926          UndefValue::get(ArgTypeL->getScalarType()));
1927        InsertElementInst *LIENext = LIE;
1928        do {
1929          unsigned Idx =
1930            cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
1931          VectElemts[Idx] = LIENext->getOperand(1);
1932        } while ((LIENext =
1933                   dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
1934
1935        LIENext = 0;
1936        Value *LIEPrev = UndefValue::get(ArgTypeH);
1937        for (unsigned i = 0; i < numElemL; ++i) {
1938          if (isa<UndefValue>(VectElemts[i])) continue;
1939          LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
1940                             ConstantInt::get(Type::getInt32Ty(Context),
1941                                              i + IdxOff),
1942                             getReplacementName(IBeforeJ ? I : J,
1943                                                true, o, i+1));
1944          LIENext->insertBefore(IBeforeJ ? J : I);
1945          LIEPrev = LIENext;
1946        }
1947
1948        LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
1949        ExpandedIEChain = true;
1950      }
1951    }
1952
1953    return ExpandedIEChain;
1954  }
1955
1956  // Returns the value to be used as the specified operand of the vector
1957  // instruction that fuses I with J.
1958  Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
1959                     Instruction *J, unsigned o, bool IBeforeJ) {
1960    Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1961    Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1962
1963    // Compute the fused vector type for this operand
1964    Type *ArgTypeI = I->getOperand(o)->getType();
1965    Type *ArgTypeJ = J->getOperand(o)->getType();
1966    VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
1967
1968    Instruction *L = I, *H = J;
1969    Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
1970
1971    unsigned numElemL;
1972    if (ArgTypeL->isVectorTy())
1973      numElemL = cast<VectorType>(ArgTypeL)->getNumElements();
1974    else
1975      numElemL = 1;
1976
1977    unsigned numElemH;
1978    if (ArgTypeH->isVectorTy())
1979      numElemH = cast<VectorType>(ArgTypeH)->getNumElements();
1980    else
1981      numElemH = 1;
1982
1983    Value *LOp = L->getOperand(o);
1984    Value *HOp = H->getOperand(o);
1985    unsigned numElem = VArgType->getNumElements();
1986
1987    // First, we check if we can reuse the "original" vector outputs (if these
1988    // exist). We might need a shuffle.
1989    ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
1990    ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
1991    ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
1992    ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
1993
1994    // FIXME: If we're fusing shuffle instructions, then we can't apply this
1995    // optimization. The input vectors to the shuffle might be a different
1996    // length from the shuffle outputs. Unfortunately, the replacement
1997    // shuffle mask has already been formed, and the mask entries are sensitive
1998    // to the sizes of the inputs.
1999    bool IsSizeChangeShuffle =
2000      isa<ShuffleVectorInst>(L) &&
2001        (LOp->getType() != L->getType() || HOp->getType() != H->getType());
2002
2003    if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
2004      // We can have at most two unique vector inputs.
2005      bool CanUseInputs = true;
2006      Value *I1, *I2 = 0;
2007      if (LEE) {
2008        I1 = LEE->getOperand(0);
2009      } else {
2010        I1 = LSV->getOperand(0);
2011        I2 = LSV->getOperand(1);
2012        if (I2 == I1 || isa<UndefValue>(I2))
2013          I2 = 0;
2014      }
2015
2016      if (HEE) {
2017        Value *I3 = HEE->getOperand(0);
2018        if (!I2 && I3 != I1)
2019          I2 = I3;
2020        else if (I3 != I1 && I3 != I2)
2021          CanUseInputs = false;
2022      } else {
2023        Value *I3 = HSV->getOperand(0);
2024        if (!I2 && I3 != I1)
2025          I2 = I3;
2026        else if (I3 != I1 && I3 != I2)
2027          CanUseInputs = false;
2028
2029        if (CanUseInputs) {
2030          Value *I4 = HSV->getOperand(1);
2031          if (!isa<UndefValue>(I4)) {
2032            if (!I2 && I4 != I1)
2033              I2 = I4;
2034            else if (I4 != I1 && I4 != I2)
2035              CanUseInputs = false;
2036          }
2037        }
2038      }
2039
2040      if (CanUseInputs) {
2041        unsigned LOpElem =
2042          cast<VectorType>(cast<Instruction>(LOp)->getOperand(0)->getType())
2043            ->getNumElements();
2044        unsigned HOpElem =
2045          cast<VectorType>(cast<Instruction>(HOp)->getOperand(0)->getType())
2046            ->getNumElements();
2047
2048        // We have one or two input vectors. We need to map each index of the
2049        // operands to the index of the original vector.
2050        SmallVector<std::pair<int, int>, 8>  II(numElem);
2051        for (unsigned i = 0; i < numElemL; ++i) {
2052          int Idx, INum;
2053          if (LEE) {
2054            Idx =
2055              cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
2056            INum = LEE->getOperand(0) == I1 ? 0 : 1;
2057          } else {
2058            Idx = LSV->getMaskValue(i);
2059            if (Idx < (int) LOpElem) {
2060              INum = LSV->getOperand(0) == I1 ? 0 : 1;
2061            } else {
2062              Idx -= LOpElem;
2063              INum = LSV->getOperand(1) == I1 ? 0 : 1;
2064            }
2065          }
2066
2067          II[i] = std::pair<int, int>(Idx, INum);
2068        }
2069        for (unsigned i = 0; i < numElemH; ++i) {
2070          int Idx, INum;
2071          if (HEE) {
2072            Idx =
2073              cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
2074            INum = HEE->getOperand(0) == I1 ? 0 : 1;
2075          } else {
2076            Idx = HSV->getMaskValue(i);
2077            if (Idx < (int) HOpElem) {
2078              INum = HSV->getOperand(0) == I1 ? 0 : 1;
2079            } else {
2080              Idx -= HOpElem;
2081              INum = HSV->getOperand(1) == I1 ? 0 : 1;
2082            }
2083          }
2084
2085          II[i + numElemL] = std::pair<int, int>(Idx, INum);
2086        }
2087
2088        // We now have an array which tells us from which index of which
2089        // input vector each element of the operand comes.
2090        VectorType *I1T = cast<VectorType>(I1->getType());
2091        unsigned I1Elem = I1T->getNumElements();
2092
2093        if (!I2) {
2094          // In this case there is only one underlying vector input. Check for
2095          // the trivial case where we can use the input directly.
2096          if (I1Elem == numElem) {
2097            bool ElemInOrder = true;
2098            for (unsigned i = 0; i < numElem; ++i) {
2099              if (II[i].first != (int) i && II[i].first != -1) {
2100                ElemInOrder = false;
2101                break;
2102              }
2103            }
2104
2105            if (ElemInOrder)
2106              return I1;
2107          }
2108
2109          // A shuffle is needed.
2110          std::vector<Constant *> Mask(numElem);
2111          for (unsigned i = 0; i < numElem; ++i) {
2112            int Idx = II[i].first;
2113            if (Idx == -1)
2114              Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
2115            else
2116              Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2117          }
2118
2119          Instruction *S =
2120            new ShuffleVectorInst(I1, UndefValue::get(I1T),
2121                                  ConstantVector::get(Mask),
2122                                  getReplacementName(IBeforeJ ? I : J,
2123                                                     true, o));
2124          S->insertBefore(IBeforeJ ? J : I);
2125          return S;
2126        }
2127
2128        VectorType *I2T = cast<VectorType>(I2->getType());
2129        unsigned I2Elem = I2T->getNumElements();
2130
2131        // This input comes from two distinct vectors. The first step is to
2132        // make sure that both vectors are the same length. If not, the
2133        // smaller one will need to grow before they can be shuffled together.
2134        if (I1Elem < I2Elem) {
2135          std::vector<Constant *> Mask(I2Elem);
2136          unsigned v = 0;
2137          for (; v < I1Elem; ++v)
2138            Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2139          for (; v < I2Elem; ++v)
2140            Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2141
2142          Instruction *NewI1 =
2143            new ShuffleVectorInst(I1, UndefValue::get(I1T),
2144                                  ConstantVector::get(Mask),
2145                                  getReplacementName(IBeforeJ ? I : J,
2146                                                     true, o, 1));
2147          NewI1->insertBefore(IBeforeJ ? J : I);
2148          I1 = NewI1;
2149          I1T = I2T;
2150          I1Elem = I2Elem;
2151        } else if (I1Elem > I2Elem) {
2152          std::vector<Constant *> Mask(I1Elem);
2153          unsigned v = 0;
2154          for (; v < I2Elem; ++v)
2155            Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2156          for (; v < I1Elem; ++v)
2157            Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2158
2159          Instruction *NewI2 =
2160            new ShuffleVectorInst(I2, UndefValue::get(I2T),
2161                                  ConstantVector::get(Mask),
2162                                  getReplacementName(IBeforeJ ? I : J,
2163                                                     true, o, 1));
2164          NewI2->insertBefore(IBeforeJ ? J : I);
2165          I2 = NewI2;
2166          I2T = I1T;
2167          I2Elem = I1Elem;
2168        }
2169
2170        // Now that both I1 and I2 are the same length we can shuffle them
2171        // together (and use the result).
2172        std::vector<Constant *> Mask(numElem);
2173        for (unsigned v = 0; v < numElem; ++v) {
2174          if (II[v].first == -1) {
2175            Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2176          } else {
2177            int Idx = II[v].first + II[v].second * I1Elem;
2178            Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2179          }
2180        }
2181
2182        Instruction *NewOp =
2183          new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
2184                                getReplacementName(IBeforeJ ? I : J, true, o));
2185        NewOp->insertBefore(IBeforeJ ? J : I);
2186        return NewOp;
2187      }
2188    }
2189
2190    Type *ArgType = ArgTypeL;
2191    if (numElemL < numElemH) {
2192      if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
2193                                         ArgTypeL, VArgType, IBeforeJ, 1)) {
2194        // This is another short-circuit case: we're combining a scalar into
2195        // a vector that is formed by an IE chain. We've just expanded the IE
2196        // chain, now insert the scalar and we're done.
2197
2198        Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
2199                           getReplacementName(IBeforeJ ? I : J, true, o));
2200        S->insertBefore(IBeforeJ ? J : I);
2201        return S;
2202      } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
2203                                ArgTypeH, IBeforeJ)) {
2204        // The two vector inputs to the shuffle must be the same length,
2205        // so extend the smaller vector to be the same length as the larger one.
2206        Instruction *NLOp;
2207        if (numElemL > 1) {
2208
2209          std::vector<Constant *> Mask(numElemH);
2210          unsigned v = 0;
2211          for (; v < numElemL; ++v)
2212            Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2213          for (; v < numElemH; ++v)
2214            Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2215
2216          NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2217                                       ConstantVector::get(Mask),
2218                                       getReplacementName(IBeforeJ ? I : J,
2219                                                          true, o, 1));
2220        } else {
2221          NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2222                                           getReplacementName(IBeforeJ ? I : J,
2223                                                              true, o, 1));
2224        }
2225
2226        NLOp->insertBefore(IBeforeJ ? J : I);
2227        LOp = NLOp;
2228      }
2229
2230      ArgType = ArgTypeH;
2231    } else if (numElemL > numElemH) {
2232      if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2233                                         ArgTypeH, VArgType, IBeforeJ)) {
2234        Instruction *S =
2235          InsertElementInst::Create(LOp, HOp,
2236                                    ConstantInt::get(Type::getInt32Ty(Context),
2237                                                     numElemL),
2238                                    getReplacementName(IBeforeJ ? I : J,
2239                                                       true, o));
2240        S->insertBefore(IBeforeJ ? J : I);
2241        return S;
2242      } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2243                                ArgTypeL, IBeforeJ)) {
2244        Instruction *NHOp;
2245        if (numElemH > 1) {
2246          std::vector<Constant *> Mask(numElemL);
2247          unsigned v = 0;
2248          for (; v < numElemH; ++v)
2249            Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2250          for (; v < numElemL; ++v)
2251            Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2252
2253          NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2254                                       ConstantVector::get(Mask),
2255                                       getReplacementName(IBeforeJ ? I : J,
2256                                                          true, o, 1));
2257        } else {
2258          NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2259                                           getReplacementName(IBeforeJ ? I : J,
2260                                                              true, o, 1));
2261        }
2262
2263        NHOp->insertBefore(IBeforeJ ? J : I);
2264        HOp = NHOp;
2265      }
2266    }
2267
2268    if (ArgType->isVectorTy()) {
2269      unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
2270      std::vector<Constant*> Mask(numElem);
2271      for (unsigned v = 0; v < numElem; ++v) {
2272        unsigned Idx = v;
2273        // If the low vector was expanded, we need to skip the extra
2274        // undefined entries.
2275        if (v >= numElemL && numElemH > numElemL)
2276          Idx += (numElemH - numElemL);
2277        Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2278      }
2279
2280      Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2281                          ConstantVector::get(Mask),
2282                          getReplacementName(IBeforeJ ? I : J, true, o));
2283      BV->insertBefore(IBeforeJ ? J : I);
2284      return BV;
2285    }
2286
2287    Instruction *BV1 = InsertElementInst::Create(
2288                                          UndefValue::get(VArgType), LOp, CV0,
2289                                          getReplacementName(IBeforeJ ? I : J,
2290                                                             true, o, 1));
2291    BV1->insertBefore(IBeforeJ ? J : I);
2292    Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
2293                                          getReplacementName(IBeforeJ ? I : J,
2294                                                             true, o, 2));
2295    BV2->insertBefore(IBeforeJ ? J : I);
2296    return BV2;
2297  }
2298
2299  // This function creates an array of values that will be used as the inputs
2300  // to the vector instruction that fuses I with J.
2301  void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
2302                     Instruction *I, Instruction *J,
2303                     SmallVector<Value *, 3> &ReplacedOperands,
2304                     bool IBeforeJ) {
2305    unsigned NumOperands = I->getNumOperands();
2306
2307    for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
2308      // Iterate backward so that we look at the store pointer
2309      // first and know whether or not we need to flip the inputs.
2310
2311      if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
2312        // This is the pointer for a load/store instruction.
2313        ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
2314        continue;
2315      } else if (isa<CallInst>(I)) {
2316        Function *F = cast<CallInst>(I)->getCalledFunction();
2317        unsigned IID = F->getIntrinsicID();
2318        if (o == NumOperands-1) {
2319          BasicBlock &BB = *I->getParent();
2320
2321          Module *M = BB.getParent()->getParent();
2322          Type *ArgTypeI = I->getType();
2323          Type *ArgTypeJ = J->getType();
2324          Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2325
2326          ReplacedOperands[o] = Intrinsic::getDeclaration(M,
2327            (Intrinsic::ID) IID, VArgType);
2328          continue;
2329        } else if (IID == Intrinsic::powi && o == 1) {
2330          // The second argument of powi is a single integer and we've already
2331          // checked that both arguments are equal. As a result, we just keep
2332          // I's second argument.
2333          ReplacedOperands[o] = I->getOperand(o);
2334          continue;
2335        }
2336      } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2337        ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2338        continue;
2339      }
2340
2341      ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
2342    }
2343  }
2344
2345  // This function creates two values that represent the outputs of the
2346  // original I and J instructions. These are generally vector shuffles
2347  // or extracts. In many cases, these will end up being unused and, thus,
2348  // eliminated by later passes.
2349  void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2350                     Instruction *J, Instruction *K,
2351                     Instruction *&InsertionPt,
2352                     Instruction *&K1, Instruction *&K2) {
2353    if (isa<StoreInst>(I)) {
2354      AA->replaceWithNewValue(I, K);
2355      AA->replaceWithNewValue(J, K);
2356    } else {
2357      Type *IType = I->getType();
2358      Type *JType = J->getType();
2359
2360      VectorType *VType = getVecTypeForPair(IType, JType);
2361      unsigned numElem = VType->getNumElements();
2362
2363      unsigned numElemI, numElemJ;
2364      if (IType->isVectorTy())
2365        numElemI = cast<VectorType>(IType)->getNumElements();
2366      else
2367        numElemI = 1;
2368
2369      if (JType->isVectorTy())
2370        numElemJ = cast<VectorType>(JType)->getNumElements();
2371      else
2372        numElemJ = 1;
2373
2374      if (IType->isVectorTy()) {
2375        std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
2376        for (unsigned v = 0; v < numElemI; ++v) {
2377          Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2378          Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
2379        }
2380
2381        K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2382                                   ConstantVector::get( Mask1),
2383                                   getReplacementName(K, false, 1));
2384      } else {
2385        Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2386        K1 = ExtractElementInst::Create(K, CV0,
2387                                          getReplacementName(K, false, 1));
2388      }
2389
2390      if (JType->isVectorTy()) {
2391        std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
2392        for (unsigned v = 0; v < numElemJ; ++v) {
2393          Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2394          Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
2395        }
2396
2397        K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2398                                   ConstantVector::get( Mask2),
2399                                   getReplacementName(K, false, 2));
2400      } else {
2401        Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2402        K2 = ExtractElementInst::Create(K, CV1,
2403                                          getReplacementName(K, false, 2));
2404      }
2405
2406      K1->insertAfter(K);
2407      K2->insertAfter(K1);
2408      InsertionPt = K2;
2409    }
2410  }
2411
2412  // Move all uses of the function I (including pairing-induced uses) after J.
2413  bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2414                     std::multimap<Value *, Value *> &LoadMoveSet,
2415                     Instruction *I, Instruction *J) {
2416    // Skip to the first instruction past I.
2417    BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2418
2419    DenseSet<Value *> Users;
2420    AliasSetTracker WriteSet(*AA);
2421    for (; cast<Instruction>(L) != J; ++L)
2422      (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet);
2423
2424    assert(cast<Instruction>(L) == J &&
2425      "Tracking has not proceeded far enough to check for dependencies");
2426    // If J is now in the use set of I, then trackUsesOfI will return true
2427    // and we have a dependency cycle (and the fusing operation must abort).
2428    return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSet);
2429  }
2430
2431  // Move all uses of the function I (including pairing-induced uses) after J.
2432  void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2433                     std::multimap<Value *, Value *> &LoadMoveSet,
2434                     Instruction *&InsertionPt,
2435                     Instruction *I, Instruction *J) {
2436    // Skip to the first instruction past I.
2437    BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2438
2439    DenseSet<Value *> Users;
2440    AliasSetTracker WriteSet(*AA);
2441    for (; cast<Instruction>(L) != J;) {
2442      if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet)) {
2443        // Move this instruction
2444        Instruction *InstToMove = L; ++L;
2445
2446        DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2447                        " to after " << *InsertionPt << "\n");
2448        InstToMove->removeFromParent();
2449        InstToMove->insertAfter(InsertionPt);
2450        InsertionPt = InstToMove;
2451      } else {
2452        ++L;
2453      }
2454    }
2455  }
2456
2457  // Collect all load instruction that are in the move set of a given first
2458  // pair member.  These loads depend on the first instruction, I, and so need
2459  // to be moved after J (the second instruction) when the pair is fused.
2460  void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2461                     DenseMap<Value *, Value *> &ChosenPairs,
2462                     std::multimap<Value *, Value *> &LoadMoveSet,
2463                     Instruction *I) {
2464    // Skip to the first instruction past I.
2465    BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2466
2467    DenseSet<Value *> Users;
2468    AliasSetTracker WriteSet(*AA);
2469
2470    // Note: We cannot end the loop when we reach J because J could be moved
2471    // farther down the use chain by another instruction pairing. Also, J
2472    // could be before I if this is an inverted input.
2473    for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
2474      if (trackUsesOfI(Users, WriteSet, I, L)) {
2475        if (L->mayReadFromMemory())
2476          LoadMoveSet.insert(ValuePair(L, I));
2477      }
2478    }
2479  }
2480
2481  // In cases where both load/stores and the computation of their pointers
2482  // are chosen for vectorization, we can end up in a situation where the
2483  // aliasing analysis starts returning different query results as the
2484  // process of fusing instruction pairs continues. Because the algorithm
2485  // relies on finding the same use trees here as were found earlier, we'll
2486  // need to precompute the necessary aliasing information here and then
2487  // manually update it during the fusion process.
2488  void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2489                     std::vector<Value *> &PairableInsts,
2490                     DenseMap<Value *, Value *> &ChosenPairs,
2491                     std::multimap<Value *, Value *> &LoadMoveSet) {
2492    for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2493         PIE = PairableInsts.end(); PI != PIE; ++PI) {
2494      DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2495      if (P == ChosenPairs.end()) continue;
2496
2497      Instruction *I = cast<Instruction>(P->first);
2498      collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet, I);
2499    }
2500  }
2501
2502  // When the first instruction in each pair is cloned, it will inherit its
2503  // parent's metadata. This metadata must be combined with that of the other
2504  // instruction in a safe way.
2505  void BBVectorize::combineMetadata(Instruction *K, const Instruction *J) {
2506    SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
2507    K->getAllMetadataOtherThanDebugLoc(Metadata);
2508    for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
2509      unsigned Kind = Metadata[i].first;
2510      MDNode *JMD = J->getMetadata(Kind);
2511      MDNode *KMD = Metadata[i].second;
2512
2513      switch (Kind) {
2514      default:
2515        K->setMetadata(Kind, 0); // Remove unknown metadata
2516        break;
2517      case LLVMContext::MD_tbaa:
2518        K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2519        break;
2520      case LLVMContext::MD_fpmath:
2521        K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2522        break;
2523      }
2524    }
2525  }
2526
2527  // This function fuses the chosen instruction pairs into vector instructions,
2528  // taking care preserve any needed scalar outputs and, then, it reorders the
2529  // remaining instructions as needed (users of the first member of the pair
2530  // need to be moved to after the location of the second member of the pair
2531  // because the vector instruction is inserted in the location of the pair's
2532  // second member).
2533  void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2534                     std::vector<Value *> &PairableInsts,
2535                     DenseMap<Value *, Value *> &ChosenPairs,
2536                     DenseSet<ValuePair> &FixedOrderPairs,
2537                     DenseMap<VPPair, unsigned> &PairConnectionTypes,
2538                     std::multimap<ValuePair, ValuePair> &ConnectedPairs,
2539                     std::multimap<ValuePair, ValuePair> &ConnectedPairDeps) {
2540    LLVMContext& Context = BB.getContext();
2541
2542    // During the vectorization process, the order of the pairs to be fused
2543    // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
2544    // list. After a pair is fused, the flipped pair is removed from the list.
2545    DenseSet<ValuePair> FlippedPairs;
2546    for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
2547         E = ChosenPairs.end(); P != E; ++P)
2548      FlippedPairs.insert(ValuePair(P->second, P->first));
2549    for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
2550         E = FlippedPairs.end(); P != E; ++P)
2551      ChosenPairs.insert(*P);
2552
2553    std::multimap<Value *, Value *> LoadMoveSet;
2554    collectLoadMoveSet(BB, PairableInsts, ChosenPairs, LoadMoveSet);
2555
2556    DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
2557
2558    for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
2559      DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
2560      if (P == ChosenPairs.end()) {
2561        ++PI;
2562        continue;
2563      }
2564
2565      if (getDepthFactor(P->first) == 0) {
2566        // These instructions are not really fused, but are tracked as though
2567        // they are. Any case in which it would be interesting to fuse them
2568        // will be taken care of by InstCombine.
2569        --NumFusedOps;
2570        ++PI;
2571        continue;
2572      }
2573
2574      Instruction *I = cast<Instruction>(P->first),
2575        *J = cast<Instruction>(P->second);
2576
2577      DEBUG(dbgs() << "BBV: fusing: " << *I <<
2578             " <-> " << *J << "\n");
2579
2580      // Remove the pair and flipped pair from the list.
2581      DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
2582      assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
2583      ChosenPairs.erase(FP);
2584      ChosenPairs.erase(P);
2585
2586      if (!canMoveUsesOfIAfterJ(BB, LoadMoveSet, I, J)) {
2587        DEBUG(dbgs() << "BBV: fusion of: " << *I <<
2588               " <-> " << *J <<
2589               " aborted because of non-trivial dependency cycle\n");
2590        --NumFusedOps;
2591        ++PI;
2592        continue;
2593      }
2594
2595      // If the pair must have the other order, then flip it.
2596      bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
2597      if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
2598        // This pair does not have a fixed order, and so we might want to
2599        // flip it if that will yield fewer shuffles. We count the number
2600        // of dependencies connected via swaps, and those directly connected,
2601        // and flip the order if the number of swaps is greater.
2602        bool OrigOrder = true;
2603        VPPIteratorPair IP = ConnectedPairDeps.equal_range(ValuePair(I, J));
2604        if (IP.first == ConnectedPairDeps.end()) {
2605          IP = ConnectedPairDeps.equal_range(ValuePair(J, I));
2606          OrigOrder = false;
2607        }
2608
2609        if (IP.first != ConnectedPairDeps.end()) {
2610          unsigned NumDepsDirect = 0, NumDepsSwap = 0;
2611          for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
2612               Q != IP.second; ++Q) {
2613            DenseMap<VPPair, unsigned>::iterator R =
2614              PairConnectionTypes.find(VPPair(Q->second, Q->first));
2615            assert(R != PairConnectionTypes.end() &&
2616                   "Cannot find pair connection type");
2617            if (R->second == PairConnectionDirect)
2618              ++NumDepsDirect;
2619            else if (R->second == PairConnectionSwap)
2620              ++NumDepsSwap;
2621          }
2622
2623          if (!OrigOrder)
2624            std::swap(NumDepsDirect, NumDepsSwap);
2625
2626          if (NumDepsSwap > NumDepsDirect) {
2627            FlipPairOrder = true;
2628            DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
2629                            " <-> " << *J << "\n");
2630          }
2631        }
2632      }
2633
2634      Instruction *L = I, *H = J;
2635      if (FlipPairOrder)
2636        std::swap(H, L);
2637
2638      // If the pair being fused uses the opposite order from that in the pair
2639      // connection map, then we need to flip the types.
2640      VPPIteratorPair IP = ConnectedPairs.equal_range(ValuePair(H, L));
2641      for (std::multimap<ValuePair, ValuePair>::iterator Q = IP.first;
2642           Q != IP.second; ++Q) {
2643        DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(*Q);
2644        assert(R != PairConnectionTypes.end() &&
2645               "Cannot find pair connection type");
2646        if (R->second == PairConnectionDirect)
2647          R->second = PairConnectionSwap;
2648        else if (R->second == PairConnectionSwap)
2649          R->second = PairConnectionDirect;
2650      }
2651
2652      bool LBeforeH = !FlipPairOrder;
2653      unsigned NumOperands = I->getNumOperands();
2654      SmallVector<Value *, 3> ReplacedOperands(NumOperands);
2655      getReplacementInputsForPair(Context, L, H, ReplacedOperands,
2656                                  LBeforeH);
2657
2658      // Make a copy of the original operation, change its type to the vector
2659      // type and replace its operands with the vector operands.
2660      Instruction *K = L->clone();
2661      if (L->hasName())
2662        K->takeName(L);
2663      else if (H->hasName())
2664        K->takeName(H);
2665
2666      if (!isa<StoreInst>(K))
2667        K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
2668
2669      combineMetadata(K, H);
2670
2671      for (unsigned o = 0; o < NumOperands; ++o)
2672        K->setOperand(o, ReplacedOperands[o]);
2673
2674      K->insertAfter(J);
2675
2676      // Instruction insertion point:
2677      Instruction *InsertionPt = K;
2678      Instruction *K1 = 0, *K2 = 0;
2679      replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
2680
2681      // The use tree of the first original instruction must be moved to after
2682      // the location of the second instruction. The entire use tree of the
2683      // first instruction is disjoint from the input tree of the second
2684      // (by definition), and so commutes with it.
2685
2686      moveUsesOfIAfterJ(BB, LoadMoveSet, InsertionPt, I, J);
2687
2688      if (!isa<StoreInst>(I)) {
2689        L->replaceAllUsesWith(K1);
2690        H->replaceAllUsesWith(K2);
2691        AA->replaceWithNewValue(L, K1);
2692        AA->replaceWithNewValue(H, K2);
2693      }
2694
2695      // Instructions that may read from memory may be in the load move set.
2696      // Once an instruction is fused, we no longer need its move set, and so
2697      // the values of the map never need to be updated. However, when a load
2698      // is fused, we need to merge the entries from both instructions in the
2699      // pair in case those instructions were in the move set of some other
2700      // yet-to-be-fused pair. The loads in question are the keys of the map.
2701      if (I->mayReadFromMemory()) {
2702        std::vector<ValuePair> NewSetMembers;
2703        VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
2704        VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
2705        for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
2706             N != IPairRange.second; ++N)
2707          NewSetMembers.push_back(ValuePair(K, N->second));
2708        for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
2709             N != JPairRange.second; ++N)
2710          NewSetMembers.push_back(ValuePair(K, N->second));
2711        for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
2712             AE = NewSetMembers.end(); A != AE; ++A)
2713          LoadMoveSet.insert(*A);
2714      }
2715
2716      // Before removing I, set the iterator to the next instruction.
2717      PI = llvm::next(BasicBlock::iterator(I));
2718      if (cast<Instruction>(PI) == J)
2719        ++PI;
2720
2721      SE->forgetValue(I);
2722      SE->forgetValue(J);
2723      I->eraseFromParent();
2724      J->eraseFromParent();
2725
2726      DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
2727                                               BB << "\n");
2728    }
2729
2730    DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
2731  }
2732}
2733
2734char BBVectorize::ID = 0;
2735static const char bb_vectorize_name[] = "Basic-Block Vectorization";
2736INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
2737INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2738INITIALIZE_PASS_DEPENDENCY(DominatorTree)
2739INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2740INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
2741
2742BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
2743  return new BBVectorize(C);
2744}
2745
2746bool
2747llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
2748  BBVectorize BBVectorizer(P, C);
2749  return BBVectorizer.vectorizeBB(BB);
2750}
2751
2752//===----------------------------------------------------------------------===//
2753VectorizeConfig::VectorizeConfig() {
2754  VectorBits = ::VectorBits;
2755  VectorizeBools = !::NoBools;
2756  VectorizeInts = !::NoInts;
2757  VectorizeFloats = !::NoFloats;
2758  VectorizePointers = !::NoPointers;
2759  VectorizeCasts = !::NoCasts;
2760  VectorizeMath = !::NoMath;
2761  VectorizeFMA = !::NoFMA;
2762  VectorizeSelect = !::NoSelect;
2763  VectorizeCmp = !::NoCmp;
2764  VectorizeGEP = !::NoGEP;
2765  VectorizeMemOps = !::NoMemOps;
2766  AlignedOnly = ::AlignedOnly;
2767  ReqChainDepth= ::ReqChainDepth;
2768  SearchLimit = ::SearchLimit;
2769  MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
2770  SplatBreaksChain = ::SplatBreaksChain;
2771  MaxInsts = ::MaxInsts;
2772  MaxIter = ::MaxIter;
2773  Pow2LenOnly = ::Pow2LenOnly;
2774  NoMemOpBoost = ::NoMemOpBoost;
2775  FastDep = ::FastDep;
2776}
2777