1 //===- BBVectorize.cpp - A Basic-Block Vectorizer -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
15 //===----------------------------------------------------------------------===//
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"
54 IgnoreTargetInfo("bb-vectorize-ignore-target-info", cl::init(false),
55 cl::Hidden, cl::desc("Ignore target information"));
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"));
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"));
66 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
67 cl::desc("Replicating one element to a pair breaks the chain"));
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"));
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"));
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"));
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"));
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"));
91 NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
92 cl::desc("Don't try to vectorize boolean (i1) values"));
95 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
96 cl::desc("Don't try to vectorize integer values"));
99 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
100 cl::desc("Don't try to vectorize floating-point values"));
102 // FIXME: This should default to false once pointer vector support works.
104 NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
105 cl::desc("Don't try to vectorize pointer values"));
108 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
109 cl::desc("Don't try to vectorize casting (conversion) operations"));
112 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
113 cl::desc("Don't try to vectorize floating-point math intrinsics"));
116 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
117 cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
120 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
121 cl::desc("Don't try to vectorize select instructions"));
124 NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
125 cl::desc("Don't try to vectorize comparison instructions"));
128 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
129 cl::desc("Don't try to vectorize getelementptr instructions"));
132 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
133 cl::desc("Don't try to vectorize loads and stores"));
136 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
137 cl::desc("Only generate aligned loads and stores"));
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"));
145 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
146 cl::desc("Use a fast instruction dependency analysis"));
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"));
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"));
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"));
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"));
171 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
174 struct BBVectorize : public BasicBlockPass {
175 static char ID; // Pass identification, replacement for typeid
177 const VectorizeConfig Config;
179 BBVectorize(const VectorizeConfig &C = VectorizeConfig())
180 : BasicBlockPass(ID), Config(C) {
181 initializeBBVectorizePass(*PassRegistry::getPassRegistry());
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;
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>
209 TargetTransformInfo *TTI;
210 const VectorTargetTransformInfo *VTTI;
212 // FIXME: const correct?
214 bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
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);
222 void computeConnectedPairs(std::multimap<Value *, Value *> &CandidatePairs,
223 std::vector<Value *> &PairableInsts,
224 std::multimap<ValuePair, ValuePair> &ConnectedPairs);
226 void buildDepMap(BasicBlock &BB,
227 std::multimap<Value *, Value *> &CandidatePairs,
228 std::vector<Value *> &PairableInsts,
229 DenseSet<ValuePair> &PairableInstUsers);
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);
238 void fuseChosenPairs(BasicBlock &BB,
239 std::vector<Value *> &PairableInsts,
240 DenseMap<Value *, Value *>& ChosenPairs);
242 bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
244 bool areInstsCompatible(Instruction *I, Instruction *J,
245 bool IsSimpleLoadStore, bool NonPow2Len,
248 bool trackUsesOfI(DenseSet<Value *> &Users,
249 AliasSetTracker &WriteSet, Instruction *I,
250 Instruction *J, bool UpdateUsers = true,
251 std::multimap<Value *, Value *> *LoadMoveSet = 0);
253 void computePairsConnectedTo(
254 std::multimap<Value *, Value *> &CandidatePairs,
255 std::vector<Value *> &PairableInsts,
256 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
259 bool pairsConflict(ValuePair P, ValuePair Q,
260 DenseSet<ValuePair> &PairableInstUsers,
261 std::multimap<ValuePair, ValuePair> *PairableInstUserMap = 0);
263 bool pairWillFormCycle(ValuePair P,
264 std::multimap<ValuePair, ValuePair> &PairableInstUsers,
265 DenseSet<ValuePair> &CurrentPairs);
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,
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);
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,
298 Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
299 Instruction *J, unsigned o, bool FlipMemInputs);
301 void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
302 unsigned MaskOffset, unsigned NumInElem,
303 unsigned NumInElem1, unsigned IdxOffset,
304 std::vector<Constant*> &Mask);
306 Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
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);
314 Value *getReplacementInput(LLVMContext& Context, Instruction *I,
315 Instruction *J, unsigned o, bool FlipMemInputs);
317 void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
318 Instruction *J, SmallVector<Value *, 3> &ReplacedOperands,
321 void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
322 Instruction *J, Instruction *K,
323 Instruction *&InsertionPt, Instruction *&K1,
324 Instruction *&K2, bool FlipMemInputs);
326 void collectPairLoadMoveSet(BasicBlock &BB,
327 DenseMap<Value *, Value *> &ChosenPairs,
328 std::multimap<Value *, Value *> &LoadMoveSet,
331 void collectLoadMoveSet(BasicBlock &BB,
332 std::vector<Value *> &PairableInsts,
333 DenseMap<Value *, Value *> &ChosenPairs,
334 std::multimap<Value *, Value *> &LoadMoveSet);
336 void collectPtrInfo(std::vector<Value *> &PairableInsts,
337 DenseMap<Value *, Value *> &ChosenPairs,
338 DenseSet<Value *> &LowPtrInsts);
340 bool canMoveUsesOfIAfterJ(BasicBlock &BB,
341 std::multimap<Value *, Value *> &LoadMoveSet,
342 Instruction *I, Instruction *J);
344 void moveUsesOfIAfterJ(BasicBlock &BB,
345 std::multimap<Value *, Value *> &LoadMoveSet,
346 Instruction *&InsertionPt,
347 Instruction *I, Instruction *J);
349 void combineMetadata(Instruction *K, const Instruction *J);
351 bool vectorizeBB(BasicBlock &BB) {
352 if (!DT->isReachableFromEntry(&BB)) {
353 DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
354 " in " << BB.getParent()->getName() << "\n");
358 DEBUG(if (VTTI) dbgs() << "BBV: using target information\n");
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.
366 (VTTI || v <= Config.VectorBits) &&
367 (!Config.MaxIter || n <= Config.MaxIter);
369 DEBUG(dbgs() << "BBV: fusing loop #" << n <<
370 " for " << BB.getName() << " in " <<
371 BB.getParent()->getName() << "...\n");
372 if (vectorizePairs(BB))
378 if (changed && !Pow2LenOnly) {
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;
388 DEBUG(dbgs() << "BBV: done!\n");
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;
401 return vectorizeBB(BB);
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();
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();
421 if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
422 numElem = VTy->getNumElements();
427 if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
428 numElem += VTy->getNumElements();
433 return VectorType::get(STy, numElem);
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.
442 Value *IVal = cast<StoreInst>(I)->getValueOperand();
443 T1 = IVal->getType();
449 T2 = cast<CastInst>(I)->getSrcTy();
453 if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
454 T2 = SI->getCondition()->getType();
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
476 if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
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;
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
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) {
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();
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();
515 const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
516 const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
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();
527 Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
528 int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
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;
537 OffsetInElmts = Offset/VTyTSS;
538 return (abs64(Offset) % VTyTSS) == 0;
544 // Returns true if the provided CallInst represents an intrinsic that can
546 bool isVectorizableIntrinsic(CallInst* I) {
547 Function *F = I->getCalledFunction();
548 if (!F) return false;
550 unsigned IID = F->getIntrinsicID();
551 if (!IID) return false;
556 case Intrinsic::sqrt:
557 case Intrinsic::powi:
561 case Intrinsic::log2:
562 case Intrinsic::log10:
564 case Intrinsic::exp2:
566 return Config.VectorizeMath;
568 return Config.VectorizeFMA;
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;
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) {
590 BasicBlock::iterator Start = BB.getFirstInsertionPt();
592 std::vector<Value *> AllPairableInsts;
593 DenseMap<Value *, Value *> AllChosenPairs;
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;
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
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).
613 std::multimap<ValuePair, ValuePair> ConnectedPairs;
614 computeConnectedPairs(CandidatePairs, PairableInsts, ConnectedPairs);
615 if (ConnectedPairs.empty()) continue;
617 // Build the pairable-instruction dependency map
618 DenseSet<ValuePair> PairableInstUsers;
619 buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
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
627 DenseMap<Value *, Value *> ChosenPairs;
628 choosePairs(CandidatePairs, CandidatePairCostSavings,
629 PairableInsts, ConnectedPairs,
630 PairableInstUsers, ChosenPairs);
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);
638 if (AllChosenPairs.empty()) return false;
639 NumFusedOps += AllChosenPairs.size();
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.
648 fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs);
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());
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;
663 if (CallInst *C = dyn_cast<CallInst>(I)) {
664 if (!isVectorizableIntrinsic(C))
666 } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
667 // Vectorize simple loads if possbile:
668 IsSimpleLoadStore = L->isSimple();
669 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
671 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
672 // Vectorize simple stores if possbile:
673 IsSimpleLoadStore = S->isSimple();
674 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
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)
681 Type *SrcTy = C->getSrcTy();
682 if (!SrcTy->isSingleValueType())
685 Type *DestTy = C->getDestTy();
686 if (!DestTy->isSingleValueType())
688 } else if (isa<SelectInst>(I)) {
689 if (!Config.VectorizeSelect)
691 } else if (isa<CmpInst>(I)) {
692 if (!Config.VectorizeCmp)
694 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
695 if (!Config.VectorizeGEP)
698 // Currently, vector GEPs exist only with one index.
699 if (G->getNumIndices() != 1)
701 } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
702 isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
706 // We can't vectorize memory operations without target data
707 if (TD == 0 && IsSimpleLoadStore)
711 getInstructionTypes(I, T1, T2);
713 // Not every type can be vectorized...
714 if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
715 !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
718 if (T1->getScalarSizeInBits() == 1) {
719 if (!Config.VectorizeBools)
722 if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
726 if (T2->getScalarSizeInBits() == 1) {
727 if (!Config.VectorizeBools)
730 if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
734 if (!Config.VectorizeFloats
735 && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
738 // Don't vectorize target-specific types.
739 if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
741 if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
744 if ((!Config.VectorizePointers || TD == 0) &&
745 (T1->getScalarType()->isPointerTy() ||
746 T2->getScalarType()->isPointerTy()))
749 if (!VTTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
750 T2->getPrimitiveSizeInBits() >= Config.VectorBits))
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,
763 DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
764 " <-> " << *J << "\n");
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)))
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)
783 // FIXME: handle addsub-type operations!
785 if (IsSimpleLoadStore) {
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;
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);
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
806 unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
807 if (BottomAlignment < VecAlignment)
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,
819 if (VCost > ICost + JCost)
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
825 unsigned VParts = VTTI->getNumberOfParts(VType);
828 else if (!VParts && VCost == ICost + JCost)
831 CostSavings = ICost + JCost - VCost;
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);
843 if (VCost > ICost + JCost)
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
849 unsigned VParts = VTTI->getNumberOfParts(VT1);
852 else if (!VParts && VCost == ICost + JCost)
855 CostSavings = ICost + JCost - VCost;
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);
862 if (CI && (FI = CI->getCalledFunction()) &&
863 FI->getIntrinsicID() == Intrinsic::powi) {
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);
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
890 bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
891 AliasSetTracker &WriteSet, Instruction *I,
892 Instruction *J, bool UpdateUsers,
893 std::multimap<Value *, Value *> *LoadMoveSet) {
896 // This instruction may already be marked as a user due, for example, to
897 // being a member of a selected pair.
902 for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
905 if (I == V || Users.count(V)) {
910 if (!UsesI && J->mayReadFromMemory()) {
912 VPIteratorPair JPairRange = LoadMoveSet->equal_range(J);
913 UsesI = isSecondInIteratorPair<Value*>(I, JPairRange);
915 for (AliasSetTracker::iterator W = WriteSet.begin(),
916 WE = WriteSet.end(); W != WE; ++W) {
917 if (W->aliasesUnknownInst(J, *AA)) {
925 if (UsesI && UpdateUsers) {
926 if (J->mayWriteToMemory()) WriteSet.add(J);
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;
943 bool ShouldContinue = false, IAfterStart = false;
944 for (BasicBlock::iterator I = Start++; I != E; ++I) {
945 if (I == Start) IAfterStart = true;
947 bool IsSimpleLoadStore;
948 if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
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;
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.
966 // When using fast dependency analysis,
967 // stop searching after first use:
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.
976 if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
977 CostSavings)) continue;
979 // J is a candidate for merging with I.
980 if (!PairableInsts.size() ||
981 PairableInsts[PairableInsts.size()-1] != I) {
982 PairableInsts.push_back(I);
985 CandidatePairs.insert(ValuePair(I, J));
987 CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
990 // The next call to this function must start after the last instruction
991 // selected during this invocation.
993 Start = llvm::next(J);
994 IAfterStart = JAfterStart = false;
997 DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
998 << *I << " <-> " << *J << " (cost savings: " <<
999 CostSavings << ")\n");
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;
1014 DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
1015 << " instructions with candidate pairs\n");
1017 return ShouldContinue;
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,
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.
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
1045 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
1047 // For each use of the first variable, look for uses of the second
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())
1055 VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
1058 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
1059 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
1062 if (isSecondInIteratorPair<Value*>(*I, JPairRange))
1063 ConnectedPairs.insert(VPPair(P, ValuePair(*J, *I)));
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())
1074 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
1075 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
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))
1086 else if ((SI = dyn_cast<StoreInst>(*I)) &&
1087 P.second == SI->getPointerOperand())
1090 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
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())
1097 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
1098 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
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) {
1111 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1112 PE = PairableInsts.end(); PI != PE; ++PI) {
1113 VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
1115 for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
1116 P != choiceRange.second; ++P)
1117 computePairsConnectedTo(CandidatePairs, PairableInsts,
1118 ConnectedPairs, *P);
1121 DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
1122 << " pair connections.\n");
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(
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);
1140 // Iterate through the basic block, recording all Users of each
1141 // pairable instruction.
1143 BasicBlock::iterator E = BB.end();
1144 for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1145 if (IsInPair.find(I) == IsInPair.end()) continue;
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);
1152 for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1154 PairableInstUsers.insert(ValuePair(I, *U));
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).
1179 VPPIteratorPair QPairRange = PairableInstUserMap->equal_range(Q);
1180 if (!isSecondInIteratorPair(P, QPairRange))
1181 PairableInstUserMap->insert(VPPair(Q, P));
1184 VPPIteratorPair PPairRange = PairableInstUserMap->equal_range(P);
1185 if (!isSecondInIteratorPair(Q, PPairRange))
1186 PairableInstUserMap->insert(VPPair(P, Q));
1190 return (QUsesP && PUsesQ);
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:
1208 ValuePair QTop = Q.pop_back_val();
1209 Visited.insert(QTop);
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) {
1219 << "BBV: rejected to prevent non-trivial cycle formation: "
1220 << *C->first.first << " <-> " << *C->first.second << "\n");
1224 if (CurrentPairs.count(C->second) && !Visited.count(C->second))
1225 Q.push_back(C->second);
1227 } while (!Q.empty());
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)));
1248 ValuePairWithDepth QTop = Q.back();
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) {
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;
1275 MaxChildDepth = std::max(MaxChildDepth, C->second);
1280 if (!MoreChildren) {
1281 // Record the current pair as part of the Tree:
1282 Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1285 } while (!Q.empty());
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)));
1304 ValuePairWithDepth QTop = Q.pop_back_val();
1305 PrunedTree.insert(QTop.first);
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;
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.
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.
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;
1340 for (DenseMap<ValuePair, size_t>::iterator C2
1341 = BestChildren.begin(), E2 = BestChildren.end();
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) {
1354 CurrentPairs.insert(C2->first);
1357 if (!CanAdd) continue;
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)) {
1373 CurrentPairs.insert(*T);
1375 if (!CanAdd) continue;
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)) {
1390 CurrentPairs.insert(C2->first);
1392 if (!CanAdd) continue;
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();
1399 if (pairsConflict(*C2, C->first, PairableInstUsers,
1400 UseCycleCheck ? &PairableInstUserMap : 0)) {
1405 CurrentPairs.insert(*C2);
1407 if (!CanAdd) continue;
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.
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))
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++);
1437 BestChildren.insert(ValuePairWithDepth(C->first, C->second));
1440 for (DenseMap<ValuePair, size_t>::iterator C
1441 = BestChildren.begin(), E2 = BestChildren.end();
1443 size_t DepthF = getDepthFactor(C->first.first);
1444 Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1446 } while (!Q.empty());
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) {
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;
1478 ChosenPairSet.insert(*C);
1480 if (DoesConflict) continue;
1482 if (UseCycleCheck &&
1483 pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1486 DenseMap<ValuePair, size_t> Tree;
1487 buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1488 PairableInstUsers, ChosenPairs, Tree, *J);
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);
1494 DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1495 << *J->first << " <-> " << *J->second << "} of depth " <<
1496 MaxDepth << " and size " << Tree.size() << "\n");
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.
1505 DenseSet<ValuePair> PrunedTree;
1506 pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1507 PairableInstUsers, PairableInstUserMap, ChosenPairs, Tree,
1508 PrunedTree, *J, UseCycleCheck);
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;
1518 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1519 E = PrunedTree.end(); S != E; ++S)
1520 EffSize += (int) getDepthFactor(S->first);
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;
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;
1555 VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
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,
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
1571 DEBUG(if (BestTree.size() > 0)
1572 dbgs() << "BBV: selected pairs in the best tree for: "
1573 << *cast<Instruction>(*I) << "\n");
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");
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++);
1600 DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
1603 std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
1608 return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
1609 (n > 0 ? "." + utostr(n) : "")).str();
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) {
1618 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
1619 int64_t OffsetInElmts;
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,
1627 // The pointer value is taken to be the one with the lowest offset.
1629 if (!FlipMemInputs) {
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);
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);
1652 Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
1654 unsigned mm = m + (int) IdxOffset;
1655 if (m >= (int) NumInElem1)
1656 mm += (int) NumInElem;
1658 Mask[v+MaskOffset] =
1659 ConstantInt::get(Type::getInt32Ty(Context), mm);
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.
1671 Type *ArgTypeI = I->getType();
1672 Type *ArgTypeJ = J->getType();
1673 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
1675 unsigned NumElemI = cast<VectorType>(ArgTypeI)->getNumElements();
1677 // Get the total number of elements in the fused vector type.
1678 // By definition, this must equal the number of elements in
1680 unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
1681 std::vector<Constant*> Mask(NumElem);
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();
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
1696 // For the mask from the first pair...
1697 fillNewShuffleMask(Context, I, 0, NumInElemJ, NumInElemI,
1700 // For the mask from the second pair...
1701 fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
1704 return ConstantVector::get(Mask);
1707 bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
1708 Instruction *J, unsigned o, Value *&LOp,
1710 Type *ArgTypeL, Type *ArgTypeH,
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;
1719 if (!isa<UndefValue>(LIENext->getOperand(0)) &&
1720 !isa<InsertElementInst>(LIENext->getOperand(0))) {
1725 dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
1728 SmallVector<Value *, 8> VectElemts(numElemL,
1729 UndefValue::get(ArgTypeL->getScalarType()));
1730 InsertElementInst *LIENext = LIE;
1733 cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
1734 VectElemts[Idx] = LIENext->getOperand(1);
1736 dyn_cast<InsertElementInst>(LIENext->getOperand(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),
1745 getReplacementName(I, true, o, i+1));
1746 LIENext->insertBefore(J);
1750 LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
1751 ExpandedIEChain = true;
1755 return ExpandedIEChain;
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);
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);
1770 Instruction *L = I, *H = J;
1771 Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
1772 if (FlipMemInputs) {
1775 ArgTypeL = ArgTypeJ;
1776 ArgTypeH = ArgTypeI;
1780 if (ArgTypeL->isVectorTy())
1781 numElemL = cast<VectorType>(ArgTypeL)->getNumElements();
1786 if (ArgTypeH->isVectorTy())
1787 numElemH = cast<VectorType>(ArgTypeH)->getNumElements();
1791 Value *LOp = L->getOperand(o);
1792 Value *HOp = H->getOperand(o);
1793 unsigned numElem = VArgType->getNumElements();
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);
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());
1811 if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
1812 // We can have at most two unique vector inputs.
1813 bool CanUseInputs = true;
1816 I1 = LEE->getOperand(0);
1818 I1 = LSV->getOperand(0);
1819 I2 = LSV->getOperand(1);
1820 if (I2 == I1 || isa<UndefValue>(I2))
1825 Value *I3 = HEE->getOperand(0);
1826 if (!I2 && I3 != I1)
1828 else if (I3 != I1 && I3 != I2)
1829 CanUseInputs = false;
1831 Value *I3 = HSV->getOperand(0);
1832 if (!I2 && I3 != I1)
1834 else if (I3 != I1 && I3 != I2)
1835 CanUseInputs = false;
1838 Value *I4 = HSV->getOperand(1);
1839 if (!isa<UndefValue>(I4)) {
1840 if (!I2 && I4 != I1)
1842 else if (I4 != I1 && I4 != I2)
1843 CanUseInputs = false;
1850 cast<VectorType>(cast<Instruction>(LOp)->getOperand(0)->getType())
1853 cast<VectorType>(cast<Instruction>(HOp)->getOperand(0)->getType())
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) {
1863 cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
1864 INum = LEE->getOperand(0) == I1 ? 0 : 1;
1866 Idx = LSV->getMaskValue(i);
1867 if (Idx < (int) LOpElem) {
1868 INum = LSV->getOperand(0) == I1 ? 0 : 1;
1871 INum = LSV->getOperand(1) == I1 ? 0 : 1;
1875 II[i] = std::pair<int, int>(Idx, INum);
1877 for (unsigned i = 0; i < numElemH; ++i) {
1881 cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
1882 INum = HEE->getOperand(0) == I1 ? 0 : 1;
1884 Idx = HSV->getMaskValue(i);
1885 if (Idx < (int) HOpElem) {
1886 INum = HSV->getOperand(0) == I1 ? 0 : 1;
1889 INum = HSV->getOperand(1) == I1 ? 0 : 1;
1893 II[i + numElemL] = std::pair<int, int>(Idx, INum);
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();
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;
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;
1922 Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
1924 Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
1928 new ShuffleVectorInst(I1, UndefValue::get(I1T),
1929 ConstantVector::get(Mask),
1930 getReplacementName(I, true, o));
1935 VectorType *I2T = cast<VectorType>(I2->getType());
1936 unsigned I2Elem = I2T->getNumElements();
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);
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));
1949 Instruction *NewI1 =
1950 new ShuffleVectorInst(I1, UndefValue::get(I1T),
1951 ConstantVector::get(Mask),
1952 getReplacementName(I, true, o, 1));
1953 NewI1->insertBefore(J);
1957 } else if (I1Elem > I2Elem) {
1958 std::vector<Constant *> Mask(I1Elem);
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));
1965 Instruction *NewI2 =
1966 new ShuffleVectorInst(I2, UndefValue::get(I2T),
1967 ConstantVector::get(Mask),
1968 getReplacementName(I, true, o, 1));
1969 NewI2->insertBefore(J);
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));
1982 int Idx = II[v].first + II[v].second * I1Elem;
1983 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
1987 Instruction *NewOp =
1988 new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
1989 getReplacementName(I, true, o));
1990 NewOp->insertBefore(J);
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.
2003 Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
2004 getReplacementName(I, true, o));
2007 } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
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.
2014 std::vector<Constant *> Mask(numElemH);
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));
2021 NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2022 ConstantVector::get(Mask),
2023 getReplacementName(I, true, o, 1));
2025 NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2026 getReplacementName(I, true, o, 1));
2029 NLOp->insertBefore(J);
2034 } else if (numElemL > numElemH) {
2035 if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2036 ArgTypeH, VArgType)) {
2038 InsertElementInst::Create(LOp, HOp,
2039 ConstantInt::get(Type::getInt32Ty(Context),
2041 getReplacementName(I, true, o));
2044 } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2048 std::vector<Constant *> Mask(numElemL);
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));
2055 NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2056 ConstantVector::get(Mask),
2057 getReplacementName(I, true, o, 1));
2059 NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2060 getReplacementName(I, true, o, 1));
2063 NHOp->insertBefore(J);
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) {
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);
2080 Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2081 ConstantVector::get(Mask),
2082 getReplacementName(I, true, o));
2083 BV->insertBefore(J);
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);
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();
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.
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,
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();
2120 Module *M = BB.getParent()->getParent();
2121 Type *ArgTypeI = I->getType();
2122 Type *ArgTypeJ = J->getType();
2123 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2125 ReplacedOperands[o] = Intrinsic::getDeclaration(M,
2126 (Intrinsic::ID) IID, VArgType);
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);
2135 } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2136 ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2140 ReplacedOperands[o] =
2141 getReplacementInput(Context, I, J, o, FlipMemInputs);
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);
2158 Type *IType = I->getType();
2159 Type *JType = J->getType();
2161 VectorType *VType = getVecTypeForPair(IType, JType);
2162 unsigned numElem = VType->getNumElements();
2164 unsigned numElemI, numElemJ;
2165 if (IType->isVectorTy())
2166 numElemI = cast<VectorType>(IType)->getNumElements();
2170 if (JType->isVectorTy())
2171 numElemJ = cast<VectorType>(JType)->getNumElements();
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);
2182 K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2183 ConstantVector::get(
2184 FlipMemInputs ? Mask2 : Mask1),
2185 getReplacementName(K, false, 1));
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));
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);
2200 K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2201 ConstantVector::get(
2202 FlipMemInputs ? Mask1 : Mask2),
2203 getReplacementName(K, false, 2));
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));
2212 K2->insertAfter(K1);
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));
2224 DenseSet<Value *> Users;
2225 AliasSetTracker WriteSet(*AA);
2226 for (; cast<Instruction>(L) != J; ++L)
2227 (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet);
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);
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));
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;
2251 DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2252 " to after " << *InsertionPt << "\n");
2253 InstToMove->removeFromParent();
2254 InstToMove->insertAfter(InsertionPt);
2255 InsertionPt = InstToMove;
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,
2269 // Skip to the first instruction past I.
2270 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2272 DenseSet<Value *> Users;
2273 AliasSetTracker WriteSet(*AA);
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));
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;
2302 Instruction *I = cast<Instruction>(P->first);
2303 collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet, I);
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
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;
2319 Instruction *I = cast<Instruction>(P->first);
2320 Instruction *J = cast<Instruction>(P->second);
2322 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
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");
2333 Value *LowPI = (OffsetInElmts > 0) ? I : J;
2334 LowPtrInsts.insert(LowPI);
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;
2351 K->setMetadata(Kind, 0); // Remove unknown metadata
2353 case LLVMContext::MD_tbaa:
2354 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2356 case LLVMContext::MD_fpmath:
2357 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
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
2369 void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2370 std::vector<Value *> &PairableInsts,
2371 DenseMap<Value *, Value *> &ChosenPairs) {
2372 LLVMContext& Context = BB.getContext();
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);
2386 std::multimap<Value *, Value *> LoadMoveSet;
2387 collectLoadMoveSet(BB, PairableInsts, ChosenPairs, LoadMoveSet);
2389 DenseSet<Value *> LowPtrInsts;
2390 collectPtrInfo(PairableInsts, ChosenPairs, LowPtrInsts);
2392 DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
2394 for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
2395 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
2396 if (P == ChosenPairs.end()) {
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.
2410 Instruction *I = cast<Instruction>(P->first),
2411 *J = cast<Instruction>(P->second);
2413 DEBUG(dbgs() << "BBV: fusing: " << *I <<
2414 " <-> " << *J << "\n");
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);
2422 if (!canMoveUsesOfIAfterJ(BB, LoadMoveSet, I, J)) {
2423 DEBUG(dbgs() << "BBV: fusion of: " << *I <<
2425 " aborted because of non-trivial dependency cycle\n");
2431 bool FlipMemInputs = false;
2432 if (isa<LoadInst>(I) || isa<StoreInst>(I))
2433 FlipMemInputs = (LowPtrInsts.find(I) == LowPtrInsts.end());
2435 unsigned NumOperands = I->getNumOperands();
2436 SmallVector<Value *, 3> ReplacedOperands(NumOperands);
2437 getReplacementInputsForPair(Context, I, J, ReplacedOperands,
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);
2445 if (!isa<StoreInst>(K))
2446 K->mutateType(getVecTypeForPair(I->getType(), J->getType()));
2448 combineMetadata(K, J);
2450 for (unsigned o = 0; o < NumOperands; ++o)
2451 K->setOperand(o, ReplacedOperands[o]);
2453 // If we've flipped the memory inputs, make sure that we take the correct
2455 if (FlipMemInputs) {
2456 if (isa<StoreInst>(K))
2457 cast<StoreInst>(K)->setAlignment(cast<StoreInst>(J)->getAlignment());
2459 cast<LoadInst>(K)->setAlignment(cast<LoadInst>(J)->getAlignment());
2464 // Instruction insertion point:
2465 Instruction *InsertionPt = K;
2466 Instruction *K1 = 0, *K2 = 0;
2467 replaceOutputsOfPair(Context, I, J, K, InsertionPt, K1, K2,
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.
2475 moveUsesOfIAfterJ(BB, LoadMoveSet, InsertionPt, I, J);
2477 if (!isa<StoreInst>(I)) {
2478 I->replaceAllUsesWith(K1);
2479 J->replaceAllUsesWith(K2);
2480 AA->replaceWithNewValue(I, K1);
2481 AA->replaceWithNewValue(J, K2);
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);
2505 // Before removing I, set the iterator to the next instruction.
2506 PI = llvm::next(BasicBlock::iterator(I));
2507 if (cast<Instruction>(PI) == J)
2512 I->eraseFromParent();
2513 J->eraseFromParent();
2516 DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
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)
2528 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
2529 return new BBVectorize(C);
2533 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
2534 BBVectorize BBVectorizer(P, C);
2535 return BBVectorizer.vectorizeBB(BB);
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;