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