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