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