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