OSDN Git Service

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