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