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