1d08df59b3375a99104e46359258128596c6f59d
[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/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Type.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Analysis/AliasAnalysis.h"
35 #include "llvm/Analysis/AliasSetTracker.h"
36 #include "llvm/Analysis/ScalarEvolution.h"
37 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
38 #include "llvm/Analysis/ValueTracking.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Support/ValueHandle.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Transforms/Vectorize.h"
45 #include <algorithm>
46 #include <map>
47 using namespace llvm;
48
49 static cl::opt<unsigned>
50 ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
51   cl::desc("The required chain depth for vectorization"));
52
53 static cl::opt<unsigned>
54 SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
55   cl::desc("The maximum search distance for instruction pairs"));
56
57 static cl::opt<bool>
58 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
59   cl::desc("Replicating one element to a pair breaks the chain"));
60
61 static cl::opt<unsigned>
62 VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
63   cl::desc("The size of the native vector registers"));
64
65 static cl::opt<unsigned>
66 MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
67   cl::desc("The maximum number of pairing iterations"));
68
69 static cl::opt<unsigned>
70 MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
71   cl::desc("The maximum number of pairable instructions per group"));
72
73 static cl::opt<unsigned>
74 MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
75   cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
76                        " a full cycle check"));
77
78 static cl::opt<bool>
79 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
80   cl::desc("Don't try to vectorize integer values"));
81
82 static cl::opt<bool>
83 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
84   cl::desc("Don't try to vectorize floating-point values"));
85
86 static cl::opt<bool>
87 NoPointers("bb-vectorize-no-pointers", cl::init(false), cl::Hidden,
88   cl::desc("Don't try to vectorize pointer values"));
89
90 static cl::opt<bool>
91 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
92   cl::desc("Don't try to vectorize casting (conversion) operations"));
93
94 static cl::opt<bool>
95 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
96   cl::desc("Don't try to vectorize floating-point math intrinsics"));
97
98 static cl::opt<bool>
99 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
100   cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
101
102 static cl::opt<bool>
103 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
104   cl::desc("Don't try to vectorize select instructions"));
105
106 static cl::opt<bool>
107 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
108   cl::desc("Don't try to vectorize getelementptr instructions"));
109
110 static cl::opt<bool>
111 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
112   cl::desc("Don't try to vectorize loads and stores"));
113
114 static cl::opt<bool>
115 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
116   cl::desc("Only generate aligned loads and stores"));
117
118 static cl::opt<bool>
119 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
120   cl::init(false), cl::Hidden,
121   cl::desc("Don't boost the chain-depth contribution of loads and stores"));
122
123 static cl::opt<bool>
124 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
125   cl::desc("Use a fast instruction dependency analysis"));
126
127 #ifndef NDEBUG
128 static cl::opt<bool>
129 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
130   cl::init(false), cl::Hidden,
131   cl::desc("When debugging is enabled, output information on the"
132            " instruction-examination process"));
133 static cl::opt<bool>
134 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
135   cl::init(false), cl::Hidden,
136   cl::desc("When debugging is enabled, output information on the"
137            " candidate-selection process"));
138 static cl::opt<bool>
139 DebugPairSelection("bb-vectorize-debug-pair-selection",
140   cl::init(false), cl::Hidden,
141   cl::desc("When debugging is enabled, output information on the"
142            " pair-selection process"));
143 static cl::opt<bool>
144 DebugCycleCheck("bb-vectorize-debug-cycle-check",
145   cl::init(false), cl::Hidden,
146   cl::desc("When debugging is enabled, output information on the"
147            " cycle-checking process"));
148 #endif
149
150 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
151
152 namespace {
153   struct BBVectorize : public BasicBlockPass {
154     static char ID; // Pass identification, replacement for typeid
155
156     const VectorizeConfig Config;
157
158     BBVectorize(const VectorizeConfig &C = VectorizeConfig())
159       : BasicBlockPass(ID), Config(C) {
160       initializeBBVectorizePass(*PassRegistry::getPassRegistry());
161     }
162
163     BBVectorize(Pass *P, const VectorizeConfig &C)
164       : BasicBlockPass(ID), Config(C) {
165       AA = &P->getAnalysis<AliasAnalysis>();
166       SE = &P->getAnalysis<ScalarEvolution>();
167       TD = P->getAnalysisIfAvailable<TargetData>();
168     }
169
170     typedef std::pair<Value *, Value *> ValuePair;
171     typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
172     typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
173     typedef std::pair<std::multimap<Value *, Value *>::iterator,
174               std::multimap<Value *, Value *>::iterator> VPIteratorPair;
175     typedef std::pair<std::multimap<ValuePair, ValuePair>::iterator,
176               std::multimap<ValuePair, ValuePair>::iterator>
177                 VPPIteratorPair;
178
179     AliasAnalysis *AA;
180     ScalarEvolution *SE;
181     TargetData *TD;
182
183     // FIXME: const correct?
184
185     bool vectorizePairs(BasicBlock &BB);
186
187     bool getCandidatePairs(BasicBlock &BB,
188                        BasicBlock::iterator &Start,
189                        std::multimap<Value *, Value *> &CandidatePairs,
190                        std::vector<Value *> &PairableInsts);
191
192     void computeConnectedPairs(std::multimap<Value *, Value *> &CandidatePairs,
193                        std::vector<Value *> &PairableInsts,
194                        std::multimap<ValuePair, ValuePair> &ConnectedPairs);
195
196     void buildDepMap(BasicBlock &BB,
197                        std::multimap<Value *, Value *> &CandidatePairs,
198                        std::vector<Value *> &PairableInsts,
199                        DenseSet<ValuePair> &PairableInstUsers);
200
201     void choosePairs(std::multimap<Value *, Value *> &CandidatePairs,
202                         std::vector<Value *> &PairableInsts,
203                         std::multimap<ValuePair, ValuePair> &ConnectedPairs,
204                         DenseSet<ValuePair> &PairableInstUsers,
205                         DenseMap<Value *, Value *>& ChosenPairs);
206
207     void fuseChosenPairs(BasicBlock &BB,
208                      std::vector<Value *> &PairableInsts,
209                      DenseMap<Value *, Value *>& ChosenPairs);
210
211     bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
212
213     bool areInstsCompatible(Instruction *I, Instruction *J,
214                        bool IsSimpleLoadStore);
215
216     bool trackUsesOfI(DenseSet<Value *> &Users,
217                       AliasSetTracker &WriteSet, Instruction *I,
218                       Instruction *J, bool UpdateUsers = true,
219                       std::multimap<Value *, Value *> *LoadMoveSet = 0);
220
221     void computePairsConnectedTo(
222                       std::multimap<Value *, Value *> &CandidatePairs,
223                       std::vector<Value *> &PairableInsts,
224                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
225                       ValuePair P);
226
227     bool pairsConflict(ValuePair P, ValuePair Q,
228                  DenseSet<ValuePair> &PairableInstUsers,
229                  std::multimap<ValuePair, ValuePair> *PairableInstUserMap = 0);
230
231     bool pairWillFormCycle(ValuePair P,
232                        std::multimap<ValuePair, ValuePair> &PairableInstUsers,
233                        DenseSet<ValuePair> &CurrentPairs);
234
235     void pruneTreeFor(
236                       std::multimap<Value *, Value *> &CandidatePairs,
237                       std::vector<Value *> &PairableInsts,
238                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
239                       DenseSet<ValuePair> &PairableInstUsers,
240                       std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
241                       DenseMap<Value *, Value *> &ChosenPairs,
242                       DenseMap<ValuePair, size_t> &Tree,
243                       DenseSet<ValuePair> &PrunedTree, ValuePair J,
244                       bool UseCycleCheck);
245
246     void buildInitialTreeFor(
247                       std::multimap<Value *, Value *> &CandidatePairs,
248                       std::vector<Value *> &PairableInsts,
249                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
250                       DenseSet<ValuePair> &PairableInstUsers,
251                       DenseMap<Value *, Value *> &ChosenPairs,
252                       DenseMap<ValuePair, size_t> &Tree, ValuePair J);
253
254     void findBestTreeFor(
255                       std::multimap<Value *, Value *> &CandidatePairs,
256                       std::vector<Value *> &PairableInsts,
257                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
258                       DenseSet<ValuePair> &PairableInstUsers,
259                       std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
260                       DenseMap<Value *, Value *> &ChosenPairs,
261                       DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
262                       size_t &BestEffSize, VPIteratorPair ChoiceRange,
263                       bool UseCycleCheck);
264
265     Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
266                      Instruction *J, unsigned o, bool &FlipMemInputs);
267
268     void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
269                      unsigned NumElem, unsigned MaskOffset, unsigned NumInElem,
270                      unsigned IdxOffset, std::vector<Constant*> &Mask);
271
272     Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
273                      Instruction *J);
274
275     Value *getReplacementInput(LLVMContext& Context, Instruction *I,
276                      Instruction *J, unsigned o, bool FlipMemInputs);
277
278     void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
279                      Instruction *J, SmallVector<Value *, 3> &ReplacedOperands,
280                      bool &FlipMemInputs);
281
282     void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
283                      Instruction *J, Instruction *K,
284                      Instruction *&InsertionPt, Instruction *&K1,
285                      Instruction *&K2, bool &FlipMemInputs);
286
287     void collectPairLoadMoveSet(BasicBlock &BB,
288                      DenseMap<Value *, Value *> &ChosenPairs,
289                      std::multimap<Value *, Value *> &LoadMoveSet,
290                      Instruction *I);
291
292     void collectLoadMoveSet(BasicBlock &BB,
293                      std::vector<Value *> &PairableInsts,
294                      DenseMap<Value *, Value *> &ChosenPairs,
295                      std::multimap<Value *, Value *> &LoadMoveSet);
296
297     bool canMoveUsesOfIAfterJ(BasicBlock &BB,
298                      std::multimap<Value *, Value *> &LoadMoveSet,
299                      Instruction *I, Instruction *J);
300
301     void moveUsesOfIAfterJ(BasicBlock &BB,
302                      std::multimap<Value *, Value *> &LoadMoveSet,
303                      Instruction *&InsertionPt,
304                      Instruction *I, Instruction *J);
305
306     bool vectorizeBB(BasicBlock &BB) {
307       bool changed = false;
308       // Iterate a sufficient number of times to merge types of size 1 bit,
309       // then 2 bits, then 4, etc. up to half of the target vector width of the
310       // target vector register.
311       for (unsigned v = 2, n = 1;
312            v <= Config.VectorBits && (!Config.MaxIter || n <= Config.MaxIter);
313            v *= 2, ++n) {
314         DEBUG(dbgs() << "BBV: fusing loop #" << n <<
315               " for " << BB.getName() << " in " <<
316               BB.getParent()->getName() << "...\n");
317         if (vectorizePairs(BB))
318           changed = true;
319         else
320           break;
321       }
322
323       DEBUG(dbgs() << "BBV: done!\n");
324       return changed;
325     }
326
327     virtual bool runOnBasicBlock(BasicBlock &BB) {
328       AA = &getAnalysis<AliasAnalysis>();
329       SE = &getAnalysis<ScalarEvolution>();
330       TD = getAnalysisIfAvailable<TargetData>();
331
332       return vectorizeBB(BB);
333     }
334
335     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
336       BasicBlockPass::getAnalysisUsage(AU);
337       AU.addRequired<AliasAnalysis>();
338       AU.addRequired<ScalarEvolution>();
339       AU.addPreserved<AliasAnalysis>();
340       AU.addPreserved<ScalarEvolution>();
341       AU.setPreservesCFG();
342     }
343
344     // This returns the vector type that holds a pair of the provided type.
345     // If the provided type is already a vector, then its length is doubled.
346     static inline VectorType *getVecTypeForPair(Type *ElemTy) {
347       if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
348         unsigned numElem = VTy->getNumElements();
349         return VectorType::get(ElemTy->getScalarType(), numElem*2);
350       }
351
352       return VectorType::get(ElemTy, 2);
353     }
354
355     // Returns the weight associated with the provided value. A chain of
356     // candidate pairs has a length given by the sum of the weights of its
357     // members (one weight per pair; the weight of each member of the pair
358     // is assumed to be the same). This length is then compared to the
359     // chain-length threshold to determine if a given chain is significant
360     // enough to be vectorized. The length is also used in comparing
361     // candidate chains where longer chains are considered to be better.
362     // Note: when this function returns 0, the resulting instructions are
363     // not actually fused.
364     inline size_t getDepthFactor(Value *V) {
365       // InsertElement and ExtractElement have a depth factor of zero. This is
366       // for two reasons: First, they cannot be usefully fused. Second, because
367       // the pass generates a lot of these, they can confuse the simple metric
368       // used to compare the trees in the next iteration. Thus, giving them a
369       // weight of zero allows the pass to essentially ignore them in
370       // subsequent iterations when looking for vectorization opportunities
371       // while still tracking dependency chains that flow through those
372       // instructions.
373       if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
374         return 0;
375
376       // Give a load or store half of the required depth so that load/store
377       // pairs will vectorize.
378       if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
379         return Config.ReqChainDepth/2;
380
381       return 1;
382     }
383
384     // This determines the relative offset of two loads or stores, returning
385     // true if the offset could be determined to be some constant value.
386     // For example, if OffsetInElmts == 1, then J accesses the memory directly
387     // after I; if OffsetInElmts == -1 then I accesses the memory
388     // directly after J. This function assumes that both instructions
389     // have the same type.
390     bool getPairPtrInfo(Instruction *I, Instruction *J,
391         Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
392         int64_t &OffsetInElmts) {
393       OffsetInElmts = 0;
394       if (isa<LoadInst>(I)) {
395         IPtr = cast<LoadInst>(I)->getPointerOperand();
396         JPtr = cast<LoadInst>(J)->getPointerOperand();
397         IAlignment = cast<LoadInst>(I)->getAlignment();
398         JAlignment = cast<LoadInst>(J)->getAlignment();
399       } else {
400         IPtr = cast<StoreInst>(I)->getPointerOperand();
401         JPtr = cast<StoreInst>(J)->getPointerOperand();
402         IAlignment = cast<StoreInst>(I)->getAlignment();
403         JAlignment = cast<StoreInst>(J)->getAlignment();
404       }
405
406       const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
407       const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
408
409       // If this is a trivial offset, then we'll get something like
410       // 1*sizeof(type). With target data, which we need anyway, this will get
411       // constant folded into a number.
412       const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
413       if (const SCEVConstant *ConstOffSCEV =
414             dyn_cast<SCEVConstant>(OffsetSCEV)) {
415         ConstantInt *IntOff = ConstOffSCEV->getValue();
416         int64_t Offset = IntOff->getSExtValue();
417
418         Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
419         int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
420
421         assert(VTy == cast<PointerType>(JPtr->getType())->getElementType());
422
423         OffsetInElmts = Offset/VTyTSS;
424         return (abs64(Offset) % VTyTSS) == 0;
425       }
426
427       return false;
428     }
429
430     // Returns true if the provided CallInst represents an intrinsic that can
431     // be vectorized.
432     bool isVectorizableIntrinsic(CallInst* I) {
433       Function *F = I->getCalledFunction();
434       if (!F) return false;
435
436       unsigned IID = F->getIntrinsicID();
437       if (!IID) return false;
438
439       switch(IID) {
440       default:
441         return false;
442       case Intrinsic::sqrt:
443       case Intrinsic::powi:
444       case Intrinsic::sin:
445       case Intrinsic::cos:
446       case Intrinsic::log:
447       case Intrinsic::log2:
448       case Intrinsic::log10:
449       case Intrinsic::exp:
450       case Intrinsic::exp2:
451       case Intrinsic::pow:
452         return Config.VectorizeMath;
453       case Intrinsic::fma:
454         return Config.VectorizeFMA;
455       }
456     }
457
458     // Returns true if J is the second element in some pair referenced by
459     // some multimap pair iterator pair.
460     template <typename V>
461     bool isSecondInIteratorPair(V J, std::pair<
462            typename std::multimap<V, V>::iterator,
463            typename std::multimap<V, V>::iterator> PairRange) {
464       for (typename std::multimap<V, V>::iterator K = PairRange.first;
465            K != PairRange.second; ++K)
466         if (K->second == J) return true;
467
468       return false;
469     }
470   };
471
472   // This function implements one vectorization iteration on the provided
473   // basic block. It returns true if the block is changed.
474   bool BBVectorize::vectorizePairs(BasicBlock &BB) {
475     bool ShouldContinue;
476     BasicBlock::iterator Start = BB.getFirstInsertionPt();
477
478     std::vector<Value *> AllPairableInsts;
479     DenseMap<Value *, Value *> AllChosenPairs;
480
481     do {
482       std::vector<Value *> PairableInsts;
483       std::multimap<Value *, Value *> CandidatePairs;
484       ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
485                                          PairableInsts);
486       if (PairableInsts.empty()) continue;
487
488       // Now we have a map of all of the pairable instructions and we need to
489       // select the best possible pairing. A good pairing is one such that the
490       // users of the pair are also paired. This defines a (directed) forest
491       // over the pairs such that two pairs are connected iff the second pair
492       // uses the first.
493
494       // Note that it only matters that both members of the second pair use some
495       // element of the first pair (to allow for splatting).
496
497       std::multimap<ValuePair, ValuePair> ConnectedPairs;
498       computeConnectedPairs(CandidatePairs, PairableInsts, ConnectedPairs);
499       if (ConnectedPairs.empty()) continue;
500
501       // Build the pairable-instruction dependency map
502       DenseSet<ValuePair> PairableInstUsers;
503       buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
504
505       // There is now a graph of the connected pairs. For each variable, pick
506       // the pairing with the largest tree meeting the depth requirement on at
507       // least one branch. Then select all pairings that are part of that tree
508       // and remove them from the list of available pairings and pairable
509       // variables.
510
511       DenseMap<Value *, Value *> ChosenPairs;
512       choosePairs(CandidatePairs, PairableInsts, ConnectedPairs,
513         PairableInstUsers, ChosenPairs);
514
515       if (ChosenPairs.empty()) continue;
516       AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
517                               PairableInsts.end());
518       AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
519     } while (ShouldContinue);
520
521     if (AllChosenPairs.empty()) return false;
522     NumFusedOps += AllChosenPairs.size();
523
524     // A set of pairs has now been selected. It is now necessary to replace the
525     // paired instructions with vector instructions. For this procedure each
526     // operand must be replaced with a vector operand. This vector is formed
527     // by using build_vector on the old operands. The replaced values are then
528     // replaced with a vector_extract on the result.  Subsequent optimization
529     // passes should coalesce the build/extract combinations.
530
531     fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs);
532     return true;
533   }
534
535   // This function returns true if the provided instruction is capable of being
536   // fused into a vector instruction. This determination is based only on the
537   // type and other attributes of the instruction.
538   bool BBVectorize::isInstVectorizable(Instruction *I,
539                                          bool &IsSimpleLoadStore) {
540     IsSimpleLoadStore = false;
541
542     if (CallInst *C = dyn_cast<CallInst>(I)) {
543       if (!isVectorizableIntrinsic(C))
544         return false;
545     } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
546       // Vectorize simple loads if possbile:
547       IsSimpleLoadStore = L->isSimple();
548       if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
549         return false;
550     } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
551       // Vectorize simple stores if possbile:
552       IsSimpleLoadStore = S->isSimple();
553       if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
554         return false;
555     } else if (CastInst *C = dyn_cast<CastInst>(I)) {
556       // We can vectorize casts, but not casts of pointer types, etc.
557       if (!Config.VectorizeCasts)
558         return false;
559
560       Type *SrcTy = C->getSrcTy();
561       if (!SrcTy->isSingleValueType())
562         return false;
563
564       Type *DestTy = C->getDestTy();
565       if (!DestTy->isSingleValueType())
566         return false;
567     } else if (isa<SelectInst>(I)) {
568       if (!Config.VectorizeSelect)
569         return false;
570     } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
571       if (!Config.VectorizeGEP)
572         return false;
573
574       // Currently, vector GEPs exist only with one index.
575       if (G->getNumIndices() != 1)
576         return false;
577     } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
578         isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
579       return false;
580     }
581
582     // We can't vectorize memory operations without target data
583     if (TD == 0 && IsSimpleLoadStore)
584       return false;
585
586     Type *T1, *T2;
587     if (isa<StoreInst>(I)) {
588       // For stores, it is the value type, not the pointer type that matters
589       // because the value is what will come from a vector register.
590
591       Value *IVal = cast<StoreInst>(I)->getValueOperand();
592       T1 = IVal->getType();
593     } else {
594       T1 = I->getType();
595     }
596
597     if (I->isCast())
598       T2 = cast<CastInst>(I)->getSrcTy();
599     else
600       T2 = T1;
601
602     // Not every type can be vectorized...
603     if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
604         !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
605       return false;
606
607     if (!Config.VectorizeInts
608         && (T1->isIntOrIntVectorTy() || T2->isIntOrIntVectorTy()))
609       return false;
610
611     if (!Config.VectorizeFloats
612         && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
613       return false;
614
615     // Don't vectorize target-specific types.
616     if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
617       return false;
618     if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
619       return false;
620
621     if ((!Config.VectorizePointers || TD == 0) &&
622         (T1->getScalarType()->isPointerTy() ||
623          T2->getScalarType()->isPointerTy()))
624       return false;
625
626     if (T1->getPrimitiveSizeInBits() > Config.VectorBits/2 ||
627         T2->getPrimitiveSizeInBits() > Config.VectorBits/2)
628       return false;
629
630     return true;
631   }
632
633   // This function returns true if the two provided instructions are compatible
634   // (meaning that they can be fused into a vector instruction). This assumes
635   // that I has already been determined to be vectorizable and that J is not
636   // in the use tree of I.
637   bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
638                        bool IsSimpleLoadStore) {
639     DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
640                      " <-> " << *J << "\n");
641
642     // Loads and stores can be merged if they have different alignments,
643     // but are otherwise the same.
644     LoadInst *LI, *LJ;
645     StoreInst *SI, *SJ;
646     if ((LI = dyn_cast<LoadInst>(I)) && (LJ = dyn_cast<LoadInst>(J))) {
647       if (I->getType() != J->getType())
648         return false;
649
650       if (LI->getPointerOperand()->getType() !=
651             LJ->getPointerOperand()->getType() ||
652           LI->isVolatile() != LJ->isVolatile() ||
653           LI->getOrdering() != LJ->getOrdering() ||
654           LI->getSynchScope() != LJ->getSynchScope())
655         return false;
656     } else if ((SI = dyn_cast<StoreInst>(I)) && (SJ = dyn_cast<StoreInst>(J))) {
657       if (SI->getValueOperand()->getType() !=
658             SJ->getValueOperand()->getType() ||
659           SI->getPointerOperand()->getType() !=
660             SJ->getPointerOperand()->getType() ||
661           SI->isVolatile() != SJ->isVolatile() ||
662           SI->getOrdering() != SJ->getOrdering() ||
663           SI->getSynchScope() != SJ->getSynchScope())
664         return false;
665     } else if (!J->isSameOperationAs(I)) {
666       return false;
667     }
668     // FIXME: handle addsub-type operations!
669
670     if (IsSimpleLoadStore) {
671       Value *IPtr, *JPtr;
672       unsigned IAlignment, JAlignment;
673       int64_t OffsetInElmts = 0;
674       if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
675             OffsetInElmts) && abs64(OffsetInElmts) == 1) {
676         if (Config.AlignedOnly) {
677           Type *aType = isa<StoreInst>(I) ?
678             cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
679           // An aligned load or store is possible only if the instruction
680           // with the lower offset has an alignment suitable for the
681           // vector type.
682
683           unsigned BottomAlignment = IAlignment;
684           if (OffsetInElmts < 0) BottomAlignment = JAlignment;
685
686           Type *VType = getVecTypeForPair(aType);
687           unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
688           if (BottomAlignment < VecAlignment)
689             return false;
690         }
691       } else {
692         return false;
693       }
694     } else if (isa<ShuffleVectorInst>(I)) {
695       // Only merge two shuffles if they're both constant
696       return isa<Constant>(I->getOperand(2)) &&
697              isa<Constant>(J->getOperand(2));
698       // FIXME: We may want to vectorize non-constant shuffles also.
699     }
700
701     // The powi intrinsic is special because only the first argument is
702     // vectorized, the second arguments must be equal.
703     CallInst *CI = dyn_cast<CallInst>(I);
704     Function *FI;
705     if (CI && (FI = CI->getCalledFunction()) &&
706         FI->getIntrinsicID() == Intrinsic::powi) {
707
708       Value *A1I = CI->getArgOperand(1),
709             *A1J = cast<CallInst>(J)->getArgOperand(1);
710       const SCEV *A1ISCEV = SE->getSCEV(A1I),
711                  *A1JSCEV = SE->getSCEV(A1J);
712       return (A1ISCEV == A1JSCEV);
713     }
714
715     return true;
716   }
717
718   // Figure out whether or not J uses I and update the users and write-set
719   // structures associated with I. Specifically, Users represents the set of
720   // instructions that depend on I. WriteSet represents the set
721   // of memory locations that are dependent on I. If UpdateUsers is true,
722   // and J uses I, then Users is updated to contain J and WriteSet is updated
723   // to contain any memory locations to which J writes. The function returns
724   // true if J uses I. By default, alias analysis is used to determine
725   // whether J reads from memory that overlaps with a location in WriteSet.
726   // If LoadMoveSet is not null, then it is a previously-computed multimap
727   // where the key is the memory-based user instruction and the value is
728   // the instruction to be compared with I. So, if LoadMoveSet is provided,
729   // then the alias analysis is not used. This is necessary because this
730   // function is called during the process of moving instructions during
731   // vectorization and the results of the alias analysis are not stable during
732   // that process.
733   bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
734                        AliasSetTracker &WriteSet, Instruction *I,
735                        Instruction *J, bool UpdateUsers,
736                        std::multimap<Value *, Value *> *LoadMoveSet) {
737     bool UsesI = false;
738
739     // This instruction may already be marked as a user due, for example, to
740     // being a member of a selected pair.
741     if (Users.count(J))
742       UsesI = true;
743
744     if (!UsesI)
745       for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
746            JU != JE; ++JU) {
747         Value *V = *JU;
748         if (I == V || Users.count(V)) {
749           UsesI = true;
750           break;
751         }
752       }
753     if (!UsesI && J->mayReadFromMemory()) {
754       if (LoadMoveSet) {
755         VPIteratorPair JPairRange = LoadMoveSet->equal_range(J);
756         UsesI = isSecondInIteratorPair<Value*>(I, JPairRange);
757       } else {
758         for (AliasSetTracker::iterator W = WriteSet.begin(),
759              WE = WriteSet.end(); W != WE; ++W) {
760           if (W->aliasesUnknownInst(J, *AA)) {
761             UsesI = true;
762             break;
763           }
764         }
765       }
766     }
767
768     if (UsesI && UpdateUsers) {
769       if (J->mayWriteToMemory()) WriteSet.add(J);
770       Users.insert(J);
771     }
772
773     return UsesI;
774   }
775
776   // This function iterates over all instruction pairs in the provided
777   // basic block and collects all candidate pairs for vectorization.
778   bool BBVectorize::getCandidatePairs(BasicBlock &BB,
779                        BasicBlock::iterator &Start,
780                        std::multimap<Value *, Value *> &CandidatePairs,
781                        std::vector<Value *> &PairableInsts) {
782     BasicBlock::iterator E = BB.end();
783     if (Start == E) return false;
784
785     bool ShouldContinue = false, IAfterStart = false;
786     for (BasicBlock::iterator I = Start++; I != E; ++I) {
787       if (I == Start) IAfterStart = true;
788
789       bool IsSimpleLoadStore;
790       if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
791
792       // Look for an instruction with which to pair instruction *I...
793       DenseSet<Value *> Users;
794       AliasSetTracker WriteSet(*AA);
795       bool JAfterStart = IAfterStart;
796       BasicBlock::iterator J = llvm::next(I);
797       for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
798         if (J == Start) JAfterStart = true;
799
800         // Determine if J uses I, if so, exit the loop.
801         bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
802         if (Config.FastDep) {
803           // Note: For this heuristic to be effective, independent operations
804           // must tend to be intermixed. This is likely to be true from some
805           // kinds of grouped loop unrolling (but not the generic LLVM pass),
806           // but otherwise may require some kind of reordering pass.
807
808           // When using fast dependency analysis,
809           // stop searching after first use:
810           if (UsesI) break;
811         } else {
812           if (UsesI) continue;
813         }
814
815         // J does not use I, and comes before the first use of I, so it can be
816         // merged with I if the instructions are compatible.
817         if (!areInstsCompatible(I, J, IsSimpleLoadStore)) continue;
818
819         // J is a candidate for merging with I.
820         if (!PairableInsts.size() ||
821              PairableInsts[PairableInsts.size()-1] != I) {
822           PairableInsts.push_back(I);
823         }
824
825         CandidatePairs.insert(ValuePair(I, J));
826
827         // The next call to this function must start after the last instruction
828         // selected during this invocation.
829         if (JAfterStart) {
830           Start = llvm::next(J);
831           IAfterStart = JAfterStart = false;
832         }
833
834         DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
835                      << *I << " <-> " << *J << "\n");
836
837         // If we have already found too many pairs, break here and this function
838         // will be called again starting after the last instruction selected
839         // during this invocation.
840         if (PairableInsts.size() >= Config.MaxInsts) {
841           ShouldContinue = true;
842           break;
843         }
844       }
845
846       if (ShouldContinue)
847         break;
848     }
849
850     DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
851            << " instructions with candidate pairs\n");
852
853     return ShouldContinue;
854   }
855
856   // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
857   // it looks for pairs such that both members have an input which is an
858   // output of PI or PJ.
859   void BBVectorize::computePairsConnectedTo(
860                       std::multimap<Value *, Value *> &CandidatePairs,
861                       std::vector<Value *> &PairableInsts,
862                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
863                       ValuePair P) {
864     StoreInst *SI, *SJ;
865
866     // For each possible pairing for this variable, look at the uses of
867     // the first value...
868     for (Value::use_iterator I = P.first->use_begin(),
869          E = P.first->use_end(); I != E; ++I) {
870       if (isa<LoadInst>(*I)) {
871         // A pair cannot be connected to a load because the load only takes one
872         // operand (the address) and it is a scalar even after vectorization.
873         continue;
874       } else if ((SI = dyn_cast<StoreInst>(*I)) &&
875                  P.first == SI->getPointerOperand()) {
876         // Similarly, a pair cannot be connected to a store through its
877         // pointer operand.
878         continue;
879       }
880
881       VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
882
883       // For each use of the first variable, look for uses of the second
884       // variable...
885       for (Value::use_iterator J = P.second->use_begin(),
886            E2 = P.second->use_end(); J != E2; ++J) {
887         if ((SJ = dyn_cast<StoreInst>(*J)) &&
888             P.second == SJ->getPointerOperand())
889           continue;
890
891         VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
892
893         // Look for <I, J>:
894         if (isSecondInIteratorPair<Value*>(*J, IPairRange))
895           ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
896
897         // Look for <J, I>:
898         if (isSecondInIteratorPair<Value*>(*I, JPairRange))
899           ConnectedPairs.insert(VPPair(P, ValuePair(*J, *I)));
900       }
901
902       if (Config.SplatBreaksChain) continue;
903       // Look for cases where just the first value in the pair is used by
904       // both members of another pair (splatting).
905       for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
906         if ((SJ = dyn_cast<StoreInst>(*J)) &&
907             P.first == SJ->getPointerOperand())
908           continue;
909
910         if (isSecondInIteratorPair<Value*>(*J, IPairRange))
911           ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
912       }
913     }
914
915     if (Config.SplatBreaksChain) return;
916     // Look for cases where just the second value in the pair is used by
917     // both members of another pair (splatting).
918     for (Value::use_iterator I = P.second->use_begin(),
919          E = P.second->use_end(); I != E; ++I) {
920       if (isa<LoadInst>(*I))
921         continue;
922       else if ((SI = dyn_cast<StoreInst>(*I)) &&
923                P.second == SI->getPointerOperand())
924         continue;
925
926       VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
927
928       for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
929         if ((SJ = dyn_cast<StoreInst>(*J)) &&
930             P.second == SJ->getPointerOperand())
931           continue;
932
933         if (isSecondInIteratorPair<Value*>(*J, IPairRange))
934           ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
935       }
936     }
937   }
938
939   // This function figures out which pairs are connected.  Two pairs are
940   // connected if some output of the first pair forms an input to both members
941   // of the second pair.
942   void BBVectorize::computeConnectedPairs(
943                       std::multimap<Value *, Value *> &CandidatePairs,
944                       std::vector<Value *> &PairableInsts,
945                       std::multimap<ValuePair, ValuePair> &ConnectedPairs) {
946
947     for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
948          PE = PairableInsts.end(); PI != PE; ++PI) {
949       VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
950
951       for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
952            P != choiceRange.second; ++P)
953         computePairsConnectedTo(CandidatePairs, PairableInsts,
954                                 ConnectedPairs, *P);
955     }
956
957     DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
958                  << " pair connections.\n");
959   }
960
961   // This function builds a set of use tuples such that <A, B> is in the set
962   // if B is in the use tree of A. If B is in the use tree of A, then B
963   // depends on the output of A.
964   void BBVectorize::buildDepMap(
965                       BasicBlock &BB,
966                       std::multimap<Value *, Value *> &CandidatePairs,
967                       std::vector<Value *> &PairableInsts,
968                       DenseSet<ValuePair> &PairableInstUsers) {
969     DenseSet<Value *> IsInPair;
970     for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
971          E = CandidatePairs.end(); C != E; ++C) {
972       IsInPair.insert(C->first);
973       IsInPair.insert(C->second);
974     }
975
976     // Iterate through the basic block, recording all Users of each
977     // pairable instruction.
978
979     BasicBlock::iterator E = BB.end();
980     for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
981       if (IsInPair.find(I) == IsInPair.end()) continue;
982
983       DenseSet<Value *> Users;
984       AliasSetTracker WriteSet(*AA);
985       for (BasicBlock::iterator J = llvm::next(I); J != E; ++J)
986         (void) trackUsesOfI(Users, WriteSet, I, J);
987
988       for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
989            U != E; ++U)
990         PairableInstUsers.insert(ValuePair(I, *U));
991     }
992   }
993
994   // Returns true if an input to pair P is an output of pair Q and also an
995   // input of pair Q is an output of pair P. If this is the case, then these
996   // two pairs cannot be simultaneously fused.
997   bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
998                      DenseSet<ValuePair> &PairableInstUsers,
999                      std::multimap<ValuePair, ValuePair> *PairableInstUserMap) {
1000     // Two pairs are in conflict if they are mutual Users of eachother.
1001     bool QUsesP = PairableInstUsers.count(ValuePair(P.first,  Q.first))  ||
1002                   PairableInstUsers.count(ValuePair(P.first,  Q.second)) ||
1003                   PairableInstUsers.count(ValuePair(P.second, Q.first))  ||
1004                   PairableInstUsers.count(ValuePair(P.second, Q.second));
1005     bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first,  P.first))  ||
1006                   PairableInstUsers.count(ValuePair(Q.first,  P.second)) ||
1007                   PairableInstUsers.count(ValuePair(Q.second, P.first))  ||
1008                   PairableInstUsers.count(ValuePair(Q.second, P.second));
1009     if (PairableInstUserMap) {
1010       // FIXME: The expensive part of the cycle check is not so much the cycle
1011       // check itself but this edge insertion procedure. This needs some
1012       // profiling and probably a different data structure (same is true of
1013       // most uses of std::multimap).
1014       if (PUsesQ) {
1015         VPPIteratorPair QPairRange = PairableInstUserMap->equal_range(Q);
1016         if (!isSecondInIteratorPair(P, QPairRange))
1017           PairableInstUserMap->insert(VPPair(Q, P));
1018       }
1019       if (QUsesP) {
1020         VPPIteratorPair PPairRange = PairableInstUserMap->equal_range(P);
1021         if (!isSecondInIteratorPair(Q, PPairRange))
1022           PairableInstUserMap->insert(VPPair(P, Q));
1023       }
1024     }
1025
1026     return (QUsesP && PUsesQ);
1027   }
1028
1029   // This function walks the use graph of current pairs to see if, starting
1030   // from P, the walk returns to P.
1031   bool BBVectorize::pairWillFormCycle(ValuePair P,
1032                        std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1033                        DenseSet<ValuePair> &CurrentPairs) {
1034     DEBUG(if (DebugCycleCheck)
1035             dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1036                    << *P.second << "\n");
1037     // A lookup table of visisted pairs is kept because the PairableInstUserMap
1038     // contains non-direct associations.
1039     DenseSet<ValuePair> Visited;
1040     SmallVector<ValuePair, 32> Q;
1041     // General depth-first post-order traversal:
1042     Q.push_back(P);
1043     do {
1044       ValuePair QTop = Q.pop_back_val();
1045       Visited.insert(QTop);
1046
1047       DEBUG(if (DebugCycleCheck)
1048               dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1049                      << *QTop.second << "\n");
1050       VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
1051       for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
1052            C != QPairRange.second; ++C) {
1053         if (C->second == P) {
1054           DEBUG(dbgs()
1055                  << "BBV: rejected to prevent non-trivial cycle formation: "
1056                  << *C->first.first << " <-> " << *C->first.second << "\n");
1057           return true;
1058         }
1059
1060         if (CurrentPairs.count(C->second) && !Visited.count(C->second))
1061           Q.push_back(C->second);
1062       }
1063     } while (!Q.empty());
1064
1065     return false;
1066   }
1067
1068   // This function builds the initial tree of connected pairs with the
1069   // pair J at the root.
1070   void BBVectorize::buildInitialTreeFor(
1071                       std::multimap<Value *, Value *> &CandidatePairs,
1072                       std::vector<Value *> &PairableInsts,
1073                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1074                       DenseSet<ValuePair> &PairableInstUsers,
1075                       DenseMap<Value *, Value *> &ChosenPairs,
1076                       DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
1077     // Each of these pairs is viewed as the root node of a Tree. The Tree
1078     // is then walked (depth-first). As this happens, we keep track of
1079     // the pairs that compose the Tree and the maximum depth of the Tree.
1080     SmallVector<ValuePairWithDepth, 32> Q;
1081     // General depth-first post-order traversal:
1082     Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1083     do {
1084       ValuePairWithDepth QTop = Q.back();
1085
1086       // Push each child onto the queue:
1087       bool MoreChildren = false;
1088       size_t MaxChildDepth = QTop.second;
1089       VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
1090       for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
1091            k != qtRange.second; ++k) {
1092         // Make sure that this child pair is still a candidate:
1093         bool IsStillCand = false;
1094         VPIteratorPair checkRange =
1095           CandidatePairs.equal_range(k->second.first);
1096         for (std::multimap<Value *, Value *>::iterator m = checkRange.first;
1097              m != checkRange.second; ++m) {
1098           if (m->second == k->second.second) {
1099             IsStillCand = true;
1100             break;
1101           }
1102         }
1103
1104         if (IsStillCand) {
1105           DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
1106           if (C == Tree.end()) {
1107             size_t d = getDepthFactor(k->second.first);
1108             Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
1109             MoreChildren = true;
1110           } else {
1111             MaxChildDepth = std::max(MaxChildDepth, C->second);
1112           }
1113         }
1114       }
1115
1116       if (!MoreChildren) {
1117         // Record the current pair as part of the Tree:
1118         Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1119         Q.pop_back();
1120       }
1121     } while (!Q.empty());
1122   }
1123
1124   // Given some initial tree, prune it by removing conflicting pairs (pairs
1125   // that cannot be simultaneously chosen for vectorization).
1126   void BBVectorize::pruneTreeFor(
1127                       std::multimap<Value *, Value *> &CandidatePairs,
1128                       std::vector<Value *> &PairableInsts,
1129                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1130                       DenseSet<ValuePair> &PairableInstUsers,
1131                       std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1132                       DenseMap<Value *, Value *> &ChosenPairs,
1133                       DenseMap<ValuePair, size_t> &Tree,
1134                       DenseSet<ValuePair> &PrunedTree, ValuePair J,
1135                       bool UseCycleCheck) {
1136     SmallVector<ValuePairWithDepth, 32> Q;
1137     // General depth-first post-order traversal:
1138     Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1139     do {
1140       ValuePairWithDepth QTop = Q.pop_back_val();
1141       PrunedTree.insert(QTop.first);
1142
1143       // Visit each child, pruning as necessary...
1144       DenseMap<ValuePair, size_t> BestChildren;
1145       VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
1146       for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
1147            K != QTopRange.second; ++K) {
1148         DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
1149         if (C == Tree.end()) continue;
1150
1151         // This child is in the Tree, now we need to make sure it is the
1152         // best of any conflicting children. There could be multiple
1153         // conflicting children, so first, determine if we're keeping
1154         // this child, then delete conflicting children as necessary.
1155
1156         // It is also necessary to guard against pairing-induced
1157         // dependencies. Consider instructions a .. x .. y .. b
1158         // such that (a,b) are to be fused and (x,y) are to be fused
1159         // but a is an input to x and b is an output from y. This
1160         // means that y cannot be moved after b but x must be moved
1161         // after b for (a,b) to be fused. In other words, after
1162         // fusing (a,b) we have y .. a/b .. x where y is an input
1163         // to a/b and x is an output to a/b: x and y can no longer
1164         // be legally fused. To prevent this condition, we must
1165         // make sure that a child pair added to the Tree is not
1166         // both an input and output of an already-selected pair.
1167
1168         // Pairing-induced dependencies can also form from more complicated
1169         // cycles. The pair vs. pair conflicts are easy to check, and so
1170         // that is done explicitly for "fast rejection", and because for
1171         // child vs. child conflicts, we may prefer to keep the current
1172         // pair in preference to the already-selected child.
1173         DenseSet<ValuePair> CurrentPairs;
1174
1175         bool CanAdd = true;
1176         for (DenseMap<ValuePair, size_t>::iterator C2
1177               = BestChildren.begin(), E2 = BestChildren.end();
1178              C2 != E2; ++C2) {
1179           if (C2->first.first == C->first.first ||
1180               C2->first.first == C->first.second ||
1181               C2->first.second == C->first.first ||
1182               C2->first.second == C->first.second ||
1183               pairsConflict(C2->first, C->first, PairableInstUsers,
1184                             UseCycleCheck ? &PairableInstUserMap : 0)) {
1185             if (C2->second >= C->second) {
1186               CanAdd = false;
1187               break;
1188             }
1189
1190             CurrentPairs.insert(C2->first);
1191           }
1192         }
1193         if (!CanAdd) continue;
1194
1195         // Even worse, this child could conflict with another node already
1196         // selected for the Tree. If that is the case, ignore this child.
1197         for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1198              E2 = PrunedTree.end(); T != E2; ++T) {
1199           if (T->first == C->first.first ||
1200               T->first == C->first.second ||
1201               T->second == C->first.first ||
1202               T->second == C->first.second ||
1203               pairsConflict(*T, C->first, PairableInstUsers,
1204                             UseCycleCheck ? &PairableInstUserMap : 0)) {
1205             CanAdd = false;
1206             break;
1207           }
1208
1209           CurrentPairs.insert(*T);
1210         }
1211         if (!CanAdd) continue;
1212
1213         // And check the queue too...
1214         for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1215              E2 = Q.end(); C2 != E2; ++C2) {
1216           if (C2->first.first == C->first.first ||
1217               C2->first.first == C->first.second ||
1218               C2->first.second == C->first.first ||
1219               C2->first.second == C->first.second ||
1220               pairsConflict(C2->first, C->first, PairableInstUsers,
1221                             UseCycleCheck ? &PairableInstUserMap : 0)) {
1222             CanAdd = false;
1223             break;
1224           }
1225
1226           CurrentPairs.insert(C2->first);
1227         }
1228         if (!CanAdd) continue;
1229
1230         // Last but not least, check for a conflict with any of the
1231         // already-chosen pairs.
1232         for (DenseMap<Value *, Value *>::iterator C2 =
1233               ChosenPairs.begin(), E2 = ChosenPairs.end();
1234              C2 != E2; ++C2) {
1235           if (pairsConflict(*C2, C->first, PairableInstUsers,
1236                             UseCycleCheck ? &PairableInstUserMap : 0)) {
1237             CanAdd = false;
1238             break;
1239           }
1240
1241           CurrentPairs.insert(*C2);
1242         }
1243         if (!CanAdd) continue;
1244
1245         // To check for non-trivial cycles formed by the addition of the
1246         // current pair we've formed a list of all relevant pairs, now use a
1247         // graph walk to check for a cycle. We start from the current pair and
1248         // walk the use tree to see if we again reach the current pair. If we
1249         // do, then the current pair is rejected.
1250
1251         // FIXME: It may be more efficient to use a topological-ordering
1252         // algorithm to improve the cycle check. This should be investigated.
1253         if (UseCycleCheck &&
1254             pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1255           continue;
1256
1257         // This child can be added, but we may have chosen it in preference
1258         // to an already-selected child. Check for this here, and if a
1259         // conflict is found, then remove the previously-selected child
1260         // before adding this one in its place.
1261         for (DenseMap<ValuePair, size_t>::iterator C2
1262               = BestChildren.begin(); C2 != BestChildren.end();) {
1263           if (C2->first.first == C->first.first ||
1264               C2->first.first == C->first.second ||
1265               C2->first.second == C->first.first ||
1266               C2->first.second == C->first.second ||
1267               pairsConflict(C2->first, C->first, PairableInstUsers))
1268             BestChildren.erase(C2++);
1269           else
1270             ++C2;
1271         }
1272
1273         BestChildren.insert(ValuePairWithDepth(C->first, C->second));
1274       }
1275
1276       for (DenseMap<ValuePair, size_t>::iterator C
1277             = BestChildren.begin(), E2 = BestChildren.end();
1278            C != E2; ++C) {
1279         size_t DepthF = getDepthFactor(C->first.first);
1280         Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1281       }
1282     } while (!Q.empty());
1283   }
1284
1285   // This function finds the best tree of mututally-compatible connected
1286   // pairs, given the choice of root pairs as an iterator range.
1287   void BBVectorize::findBestTreeFor(
1288                       std::multimap<Value *, Value *> &CandidatePairs,
1289                       std::vector<Value *> &PairableInsts,
1290                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1291                       DenseSet<ValuePair> &PairableInstUsers,
1292                       std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1293                       DenseMap<Value *, Value *> &ChosenPairs,
1294                       DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1295                       size_t &BestEffSize, VPIteratorPair ChoiceRange,
1296                       bool UseCycleCheck) {
1297     for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
1298          J != ChoiceRange.second; ++J) {
1299
1300       // Before going any further, make sure that this pair does not
1301       // conflict with any already-selected pairs (see comment below
1302       // near the Tree pruning for more details).
1303       DenseSet<ValuePair> ChosenPairSet;
1304       bool DoesConflict = false;
1305       for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1306            E = ChosenPairs.end(); C != E; ++C) {
1307         if (pairsConflict(*C, *J, PairableInstUsers,
1308                           UseCycleCheck ? &PairableInstUserMap : 0)) {
1309           DoesConflict = true;
1310           break;
1311         }
1312
1313         ChosenPairSet.insert(*C);
1314       }
1315       if (DoesConflict) continue;
1316
1317       if (UseCycleCheck &&
1318           pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1319         continue;
1320
1321       DenseMap<ValuePair, size_t> Tree;
1322       buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1323                           PairableInstUsers, ChosenPairs, Tree, *J);
1324
1325       // Because we'll keep the child with the largest depth, the largest
1326       // depth is still the same in the unpruned Tree.
1327       size_t MaxDepth = Tree.lookup(*J);
1328
1329       DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1330                    << *J->first << " <-> " << *J->second << "} of depth " <<
1331                    MaxDepth << " and size " << Tree.size() << "\n");
1332
1333       // At this point the Tree has been constructed, but, may contain
1334       // contradictory children (meaning that different children of
1335       // some tree node may be attempting to fuse the same instruction).
1336       // So now we walk the tree again, in the case of a conflict,
1337       // keep only the child with the largest depth. To break a tie,
1338       // favor the first child.
1339
1340       DenseSet<ValuePair> PrunedTree;
1341       pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1342                    PairableInstUsers, PairableInstUserMap, ChosenPairs, Tree,
1343                    PrunedTree, *J, UseCycleCheck);
1344
1345       size_t EffSize = 0;
1346       for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1347            E = PrunedTree.end(); S != E; ++S)
1348         EffSize += getDepthFactor(S->first);
1349
1350       DEBUG(if (DebugPairSelection)
1351              dbgs() << "BBV: found pruned Tree for pair {"
1352              << *J->first << " <-> " << *J->second << "} of depth " <<
1353              MaxDepth << " and size " << PrunedTree.size() <<
1354             " (effective size: " << EffSize << ")\n");
1355       if (MaxDepth >= Config.ReqChainDepth && EffSize > BestEffSize) {
1356         BestMaxDepth = MaxDepth;
1357         BestEffSize = EffSize;
1358         BestTree = PrunedTree;
1359       }
1360     }
1361   }
1362
1363   // Given the list of candidate pairs, this function selects those
1364   // that will be fused into vector instructions.
1365   void BBVectorize::choosePairs(
1366                       std::multimap<Value *, Value *> &CandidatePairs,
1367                       std::vector<Value *> &PairableInsts,
1368                       std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1369                       DenseSet<ValuePair> &PairableInstUsers,
1370                       DenseMap<Value *, Value *>& ChosenPairs) {
1371     bool UseCycleCheck =
1372      CandidatePairs.size() <= Config.MaxCandPairsForCycleCheck;
1373     std::multimap<ValuePair, ValuePair> PairableInstUserMap;
1374     for (std::vector<Value *>::iterator I = PairableInsts.begin(),
1375          E = PairableInsts.end(); I != E; ++I) {
1376       // The number of possible pairings for this variable:
1377       size_t NumChoices = CandidatePairs.count(*I);
1378       if (!NumChoices) continue;
1379
1380       VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
1381
1382       // The best pair to choose and its tree:
1383       size_t BestMaxDepth = 0, BestEffSize = 0;
1384       DenseSet<ValuePair> BestTree;
1385       findBestTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1386                       PairableInstUsers, PairableInstUserMap, ChosenPairs,
1387                       BestTree, BestMaxDepth, BestEffSize, ChoiceRange,
1388                       UseCycleCheck);
1389
1390       // A tree has been chosen (or not) at this point. If no tree was
1391       // chosen, then this instruction, I, cannot be paired (and is no longer
1392       // considered).
1393
1394       DEBUG(if (BestTree.size() > 0)
1395               dbgs() << "BBV: selected pairs in the best tree for: "
1396                      << *cast<Instruction>(*I) << "\n");
1397
1398       for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
1399            SE2 = BestTree.end(); S != SE2; ++S) {
1400         // Insert the members of this tree into the list of chosen pairs.
1401         ChosenPairs.insert(ValuePair(S->first, S->second));
1402         DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
1403                *S->second << "\n");
1404
1405         // Remove all candidate pairs that have values in the chosen tree.
1406         for (std::multimap<Value *, Value *>::iterator K =
1407                CandidatePairs.begin(); K != CandidatePairs.end();) {
1408           if (K->first == S->first || K->second == S->first ||
1409               K->second == S->second || K->first == S->second) {
1410             // Don't remove the actual pair chosen so that it can be used
1411             // in subsequent tree selections.
1412             if (!(K->first == S->first && K->second == S->second))
1413               CandidatePairs.erase(K++);
1414             else
1415               ++K;
1416           } else {
1417             ++K;
1418           }
1419         }
1420       }
1421     }
1422
1423     DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
1424   }
1425
1426   std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
1427                      unsigned n = 0) {
1428     if (!I->hasName())
1429       return "";
1430
1431     return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
1432              (n > 0 ? "." + utostr(n) : "")).str();
1433   }
1434
1435   // Returns the value that is to be used as the pointer input to the vector
1436   // instruction that fuses I with J.
1437   Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
1438                      Instruction *I, Instruction *J, unsigned o,
1439                      bool &FlipMemInputs) {
1440     Value *IPtr, *JPtr;
1441     unsigned IAlignment, JAlignment;
1442     int64_t OffsetInElmts;
1443     (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
1444                           OffsetInElmts);
1445
1446     // The pointer value is taken to be the one with the lowest offset.
1447     Value *VPtr;
1448     if (OffsetInElmts > 0) {
1449       VPtr = IPtr;
1450     } else {
1451       FlipMemInputs = true;
1452       VPtr = JPtr;
1453     }
1454
1455     Type *ArgType = cast<PointerType>(IPtr->getType())->getElementType();
1456     Type *VArgType = getVecTypeForPair(ArgType);
1457     Type *VArgPtrType = PointerType::get(VArgType,
1458       cast<PointerType>(IPtr->getType())->getAddressSpace());
1459     return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
1460                         /* insert before */ FlipMemInputs ? J : I);
1461   }
1462
1463   void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
1464                      unsigned NumElem, unsigned MaskOffset, unsigned NumInElem,
1465                      unsigned IdxOffset, std::vector<Constant*> &Mask) {
1466     for (unsigned v = 0; v < NumElem/2; ++v) {
1467       int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
1468       if (m < 0) {
1469         Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
1470       } else {
1471         unsigned mm = m + (int) IdxOffset;
1472         if (m >= (int) NumInElem)
1473           mm += (int) NumInElem;
1474
1475         Mask[v+MaskOffset] =
1476           ConstantInt::get(Type::getInt32Ty(Context), mm);
1477       }
1478     }
1479   }
1480
1481   // Returns the value that is to be used as the vector-shuffle mask to the
1482   // vector instruction that fuses I with J.
1483   Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
1484                      Instruction *I, Instruction *J) {
1485     // This is the shuffle mask. We need to append the second
1486     // mask to the first, and the numbers need to be adjusted.
1487
1488     Type *ArgType = I->getType();
1489     Type *VArgType = getVecTypeForPair(ArgType);
1490
1491     // Get the total number of elements in the fused vector type.
1492     // By definition, this must equal the number of elements in
1493     // the final mask.
1494     unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
1495     std::vector<Constant*> Mask(NumElem);
1496
1497     Type *OpType = I->getOperand(0)->getType();
1498     unsigned NumInElem = cast<VectorType>(OpType)->getNumElements();
1499
1500     // For the mask from the first pair...
1501     fillNewShuffleMask(Context, I, NumElem, 0, NumInElem, 0, Mask);
1502
1503     // For the mask from the second pair...
1504     fillNewShuffleMask(Context, J, NumElem, NumElem/2, NumInElem, NumInElem,
1505                        Mask);
1506
1507     return ConstantVector::get(Mask);
1508   }
1509
1510   // Returns the value to be used as the specified operand of the vector
1511   // instruction that fuses I with J.
1512   Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
1513                      Instruction *J, unsigned o, bool FlipMemInputs) {
1514     Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1515     Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1516
1517       // Compute the fused vector type for this operand
1518     Type *ArgType = I->getOperand(o)->getType();
1519     VectorType *VArgType = getVecTypeForPair(ArgType);
1520
1521     Instruction *L = I, *H = J;
1522     if (FlipMemInputs) {
1523       L = J;
1524       H = I;
1525     }
1526
1527     if (ArgType->isVectorTy()) {
1528       unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
1529       std::vector<Constant*> Mask(numElem);
1530       for (unsigned v = 0; v < numElem; ++v)
1531         Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1532
1533       Instruction *BV = new ShuffleVectorInst(L->getOperand(o),
1534                                               H->getOperand(o),
1535                                               ConstantVector::get(Mask),
1536                                               getReplacementName(I, true, o));
1537       BV->insertBefore(J);
1538       return BV;
1539     }
1540
1541     // If these two inputs are the output of another vector instruction,
1542     // then we should use that output directly. It might be necessary to
1543     // permute it first. [When pairings are fused recursively, you can
1544     // end up with cases where a large vector is decomposed into scalars
1545     // using extractelement instructions, then built into size-2
1546     // vectors using insertelement and the into larger vectors using
1547     // shuffles. InstCombine does not simplify all of these cases well,
1548     // and so we make sure that shuffles are generated here when possible.
1549     ExtractElementInst *LEE
1550       = dyn_cast<ExtractElementInst>(L->getOperand(o));
1551     ExtractElementInst *HEE
1552       = dyn_cast<ExtractElementInst>(H->getOperand(o));
1553
1554     if (LEE && HEE &&
1555         LEE->getOperand(0)->getType() == HEE->getOperand(0)->getType()) {
1556       VectorType *EEType = cast<VectorType>(LEE->getOperand(0)->getType());
1557       unsigned LowIndx = cast<ConstantInt>(LEE->getOperand(1))->getZExtValue();
1558       unsigned HighIndx = cast<ConstantInt>(HEE->getOperand(1))->getZExtValue();
1559       if (LEE->getOperand(0) == HEE->getOperand(0)) {
1560         if (LowIndx == 0 && HighIndx == 1)
1561           return LEE->getOperand(0);
1562
1563         std::vector<Constant*> Mask(2);
1564         Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
1565         Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
1566
1567         Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
1568                                           UndefValue::get(EEType),
1569                                           ConstantVector::get(Mask),
1570                                           getReplacementName(I, true, o));
1571         BV->insertBefore(J);
1572         return BV;
1573       }
1574
1575       std::vector<Constant*> Mask(2);
1576       HighIndx += EEType->getNumElements();
1577       Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
1578       Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
1579
1580       Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
1581                                           HEE->getOperand(0),
1582                                           ConstantVector::get(Mask),
1583                                           getReplacementName(I, true, o));
1584       BV->insertBefore(J);
1585       return BV;
1586     }
1587
1588     Instruction *BV1 = InsertElementInst::Create(
1589                                           UndefValue::get(VArgType),
1590                                           L->getOperand(o), CV0,
1591                                           getReplacementName(I, true, o, 1));
1592     BV1->insertBefore(I);
1593     Instruction *BV2 = InsertElementInst::Create(BV1, H->getOperand(o),
1594                                           CV1,
1595                                           getReplacementName(I, true, o, 2));
1596     BV2->insertBefore(J);
1597     return BV2;
1598   }
1599
1600   // This function creates an array of values that will be used as the inputs
1601   // to the vector instruction that fuses I with J.
1602   void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
1603                      Instruction *I, Instruction *J,
1604                      SmallVector<Value *, 3> &ReplacedOperands,
1605                      bool &FlipMemInputs) {
1606     FlipMemInputs = false;
1607     unsigned NumOperands = I->getNumOperands();
1608
1609     for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
1610       // Iterate backward so that we look at the store pointer
1611       // first and know whether or not we need to flip the inputs.
1612
1613       if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
1614         // This is the pointer for a load/store instruction.
1615         ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o,
1616                                 FlipMemInputs);
1617         continue;
1618       } else if (isa<CallInst>(I)) {
1619         Function *F = cast<CallInst>(I)->getCalledFunction();
1620         unsigned IID = F->getIntrinsicID();
1621         if (o == NumOperands-1) {
1622           BasicBlock &BB = *I->getParent();
1623
1624           Module *M = BB.getParent()->getParent();
1625           Type *ArgType = I->getType();
1626           Type *VArgType = getVecTypeForPair(ArgType);
1627
1628           // FIXME: is it safe to do this here?
1629           ReplacedOperands[o] = Intrinsic::getDeclaration(M,
1630             (Intrinsic::ID) IID, VArgType);
1631           continue;
1632         } else if (IID == Intrinsic::powi && o == 1) {
1633           // The second argument of powi is a single integer and we've already
1634           // checked that both arguments are equal. As a result, we just keep
1635           // I's second argument.
1636           ReplacedOperands[o] = I->getOperand(o);
1637           continue;
1638         }
1639       } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
1640         ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
1641         continue;
1642       }
1643
1644       ReplacedOperands[o] =
1645         getReplacementInput(Context, I, J, o, FlipMemInputs);
1646     }
1647   }
1648
1649   // This function creates two values that represent the outputs of the
1650   // original I and J instructions. These are generally vector shuffles
1651   // or extracts. In many cases, these will end up being unused and, thus,
1652   // eliminated by later passes.
1653   void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
1654                      Instruction *J, Instruction *K,
1655                      Instruction *&InsertionPt,
1656                      Instruction *&K1, Instruction *&K2,
1657                      bool &FlipMemInputs) {
1658     Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1659     Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1660
1661     if (isa<StoreInst>(I)) {
1662       AA->replaceWithNewValue(I, K);
1663       AA->replaceWithNewValue(J, K);
1664     } else {
1665       Type *IType = I->getType();
1666       Type *VType = getVecTypeForPair(IType);
1667
1668       if (IType->isVectorTy()) {
1669           unsigned numElem = cast<VectorType>(IType)->getNumElements();
1670           std::vector<Constant*> Mask1(numElem), Mask2(numElem);
1671           for (unsigned v = 0; v < numElem; ++v) {
1672             Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1673             Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElem+v);
1674           }
1675
1676           K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
1677                                        ConstantVector::get(
1678                                          FlipMemInputs ? Mask2 : Mask1),
1679                                        getReplacementName(K, false, 1));
1680           K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
1681                                        ConstantVector::get(
1682                                          FlipMemInputs ? Mask1 : Mask2),
1683                                        getReplacementName(K, false, 2));
1684       } else {
1685         K1 = ExtractElementInst::Create(K, FlipMemInputs ? CV1 : CV0,
1686                                           getReplacementName(K, false, 1));
1687         K2 = ExtractElementInst::Create(K, FlipMemInputs ? CV0 : CV1,
1688                                           getReplacementName(K, false, 2));
1689       }
1690
1691       K1->insertAfter(K);
1692       K2->insertAfter(K1);
1693       InsertionPt = K2;
1694     }
1695   }
1696
1697   // Move all uses of the function I (including pairing-induced uses) after J.
1698   bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
1699                      std::multimap<Value *, Value *> &LoadMoveSet,
1700                      Instruction *I, Instruction *J) {
1701     // Skip to the first instruction past I.
1702     BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1703
1704     DenseSet<Value *> Users;
1705     AliasSetTracker WriteSet(*AA);
1706     for (; cast<Instruction>(L) != J; ++L)
1707       (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet);
1708
1709     assert(cast<Instruction>(L) == J &&
1710       "Tracking has not proceeded far enough to check for dependencies");
1711     // If J is now in the use set of I, then trackUsesOfI will return true
1712     // and we have a dependency cycle (and the fusing operation must abort).
1713     return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSet);
1714   }
1715
1716   // Move all uses of the function I (including pairing-induced uses) after J.
1717   void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
1718                      std::multimap<Value *, Value *> &LoadMoveSet,
1719                      Instruction *&InsertionPt,
1720                      Instruction *I, Instruction *J) {
1721     // Skip to the first instruction past I.
1722     BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1723
1724     DenseSet<Value *> Users;
1725     AliasSetTracker WriteSet(*AA);
1726     for (; cast<Instruction>(L) != J;) {
1727       if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet)) {
1728         // Move this instruction
1729         Instruction *InstToMove = L; ++L;
1730
1731         DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
1732                         " to after " << *InsertionPt << "\n");
1733         InstToMove->removeFromParent();
1734         InstToMove->insertAfter(InsertionPt);
1735         InsertionPt = InstToMove;
1736       } else {
1737         ++L;
1738       }
1739     }
1740   }
1741
1742   // Collect all load instruction that are in the move set of a given first
1743   // pair member.  These loads depend on the first instruction, I, and so need
1744   // to be moved after J (the second instruction) when the pair is fused.
1745   void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
1746                      DenseMap<Value *, Value *> &ChosenPairs,
1747                      std::multimap<Value *, Value *> &LoadMoveSet,
1748                      Instruction *I) {
1749     // Skip to the first instruction past I.
1750     BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
1751
1752     DenseSet<Value *> Users;
1753     AliasSetTracker WriteSet(*AA);
1754
1755     // Note: We cannot end the loop when we reach J because J could be moved
1756     // farther down the use chain by another instruction pairing. Also, J
1757     // could be before I if this is an inverted input.
1758     for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
1759       if (trackUsesOfI(Users, WriteSet, I, L)) {
1760         if (L->mayReadFromMemory())
1761           LoadMoveSet.insert(ValuePair(L, I));
1762       }
1763     }
1764   }
1765
1766   // In cases where both load/stores and the computation of their pointers
1767   // are chosen for vectorization, we can end up in a situation where the
1768   // aliasing analysis starts returning different query results as the
1769   // process of fusing instruction pairs continues. Because the algorithm
1770   // relies on finding the same use trees here as were found earlier, we'll
1771   // need to precompute the necessary aliasing information here and then
1772   // manually update it during the fusion process.
1773   void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
1774                      std::vector<Value *> &PairableInsts,
1775                      DenseMap<Value *, Value *> &ChosenPairs,
1776                      std::multimap<Value *, Value *> &LoadMoveSet) {
1777     for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1778          PIE = PairableInsts.end(); PI != PIE; ++PI) {
1779       DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
1780       if (P == ChosenPairs.end()) continue;
1781
1782       Instruction *I = cast<Instruction>(P->first);
1783       collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet, I);
1784     }
1785   }
1786
1787   // This function fuses the chosen instruction pairs into vector instructions,
1788   // taking care preserve any needed scalar outputs and, then, it reorders the
1789   // remaining instructions as needed (users of the first member of the pair
1790   // need to be moved to after the location of the second member of the pair
1791   // because the vector instruction is inserted in the location of the pair's
1792   // second member).
1793   void BBVectorize::fuseChosenPairs(BasicBlock &BB,
1794                      std::vector<Value *> &PairableInsts,
1795                      DenseMap<Value *, Value *> &ChosenPairs) {
1796     LLVMContext& Context = BB.getContext();
1797
1798     // During the vectorization process, the order of the pairs to be fused
1799     // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
1800     // list. After a pair is fused, the flipped pair is removed from the list.
1801     std::vector<ValuePair> FlippedPairs;
1802     FlippedPairs.reserve(ChosenPairs.size());
1803     for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
1804          E = ChosenPairs.end(); P != E; ++P)
1805       FlippedPairs.push_back(ValuePair(P->second, P->first));
1806     for (std::vector<ValuePair>::iterator P = FlippedPairs.begin(),
1807          E = FlippedPairs.end(); P != E; ++P)
1808       ChosenPairs.insert(*P);
1809
1810     std::multimap<Value *, Value *> LoadMoveSet;
1811     collectLoadMoveSet(BB, PairableInsts, ChosenPairs, LoadMoveSet);
1812
1813     DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
1814
1815     for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
1816       DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
1817       if (P == ChosenPairs.end()) {
1818         ++PI;
1819         continue;
1820       }
1821
1822       if (getDepthFactor(P->first) == 0) {
1823         // These instructions are not really fused, but are tracked as though
1824         // they are. Any case in which it would be interesting to fuse them
1825         // will be taken care of by InstCombine.
1826         --NumFusedOps;
1827         ++PI;
1828         continue;
1829       }
1830
1831       Instruction *I = cast<Instruction>(P->first),
1832         *J = cast<Instruction>(P->second);
1833
1834       DEBUG(dbgs() << "BBV: fusing: " << *I <<
1835              " <-> " << *J << "\n");
1836
1837       // Remove the pair and flipped pair from the list.
1838       DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
1839       assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
1840       ChosenPairs.erase(FP);
1841       ChosenPairs.erase(P);
1842
1843       if (!canMoveUsesOfIAfterJ(BB, LoadMoveSet, I, J)) {
1844         DEBUG(dbgs() << "BBV: fusion of: " << *I <<
1845                " <-> " << *J <<
1846                " aborted because of non-trivial dependency cycle\n");
1847         --NumFusedOps;
1848         ++PI;
1849         continue;
1850       }
1851
1852       bool FlipMemInputs;
1853       unsigned NumOperands = I->getNumOperands();
1854       SmallVector<Value *, 3> ReplacedOperands(NumOperands);
1855       getReplacementInputsForPair(Context, I, J, ReplacedOperands,
1856         FlipMemInputs);
1857
1858       // Make a copy of the original operation, change its type to the vector
1859       // type and replace its operands with the vector operands.
1860       Instruction *K = I->clone();
1861       if (I->hasName()) K->takeName(I);
1862
1863       if (!isa<StoreInst>(K))
1864         K->mutateType(getVecTypeForPair(I->getType()));
1865
1866       for (unsigned o = 0; o < NumOperands; ++o)
1867         K->setOperand(o, ReplacedOperands[o]);
1868
1869       // If we've flipped the memory inputs, make sure that we take the correct
1870       // alignment.
1871       if (FlipMemInputs) {
1872         if (isa<StoreInst>(K))
1873           cast<StoreInst>(K)->setAlignment(cast<StoreInst>(J)->getAlignment());
1874         else
1875           cast<LoadInst>(K)->setAlignment(cast<LoadInst>(J)->getAlignment());
1876       }
1877
1878       K->insertAfter(J);
1879
1880       // Instruction insertion point:
1881       Instruction *InsertionPt = K;
1882       Instruction *K1 = 0, *K2 = 0;
1883       replaceOutputsOfPair(Context, I, J, K, InsertionPt, K1, K2,
1884         FlipMemInputs);
1885
1886       // The use tree of the first original instruction must be moved to after
1887       // the location of the second instruction. The entire use tree of the
1888       // first instruction is disjoint from the input tree of the second
1889       // (by definition), and so commutes with it.
1890
1891       moveUsesOfIAfterJ(BB, LoadMoveSet, InsertionPt, I, J);
1892
1893       if (!isa<StoreInst>(I)) {
1894         I->replaceAllUsesWith(K1);
1895         J->replaceAllUsesWith(K2);
1896         AA->replaceWithNewValue(I, K1);
1897         AA->replaceWithNewValue(J, K2);
1898       }
1899
1900       // Instructions that may read from memory may be in the load move set.
1901       // Once an instruction is fused, we no longer need its move set, and so
1902       // the values of the map never need to be updated. However, when a load
1903       // is fused, we need to merge the entries from both instructions in the
1904       // pair in case those instructions were in the move set of some other
1905       // yet-to-be-fused pair. The loads in question are the keys of the map.
1906       if (I->mayReadFromMemory()) {
1907         std::vector<ValuePair> NewSetMembers;
1908         VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
1909         VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
1910         for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
1911              N != IPairRange.second; ++N)
1912           NewSetMembers.push_back(ValuePair(K, N->second));
1913         for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
1914              N != JPairRange.second; ++N)
1915           NewSetMembers.push_back(ValuePair(K, N->second));
1916         for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
1917              AE = NewSetMembers.end(); A != AE; ++A)
1918           LoadMoveSet.insert(*A);
1919       }
1920
1921       // Before removing I, set the iterator to the next instruction.
1922       PI = llvm::next(BasicBlock::iterator(I));
1923       if (cast<Instruction>(PI) == J)
1924         ++PI;
1925
1926       SE->forgetValue(I);
1927       SE->forgetValue(J);
1928       I->eraseFromParent();
1929       J->eraseFromParent();
1930     }
1931
1932     DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
1933   }
1934 }
1935
1936 char BBVectorize::ID = 0;
1937 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
1938 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
1939 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1940 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1941 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
1942
1943 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
1944   return new BBVectorize(C);
1945 }
1946
1947 bool
1948 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
1949   BBVectorize BBVectorizer(P, C);
1950   return BBVectorizer.vectorizeBB(BB);
1951 }
1952
1953 //===----------------------------------------------------------------------===//
1954 VectorizeConfig::VectorizeConfig() {
1955   VectorBits = ::VectorBits;
1956   VectorizeInts = !::NoInts;
1957   VectorizeFloats = !::NoFloats;
1958   VectorizePointers = !::NoPointers;
1959   VectorizeCasts = !::NoCasts;
1960   VectorizeMath = !::NoMath;
1961   VectorizeFMA = !::NoFMA;
1962   VectorizeSelect = !::NoSelect;
1963   VectorizeGEP = !::NoGEP;
1964   VectorizeMemOps = !::NoMemOps;
1965   AlignedOnly = ::AlignedOnly;
1966   ReqChainDepth= ::ReqChainDepth;
1967   SearchLimit = ::SearchLimit;
1968   MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
1969   SplatBreaksChain = ::SplatBreaksChain;
1970   MaxInsts = ::MaxInsts;
1971   MaxIter = ::MaxIter;
1972   NoMemOpBoost = ::NoMemOpBoost;
1973   FastDep = ::FastDep;
1974 }