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