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