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