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