BBVectorize.cpp revision 5c05f2b99e6d377786b4384925e61577f385f49c
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          for (AliasSet::iterator A = W->begin(), AE = W->end();
696               A != AE; ++A) {
697            AliasAnalysis::Location ptrLoc(A->getValue(), A->getSize(),
698                                           A->getTBAAInfo());
699            if (AA->getModRefInfo(J, ptrLoc) != AliasAnalysis::NoModRef) {
700              UsesI = true;
701              break;
702            }
703          }
704          if (UsesI) break;
705        }
706      }
707    }
708
709    if (UsesI && UpdateUsers) {
710      if (J->mayWriteToMemory()) WriteSet.add(J);
711      Users.insert(J);
712    }
713
714    return UsesI;
715  }
716
717  // This function iterates over all instruction pairs in the provided
718  // basic block and collects all candidate pairs for vectorization.
719  bool BBVectorize::getCandidatePairs(BasicBlock &BB,
720                       BasicBlock::iterator &Start,
721                       std::multimap<Value *, Value *> &CandidatePairs,
722                       std::vector<Value *> &PairableInsts) {
723    BasicBlock::iterator E = BB.end();
724    if (Start == E) return false;
725
726    bool ShouldContinue = false, IAfterStart = false;
727    for (BasicBlock::iterator I = Start++; I != E; ++I) {
728      if (I == Start) IAfterStart = true;
729
730      bool IsSimpleLoadStore;
731      if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
732
733      // Look for an instruction with which to pair instruction *I...
734      DenseSet<Value *> Users;
735      AliasSetTracker WriteSet(*AA);
736      bool JAfterStart = IAfterStart;
737      BasicBlock::iterator J = llvm::next(I);
738      for (unsigned ss = 0; J != E && ss <= SearchLimit; ++J, ++ss) {
739        if (J == Start) JAfterStart = true;
740
741        // Determine if J uses I, if so, exit the loop.
742        bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !FastDep);
743        if (FastDep) {
744          // Note: For this heuristic to be effective, independent operations
745          // must tend to be intermixed. This is likely to be true from some
746          // kinds of grouped loop unrolling (but not the generic LLVM pass),
747          // but otherwise may require some kind of reordering pass.
748
749          // When using fast dependency analysis,
750          // stop searching after first use:
751          if (UsesI) break;
752        } else {
753          if (UsesI) continue;
754        }
755
756        // J does not use I, and comes before the first use of I, so it can be
757        // merged with I if the instructions are compatible.
758        if (!areInstsCompatible(I, J, IsSimpleLoadStore)) continue;
759
760        // J is a candidate for merging with I.
761        if (!PairableInsts.size() ||
762             PairableInsts[PairableInsts.size()-1] != I) {
763          PairableInsts.push_back(I);
764        }
765
766        CandidatePairs.insert(ValuePair(I, J));
767
768        // The next call to this function must start after the last instruction
769        // selected during this invocation.
770        if (JAfterStart) {
771          Start = llvm::next(J);
772          IAfterStart = JAfterStart = false;
773        }
774
775        DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
776                     << *I << " <-> " << *J << "\n");
777
778        // If we have already found too many pairs, break here and this function
779        // will be called again starting after the last instruction selected
780        // during this invocation.
781        if (PairableInsts.size() >= MaxInsts) {
782          ShouldContinue = true;
783          break;
784        }
785      }
786
787      if (ShouldContinue)
788        break;
789    }
790
791    DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
792           << " instructions with candidate pairs\n");
793
794    return ShouldContinue;
795  }
796
797  // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
798  // it looks for pairs such that both members have an input which is an
799  // output of PI or PJ.
800  void BBVectorize::computePairsConnectedTo(
801                      std::multimap<Value *, Value *> &CandidatePairs,
802                      std::vector<Value *> &PairableInsts,
803                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
804                      ValuePair P) {
805    // For each possible pairing for this variable, look at the uses of
806    // the first value...
807    for (Value::use_iterator I = P.first->use_begin(),
808         E = P.first->use_end(); I != E; ++I) {
809      VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
810
811      // For each use of the first variable, look for uses of the second
812      // variable...
813      for (Value::use_iterator J = P.second->use_begin(),
814           E2 = P.second->use_end(); J != E2; ++J) {
815        VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
816
817        // Look for <I, J>:
818        if (isSecondInIteratorPair<Value*>(*J, IPairRange))
819          ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
820
821        // Look for <J, I>:
822        if (isSecondInIteratorPair<Value*>(*I, JPairRange))
823          ConnectedPairs.insert(VPPair(P, ValuePair(*J, *I)));
824      }
825
826      if (SplatBreaksChain) continue;
827      // Look for cases where just the first value in the pair is used by
828      // both members of another pair (splatting).
829      for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
830        if (isSecondInIteratorPair<Value*>(*J, IPairRange))
831          ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
832      }
833    }
834
835    if (SplatBreaksChain) return;
836    // Look for cases where just the second value in the pair is used by
837    // both members of another pair (splatting).
838    for (Value::use_iterator I = P.second->use_begin(),
839         E = P.second->use_end(); I != E; ++I) {
840      VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
841
842      for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
843        if (isSecondInIteratorPair<Value*>(*J, IPairRange))
844          ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
845      }
846    }
847  }
848
849  // This function figures out which pairs are connected.  Two pairs are
850  // connected if some output of the first pair forms an input to both members
851  // of the second pair.
852  void BBVectorize::computeConnectedPairs(
853                      std::multimap<Value *, Value *> &CandidatePairs,
854                      std::vector<Value *> &PairableInsts,
855                      std::multimap<ValuePair, ValuePair> &ConnectedPairs) {
856
857    for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
858         PE = PairableInsts.end(); PI != PE; ++PI) {
859      VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
860
861      for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
862           P != choiceRange.second; ++P)
863        computePairsConnectedTo(CandidatePairs, PairableInsts,
864                                ConnectedPairs, *P);
865    }
866
867    DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
868                 << " pair connections.\n");
869  }
870
871  // This function builds a set of use tuples such that <A, B> is in the set
872  // if B is in the use tree of A. If B is in the use tree of A, then B
873  // depends on the output of A.
874  void BBVectorize::buildDepMap(
875                      BasicBlock &BB,
876                      std::multimap<Value *, Value *> &CandidatePairs,
877                      std::vector<Value *> &PairableInsts,
878                      DenseSet<ValuePair> &PairableInstUsers) {
879    DenseSet<Value *> IsInPair;
880    for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
881         E = CandidatePairs.end(); C != E; ++C) {
882      IsInPair.insert(C->first);
883      IsInPair.insert(C->second);
884    }
885
886    // Iterate through the basic block, recording all Users of each
887    // pairable instruction.
888
889    BasicBlock::iterator E = BB.end();
890    for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
891      if (IsInPair.find(I) == IsInPair.end()) continue;
892
893      DenseSet<Value *> Users;
894      AliasSetTracker WriteSet(*AA);
895      for (BasicBlock::iterator J = llvm::next(I); J != E; ++J)
896        (void) trackUsesOfI(Users, WriteSet, I, J);
897
898      for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
899           U != E; ++U)
900        PairableInstUsers.insert(ValuePair(I, *U));
901    }
902  }
903
904  // Returns true if an input to pair P is an output of pair Q and also an
905  // input of pair Q is an output of pair P. If this is the case, then these
906  // two pairs cannot be simultaneously fused.
907  bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
908                     DenseSet<ValuePair> &PairableInstUsers,
909                     std::multimap<ValuePair, ValuePair> *PairableInstUserMap) {
910    // Two pairs are in conflict if they are mutual Users of eachother.
911    bool QUsesP = PairableInstUsers.count(ValuePair(P.first,  Q.first))  ||
912                  PairableInstUsers.count(ValuePair(P.first,  Q.second)) ||
913                  PairableInstUsers.count(ValuePair(P.second, Q.first))  ||
914                  PairableInstUsers.count(ValuePair(P.second, Q.second));
915    bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first,  P.first))  ||
916                  PairableInstUsers.count(ValuePair(Q.first,  P.second)) ||
917                  PairableInstUsers.count(ValuePair(Q.second, P.first))  ||
918                  PairableInstUsers.count(ValuePair(Q.second, P.second));
919    if (PairableInstUserMap) {
920      // FIXME: The expensive part of the cycle check is not so much the cycle
921      // check itself but this edge insertion procedure. This needs some
922      // profiling and probably a different data structure (same is true of
923      // most uses of std::multimap).
924      if (PUsesQ) {
925        VPPIteratorPair QPairRange = PairableInstUserMap->equal_range(Q);
926        if (!isSecondInIteratorPair(P, QPairRange))
927          PairableInstUserMap->insert(VPPair(Q, P));
928      }
929      if (QUsesP) {
930        VPPIteratorPair PPairRange = PairableInstUserMap->equal_range(P);
931        if (!isSecondInIteratorPair(Q, PPairRange))
932          PairableInstUserMap->insert(VPPair(P, Q));
933      }
934    }
935
936    return (QUsesP && PUsesQ);
937  }
938
939  // This function walks the use graph of current pairs to see if, starting
940  // from P, the walk returns to P.
941  bool BBVectorize::pairWillFormCycle(ValuePair P,
942                       std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
943                       DenseSet<ValuePair> &CurrentPairs) {
944    DEBUG(if (DebugCycleCheck)
945            dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
946                   << *P.second << "\n");
947    // A lookup table of visisted pairs is kept because the PairableInstUserMap
948    // contains non-direct associations.
949    DenseSet<ValuePair> Visited;
950    SmallVector<ValuePair, 32> Q;
951    // General depth-first post-order traversal:
952    Q.push_back(P);
953    do {
954      ValuePair QTop = Q.pop_back_val();
955      Visited.insert(QTop);
956
957      DEBUG(if (DebugCycleCheck)
958              dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
959                     << *QTop.second << "\n");
960      VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
961      for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
962           C != QPairRange.second; ++C) {
963        if (C->second == P) {
964          DEBUG(dbgs()
965                 << "BBV: rejected to prevent non-trivial cycle formation: "
966                 << *C->first.first << " <-> " << *C->first.second << "\n");
967          return true;
968        }
969
970        if (CurrentPairs.count(C->second) != 0 &&
971            Visited.count(C->second) == 0)
972          Q.push_back(C->second);
973      }
974    } while (!Q.empty());
975
976    return false;
977  }
978
979  // This function builds the initial tree of connected pairs with the
980  // pair J at the root.
981  void BBVectorize::buildInitialTreeFor(
982                      std::multimap<Value *, Value *> &CandidatePairs,
983                      std::vector<Value *> &PairableInsts,
984                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
985                      DenseSet<ValuePair> &PairableInstUsers,
986                      DenseMap<Value *, Value *> &ChosenPairs,
987                      DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
988    // Each of these pairs is viewed as the root node of a Tree. The Tree
989    // is then walked (depth-first). As this happens, we keep track of
990    // the pairs that compose the Tree and the maximum depth of the Tree.
991    SmallVector<ValuePairWithDepth, 32> Q;
992    // General depth-first post-order traversal:
993    Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
994    do {
995      ValuePairWithDepth QTop = Q.back();
996
997      // Push each child onto the queue:
998      bool MoreChildren = false;
999      size_t MaxChildDepth = QTop.second;
1000      VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
1001      for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
1002           k != qtRange.second; ++k) {
1003        // Make sure that this child pair is still a candidate:
1004        bool IsStillCand = false;
1005        VPIteratorPair checkRange =
1006          CandidatePairs.equal_range(k->second.first);
1007        for (std::multimap<Value *, Value *>::iterator m = checkRange.first;
1008             m != checkRange.second; ++m) {
1009          if (m->second == k->second.second) {
1010            IsStillCand = true;
1011            break;
1012          }
1013        }
1014
1015        if (IsStillCand) {
1016          DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
1017          if (C == Tree.end()) {
1018            size_t d = getDepthFactor(k->second.first);
1019            Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
1020            MoreChildren = true;
1021          } else {
1022            MaxChildDepth = std::max(MaxChildDepth, C->second);
1023          }
1024        }
1025      }
1026
1027      if (!MoreChildren) {
1028        // Record the current pair as part of the Tree:
1029        Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1030        Q.pop_back();
1031      }
1032    } while (!Q.empty());
1033  }
1034
1035  // Given some initial tree, prune it by removing conflicting pairs (pairs
1036  // that cannot be simultaneously chosen for vectorization).
1037  void BBVectorize::pruneTreeFor(
1038                      std::multimap<Value *, Value *> &CandidatePairs,
1039                      std::vector<Value *> &PairableInsts,
1040                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1041                      DenseSet<ValuePair> &PairableInstUsers,
1042                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1043                      DenseMap<Value *, Value *> &ChosenPairs,
1044                      DenseMap<ValuePair, size_t> &Tree,
1045                      DenseSet<ValuePair> &PrunedTree, ValuePair J,
1046                      bool UseCycleCheck) {
1047    SmallVector<ValuePairWithDepth, 32> Q;
1048    // General depth-first post-order traversal:
1049    Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1050    do {
1051      ValuePairWithDepth QTop = Q.pop_back_val();
1052      PrunedTree.insert(QTop.first);
1053
1054      // Visit each child, pruning as necessary...
1055      DenseMap<ValuePair, size_t> BestChilden;
1056      VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
1057      for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
1058           K != QTopRange.second; ++K) {
1059        DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
1060        if (C == Tree.end()) continue;
1061
1062        // This child is in the Tree, now we need to make sure it is the
1063        // best of any conflicting children. There could be multiple
1064        // conflicting children, so first, determine if we're keeping
1065        // this child, then delete conflicting children as necessary.
1066
1067        // It is also necessary to guard against pairing-induced
1068        // dependencies. Consider instructions a .. x .. y .. b
1069        // such that (a,b) are to be fused and (x,y) are to be fused
1070        // but a is an input to x and b is an output from y. This
1071        // means that y cannot be moved after b but x must be moved
1072        // after b for (a,b) to be fused. In other words, after
1073        // fusing (a,b) we have y .. a/b .. x where y is an input
1074        // to a/b and x is an output to a/b: x and y can no longer
1075        // be legally fused. To prevent this condition, we must
1076        // make sure that a child pair added to the Tree is not
1077        // both an input and output of an already-selected pair.
1078
1079        // Pairing-induced dependencies can also form from more complicated
1080        // cycles. The pair vs. pair conflicts are easy to check, and so
1081        // that is done explicitly for "fast rejection", and because for
1082        // child vs. child conflicts, we may prefer to keep the current
1083        // pair in preference to the already-selected child.
1084        DenseSet<ValuePair> CurrentPairs;
1085
1086        bool CanAdd = true;
1087        for (DenseMap<ValuePair, size_t>::iterator C2
1088              = BestChilden.begin(), E2 = BestChilden.end();
1089             C2 != E2; ++C2) {
1090          if (C2->first.first == C->first.first ||
1091              C2->first.first == C->first.second ||
1092              C2->first.second == C->first.first ||
1093              C2->first.second == C->first.second ||
1094              pairsConflict(C2->first, C->first, PairableInstUsers,
1095                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1096            if (C2->second >= C->second) {
1097              CanAdd = false;
1098              break;
1099            }
1100
1101            CurrentPairs.insert(C2->first);
1102          }
1103        }
1104        if (!CanAdd) continue;
1105
1106        // Even worse, this child could conflict with another node already
1107        // selected for the Tree. If that is the case, ignore this child.
1108        for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1109             E2 = PrunedTree.end(); T != E2; ++T) {
1110          if (T->first == C->first.first ||
1111              T->first == C->first.second ||
1112              T->second == C->first.first ||
1113              T->second == C->first.second ||
1114              pairsConflict(*T, C->first, PairableInstUsers,
1115                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1116            CanAdd = false;
1117            break;
1118          }
1119
1120          CurrentPairs.insert(*T);
1121        }
1122        if (!CanAdd) continue;
1123
1124        // And check the queue too...
1125        for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1126             E2 = Q.end(); C2 != E2; ++C2) {
1127          if (C2->first.first == C->first.first ||
1128              C2->first.first == C->first.second ||
1129              C2->first.second == C->first.first ||
1130              C2->first.second == C->first.second ||
1131              pairsConflict(C2->first, C->first, PairableInstUsers,
1132                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1133            CanAdd = false;
1134            break;
1135          }
1136
1137          CurrentPairs.insert(C2->first);
1138        }
1139        if (!CanAdd) continue;
1140
1141        // Last but not least, check for a conflict with any of the
1142        // already-chosen pairs.
1143        for (DenseMap<Value *, Value *>::iterator C2 =
1144              ChosenPairs.begin(), E2 = ChosenPairs.end();
1145             C2 != E2; ++C2) {
1146          if (pairsConflict(*C2, C->first, PairableInstUsers,
1147                            UseCycleCheck ? &PairableInstUserMap : 0)) {
1148            CanAdd = false;
1149            break;
1150          }
1151
1152          CurrentPairs.insert(*C2);
1153        }
1154        if (!CanAdd) continue;
1155
1156	// To check for non-trivial cycles formed by the addition of the
1157	// current pair we've formed a list of all relevant pairs, now use a
1158	// graph walk to check for a cycle. We start from the current pair and
1159	// walk the use tree to see if we again reach the current pair. If we
1160	// do, then the current pair is rejected.
1161
1162        // FIXME: It may be more efficient to use a topological-ordering
1163        // algorithm to improve the cycle check. This should be investigated.
1164        if (UseCycleCheck &&
1165            pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1166          continue;
1167
1168        // This child can be added, but we may have chosen it in preference
1169        // to an already-selected child. Check for this here, and if a
1170        // conflict is found, then remove the previously-selected child
1171        // before adding this one in its place.
1172        for (DenseMap<ValuePair, size_t>::iterator C2
1173              = BestChilden.begin(); C2 != BestChilden.end();) {
1174          if (C2->first.first == C->first.first ||
1175              C2->first.first == C->first.second ||
1176              C2->first.second == C->first.first ||
1177              C2->first.second == C->first.second ||
1178              pairsConflict(C2->first, C->first, PairableInstUsers))
1179            BestChilden.erase(C2++);
1180          else
1181            ++C2;
1182        }
1183
1184        BestChilden.insert(ValuePairWithDepth(C->first, C->second));
1185      }
1186
1187      for (DenseMap<ValuePair, size_t>::iterator C
1188            = BestChilden.begin(), E2 = BestChilden.end();
1189           C != E2; ++C) {
1190        size_t DepthF = getDepthFactor(C->first.first);
1191        Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1192      }
1193    } while (!Q.empty());
1194  }
1195
1196  // This function finds the best tree of mututally-compatible connected
1197  // pairs, given the choice of root pairs as an iterator range.
1198  void BBVectorize::findBestTreeFor(
1199                      std::multimap<Value *, Value *> &CandidatePairs,
1200                      std::vector<Value *> &PairableInsts,
1201                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1202                      DenseSet<ValuePair> &PairableInstUsers,
1203                      std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1204                      DenseMap<Value *, Value *> &ChosenPairs,
1205                      DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1206                      size_t &BestEffSize, VPIteratorPair ChoiceRange,
1207                      bool UseCycleCheck) {
1208    for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
1209         J != ChoiceRange.second; ++J) {
1210
1211      // Before going any further, make sure that this pair does not
1212      // conflict with any already-selected pairs (see comment below
1213      // near the Tree pruning for more details).
1214      DenseSet<ValuePair> ChosenPairSet;
1215      bool DoesConflict = false;
1216      for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1217           E = ChosenPairs.end(); C != E; ++C) {
1218        if (pairsConflict(*C, *J, PairableInstUsers,
1219                          UseCycleCheck ? &PairableInstUserMap : 0)) {
1220          DoesConflict = true;
1221          break;
1222        }
1223
1224        ChosenPairSet.insert(*C);
1225      }
1226      if (DoesConflict) continue;
1227
1228      if (UseCycleCheck &&
1229          pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1230        continue;
1231
1232      DenseMap<ValuePair, size_t> Tree;
1233      buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1234                          PairableInstUsers, ChosenPairs, Tree, *J);
1235
1236      // Because we'll keep the child with the largest depth, the largest
1237      // depth is still the same in the unpruned Tree.
1238      size_t MaxDepth = Tree.lookup(*J);
1239
1240      DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1241                   << *J->first << " <-> " << *J->second << "} of depth " <<
1242                   MaxDepth << " and size " << Tree.size() << "\n");
1243
1244      // At this point the Tree has been constructed, but, may contain
1245      // contradictory children (meaning that different children of
1246      // some tree node may be attempting to fuse the same instruction).
1247      // So now we walk the tree again, in the case of a conflict,
1248      // keep only the child with the largest depth. To break a tie,
1249      // favor the first child.
1250
1251      DenseSet<ValuePair> PrunedTree;
1252      pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1253                   PairableInstUsers, PairableInstUserMap, ChosenPairs, Tree,
1254                   PrunedTree, *J, UseCycleCheck);
1255
1256      size_t EffSize = 0;
1257      for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1258           E = PrunedTree.end(); S != E; ++S)
1259        EffSize += getDepthFactor(S->first);
1260
1261      DEBUG(if (DebugPairSelection)
1262             dbgs() << "BBV: found pruned Tree for pair {"
1263             << *J->first << " <-> " << *J->second << "} of depth " <<
1264             MaxDepth << " and size " << PrunedTree.size() <<
1265            " (effective size: " << EffSize << ")\n");
1266      if (MaxDepth >= ReqChainDepth && EffSize > BestEffSize) {
1267        BestMaxDepth = MaxDepth;
1268        BestEffSize = EffSize;
1269        BestTree = PrunedTree;
1270      }
1271    }
1272  }
1273
1274  // Given the list of candidate pairs, this function selects those
1275  // that will be fused into vector instructions.
1276  void BBVectorize::choosePairs(
1277                      std::multimap<Value *, Value *> &CandidatePairs,
1278                      std::vector<Value *> &PairableInsts,
1279                      std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1280                      DenseSet<ValuePair> &PairableInstUsers,
1281                      DenseMap<Value *, Value *>& ChosenPairs) {
1282    bool UseCycleCheck = CandidatePairs.size() <= MaxCandPairsForCycleCheck;
1283    std::multimap<ValuePair, ValuePair> PairableInstUserMap;
1284    for (std::vector<Value *>::iterator I = PairableInsts.begin(),
1285         E = PairableInsts.end(); I != E; ++I) {
1286      // The number of possible pairings for this variable:
1287      size_t NumChoices = CandidatePairs.count(*I);
1288      if (!NumChoices) continue;
1289
1290      VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
1291
1292      // The best pair to choose and its tree:
1293      size_t BestMaxDepth = 0, BestEffSize = 0;
1294      DenseSet<ValuePair> BestTree;
1295      findBestTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1296                      PairableInstUsers, PairableInstUserMap, ChosenPairs,
1297                      BestTree, BestMaxDepth, BestEffSize, ChoiceRange,
1298                      UseCycleCheck);
1299
1300      // A tree has been chosen (or not) at this point. If no tree was
1301      // chosen, then this instruction, I, cannot be paired (and is no longer
1302      // considered).
1303
1304      DEBUG(if (BestTree.size() > 0)
1305              dbgs() << "BBV: selected pairs in the best tree for: "
1306                     << *cast<Instruction>(*I) << "\n");
1307
1308      for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
1309           SE2 = BestTree.end(); S != SE2; ++S) {
1310        // Insert the members of this tree into the list of chosen pairs.
1311        ChosenPairs.insert(ValuePair(S->first, S->second));
1312        DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
1313               *S->second << "\n");
1314
1315        // Remove all candidate pairs that have values in the chosen tree.
1316        for (std::multimap<Value *, Value *>::iterator K =
1317               CandidatePairs.begin(); K != CandidatePairs.end();) {
1318          if (K->first == S->first || K->second == S->first ||
1319              K->second == S->second || K->first == S->second) {
1320            // Don't remove the actual pair chosen so that it can be used
1321            // in subsequent tree selections.
1322            if (!(K->first == S->first && K->second == S->second))
1323              CandidatePairs.erase(K++);
1324            else
1325              ++K;
1326          } else {
1327            ++K;
1328          }
1329        }
1330      }
1331    }
1332
1333    DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
1334  }
1335
1336  std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
1337                     unsigned n = 0) {
1338    if (!I->hasName())
1339      return "";
1340
1341    return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
1342             (n > 0 ? "." + utostr(n) : "")).str();
1343  }
1344
1345  // Returns the value that is to be used as the pointer input to the vector
1346  // instruction that fuses I with J.
1347  Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
1348                     Instruction *I, Instruction *J, unsigned o,
1349                     bool &FlipMemInputs) {
1350    Value *IPtr, *JPtr;
1351    unsigned IAlignment, JAlignment;
1352    int64_t OffsetInElmts;
1353    (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
1354                          OffsetInElmts);
1355
1356    // The pointer value is taken to be the one with the lowest offset.
1357    Value *VPtr;
1358    if (OffsetInElmts > 0) {
1359      VPtr = IPtr;
1360    } else {
1361      FlipMemInputs = true;
1362      VPtr = JPtr;
1363    }
1364
1365    Type *ArgType = cast<PointerType>(IPtr->getType())->getElementType();
1366    Type *VArgType = getVecTypeForPair(ArgType);
1367    Type *VArgPtrType = PointerType::get(VArgType,
1368      cast<PointerType>(IPtr->getType())->getAddressSpace());
1369    return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
1370                        /* insert before */ FlipMemInputs ? J : I);
1371  }
1372
1373  void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
1374                     unsigned NumElem, unsigned MaskOffset, unsigned NumInElem,
1375                     unsigned IdxOffset, std::vector<Constant*> &Mask) {
1376    for (unsigned v = 0; v < NumElem/2; ++v) {
1377      int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
1378      if (m < 0) {
1379        Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
1380      } else {
1381        unsigned mm = m + (int) IdxOffset;
1382        if (m >= (int) NumInElem)
1383          mm += (int) NumInElem;
1384
1385        Mask[v+MaskOffset] =
1386          ConstantInt::get(Type::getInt32Ty(Context), mm);
1387      }
1388    }
1389  }
1390
1391  // Returns the value that is to be used as the vector-shuffle mask to the
1392  // vector instruction that fuses I with J.
1393  Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
1394                     Instruction *I, Instruction *J) {
1395    // This is the shuffle mask. We need to append the second
1396    // mask to the first, and the numbers need to be adjusted.
1397
1398    Type *ArgType = I->getType();
1399    Type *VArgType = getVecTypeForPair(ArgType);
1400
1401    // Get the total number of elements in the fused vector type.
1402    // By definition, this must equal the number of elements in
1403    // the final mask.
1404    unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
1405    std::vector<Constant*> Mask(NumElem);
1406
1407    Type *OpType = I->getOperand(0)->getType();
1408    unsigned NumInElem = cast<VectorType>(OpType)->getNumElements();
1409
1410    // For the mask from the first pair...
1411    fillNewShuffleMask(Context, I, NumElem, 0, NumInElem, 0, Mask);
1412
1413    // For the mask from the second pair...
1414    fillNewShuffleMask(Context, J, NumElem, NumElem/2, NumInElem, NumInElem,
1415                       Mask);
1416
1417    return ConstantVector::get(Mask);
1418  }
1419
1420  // Returns the value to be used as the specified operand of the vector
1421  // instruction that fuses I with J.
1422  Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
1423                     Instruction *J, unsigned o, bool FlipMemInputs) {
1424    Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1425    Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1426
1427      // Compute the fused vector type for this operand
1428    Type *ArgType = I->getOperand(o)->getType();
1429    VectorType *VArgType = getVecTypeForPair(ArgType);
1430
1431    Instruction *L = I, *H = J;
1432    if (FlipMemInputs) {
1433      L = J;
1434      H = I;
1435    }
1436
1437    if (ArgType->isVectorTy()) {
1438      unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
1439      std::vector<Constant*> Mask(numElem);
1440      for (unsigned v = 0; v < numElem; ++v)
1441        Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1442
1443      Instruction *BV = new ShuffleVectorInst(L->getOperand(o),
1444                                              H->getOperand(o),
1445                                              ConstantVector::get(Mask),
1446                                              getReplacementName(I, true, o));
1447      BV->insertBefore(J);
1448      return BV;
1449    }
1450
1451    // If these two inputs are the output of another vector instruction,
1452    // then we should use that output directly. It might be necessary to
1453    // permute it first. [When pairings are fused recursively, you can
1454    // end up with cases where a large vector is decomposed into scalars
1455    // using extractelement instructions, then built into size-2
1456    // vectors using insertelement and the into larger vectors using
1457    // shuffles. InstCombine does not simplify all of these cases well,
1458    // and so we make sure that shuffles are generated here when possible.
1459    ExtractElementInst *LEE
1460      = dyn_cast<ExtractElementInst>(L->getOperand(o));
1461    ExtractElementInst *HEE
1462      = dyn_cast<ExtractElementInst>(H->getOperand(o));
1463
1464    if (LEE && HEE &&
1465        LEE->getOperand(0)->getType() == HEE->getOperand(0)->getType()) {
1466      VectorType *EEType = cast<VectorType>(LEE->getOperand(0)->getType());
1467      unsigned LowIndx = cast<ConstantInt>(LEE->getOperand(1))->getZExtValue();
1468      unsigned HighIndx = cast<ConstantInt>(HEE->getOperand(1))->getZExtValue();
1469      if (LEE->getOperand(0) == HEE->getOperand(0)) {
1470        if (LowIndx == 0 && HighIndx == 1)
1471          return LEE->getOperand(0);
1472
1473        std::vector<Constant*> Mask(2);
1474        Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
1475        Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
1476
1477        Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
1478                                          UndefValue::get(EEType),
1479                                          ConstantVector::get(Mask),
1480                                          getReplacementName(I, true, o));
1481        BV->insertBefore(J);
1482        return BV;
1483      }
1484
1485      std::vector<Constant*> Mask(2);
1486      HighIndx += EEType->getNumElements();
1487      Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
1488      Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
1489
1490      Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
1491                                          HEE->getOperand(0),
1492                                          ConstantVector::get(Mask),
1493                                          getReplacementName(I, true, o));
1494      BV->insertBefore(J);
1495      return BV;
1496    }
1497
1498    Instruction *BV1 = InsertElementInst::Create(
1499                                          UndefValue::get(VArgType),
1500                                          L->getOperand(o), CV0,
1501                                          getReplacementName(I, true, o, 1));
1502    BV1->insertBefore(I);
1503    Instruction *BV2 = InsertElementInst::Create(BV1, H->getOperand(o),
1504                                          CV1,
1505                                          getReplacementName(I, true, o, 2));
1506    BV2->insertBefore(J);
1507    return BV2;
1508  }
1509
1510  // This function creates an array of values that will be used as the inputs
1511  // to the vector instruction that fuses I with J.
1512  void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
1513                     Instruction *I, Instruction *J,
1514                     SmallVector<Value *, 3> &ReplacedOperands,
1515                     bool &FlipMemInputs) {
1516    FlipMemInputs = false;
1517    unsigned NumOperands = I->getNumOperands();
1518
1519    for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
1520      // Iterate backward so that we look at the store pointer
1521      // first and know whether or not we need to flip the inputs.
1522
1523      if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
1524        // This is the pointer for a load/store instruction.
1525        ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o,
1526                                FlipMemInputs);
1527        continue;
1528      } else if (isa<CallInst>(I) && o == NumOperands-1) {
1529        Function *F = cast<CallInst>(I)->getCalledFunction();
1530        unsigned IID = F->getIntrinsicID();
1531        BasicBlock &BB = *I->getParent();
1532
1533        Module *M = BB.getParent()->getParent();
1534        Type *ArgType = I->getType();
1535        Type *VArgType = getVecTypeForPair(ArgType);
1536
1537        // FIXME: is it safe to do this here?
1538        ReplacedOperands[o] = Intrinsic::getDeclaration(M,
1539          (Intrinsic::ID) IID, VArgType);
1540        continue;
1541      } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
1542        ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
1543        continue;
1544      }
1545
1546      ReplacedOperands[o] =
1547        getReplacementInput(Context, I, J, o, FlipMemInputs);
1548    }
1549  }
1550
1551  // This function creates two values that represent the outputs of the
1552  // original I and J instructions. These are generally vector shuffles
1553  // or extracts. In many cases, these will end up being unused and, thus,
1554  // eliminated by later passes.
1555  void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
1556                     Instruction *J, Instruction *K,
1557                     Instruction *&InsertionPt,
1558                     Instruction *&K1, Instruction *&K2,
1559                     bool &FlipMemInputs) {
1560    Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1561    Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1562
1563    if (isa<StoreInst>(I)) {
1564      AA->replaceWithNewValue(I, K);
1565      AA->replaceWithNewValue(J, K);
1566    } else {
1567      Type *IType = I->getType();
1568      Type *VType = getVecTypeForPair(IType);
1569
1570      if (IType->isVectorTy()) {
1571          unsigned numElem = cast<VectorType>(IType)->getNumElements();
1572          std::vector<Constant*> Mask1(numElem), Mask2(numElem);
1573          for (unsigned v = 0; v < numElem; ++v) {
1574            Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1575            Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElem+v);
1576          }
1577
1578          K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
1579                                       ConstantVector::get(
1580                                         FlipMemInputs ? Mask2 : Mask1),
1581                                       getReplacementName(K, false, 1));
1582          K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
1583                                       ConstantVector::get(
1584                                         FlipMemInputs ? Mask1 : Mask2),
1585                                       getReplacementName(K, false, 2));
1586      } else {
1587        K1 = ExtractElementInst::Create(K, FlipMemInputs ? CV1 : CV0,
1588                                          getReplacementName(K, false, 1));
1589        K2 = ExtractElementInst::Create(K, FlipMemInputs ? CV0 : CV1,
1590                                          getReplacementName(K, false, 2));
1591      }
1592
1593      K1->insertAfter(K);
1594      K2->insertAfter(K1);
1595      InsertionPt = K2;
1596    }
1597  }
1598
1599  // Move all uses of the function I (including pairing-induced uses) after J.
1600  bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
1601                     std::multimap<Value *, Value *> &LoadMoveSet,
1602                     Instruction *I, Instruction *J) {
1603    // Skip to the first instruction past I.
1604    BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1605
1606    DenseSet<Value *> Users;
1607    AliasSetTracker WriteSet(*AA);
1608    for (; cast<Instruction>(L) != J; ++L)
1609      (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet);
1610
1611    assert(cast<Instruction>(L) == J &&
1612      "Tracking has not proceeded far enough to check for dependencies");
1613    // If J is now in the use set of I, then trackUsesOfI will return true
1614    // and we have a dependency cycle (and the fusing operation must abort).
1615    return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSet);
1616  }
1617
1618  // Move all uses of the function I (including pairing-induced uses) after J.
1619  void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
1620                     std::multimap<Value *, Value *> &LoadMoveSet,
1621                     Instruction *&InsertionPt,
1622                     Instruction *I, Instruction *J) {
1623    // Skip to the first instruction past I.
1624    BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1625
1626    DenseSet<Value *> Users;
1627    AliasSetTracker WriteSet(*AA);
1628    for (; cast<Instruction>(L) != J;) {
1629      if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet)) {
1630        // Move this instruction
1631        Instruction *InstToMove = L; ++L;
1632
1633        DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
1634                        " to after " << *InsertionPt << "\n");
1635        InstToMove->removeFromParent();
1636        InstToMove->insertAfter(InsertionPt);
1637        InsertionPt = InstToMove;
1638      } else {
1639        ++L;
1640      }
1641    }
1642  }
1643
1644  // Collect all load instruction that are in the move set of a given first
1645  // pair member.  These loads depend on the first instruction, I, and so need
1646  // to be moved after J (the second instruction) when the pair is fused.
1647  void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
1648                     DenseMap<Value *, Value *> &ChosenPairs,
1649                     std::multimap<Value *, Value *> &LoadMoveSet,
1650                     Instruction *I) {
1651    // Skip to the first instruction past I.
1652    BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1653
1654    DenseSet<Value *> Users;
1655    AliasSetTracker WriteSet(*AA);
1656
1657    // Note: We cannot end the loop when we reach J because J could be moved
1658    // farther down the use chain by another instruction pairing. Also, J
1659    // could be before I if this is an inverted input.
1660    for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
1661      if (trackUsesOfI(Users, WriteSet, I, L)) {
1662        if (L->mayReadFromMemory())
1663          LoadMoveSet.insert(ValuePair(L, I));
1664      }
1665    }
1666  }
1667
1668  // In cases where both load/stores and the computation of their pointers
1669  // are chosen for vectorization, we can end up in a situation where the
1670  // aliasing analysis starts returning different query results as the
1671  // process of fusing instruction pairs continues. Because the algorithm
1672  // relies on finding the same use trees here as were found earlier, we'll
1673  // need to precompute the necessary aliasing information here and then
1674  // manually update it during the fusion process.
1675  void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
1676                     std::vector<Value *> &PairableInsts,
1677                     DenseMap<Value *, Value *> &ChosenPairs,
1678                     std::multimap<Value *, Value *> &LoadMoveSet) {
1679    for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1680         PIE = PairableInsts.end(); PI != PIE; ++PI) {
1681      DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
1682      if (P == ChosenPairs.end()) continue;
1683
1684      Instruction *I = cast<Instruction>(P->first);
1685      collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet, I);
1686    }
1687  }
1688
1689  // This function fuses the chosen instruction pairs into vector instructions,
1690  // taking care preserve any needed scalar outputs and, then, it reorders the
1691  // remaining instructions as needed (users of the first member of the pair
1692  // need to be moved to after the location of the second member of the pair
1693  // because the vector instruction is inserted in the location of the pair's
1694  // second member).
1695  void BBVectorize::fuseChosenPairs(BasicBlock &BB,
1696                     std::vector<Value *> &PairableInsts,
1697                     DenseMap<Value *, Value *> &ChosenPairs) {
1698    LLVMContext& Context = BB.getContext();
1699
1700    // During the vectorization process, the order of the pairs to be fused
1701    // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
1702    // list. After a pair is fused, the flipped pair is removed from the list.
1703    std::vector<ValuePair> FlippedPairs;
1704    FlippedPairs.reserve(ChosenPairs.size());
1705    for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
1706         E = ChosenPairs.end(); P != E; ++P)
1707      FlippedPairs.push_back(ValuePair(P->second, P->first));
1708    for (std::vector<ValuePair>::iterator P = FlippedPairs.begin(),
1709         E = FlippedPairs.end(); P != E; ++P)
1710      ChosenPairs.insert(*P);
1711
1712    std::multimap<Value *, Value *> LoadMoveSet;
1713    collectLoadMoveSet(BB, PairableInsts, ChosenPairs, LoadMoveSet);
1714
1715    DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
1716
1717    for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
1718      DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
1719      if (P == ChosenPairs.end()) {
1720        ++PI;
1721        continue;
1722      }
1723
1724      if (getDepthFactor(P->first) == 0) {
1725        // These instructions are not really fused, but are tracked as though
1726        // they are. Any case in which it would be interesting to fuse them
1727        // will be taken care of by InstCombine.
1728        --NumFusedOps;
1729        ++PI;
1730        continue;
1731      }
1732
1733      Instruction *I = cast<Instruction>(P->first),
1734        *J = cast<Instruction>(P->second);
1735
1736      DEBUG(dbgs() << "BBV: fusing: " << *I <<
1737             " <-> " << *J << "\n");
1738
1739      // Remove the pair and flipped pair from the list.
1740      DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
1741      assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
1742      ChosenPairs.erase(FP);
1743      ChosenPairs.erase(P);
1744
1745      if (!canMoveUsesOfIAfterJ(BB, LoadMoveSet, I, J)) {
1746        DEBUG(dbgs() << "BBV: fusion of: " << *I <<
1747               " <-> " << *J <<
1748               " aborted because of non-trivial dependency cycle\n");
1749        --NumFusedOps;
1750        ++PI;
1751        continue;
1752      }
1753
1754      bool FlipMemInputs;
1755      unsigned NumOperands = I->getNumOperands();
1756      SmallVector<Value *, 3> ReplacedOperands(NumOperands);
1757      getReplacementInputsForPair(Context, I, J, ReplacedOperands,
1758        FlipMemInputs);
1759
1760      // Make a copy of the original operation, change its type to the vector
1761      // type and replace its operands with the vector operands.
1762      Instruction *K = I->clone();
1763      if (I->hasName()) K->takeName(I);
1764
1765      if (!isa<StoreInst>(K))
1766        K->mutateType(getVecTypeForPair(I->getType()));
1767
1768      for (unsigned o = 0; o < NumOperands; ++o)
1769        K->setOperand(o, ReplacedOperands[o]);
1770
1771      // If we've flipped the memory inputs, make sure that we take the correct
1772      // alignment.
1773      if (FlipMemInputs) {
1774        if (isa<StoreInst>(K))
1775          cast<StoreInst>(K)->setAlignment(cast<StoreInst>(J)->getAlignment());
1776        else
1777          cast<LoadInst>(K)->setAlignment(cast<LoadInst>(J)->getAlignment());
1778      }
1779
1780      K->insertAfter(J);
1781
1782      // Instruction insertion point:
1783      Instruction *InsertionPt = K;
1784      Instruction *K1 = 0, *K2 = 0;
1785      replaceOutputsOfPair(Context, I, J, K, InsertionPt, K1, K2,
1786        FlipMemInputs);
1787
1788      // The use tree of the first original instruction must be moved to after
1789      // the location of the second instruction. The entire use tree of the
1790      // first instruction is disjoint from the input tree of the second
1791      // (by definition), and so commutes with it.
1792
1793      moveUsesOfIAfterJ(BB, LoadMoveSet, InsertionPt, I, J);
1794
1795      if (!isa<StoreInst>(I)) {
1796        I->replaceAllUsesWith(K1);
1797        J->replaceAllUsesWith(K2);
1798        AA->replaceWithNewValue(I, K1);
1799        AA->replaceWithNewValue(J, K2);
1800      }
1801
1802      // Instructions that may read from memory may be in the load move set.
1803      // Once an instruction is fused, we no longer need its move set, and so
1804      // the values of the map never need to be updated. However, when a load
1805      // is fused, we need to merge the entries from both instructions in the
1806      // pair in case those instructions were in the move set of some other
1807      // yet-to-be-fused pair. The loads in question are the keys of the map.
1808      if (I->mayReadFromMemory()) {
1809        std::vector<ValuePair> NewSetMembers;
1810        VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
1811        VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
1812        for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
1813             N != IPairRange.second; ++N)
1814          NewSetMembers.push_back(ValuePair(K, N->second));
1815        for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
1816             N != JPairRange.second; ++N)
1817          NewSetMembers.push_back(ValuePair(K, N->second));
1818        for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
1819             AE = NewSetMembers.end(); A != AE; ++A)
1820          LoadMoveSet.insert(*A);
1821      }
1822
1823      // Before removing I, set the iterator to the next instruction.
1824      PI = llvm::next(BasicBlock::iterator(I));
1825      if (cast<Instruction>(PI) == J)
1826        ++PI;
1827
1828      SE->forgetValue(I);
1829      SE->forgetValue(J);
1830      I->eraseFromParent();
1831      J->eraseFromParent();
1832    }
1833
1834    DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
1835  }
1836}
1837
1838char BBVectorize::ID = 0;
1839static const char bb_vectorize_name[] = "Basic-Block Vectorization";
1840INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
1841INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1842INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1843INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
1844
1845BasicBlockPass *llvm::createBBVectorizePass() {
1846  return new BBVectorize();
1847}
1848
1849