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