OSDN Git Service

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