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