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