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