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