BBVectorize.cpp revision 38a7f22445b8782682d1f8f253454ea0390d4ac5
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/Pass.h"
27#include "llvm/Type.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/DenseSet.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/StringExtras.h"
34#include "llvm/Analysis/AliasAnalysis.h"
35#include "llvm/Analysis/AliasSetTracker.h"
36#include "llvm/Analysis/ScalarEvolution.h"
37#include "llvm/Analysis/ScalarEvolutionExpressions.h"
38#include "llvm/Analysis/ValueTracking.h"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/Debug.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/Support/ValueHandle.h"
43#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Vectorize.h"
45#include <algorithm>
46#include <map>
47using namespace llvm;
48
49static cl::opt<unsigned>
50ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
51  cl::desc("The required chain depth for vectorization"));
52
53static cl::opt<unsigned>
54SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
55  cl::desc("The maximum search distance for instruction pairs"));
56
57static cl::opt<bool>
58SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
59  cl::desc("Replicating one element to a pair breaks the chain"));
60
61static cl::opt<unsigned>
62VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
63  cl::desc("The size of the native vector registers"));
64
65static cl::opt<unsigned>
66MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
67  cl::desc("The maximum number of pairing iterations"));
68
69static cl::opt<unsigned>
70MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
71  cl::desc("The maximum number of pairable instructions per group"));
72
73static cl::opt<unsigned>
74MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
75  cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
76                       " a full cycle check"));
77
78static cl::opt<bool>
79NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
80  cl::desc("Don't try to vectorize integer values"));
81
82static cl::opt<bool>
83NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
84  cl::desc("Don't try to vectorize floating-point values"));
85
86static cl::opt<bool>
87NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
88  cl::desc("Don't try to vectorize casting (conversion) operations"));
89
90static cl::opt<bool>
91NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
92  cl::desc("Don't try to vectorize floating-point math intrinsics"));
93
94static cl::opt<bool>
95NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
96  cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
97
98static cl::opt<bool>
99NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
100  cl::desc("Don't try to vectorize loads and stores"));
101
102static cl::opt<bool>
103AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
104  cl::desc("Only generate aligned loads and stores"));
105
106static cl::opt<bool>
107NoMemOpBoost("bb-vectorize-no-mem-op-boost",
108  cl::init(false), cl::Hidden,
109  cl::desc("Don't boost the chain-depth contribution of loads and stores"));
110
111static cl::opt<bool>
112FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
113  cl::desc("Use a fast instruction dependency analysis"));
114
115#ifndef NDEBUG
116static cl::opt<bool>
117DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
118  cl::init(false), cl::Hidden,
119  cl::desc("When debugging is enabled, output information on the"
120           " instruction-examination process"));
121static cl::opt<bool>
122DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
123  cl::init(false), cl::Hidden,
124  cl::desc("When debugging is enabled, output information on the"
125           " candidate-selection process"));
126static cl::opt<bool>
127DebugPairSelection("bb-vectorize-debug-pair-selection",
128  cl::init(false), cl::Hidden,
129  cl::desc("When debugging is enabled, output information on the"
130           " pair-selection process"));
131static cl::opt<bool>
132DebugCycleCheck("bb-vectorize-debug-cycle-check",
133  cl::init(false), cl::Hidden,
134  cl::desc("When debugging is enabled, output information on the"
135           " cycle-checking process"));
136#endif
137
138STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
139
140namespace {
141  struct BBVectorize : public BasicBlockPass {
142    static char ID; // Pass identification, replacement for typeid
143    BBVectorize() : BasicBlockPass(ID) {
144      initializeBBVectorizePass(*PassRegistry::getPassRegistry());
145    }
146
147    typedef std::pair<Value *, Value *> ValuePair;
148    typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
149    typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
150    typedef std::pair<std::multimap<Value *, Value *>::iterator,
151              std::multimap<Value *, Value *>::iterator> VPIteratorPair;
152    typedef std::pair<std::multimap<ValuePair, ValuePair>::iterator,
153              std::multimap<ValuePair, ValuePair>::iterator>
154                VPPIteratorPair;
155
156    AliasAnalysis *AA;
157    ScalarEvolution *SE;
158    TargetData *TD;
159
160    // FIXME: const correct?
161
162    bool vectorizePairs(BasicBlock &BB);
163
164    bool getCandidatePairs(BasicBlock &BB,
165                       BasicBlock::iterator &Start,
166                       std::multimap<Value *, Value *> &CandidatePairs,
167                       std::vector<Value *> &PairableInsts);
168
169    void computeConnectedPairs(std::multimap<Value *, Value *> &CandidatePairs,
170                       std::vector<Value *> &PairableInsts,
171                       std::multimap<ValuePair, ValuePair> &ConnectedPairs);
172
173    void buildDepMap(BasicBlock &BB,
174                       std::multimap<Value *, Value *> &CandidatePairs,
175                       std::vector<Value *> &PairableInsts,
176                       DenseSet<ValuePair> &PairableInstUsers);
177
178    void choosePairs(std::multimap<Value *, Value *> &CandidatePairs,
179                        std::vector<Value *> &PairableInsts,
180                        std::multimap<ValuePair, ValuePair> &ConnectedPairs,
181                        DenseSet<ValuePair> &PairableInstUsers,
182                        DenseMap<Value *, Value *>& ChosenPairs);
183
184    void fuseChosenPairs(BasicBlock &BB,
185                     std::vector<Value *> &PairableInsts,
186                     DenseMap<Value *, Value *>& ChosenPairs);
187
188    bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
189
190    bool areInstsCompatible(Instruction *I, Instruction *J,
191                       bool IsSimpleLoadStore);
192
193    bool trackUsesOfI(DenseSet<Value *> &Users,
194                      AliasSetTracker &WriteSet, Instruction *I,
195                      Instruction *J, bool UpdateUsers = true,
196                      std::multimap<Value *, Value *> *LoadMoveSet = 0);
197
198    void computePairsConnectedTo(
199                      std::multimap<Value *, Value *> &CandidatePairs,
200                      std::vector<Value *> &PairableInsts,
201                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
202                      ValuePair P);
203
204    bool pairsConflict(ValuePair P, ValuePair Q,
205                 DenseSet<ValuePair> &PairableInstUsers,
206                 std::multimap<ValuePair, ValuePair> *PairableInstUserMap = 0);
207
208    bool pairWillFormCycle(ValuePair P,
209                       std::multimap<ValuePair, ValuePair> &PairableInstUsers,
210                       DenseSet<ValuePair> &CurrentPairs);
211
212    void pruneTreeFor(
213                      std::multimap<Value *, Value *> &CandidatePairs,
214                      std::vector<Value *> &PairableInsts,
215                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
216                      DenseSet<ValuePair> &PairableInstUsers,
217                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
218                      DenseMap<Value *, Value *> &ChosenPairs,
219                      DenseMap<ValuePair, size_t> &Tree,
220                      DenseSet<ValuePair> &PrunedTree, ValuePair J,
221                      bool UseCycleCheck);
222
223    void buildInitialTreeFor(
224                      std::multimap<Value *, Value *> &CandidatePairs,
225                      std::vector<Value *> &PairableInsts,
226                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
227                      DenseSet<ValuePair> &PairableInstUsers,
228                      DenseMap<Value *, Value *> &ChosenPairs,
229                      DenseMap<ValuePair, size_t> &Tree, ValuePair J);
230
231    void findBestTreeFor(
232                      std::multimap<Value *, Value *> &CandidatePairs,
233                      std::vector<Value *> &PairableInsts,
234                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
235                      DenseSet<ValuePair> &PairableInstUsers,
236                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
237                      DenseMap<Value *, Value *> &ChosenPairs,
238                      DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
239                      size_t &BestEffSize, VPIteratorPair ChoiceRange,
240                      bool UseCycleCheck);
241
242    Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
243                     Instruction *J, unsigned o, bool &FlipMemInputs);
244
245    void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
246                     unsigned NumElem, unsigned MaskOffset, unsigned NumInElem,
247                     unsigned IdxOffset, std::vector<Constant*> &Mask);
248
249    Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
250                     Instruction *J);
251
252    Value *getReplacementInput(LLVMContext& Context, Instruction *I,
253                     Instruction *J, unsigned o, bool FlipMemInputs);
254
255    void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
256                     Instruction *J, SmallVector<Value *, 3> &ReplacedOperands,
257                     bool &FlipMemInputs);
258
259    void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
260                     Instruction *J, Instruction *K,
261                     Instruction *&InsertionPt, Instruction *&K1,
262                     Instruction *&K2, bool &FlipMemInputs);
263
264    void collectPairLoadMoveSet(BasicBlock &BB,
265                     DenseMap<Value *, Value *> &ChosenPairs,
266                     std::multimap<Value *, Value *> &LoadMoveSet,
267                     Instruction *I);
268
269    void collectLoadMoveSet(BasicBlock &BB,
270                     std::vector<Value *> &PairableInsts,
271                     DenseMap<Value *, Value *> &ChosenPairs,
272                     std::multimap<Value *, Value *> &LoadMoveSet);
273
274    bool canMoveUsesOfIAfterJ(BasicBlock &BB,
275                     std::multimap<Value *, Value *> &LoadMoveSet,
276                     Instruction *I, Instruction *J);
277
278    void moveUsesOfIAfterJ(BasicBlock &BB,
279                     std::multimap<Value *, Value *> &LoadMoveSet,
280                     Instruction *&InsertionPt,
281                     Instruction *I, Instruction *J);
282
283    virtual bool runOnBasicBlock(BasicBlock &BB) {
284      AA = &getAnalysis<AliasAnalysis>();
285      SE = &getAnalysis<ScalarEvolution>();
286      TD = getAnalysisIfAvailable<TargetData>();
287
288      bool changed = false;
289      // Iterate a sufficient number of times to merge types of size 1 bit,
290      // then 2 bits, then 4, etc. up to half of the target vector width of the
291      // target vector register.
292      for (unsigned v = 2, n = 1; v <= VectorBits && (!MaxIter || n <= MaxIter);
293           v *= 2, ++n) {
294        DEBUG(dbgs() << "BBV: fusing loop #" << n <<
295              " for " << BB.getName() << " in " <<
296              BB.getParent()->getName() << "...\n");
297        if (vectorizePairs(BB))
298          changed = true;
299        else
300          break;
301      }
302
303      DEBUG(dbgs() << "BBV: done!\n");
304      return changed;
305    }
306
307    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
308      BasicBlockPass::getAnalysisUsage(AU);
309      AU.addRequired<AliasAnalysis>();
310      AU.addRequired<ScalarEvolution>();
311      AU.addPreserved<AliasAnalysis>();
312      AU.addPreserved<ScalarEvolution>();
313      AU.setPreservesCFG();
314    }
315
316    // This returns the vector type that holds a pair of the provided type.
317    // If the provided type is already a vector, then its length is doubled.
318    static inline VectorType *getVecTypeForPair(Type *ElemTy) {
319      if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
320        unsigned numElem = VTy->getNumElements();
321        return VectorType::get(ElemTy->getScalarType(), numElem*2);
322      }
323
324      return VectorType::get(ElemTy, 2);
325    }
326
327    // Returns the weight associated with the provided value. A chain of
328    // candidate pairs has a length given by the sum of the weights of its
329    // members (one weight per pair; the weight of each member of the pair
330    // is assumed to be the same). This length is then compared to the
331    // chain-length threshold to determine if a given chain is significant
332    // enough to be vectorized. The length is also used in comparing
333    // candidate chains where longer chains are considered to be better.
334    // Note: when this function returns 0, the resulting instructions are
335    // not actually fused.
336    static inline size_t getDepthFactor(Value *V) {
337      // InsertElement and ExtractElement have a depth factor of zero. This is
338      // for two reasons: First, they cannot be usefully fused. Second, because
339      // the pass generates a lot of these, they can confuse the simple metric
340      // used to compare the trees in the next iteration. Thus, giving them a
341      // weight of zero allows the pass to essentially ignore them in
342      // subsequent iterations when looking for vectorization opportunities
343      // while still tracking dependency chains that flow through those
344      // instructions.
345      if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
346        return 0;
347
348      // Give a load or store half of the required depth so that load/store
349      // pairs will vectorize.
350      if (!NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
351        return ReqChainDepth/2;
352
353      return 1;
354    }
355
356    // This determines the relative offset of two loads or stores, returning
357    // true if the offset could be determined to be some constant value.
358    // For example, if OffsetInElmts == 1, then J accesses the memory directly
359    // after I; if OffsetInElmts == -1 then I accesses the memory
360    // directly after J. This function assumes that both instructions
361    // have the same type.
362    bool getPairPtrInfo(Instruction *I, Instruction *J,
363        Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
364        int64_t &OffsetInElmts) {
365      OffsetInElmts = 0;
366      if (isa<LoadInst>(I)) {
367        IPtr = cast<LoadInst>(I)->getPointerOperand();
368        JPtr = cast<LoadInst>(J)->getPointerOperand();
369        IAlignment = cast<LoadInst>(I)->getAlignment();
370        JAlignment = cast<LoadInst>(J)->getAlignment();
371      } else {
372        IPtr = cast<StoreInst>(I)->getPointerOperand();
373        JPtr = cast<StoreInst>(J)->getPointerOperand();
374        IAlignment = cast<StoreInst>(I)->getAlignment();
375        JAlignment = cast<StoreInst>(J)->getAlignment();
376      }
377
378      const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
379      const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
380
381      // If this is a trivial offset, then we'll get something like
382      // 1*sizeof(type). With target data, which we need anyway, this will get
383      // constant folded into a number.
384      const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
385      if (const SCEVConstant *ConstOffSCEV =
386            dyn_cast<SCEVConstant>(OffsetSCEV)) {
387        ConstantInt *IntOff = ConstOffSCEV->getValue();
388        int64_t Offset = IntOff->getSExtValue();
389
390        Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
391        int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
392
393        assert(VTy == cast<PointerType>(JPtr->getType())->getElementType());
394
395        OffsetInElmts = Offset/VTyTSS;
396        return (abs64(Offset) % VTyTSS) == 0;
397      }
398
399      return false;
400    }
401
402    // Returns true if the provided CallInst represents an intrinsic that can
403    // be vectorized.
404    bool isVectorizableIntrinsic(CallInst* I) {
405      Function *F = I->getCalledFunction();
406      if (!F) return false;
407
408      unsigned IID = F->getIntrinsicID();
409      if (!IID) return false;
410
411      switch(IID) {
412      default:
413        return false;
414      case Intrinsic::sqrt:
415      case Intrinsic::powi:
416      case Intrinsic::sin:
417      case Intrinsic::cos:
418      case Intrinsic::log:
419      case Intrinsic::log2:
420      case Intrinsic::log10:
421      case Intrinsic::exp:
422      case Intrinsic::exp2:
423      case Intrinsic::pow:
424        return !NoMath;
425      case Intrinsic::fma:
426        return !NoFMA;
427      }
428    }
429
430    // Returns true if J is the second element in some pair referenced by
431    // some multimap pair iterator pair.
432    template <typename V>
433    bool isSecondInIteratorPair(V J, std::pair<
434           typename std::multimap<V, V>::iterator,
435           typename std::multimap<V, V>::iterator> PairRange) {
436      for (typename std::multimap<V, V>::iterator K = PairRange.first;
437           K != PairRange.second; ++K)
438        if (K->second == J) return true;
439
440      return false;
441    }
442  };
443
444  // This function implements one vectorization iteration on the provided
445  // basic block. It returns true if the block is changed.
446  bool BBVectorize::vectorizePairs(BasicBlock &BB) {
447    bool ShouldContinue;
448    BasicBlock::iterator Start = BB.getFirstInsertionPt();
449
450    std::vector<Value *> AllPairableInsts;
451    DenseMap<Value *, Value *> AllChosenPairs;
452
453    do {
454      std::vector<Value *> PairableInsts;
455      std::multimap<Value *, Value *> CandidatePairs;
456      ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
457                                         PairableInsts);
458      if (PairableInsts.empty()) continue;
459
460      // Now we have a map of all of the pairable instructions and we need to
461      // select the best possible pairing. A good pairing is one such that the
462      // users of the pair are also paired. This defines a (directed) forest
463      // over the pairs such that two pairs are connected iff the second pair
464      // uses the first.
465
466      // Note that it only matters that both members of the second pair use some
467      // element of the first pair (to allow for splatting).
468
469      std::multimap<ValuePair, ValuePair> ConnectedPairs;
470      computeConnectedPairs(CandidatePairs, PairableInsts, ConnectedPairs);
471      if (ConnectedPairs.empty()) continue;
472
473      // Build the pairable-instruction dependency map
474      DenseSet<ValuePair> PairableInstUsers;
475      buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
476
477      // There is now a graph of the connected pairs. For each variable, pick
478      // the pairing with the largest tree meeting the depth requirement on at
479      // least one branch. Then select all pairings that are part of that tree
480      // and remove them from the list of available pairings and pairable
481      // variables.
482
483      DenseMap<Value *, Value *> ChosenPairs;
484      choosePairs(CandidatePairs, PairableInsts, ConnectedPairs,
485        PairableInstUsers, ChosenPairs);
486
487      if (ChosenPairs.empty()) continue;
488      AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
489                              PairableInsts.end());
490      AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
491    } while (ShouldContinue);
492
493    if (AllChosenPairs.empty()) return false;
494    NumFusedOps += AllChosenPairs.size();
495
496    // A set of pairs has now been selected. It is now necessary to replace the
497    // paired instructions with vector instructions. For this procedure each
498    // operand much be replaced with a vector operand. This vector is formed
499    // by using build_vector on the old operands. The replaced values are then
500    // replaced with a vector_extract on the result.  Subsequent optimization
501    // passes should coalesce the build/extract combinations.
502
503    fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs);
504    return true;
505  }
506
507  // This function returns true if the provided instruction is capable of being
508  // fused into a vector instruction. This determination is based only on the
509  // type and other attributes of the instruction.
510  bool BBVectorize::isInstVectorizable(Instruction *I,
511                                         bool &IsSimpleLoadStore) {
512    IsSimpleLoadStore = false;
513
514    if (CallInst *C = dyn_cast<CallInst>(I)) {
515      if (!isVectorizableIntrinsic(C))
516        return false;
517    } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
518      // Vectorize simple loads if possbile:
519      IsSimpleLoadStore = L->isSimple();
520      if (!IsSimpleLoadStore || NoMemOps)
521        return false;
522    } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
523      // Vectorize simple stores if possbile:
524      IsSimpleLoadStore = S->isSimple();
525      if (!IsSimpleLoadStore || NoMemOps)
526        return false;
527    } else if (CastInst *C = dyn_cast<CastInst>(I)) {
528      // We can vectorize casts, but not casts of pointer types, etc.
529      if (NoCasts)
530        return false;
531
532      Type *SrcTy = C->getSrcTy();
533      if (!SrcTy->isSingleValueType() || SrcTy->isPointerTy())
534        return false;
535
536      Type *DestTy = C->getDestTy();
537      if (!DestTy->isSingleValueType() || DestTy->isPointerTy())
538        return false;
539    } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
540        isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
541      return false;
542    }
543
544    // We can't vectorize memory operations without target data
545    if (TD == 0 && IsSimpleLoadStore)
546      return false;
547
548    Type *T1, *T2;
549    if (isa<StoreInst>(I)) {
550      // For stores, it is the value type, not the pointer type that matters
551      // because the value is what will come from a vector register.
552
553      Value *IVal = cast<StoreInst>(I)->getValueOperand();
554      T1 = IVal->getType();
555    } else {
556      T1 = I->getType();
557    }
558
559    if (I->isCast())
560      T2 = cast<CastInst>(I)->getSrcTy();
561    else
562      T2 = T1;
563
564    // Not every type can be vectorized...
565    if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
566        !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
567      return false;
568
569    if (NoInts && (T1->isIntOrIntVectorTy() || T2->isIntOrIntVectorTy()))
570      return false;
571
572    if (NoFloats && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
573      return false;
574
575    if (T1->getPrimitiveSizeInBits() > VectorBits/2 ||
576        T2->getPrimitiveSizeInBits() > VectorBits/2)
577      return false;
578
579    return true;
580  }
581
582  // This function returns true if the two provided instructions are compatible
583  // (meaning that they can be fused into a vector instruction). This assumes
584  // that I has already been determined to be vectorizable and that J is not
585  // in the use tree of I.
586  bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
587                       bool IsSimpleLoadStore) {
588    DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
589                     " <-> " << *J << "\n");
590
591    // Loads and stores can be merged if they have different alignments,
592    // but are otherwise the same.
593    LoadInst *LI, *LJ;
594    StoreInst *SI, *SJ;
595    if ((LI = dyn_cast<LoadInst>(I)) && (LJ = dyn_cast<LoadInst>(J))) {
596      if (I->getType() != J->getType())
597        return false;
598
599      if (LI->getPointerOperand()->getType() !=
600            LJ->getPointerOperand()->getType() ||
601          LI->isVolatile() != LJ->isVolatile() ||
602          LI->getOrdering() != LJ->getOrdering() ||
603          LI->getSynchScope() != LJ->getSynchScope())
604        return false;
605    } else if ((SI = dyn_cast<StoreInst>(I)) && (SJ = dyn_cast<StoreInst>(J))) {
606      if (SI->getValueOperand()->getType() !=
607            SJ->getValueOperand()->getType() ||
608          SI->getPointerOperand()->getType() !=
609            SJ->getPointerOperand()->getType() ||
610          SI->isVolatile() != SJ->isVolatile() ||
611          SI->getOrdering() != SJ->getOrdering() ||
612          SI->getSynchScope() != SJ->getSynchScope())
613        return false;
614    } else if (!J->isSameOperationAs(I)) {
615      return false;
616    }
617    // FIXME: handle addsub-type operations!
618
619    if (IsSimpleLoadStore) {
620      Value *IPtr, *JPtr;
621      unsigned IAlignment, JAlignment;
622      int64_t OffsetInElmts = 0;
623      if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
624            OffsetInElmts) && abs64(OffsetInElmts) == 1) {
625        if (AlignedOnly) {
626          Type *aType = isa<StoreInst>(I) ?
627            cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
628          // An aligned load or store is possible only if the instruction
629          // with the lower offset has an alignment suitable for the
630          // vector type.
631
632          unsigned BottomAlignment = IAlignment;
633          if (OffsetInElmts < 0) BottomAlignment = JAlignment;
634
635          Type *VType = getVecTypeForPair(aType);
636          unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
637          if (BottomAlignment < VecAlignment)
638            return false;
639        }
640      } else {
641        return false;
642      }
643    } else if (isa<ShuffleVectorInst>(I)) {
644      // Only merge two shuffles if they're both constant
645      return isa<Constant>(I->getOperand(2)) &&
646             isa<Constant>(J->getOperand(2));
647      // FIXME: We may want to vectorize non-constant shuffles also.
648    }
649
650    return true;
651  }
652
653  // Figure out whether or not J uses I and update the users and write-set
654  // structures associated with I. Specifically, Users represents the set of
655  // instructions that depend on I. WriteSet represents the set
656  // of memory locations that are dependent on I. If UpdateUsers is true,
657  // and J uses I, then Users is updated to contain J and WriteSet is updated
658  // to contain any memory locations to which J writes. The function returns
659  // true if J uses I. By default, alias analysis is used to determine
660  // whether J reads from memory that overlaps with a location in WriteSet.
661  // If LoadMoveSet is not null, then it is a previously-computed multimap
662  // where the key is the memory-based user instruction and the value is
663  // the instruction to be compared with I. So, if LoadMoveSet is provided,
664  // then the alias analysis is not used. This is necessary because this
665  // function is called during the process of moving instructions during
666  // vectorization and the results of the alias analysis are not stable during
667  // that process.
668  bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
669                       AliasSetTracker &WriteSet, Instruction *I,
670                       Instruction *J, bool UpdateUsers,
671                       std::multimap<Value *, Value *> *LoadMoveSet) {
672    bool UsesI = false;
673
674    // This instruction may already be marked as a user due, for example, to
675    // being a member of a selected pair.
676    if (Users.count(J))
677      UsesI = true;
678
679    if (!UsesI)
680      for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
681           JU != JE; ++JU) {
682        Value *V = *JU;
683        if (I == V || Users.count(V)) {
684          UsesI = true;
685          break;
686        }
687      }
688    if (!UsesI && J->mayReadFromMemory()) {
689      if (LoadMoveSet) {
690        VPIteratorPair JPairRange = LoadMoveSet->equal_range(J);
691        UsesI = isSecondInIteratorPair<Value*>(I, JPairRange);
692      } else {
693        for (AliasSetTracker::iterator W = WriteSet.begin(),
694             WE = WriteSet.end(); W != WE; ++W) {
695          if (W->aliasesUnknownInst(J, *AA)) {
696            UsesI = true;
697            break;
698          }
699        }
700      }
701    }
702
703    if (UsesI && UpdateUsers) {
704      if (J->mayWriteToMemory()) WriteSet.add(J);
705      Users.insert(J);
706    }
707
708    return UsesI;
709  }
710
711  // This function iterates over all instruction pairs in the provided
712  // basic block and collects all candidate pairs for vectorization.
713  bool BBVectorize::getCandidatePairs(BasicBlock &BB,
714                       BasicBlock::iterator &Start,
715                       std::multimap<Value *, Value *> &CandidatePairs,
716                       std::vector<Value *> &PairableInsts) {
717    BasicBlock::iterator E = BB.end();
718    if (Start == E) return false;
719
720    bool ShouldContinue = false, IAfterStart = false;
721    for (BasicBlock::iterator I = Start++; I != E; ++I) {
722      if (I == Start) IAfterStart = true;
723
724      bool IsSimpleLoadStore;
725      if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
726
727      // Look for an instruction with which to pair instruction *I...
728      DenseSet<Value *> Users;
729      AliasSetTracker WriteSet(*AA);
730      bool JAfterStart = IAfterStart;
731      BasicBlock::iterator J = llvm::next(I);
732      for (unsigned ss = 0; J != E && ss <= SearchLimit; ++J, ++ss) {
733        if (J == Start) JAfterStart = true;
734
735        // Determine if J uses I, if so, exit the loop.
736        bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !FastDep);
737        if (FastDep) {
738          // Note: For this heuristic to be effective, independent operations
739          // must tend to be intermixed. This is likely to be true from some
740          // kinds of grouped loop unrolling (but not the generic LLVM pass),
741          // but otherwise may require some kind of reordering pass.
742
743          // When using fast dependency analysis,
744          // stop searching after first use:
745          if (UsesI) break;
746        } else {
747          if (UsesI) continue;
748        }
749
750        // J does not use I, and comes before the first use of I, so it can be
751        // merged with I if the instructions are compatible.
752        if (!areInstsCompatible(I, J, IsSimpleLoadStore)) continue;
753
754        // J is a candidate for merging with I.
755        if (!PairableInsts.size() ||
756             PairableInsts[PairableInsts.size()-1] != I) {
757          PairableInsts.push_back(I);
758        }
759
760        CandidatePairs.insert(ValuePair(I, J));
761
762        // The next call to this function must start after the last instruction
763        // selected during this invocation.
764        if (JAfterStart) {
765          Start = llvm::next(J);
766          IAfterStart = JAfterStart = false;
767        }
768
769        DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
770                     << *I << " <-> " << *J << "\n");
771
772        // If we have already found too many pairs, break here and this function
773        // will be called again starting after the last instruction selected
774        // during this invocation.
775        if (PairableInsts.size() >= MaxInsts) {
776          ShouldContinue = true;
777          break;
778        }
779      }
780
781      if (ShouldContinue)
782        break;
783    }
784
785    DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
786           << " instructions with candidate pairs\n");
787
788    return ShouldContinue;
789  }
790
791  // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
792  // it looks for pairs such that both members have an input which is an
793  // output of PI or PJ.
794  void BBVectorize::computePairsConnectedTo(
795                      std::multimap<Value *, Value *> &CandidatePairs,
796                      std::vector<Value *> &PairableInsts,
797                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
798                      ValuePair P) {
799    // For each possible pairing for this variable, look at the uses of
800    // the first value...
801    for (Value::use_iterator I = P.first->use_begin(),
802         E = P.first->use_end(); I != E; ++I) {
803      VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
804
805      // For each use of the first variable, look for uses of the second
806      // variable...
807      for (Value::use_iterator J = P.second->use_begin(),
808           E2 = P.second->use_end(); J != E2; ++J) {
809        VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
810
811        // Look for <I, J>:
812        if (isSecondInIteratorPair<Value*>(*J, IPairRange))
813          ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
814
815        // Look for <J, I>:
816        if (isSecondInIteratorPair<Value*>(*I, JPairRange))
817          ConnectedPairs.insert(VPPair(P, ValuePair(*J, *I)));
818      }
819
820      if (SplatBreaksChain) continue;
821      // Look for cases where just the first value in the pair is used by
822      // both members of another pair (splatting).
823      for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
824        if (isSecondInIteratorPair<Value*>(*J, IPairRange))
825          ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
826      }
827    }
828
829    if (SplatBreaksChain) return;
830    // Look for cases where just the second value in the pair is used by
831    // both members of another pair (splatting).
832    for (Value::use_iterator I = P.second->use_begin(),
833         E = P.second->use_end(); I != E; ++I) {
834      VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
835
836      for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
837        if (isSecondInIteratorPair<Value*>(*J, IPairRange))
838          ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
839      }
840    }
841  }
842
843  // This function figures out which pairs are connected.  Two pairs are
844  // connected if some output of the first pair forms an input to both members
845  // of the second pair.
846  void BBVectorize::computeConnectedPairs(
847                      std::multimap<Value *, Value *> &CandidatePairs,
848                      std::vector<Value *> &PairableInsts,
849                      std::multimap<ValuePair, ValuePair> &ConnectedPairs) {
850
851    for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
852         PE = PairableInsts.end(); PI != PE; ++PI) {
853      VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
854
855      for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
856           P != choiceRange.second; ++P)
857        computePairsConnectedTo(CandidatePairs, PairableInsts,
858                                ConnectedPairs, *P);
859    }
860
861    DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
862                 << " pair connections.\n");
863  }
864
865  // This function builds a set of use tuples such that <A, B> is in the set
866  // if B is in the use tree of A. If B is in the use tree of A, then B
867  // depends on the output of A.
868  void BBVectorize::buildDepMap(
869                      BasicBlock &BB,
870                      std::multimap<Value *, Value *> &CandidatePairs,
871                      std::vector<Value *> &PairableInsts,
872                      DenseSet<ValuePair> &PairableInstUsers) {
873    DenseSet<Value *> IsInPair;
874    for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
875         E = CandidatePairs.end(); C != E; ++C) {
876      IsInPair.insert(C->first);
877      IsInPair.insert(C->second);
878    }
879
880    // Iterate through the basic block, recording all Users of each
881    // pairable instruction.
882
883    BasicBlock::iterator E = BB.end();
884    for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
885      if (IsInPair.find(I) == IsInPair.end()) continue;
886
887      DenseSet<Value *> Users;
888      AliasSetTracker WriteSet(*AA);
889      for (BasicBlock::iterator J = llvm::next(I); J != E; ++J)
890        (void) trackUsesOfI(Users, WriteSet, I, J);
891
892      for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
893           U != E; ++U)
894        PairableInstUsers.insert(ValuePair(I, *U));
895    }
896  }
897
898  // Returns true if an input to pair P is an output of pair Q and also an
899  // input of pair Q is an output of pair P. If this is the case, then these
900  // two pairs cannot be simultaneously fused.
901  bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
902                     DenseSet<ValuePair> &PairableInstUsers,
903                     std::multimap<ValuePair, ValuePair> *PairableInstUserMap) {
904    // Two pairs are in conflict if they are mutual Users of eachother.
905    bool QUsesP = PairableInstUsers.count(ValuePair(P.first,  Q.first))  ||
906                  PairableInstUsers.count(ValuePair(P.first,  Q.second)) ||
907                  PairableInstUsers.count(ValuePair(P.second, Q.first))  ||
908                  PairableInstUsers.count(ValuePair(P.second, Q.second));
909    bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first,  P.first))  ||
910                  PairableInstUsers.count(ValuePair(Q.first,  P.second)) ||
911                  PairableInstUsers.count(ValuePair(Q.second, P.first))  ||
912                  PairableInstUsers.count(ValuePair(Q.second, P.second));
913    if (PairableInstUserMap) {
914      // FIXME: The expensive part of the cycle check is not so much the cycle
915      // check itself but this edge insertion procedure. This needs some
916      // profiling and probably a different data structure (same is true of
917      // most uses of std::multimap).
918      if (PUsesQ) {
919        VPPIteratorPair QPairRange = PairableInstUserMap->equal_range(Q);
920        if (!isSecondInIteratorPair(P, QPairRange))
921          PairableInstUserMap->insert(VPPair(Q, P));
922      }
923      if (QUsesP) {
924        VPPIteratorPair PPairRange = PairableInstUserMap->equal_range(P);
925        if (!isSecondInIteratorPair(Q, PPairRange))
926          PairableInstUserMap->insert(VPPair(P, Q));
927      }
928    }
929
930    return (QUsesP && PUsesQ);
931  }
932
933  // This function walks the use graph of current pairs to see if, starting
934  // from P, the walk returns to P.
935  bool BBVectorize::pairWillFormCycle(ValuePair P,
936                       std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
937                       DenseSet<ValuePair> &CurrentPairs) {
938    DEBUG(if (DebugCycleCheck)
939            dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
940                   << *P.second << "\n");
941    // A lookup table of visisted pairs is kept because the PairableInstUserMap
942    // contains non-direct associations.
943    DenseSet<ValuePair> Visited;
944    SmallVector<ValuePair, 32> Q;
945    // General depth-first post-order traversal:
946    Q.push_back(P);
947    do {
948      ValuePair QTop = Q.pop_back_val();
949      Visited.insert(QTop);
950
951      DEBUG(if (DebugCycleCheck)
952              dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
953                     << *QTop.second << "\n");
954      VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
955      for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
956           C != QPairRange.second; ++C) {
957        if (C->second == P) {
958          DEBUG(dbgs()
959                 << "BBV: rejected to prevent non-trivial cycle formation: "
960                 << *C->first.first << " <-> " << *C->first.second << "\n");
961          return true;
962        }
963
964        if (CurrentPairs.count(C->second) && !Visited.count(C->second))
965          Q.push_back(C->second);
966      }
967    } while (!Q.empty());
968
969    return false;
970  }
971
972  // This function builds the initial tree of connected pairs with the
973  // pair J at the root.
974  void BBVectorize::buildInitialTreeFor(
975                      std::multimap<Value *, Value *> &CandidatePairs,
976                      std::vector<Value *> &PairableInsts,
977                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
978                      DenseSet<ValuePair> &PairableInstUsers,
979                      DenseMap<Value *, Value *> &ChosenPairs,
980                      DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
981    // Each of these pairs is viewed as the root node of a Tree. The Tree
982    // is then walked (depth-first). As this happens, we keep track of
983    // the pairs that compose the Tree and the maximum depth of the Tree.
984    SmallVector<ValuePairWithDepth, 32> Q;
985    // General depth-first post-order traversal:
986    Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
987    do {
988      ValuePairWithDepth QTop = Q.back();
989
990      // Push each child onto the queue:
991      bool MoreChildren = false;
992      size_t MaxChildDepth = QTop.second;
993      VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
994      for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
995           k != qtRange.second; ++k) {
996        // Make sure that this child pair is still a candidate:
997        bool IsStillCand = false;
998        VPIteratorPair checkRange =
999          CandidatePairs.equal_range(k->second.first);
1000        for (std::multimap<Value *, Value *>::iterator m = checkRange.first;
1001             m != checkRange.second; ++m) {
1002          if (m->second == k->second.second) {
1003            IsStillCand = true;
1004            break;
1005          }
1006        }
1007
1008        if (IsStillCand) {
1009          DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
1010          if (C == Tree.end()) {
1011            size_t d = getDepthFactor(k->second.first);
1012            Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
1013            MoreChildren = true;
1014          } else {
1015            MaxChildDepth = std::max(MaxChildDepth, C->second);
1016          }
1017        }
1018      }
1019
1020      if (!MoreChildren) {
1021        // Record the current pair as part of the Tree:
1022        Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1023        Q.pop_back();
1024      }
1025    } while (!Q.empty());
1026  }
1027
1028  // Given some initial tree, prune it by removing conflicting pairs (pairs
1029  // that cannot be simultaneously chosen for vectorization).
1030  void BBVectorize::pruneTreeFor(
1031                      std::multimap<Value *, Value *> &CandidatePairs,
1032                      std::vector<Value *> &PairableInsts,
1033                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1034                      DenseSet<ValuePair> &PairableInstUsers,
1035                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1036                      DenseMap<Value *, Value *> &ChosenPairs,
1037                      DenseMap<ValuePair, size_t> &Tree,
1038                      DenseSet<ValuePair> &PrunedTree, ValuePair J,
1039                      bool UseCycleCheck) {
1040    SmallVector<ValuePairWithDepth, 32> Q;
1041    // General depth-first post-order traversal:
1042    Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1043    do {
1044      ValuePairWithDepth QTop = Q.pop_back_val();
1045      PrunedTree.insert(QTop.first);
1046
1047      // Visit each child, pruning as necessary...
1048      DenseMap<ValuePair, size_t> BestChilden;
1049      VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
1050      for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
1051           K != QTopRange.second; ++K) {
1052        DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
1053        if (C == Tree.end()) continue;
1054
1055        // This child is in the Tree, now we need to make sure it is the
1056        // best of any conflicting children. There could be multiple
1057        // conflicting children, so first, determine if we're keeping
1058        // this child, then delete conflicting children as necessary.
1059
1060        // It is also necessary to guard against pairing-induced
1061        // dependencies. Consider instructions a .. x .. y .. b
1062        // such that (a,b) are to be fused and (x,y) are to be fused
1063        // but a is an input to x and b is an output from y. This
1064        // means that y cannot be moved after b but x must be moved
1065        // after b for (a,b) to be fused. In other words, after
1066        // fusing (a,b) we have y .. a/b .. x where y is an input
1067        // to a/b and x is an output to a/b: x and y can no longer
1068        // be legally fused. To prevent this condition, we must
1069        // make sure that a child pair added to the Tree is not
1070        // both an input and output of an already-selected pair.
1071
1072        // Pairing-induced dependencies can also form from more complicated
1073        // cycles. The pair vs. pair conflicts are easy to check, and so
1074        // that is done explicitly for "fast rejection", and because for
1075        // child vs. child conflicts, we may prefer to keep the current
1076        // pair in preference to the already-selected child.
1077        DenseSet<ValuePair> CurrentPairs;
1078
1079        bool CanAdd = true;
1080        for (DenseMap<ValuePair, size_t>::iterator C2
1081              = BestChilden.begin(), E2 = BestChilden.end();
1082             C2 != E2; ++C2) {
1083          if (C2->first.first == C->first.first ||
1084              C2->first.first == C->first.second ||
1085              C2->first.second == C->first.first ||
1086              C2->first.second == C->first.second ||
1087              pairsConflict(C2->first, C->first, PairableInstUsers,
1088                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1089            if (C2->second >= C->second) {
1090              CanAdd = false;
1091              break;
1092            }
1093
1094            CurrentPairs.insert(C2->first);
1095          }
1096        }
1097        if (!CanAdd) continue;
1098
1099        // Even worse, this child could conflict with another node already
1100        // selected for the Tree. If that is the case, ignore this child.
1101        for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1102             E2 = PrunedTree.end(); T != E2; ++T) {
1103          if (T->first == C->first.first ||
1104              T->first == C->first.second ||
1105              T->second == C->first.first ||
1106              T->second == C->first.second ||
1107              pairsConflict(*T, C->first, PairableInstUsers,
1108                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1109            CanAdd = false;
1110            break;
1111          }
1112
1113          CurrentPairs.insert(*T);
1114        }
1115        if (!CanAdd) continue;
1116
1117        // And check the queue too...
1118        for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1119             E2 = Q.end(); C2 != E2; ++C2) {
1120          if (C2->first.first == C->first.first ||
1121              C2->first.first == C->first.second ||
1122              C2->first.second == C->first.first ||
1123              C2->first.second == C->first.second ||
1124              pairsConflict(C2->first, C->first, PairableInstUsers,
1125                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1126            CanAdd = false;
1127            break;
1128          }
1129
1130          CurrentPairs.insert(C2->first);
1131        }
1132        if (!CanAdd) continue;
1133
1134        // Last but not least, check for a conflict with any of the
1135        // already-chosen pairs.
1136        for (DenseMap<Value *, Value *>::iterator C2 =
1137              ChosenPairs.begin(), E2 = ChosenPairs.end();
1138             C2 != E2; ++C2) {
1139          if (pairsConflict(*C2, C->first, PairableInstUsers,
1140                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1141            CanAdd = false;
1142            break;
1143          }
1144
1145          CurrentPairs.insert(*C2);
1146        }
1147        if (!CanAdd) continue;
1148
1149        // To check for non-trivial cycles formed by the addition of the
1150        // current pair we've formed a list of all relevant pairs, now use a
1151        // graph walk to check for a cycle. We start from the current pair and
1152        // walk the use tree to see if we again reach the current pair. If we
1153        // do, then the current pair is rejected.
1154
1155        // FIXME: It may be more efficient to use a topological-ordering
1156        // algorithm to improve the cycle check. This should be investigated.
1157        if (UseCycleCheck &&
1158            pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1159          continue;
1160
1161        // This child can be added, but we may have chosen it in preference
1162        // to an already-selected child. Check for this here, and if a
1163        // conflict is found, then remove the previously-selected child
1164        // before adding this one in its place.
1165        for (DenseMap<ValuePair, size_t>::iterator C2
1166              = BestChilden.begin(); C2 != BestChilden.end();) {
1167          if (C2->first.first == C->first.first ||
1168              C2->first.first == C->first.second ||
1169              C2->first.second == C->first.first ||
1170              C2->first.second == C->first.second ||
1171              pairsConflict(C2->first, C->first, PairableInstUsers))
1172            BestChilden.erase(C2++);
1173          else
1174            ++C2;
1175        }
1176
1177        BestChilden.insert(ValuePairWithDepth(C->first, C->second));
1178      }
1179
1180      for (DenseMap<ValuePair, size_t>::iterator C
1181            = BestChilden.begin(), E2 = BestChilden.end();
1182           C != E2; ++C) {
1183        size_t DepthF = getDepthFactor(C->first.first);
1184        Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1185      }
1186    } while (!Q.empty());
1187  }
1188
1189  // This function finds the best tree of mututally-compatible connected
1190  // pairs, given the choice of root pairs as an iterator range.
1191  void BBVectorize::findBestTreeFor(
1192                      std::multimap<Value *, Value *> &CandidatePairs,
1193                      std::vector<Value *> &PairableInsts,
1194                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1195                      DenseSet<ValuePair> &PairableInstUsers,
1196                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1197                      DenseMap<Value *, Value *> &ChosenPairs,
1198                      DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1199                      size_t &BestEffSize, VPIteratorPair ChoiceRange,
1200                      bool UseCycleCheck) {
1201    for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
1202         J != ChoiceRange.second; ++J) {
1203
1204      // Before going any further, make sure that this pair does not
1205      // conflict with any already-selected pairs (see comment below
1206      // near the Tree pruning for more details).
1207      DenseSet<ValuePair> ChosenPairSet;
1208      bool DoesConflict = false;
1209      for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1210           E = ChosenPairs.end(); C != E; ++C) {
1211        if (pairsConflict(*C, *J, PairableInstUsers,
1212                          UseCycleCheck ? &PairableInstUserMap : 0)) {
1213          DoesConflict = true;
1214          break;
1215        }
1216
1217        ChosenPairSet.insert(*C);
1218      }
1219      if (DoesConflict) continue;
1220
1221      if (UseCycleCheck &&
1222          pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1223        continue;
1224
1225      DenseMap<ValuePair, size_t> Tree;
1226      buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1227                          PairableInstUsers, ChosenPairs, Tree, *J);
1228
1229      // Because we'll keep the child with the largest depth, the largest
1230      // depth is still the same in the unpruned Tree.
1231      size_t MaxDepth = Tree.lookup(*J);
1232
1233      DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1234                   << *J->first << " <-> " << *J->second << "} of depth " <<
1235                   MaxDepth << " and size " << Tree.size() << "\n");
1236
1237      // At this point the Tree has been constructed, but, may contain
1238      // contradictory children (meaning that different children of
1239      // some tree node may be attempting to fuse the same instruction).
1240      // So now we walk the tree again, in the case of a conflict,
1241      // keep only the child with the largest depth. To break a tie,
1242      // favor the first child.
1243
1244      DenseSet<ValuePair> PrunedTree;
1245      pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1246                   PairableInstUsers, PairableInstUserMap, ChosenPairs, Tree,
1247                   PrunedTree, *J, UseCycleCheck);
1248
1249      size_t EffSize = 0;
1250      for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1251           E = PrunedTree.end(); S != E; ++S)
1252        EffSize += getDepthFactor(S->first);
1253
1254      DEBUG(if (DebugPairSelection)
1255             dbgs() << "BBV: found pruned Tree for pair {"
1256             << *J->first << " <-> " << *J->second << "} of depth " <<
1257             MaxDepth << " and size " << PrunedTree.size() <<
1258            " (effective size: " << EffSize << ")\n");
1259      if (MaxDepth >= ReqChainDepth && EffSize > BestEffSize) {
1260        BestMaxDepth = MaxDepth;
1261        BestEffSize = EffSize;
1262        BestTree = PrunedTree;
1263      }
1264    }
1265  }
1266
1267  // Given the list of candidate pairs, this function selects those
1268  // that will be fused into vector instructions.
1269  void BBVectorize::choosePairs(
1270                      std::multimap<Value *, Value *> &CandidatePairs,
1271                      std::vector<Value *> &PairableInsts,
1272                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1273                      DenseSet<ValuePair> &PairableInstUsers,
1274                      DenseMap<Value *, Value *>& ChosenPairs) {
1275    bool UseCycleCheck = CandidatePairs.size() <= MaxCandPairsForCycleCheck;
1276    std::multimap<ValuePair, ValuePair> PairableInstUserMap;
1277    for (std::vector<Value *>::iterator I = PairableInsts.begin(),
1278         E = PairableInsts.end(); I != E; ++I) {
1279      // The number of possible pairings for this variable:
1280      size_t NumChoices = CandidatePairs.count(*I);
1281      if (!NumChoices) continue;
1282
1283      VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
1284
1285      // The best pair to choose and its tree:
1286      size_t BestMaxDepth = 0, BestEffSize = 0;
1287      DenseSet<ValuePair> BestTree;
1288      findBestTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1289                      PairableInstUsers, PairableInstUserMap, ChosenPairs,
1290                      BestTree, BestMaxDepth, BestEffSize, ChoiceRange,
1291                      UseCycleCheck);
1292
1293      // A tree has been chosen (or not) at this point. If no tree was
1294      // chosen, then this instruction, I, cannot be paired (and is no longer
1295      // considered).
1296
1297      DEBUG(if (BestTree.size() > 0)
1298              dbgs() << "BBV: selected pairs in the best tree for: "
1299                     << *cast<Instruction>(*I) << "\n");
1300
1301      for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
1302           SE2 = BestTree.end(); S != SE2; ++S) {
1303        // Insert the members of this tree into the list of chosen pairs.
1304        ChosenPairs.insert(ValuePair(S->first, S->second));
1305        DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
1306               *S->second << "\n");
1307
1308        // Remove all candidate pairs that have values in the chosen tree.
1309        for (std::multimap<Value *, Value *>::iterator K =
1310               CandidatePairs.begin(); K != CandidatePairs.end();) {
1311          if (K->first == S->first || K->second == S->first ||
1312              K->second == S->second || K->first == S->second) {
1313            // Don't remove the actual pair chosen so that it can be used
1314            // in subsequent tree selections.
1315            if (!(K->first == S->first && K->second == S->second))
1316              CandidatePairs.erase(K++);
1317            else
1318              ++K;
1319          } else {
1320            ++K;
1321          }
1322        }
1323      }
1324    }
1325
1326    DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
1327  }
1328
1329  std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
1330                     unsigned n = 0) {
1331    if (!I->hasName())
1332      return "";
1333
1334    return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
1335             (n > 0 ? "." + utostr(n) : "")).str();
1336  }
1337
1338  // Returns the value that is to be used as the pointer input to the vector
1339  // instruction that fuses I with J.
1340  Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
1341                     Instruction *I, Instruction *J, unsigned o,
1342                     bool &FlipMemInputs) {
1343    Value *IPtr, *JPtr;
1344    unsigned IAlignment, JAlignment;
1345    int64_t OffsetInElmts;
1346    (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
1347                          OffsetInElmts);
1348
1349    // The pointer value is taken to be the one with the lowest offset.
1350    Value *VPtr;
1351    if (OffsetInElmts > 0) {
1352      VPtr = IPtr;
1353    } else {
1354      FlipMemInputs = true;
1355      VPtr = JPtr;
1356    }
1357
1358    Type *ArgType = cast<PointerType>(IPtr->getType())->getElementType();
1359    Type *VArgType = getVecTypeForPair(ArgType);
1360    Type *VArgPtrType = PointerType::get(VArgType,
1361      cast<PointerType>(IPtr->getType())->getAddressSpace());
1362    return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
1363                        /* insert before */ FlipMemInputs ? J : I);
1364  }
1365
1366  void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
1367                     unsigned NumElem, unsigned MaskOffset, unsigned NumInElem,
1368                     unsigned IdxOffset, std::vector<Constant*> &Mask) {
1369    for (unsigned v = 0; v < NumElem/2; ++v) {
1370      int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
1371      if (m < 0) {
1372        Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
1373      } else {
1374        unsigned mm = m + (int) IdxOffset;
1375        if (m >= (int) NumInElem)
1376          mm += (int) NumInElem;
1377
1378        Mask[v+MaskOffset] =
1379          ConstantInt::get(Type::getInt32Ty(Context), mm);
1380      }
1381    }
1382  }
1383
1384  // Returns the value that is to be used as the vector-shuffle mask to the
1385  // vector instruction that fuses I with J.
1386  Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
1387                     Instruction *I, Instruction *J) {
1388    // This is the shuffle mask. We need to append the second
1389    // mask to the first, and the numbers need to be adjusted.
1390
1391    Type *ArgType = I->getType();
1392    Type *VArgType = getVecTypeForPair(ArgType);
1393
1394    // Get the total number of elements in the fused vector type.
1395    // By definition, this must equal the number of elements in
1396    // the final mask.
1397    unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
1398    std::vector<Constant*> Mask(NumElem);
1399
1400    Type *OpType = I->getOperand(0)->getType();
1401    unsigned NumInElem = cast<VectorType>(OpType)->getNumElements();
1402
1403    // For the mask from the first pair...
1404    fillNewShuffleMask(Context, I, NumElem, 0, NumInElem, 0, Mask);
1405
1406    // For the mask from the second pair...
1407    fillNewShuffleMask(Context, J, NumElem, NumElem/2, NumInElem, NumInElem,
1408                       Mask);
1409
1410    return ConstantVector::get(Mask);
1411  }
1412
1413  // Returns the value to be used as the specified operand of the vector
1414  // instruction that fuses I with J.
1415  Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
1416                     Instruction *J, unsigned o, bool FlipMemInputs) {
1417    Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1418    Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1419
1420      // Compute the fused vector type for this operand
1421    Type *ArgType = I->getOperand(o)->getType();
1422    VectorType *VArgType = getVecTypeForPair(ArgType);
1423
1424    Instruction *L = I, *H = J;
1425    if (FlipMemInputs) {
1426      L = J;
1427      H = I;
1428    }
1429
1430    if (ArgType->isVectorTy()) {
1431      unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
1432      std::vector<Constant*> Mask(numElem);
1433      for (unsigned v = 0; v < numElem; ++v)
1434        Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1435
1436      Instruction *BV = new ShuffleVectorInst(L->getOperand(o),
1437                                              H->getOperand(o),
1438                                              ConstantVector::get(Mask),
1439                                              getReplacementName(I, true, o));
1440      BV->insertBefore(J);
1441      return BV;
1442    }
1443
1444    // If these two inputs are the output of another vector instruction,
1445    // then we should use that output directly. It might be necessary to
1446    // permute it first. [When pairings are fused recursively, you can
1447    // end up with cases where a large vector is decomposed into scalars
1448    // using extractelement instructions, then built into size-2
1449    // vectors using insertelement and the into larger vectors using
1450    // shuffles. InstCombine does not simplify all of these cases well,
1451    // and so we make sure that shuffles are generated here when possible.
1452    ExtractElementInst *LEE
1453      = dyn_cast<ExtractElementInst>(L->getOperand(o));
1454    ExtractElementInst *HEE
1455      = dyn_cast<ExtractElementInst>(H->getOperand(o));
1456
1457    if (LEE && HEE &&
1458        LEE->getOperand(0)->getType() == HEE->getOperand(0)->getType()) {
1459      VectorType *EEType = cast<VectorType>(LEE->getOperand(0)->getType());
1460      unsigned LowIndx = cast<ConstantInt>(LEE->getOperand(1))->getZExtValue();
1461      unsigned HighIndx = cast<ConstantInt>(HEE->getOperand(1))->getZExtValue();
1462      if (LEE->getOperand(0) == HEE->getOperand(0)) {
1463        if (LowIndx == 0 && HighIndx == 1)
1464          return LEE->getOperand(0);
1465
1466        std::vector<Constant*> Mask(2);
1467        Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
1468        Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
1469
1470        Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
1471                                          UndefValue::get(EEType),
1472                                          ConstantVector::get(Mask),
1473                                          getReplacementName(I, true, o));
1474        BV->insertBefore(J);
1475        return BV;
1476      }
1477
1478      std::vector<Constant*> Mask(2);
1479      HighIndx += EEType->getNumElements();
1480      Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
1481      Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
1482
1483      Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
1484                                          HEE->getOperand(0),
1485                                          ConstantVector::get(Mask),
1486                                          getReplacementName(I, true, o));
1487      BV->insertBefore(J);
1488      return BV;
1489    }
1490
1491    Instruction *BV1 = InsertElementInst::Create(
1492                                          UndefValue::get(VArgType),
1493                                          L->getOperand(o), CV0,
1494                                          getReplacementName(I, true, o, 1));
1495    BV1->insertBefore(I);
1496    Instruction *BV2 = InsertElementInst::Create(BV1, H->getOperand(o),
1497                                          CV1,
1498                                          getReplacementName(I, true, o, 2));
1499    BV2->insertBefore(J);
1500    return BV2;
1501  }
1502
1503  // This function creates an array of values that will be used as the inputs
1504  // to the vector instruction that fuses I with J.
1505  void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
1506                     Instruction *I, Instruction *J,
1507                     SmallVector<Value *, 3> &ReplacedOperands,
1508                     bool &FlipMemInputs) {
1509    FlipMemInputs = false;
1510    unsigned NumOperands = I->getNumOperands();
1511
1512    for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
1513      // Iterate backward so that we look at the store pointer
1514      // first and know whether or not we need to flip the inputs.
1515
1516      if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
1517        // This is the pointer for a load/store instruction.
1518        ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o,
1519                                FlipMemInputs);
1520        continue;
1521      } else if (isa<CallInst>(I) && o == NumOperands-1) {
1522        Function *F = cast<CallInst>(I)->getCalledFunction();
1523        unsigned IID = F->getIntrinsicID();
1524        BasicBlock &BB = *I->getParent();
1525
1526        Module *M = BB.getParent()->getParent();
1527        Type *ArgType = I->getType();
1528        Type *VArgType = getVecTypeForPair(ArgType);
1529
1530        // FIXME: is it safe to do this here?
1531        ReplacedOperands[o] = Intrinsic::getDeclaration(M,
1532          (Intrinsic::ID) IID, VArgType);
1533        continue;
1534      } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
1535        ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
1536        continue;
1537      }
1538
1539      ReplacedOperands[o] =
1540        getReplacementInput(Context, I, J, o, FlipMemInputs);
1541    }
1542  }
1543
1544  // This function creates two values that represent the outputs of the
1545  // original I and J instructions. These are generally vector shuffles
1546  // or extracts. In many cases, these will end up being unused and, thus,
1547  // eliminated by later passes.
1548  void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
1549                     Instruction *J, Instruction *K,
1550                     Instruction *&InsertionPt,
1551                     Instruction *&K1, Instruction *&K2,
1552                     bool &FlipMemInputs) {
1553    Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1554    Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1555
1556    if (isa<StoreInst>(I)) {
1557      AA->replaceWithNewValue(I, K);
1558      AA->replaceWithNewValue(J, K);
1559    } else {
1560      Type *IType = I->getType();
1561      Type *VType = getVecTypeForPair(IType);
1562
1563      if (IType->isVectorTy()) {
1564          unsigned numElem = cast<VectorType>(IType)->getNumElements();
1565          std::vector<Constant*> Mask1(numElem), Mask2(numElem);
1566          for (unsigned v = 0; v < numElem; ++v) {
1567            Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1568            Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElem+v);
1569          }
1570
1571          K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
1572                                       ConstantVector::get(
1573                                         FlipMemInputs ? Mask2 : Mask1),
1574                                       getReplacementName(K, false, 1));
1575          K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
1576                                       ConstantVector::get(
1577                                         FlipMemInputs ? Mask1 : Mask2),
1578                                       getReplacementName(K, false, 2));
1579      } else {
1580        K1 = ExtractElementInst::Create(K, FlipMemInputs ? CV1 : CV0,
1581                                          getReplacementName(K, false, 1));
1582        K2 = ExtractElementInst::Create(K, FlipMemInputs ? CV0 : CV1,
1583                                          getReplacementName(K, false, 2));
1584      }
1585
1586      K1->insertAfter(K);
1587      K2->insertAfter(K1);
1588      InsertionPt = K2;
1589    }
1590  }
1591
1592  // Move all uses of the function I (including pairing-induced uses) after J.
1593  bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
1594                     std::multimap<Value *, Value *> &LoadMoveSet,
1595                     Instruction *I, Instruction *J) {
1596    // Skip to the first instruction past I.
1597    BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1598
1599    DenseSet<Value *> Users;
1600    AliasSetTracker WriteSet(*AA);
1601    for (; cast<Instruction>(L) != J; ++L)
1602      (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet);
1603
1604    assert(cast<Instruction>(L) == J &&
1605      "Tracking has not proceeded far enough to check for dependencies");
1606    // If J is now in the use set of I, then trackUsesOfI will return true
1607    // and we have a dependency cycle (and the fusing operation must abort).
1608    return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSet);
1609  }
1610
1611  // Move all uses of the function I (including pairing-induced uses) after J.
1612  void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
1613                     std::multimap<Value *, Value *> &LoadMoveSet,
1614                     Instruction *&InsertionPt,
1615                     Instruction *I, Instruction *J) {
1616    // Skip to the first instruction past I.
1617    BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1618
1619    DenseSet<Value *> Users;
1620    AliasSetTracker WriteSet(*AA);
1621    for (; cast<Instruction>(L) != J;) {
1622      if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet)) {
1623        // Move this instruction
1624        Instruction *InstToMove = L; ++L;
1625
1626        DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
1627                        " to after " << *InsertionPt << "\n");
1628        InstToMove->removeFromParent();
1629        InstToMove->insertAfter(InsertionPt);
1630        InsertionPt = InstToMove;
1631      } else {
1632        ++L;
1633      }
1634    }
1635  }
1636
1637  // Collect all load instruction that are in the move set of a given first
1638  // pair member.  These loads depend on the first instruction, I, and so need
1639  // to be moved after J (the second instruction) when the pair is fused.
1640  void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
1641                     DenseMap<Value *, Value *> &ChosenPairs,
1642                     std::multimap<Value *, Value *> &LoadMoveSet,
1643                     Instruction *I) {
1644    // Skip to the first instruction past I.
1645    BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1646
1647    DenseSet<Value *> Users;
1648    AliasSetTracker WriteSet(*AA);
1649
1650    // Note: We cannot end the loop when we reach J because J could be moved
1651    // farther down the use chain by another instruction pairing. Also, J
1652    // could be before I if this is an inverted input.
1653    for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
1654      if (trackUsesOfI(Users, WriteSet, I, L)) {
1655        if (L->mayReadFromMemory())
1656          LoadMoveSet.insert(ValuePair(L, I));
1657      }
1658    }
1659  }
1660
1661  // In cases where both load/stores and the computation of their pointers
1662  // are chosen for vectorization, we can end up in a situation where the
1663  // aliasing analysis starts returning different query results as the
1664  // process of fusing instruction pairs continues. Because the algorithm
1665  // relies on finding the same use trees here as were found earlier, we'll
1666  // need to precompute the necessary aliasing information here and then
1667  // manually update it during the fusion process.
1668  void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
1669                     std::vector<Value *> &PairableInsts,
1670                     DenseMap<Value *, Value *> &ChosenPairs,
1671                     std::multimap<Value *, Value *> &LoadMoveSet) {
1672    for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1673         PIE = PairableInsts.end(); PI != PIE; ++PI) {
1674      DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
1675      if (P == ChosenPairs.end()) continue;
1676
1677      Instruction *I = cast<Instruction>(P->first);
1678      collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet, I);
1679    }
1680  }
1681
1682  // This function fuses the chosen instruction pairs into vector instructions,
1683  // taking care preserve any needed scalar outputs and, then, it reorders the
1684  // remaining instructions as needed (users of the first member of the pair
1685  // need to be moved to after the location of the second member of the pair
1686  // because the vector instruction is inserted in the location of the pair's
1687  // second member).
1688  void BBVectorize::fuseChosenPairs(BasicBlock &BB,
1689                     std::vector<Value *> &PairableInsts,
1690                     DenseMap<Value *, Value *> &ChosenPairs) {
1691    LLVMContext& Context = BB.getContext();
1692
1693    // During the vectorization process, the order of the pairs to be fused
1694    // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
1695    // list. After a pair is fused, the flipped pair is removed from the list.
1696    std::vector<ValuePair> FlippedPairs;
1697    FlippedPairs.reserve(ChosenPairs.size());
1698    for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
1699         E = ChosenPairs.end(); P != E; ++P)
1700      FlippedPairs.push_back(ValuePair(P->second, P->first));
1701    for (std::vector<ValuePair>::iterator P = FlippedPairs.begin(),
1702         E = FlippedPairs.end(); P != E; ++P)
1703      ChosenPairs.insert(*P);
1704
1705    std::multimap<Value *, Value *> LoadMoveSet;
1706    collectLoadMoveSet(BB, PairableInsts, ChosenPairs, LoadMoveSet);
1707
1708    DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
1709
1710    for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
1711      DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
1712      if (P == ChosenPairs.end()) {
1713        ++PI;
1714        continue;
1715      }
1716
1717      if (getDepthFactor(P->first) == 0) {
1718        // These instructions are not really fused, but are tracked as though
1719        // they are. Any case in which it would be interesting to fuse them
1720        // will be taken care of by InstCombine.
1721        --NumFusedOps;
1722        ++PI;
1723        continue;
1724      }
1725
1726      Instruction *I = cast<Instruction>(P->first),
1727        *J = cast<Instruction>(P->second);
1728
1729      DEBUG(dbgs() << "BBV: fusing: " << *I <<
1730             " <-> " << *J << "\n");
1731
1732      // Remove the pair and flipped pair from the list.
1733      DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
1734      assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
1735      ChosenPairs.erase(FP);
1736      ChosenPairs.erase(P);
1737
1738      if (!canMoveUsesOfIAfterJ(BB, LoadMoveSet, I, J)) {
1739        DEBUG(dbgs() << "BBV: fusion of: " << *I <<
1740               " <-> " << *J <<
1741               " aborted because of non-trivial dependency cycle\n");
1742        --NumFusedOps;
1743        ++PI;
1744        continue;
1745      }
1746
1747      bool FlipMemInputs;
1748      unsigned NumOperands = I->getNumOperands();
1749      SmallVector<Value *, 3> ReplacedOperands(NumOperands);
1750      getReplacementInputsForPair(Context, I, J, ReplacedOperands,
1751        FlipMemInputs);
1752
1753      // Make a copy of the original operation, change its type to the vector
1754      // type and replace its operands with the vector operands.
1755      Instruction *K = I->clone();
1756      if (I->hasName()) K->takeName(I);
1757
1758      if (!isa<StoreInst>(K))
1759        K->mutateType(getVecTypeForPair(I->getType()));
1760
1761      for (unsigned o = 0; o < NumOperands; ++o)
1762        K->setOperand(o, ReplacedOperands[o]);
1763
1764      // If we've flipped the memory inputs, make sure that we take the correct
1765      // alignment.
1766      if (FlipMemInputs) {
1767        if (isa<StoreInst>(K))
1768          cast<StoreInst>(K)->setAlignment(cast<StoreInst>(J)->getAlignment());
1769        else
1770          cast<LoadInst>(K)->setAlignment(cast<LoadInst>(J)->getAlignment());
1771      }
1772
1773      K->insertAfter(J);
1774
1775      // Instruction insertion point:
1776      Instruction *InsertionPt = K;
1777      Instruction *K1 = 0, *K2 = 0;
1778      replaceOutputsOfPair(Context, I, J, K, InsertionPt, K1, K2,
1779        FlipMemInputs);
1780
1781      // The use tree of the first original instruction must be moved to after
1782      // the location of the second instruction. The entire use tree of the
1783      // first instruction is disjoint from the input tree of the second
1784      // (by definition), and so commutes with it.
1785
1786      moveUsesOfIAfterJ(BB, LoadMoveSet, InsertionPt, I, J);
1787
1788      if (!isa<StoreInst>(I)) {
1789        I->replaceAllUsesWith(K1);
1790        J->replaceAllUsesWith(K2);
1791        AA->replaceWithNewValue(I, K1);
1792        AA->replaceWithNewValue(J, K2);
1793      }
1794
1795      // Instructions that may read from memory may be in the load move set.
1796      // Once an instruction is fused, we no longer need its move set, and so
1797      // the values of the map never need to be updated. However, when a load
1798      // is fused, we need to merge the entries from both instructions in the
1799      // pair in case those instructions were in the move set of some other
1800      // yet-to-be-fused pair. The loads in question are the keys of the map.
1801      if (I->mayReadFromMemory()) {
1802        std::vector<ValuePair> NewSetMembers;
1803        VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
1804        VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
1805        for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
1806             N != IPairRange.second; ++N)
1807          NewSetMembers.push_back(ValuePair(K, N->second));
1808        for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
1809             N != JPairRange.second; ++N)
1810          NewSetMembers.push_back(ValuePair(K, N->second));
1811        for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
1812             AE = NewSetMembers.end(); A != AE; ++A)
1813          LoadMoveSet.insert(*A);
1814      }
1815
1816      // Before removing I, set the iterator to the next instruction.
1817      PI = llvm::next(BasicBlock::iterator(I));
1818      if (cast<Instruction>(PI) == J)
1819        ++PI;
1820
1821      SE->forgetValue(I);
1822      SE->forgetValue(J);
1823      I->eraseFromParent();
1824      J->eraseFromParent();
1825    }
1826
1827    DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
1828  }
1829}
1830
1831char BBVectorize::ID = 0;
1832static const char bb_vectorize_name[] = "Basic-Block Vectorization";
1833INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
1834INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1835INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1836INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
1837
1838BasicBlockPass *llvm::createBBVectorizePass() {
1839  return new BBVectorize();
1840}
1841
1842