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