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