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"));
103 NoPointers("bb-vectorize-no-pointers", cl::init(false), cl::Hidden,
104 cl::desc("Don't try to vectorize pointer values"));
107 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
108 cl::desc("Don't try to vectorize casting (conversion) operations"));
111 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
112 cl::desc("Don't try to vectorize floating-point math intrinsics"));
115 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
116 cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
119 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
120 cl::desc("Don't try to vectorize select instructions"));
123 NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
124 cl::desc("Don't try to vectorize comparison instructions"));
127 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
128 cl::desc("Don't try to vectorize getelementptr instructions"));
131 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
132 cl::desc("Don't try to vectorize loads and stores"));
135 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
136 cl::desc("Only generate aligned loads and stores"));
139 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
140 cl::init(false), cl::Hidden,
141 cl::desc("Don't boost the chain-depth contribution of loads and stores"));
144 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
145 cl::desc("Use a fast instruction dependency analysis"));
149 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
150 cl::init(false), cl::Hidden,
151 cl::desc("When debugging is enabled, output information on the"
152 " instruction-examination process"));
154 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
155 cl::init(false), cl::Hidden,
156 cl::desc("When debugging is enabled, output information on the"
157 " candidate-selection process"));
159 DebugPairSelection("bb-vectorize-debug-pair-selection",
160 cl::init(false), cl::Hidden,
161 cl::desc("When debugging is enabled, output information on the"
162 " pair-selection process"));
164 DebugCycleCheck("bb-vectorize-debug-cycle-check",
165 cl::init(false), cl::Hidden,
166 cl::desc("When debugging is enabled, output information on the"
167 " cycle-checking process"));
170 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
173 struct BBVectorize : public BasicBlockPass {
174 static char ID; // Pass identification, replacement for typeid
176 const VectorizeConfig Config;
178 BBVectorize(const VectorizeConfig &C = VectorizeConfig())
179 : BasicBlockPass(ID), Config(C) {
180 initializeBBVectorizePass(*PassRegistry::getPassRegistry());
183 BBVectorize(Pass *P, const VectorizeConfig &C)
184 : BasicBlockPass(ID), Config(C) {
185 AA = &P->getAnalysis<AliasAnalysis>();
186 DT = &P->getAnalysis<DominatorTree>();
187 SE = &P->getAnalysis<ScalarEvolution>();
188 TD = P->getAnalysisIfAvailable<DataLayout>();
189 TTI = IgnoreTargetInfo ? 0 :
190 P->getAnalysisIfAvailable<TargetTransformInfo>();
191 VTTI = TTI ? TTI->getVectorTargetTransformInfo() : 0;
194 typedef std::pair<Value *, Value *> ValuePair;
195 typedef std::pair<ValuePair, int> ValuePairWithCost;
196 typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
197 typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
198 typedef std::pair<std::multimap<Value *, Value *>::iterator,
199 std::multimap<Value *, Value *>::iterator> VPIteratorPair;
200 typedef std::pair<std::multimap<ValuePair, ValuePair>::iterator,
201 std::multimap<ValuePair, ValuePair>::iterator>
208 TargetTransformInfo *TTI;
209 const VectorTargetTransformInfo *VTTI;
211 // FIXME: const correct?
213 bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
215 bool getCandidatePairs(BasicBlock &BB,
216 BasicBlock::iterator &Start,
217 std::multimap<Value *, Value *> &CandidatePairs,
218 DenseMap<ValuePair, int> &CandidatePairCostSavings,
219 std::vector<Value *> &PairableInsts, bool NonPow2Len);
221 void computeConnectedPairs(std::multimap<Value *, Value *> &CandidatePairs,
222 std::vector<Value *> &PairableInsts,
223 std::multimap<ValuePair, ValuePair> &ConnectedPairs);
225 void buildDepMap(BasicBlock &BB,
226 std::multimap<Value *, Value *> &CandidatePairs,
227 std::vector<Value *> &PairableInsts,
228 DenseSet<ValuePair> &PairableInstUsers);
230 void choosePairs(std::multimap<Value *, Value *> &CandidatePairs,
231 DenseMap<ValuePair, int> &CandidatePairCostSavings,
232 std::vector<Value *> &PairableInsts,
233 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
234 DenseSet<ValuePair> &PairableInstUsers,
235 DenseMap<Value *, Value *>& ChosenPairs);
237 void fuseChosenPairs(BasicBlock &BB,
238 std::vector<Value *> &PairableInsts,
239 DenseMap<Value *, Value *>& ChosenPairs);
241 bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
243 bool areInstsCompatible(Instruction *I, Instruction *J,
244 bool IsSimpleLoadStore, bool NonPow2Len,
247 bool trackUsesOfI(DenseSet<Value *> &Users,
248 AliasSetTracker &WriteSet, Instruction *I,
249 Instruction *J, bool UpdateUsers = true,
250 std::multimap<Value *, Value *> *LoadMoveSet = 0);
252 void computePairsConnectedTo(
253 std::multimap<Value *, Value *> &CandidatePairs,
254 std::vector<Value *> &PairableInsts,
255 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
258 bool pairsConflict(ValuePair P, ValuePair Q,
259 DenseSet<ValuePair> &PairableInstUsers,
260 std::multimap<ValuePair, ValuePair> *PairableInstUserMap = 0);
262 bool pairWillFormCycle(ValuePair P,
263 std::multimap<ValuePair, ValuePair> &PairableInstUsers,
264 DenseSet<ValuePair> &CurrentPairs);
267 std::multimap<Value *, Value *> &CandidatePairs,
268 std::vector<Value *> &PairableInsts,
269 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
270 DenseSet<ValuePair> &PairableInstUsers,
271 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
272 DenseMap<Value *, Value *> &ChosenPairs,
273 DenseMap<ValuePair, size_t> &Tree,
274 DenseSet<ValuePair> &PrunedTree, ValuePair J,
277 void buildInitialTreeFor(
278 std::multimap<Value *, Value *> &CandidatePairs,
279 std::vector<Value *> &PairableInsts,
280 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
281 DenseSet<ValuePair> &PairableInstUsers,
282 DenseMap<Value *, Value *> &ChosenPairs,
283 DenseMap<ValuePair, size_t> &Tree, ValuePair J);
285 void findBestTreeFor(
286 std::multimap<Value *, Value *> &CandidatePairs,
287 DenseMap<ValuePair, int> &CandidatePairCostSavings,
288 std::vector<Value *> &PairableInsts,
289 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
290 DenseSet<ValuePair> &PairableInstUsers,
291 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
292 DenseMap<Value *, Value *> &ChosenPairs,
293 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
294 int &BestEffSize, VPIteratorPair ChoiceRange,
297 Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
298 Instruction *J, unsigned o, bool FlipMemInputs);
300 void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
301 unsigned MaskOffset, unsigned NumInElem,
302 unsigned NumInElem1, unsigned IdxOffset,
303 std::vector<Constant*> &Mask);
305 Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
308 bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
309 unsigned o, Value *&LOp, unsigned numElemL,
310 Type *ArgTypeL, Type *ArgTypeR,
311 unsigned IdxOff = 0);
313 Value *getReplacementInput(LLVMContext& Context, Instruction *I,
314 Instruction *J, unsigned o, bool FlipMemInputs);
316 void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
317 Instruction *J, SmallVector<Value *, 3> &ReplacedOperands,
320 void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
321 Instruction *J, Instruction *K,
322 Instruction *&InsertionPt, Instruction *&K1,
323 Instruction *&K2, bool FlipMemInputs);
325 void collectPairLoadMoveSet(BasicBlock &BB,
326 DenseMap<Value *, Value *> &ChosenPairs,
327 std::multimap<Value *, Value *> &LoadMoveSet,
330 void collectLoadMoveSet(BasicBlock &BB,
331 std::vector<Value *> &PairableInsts,
332 DenseMap<Value *, Value *> &ChosenPairs,
333 std::multimap<Value *, Value *> &LoadMoveSet);
335 void collectPtrInfo(std::vector<Value *> &PairableInsts,
336 DenseMap<Value *, Value *> &ChosenPairs,
337 DenseSet<Value *> &LowPtrInsts);
339 bool canMoveUsesOfIAfterJ(BasicBlock &BB,
340 std::multimap<Value *, Value *> &LoadMoveSet,
341 Instruction *I, Instruction *J);
343 void moveUsesOfIAfterJ(BasicBlock &BB,
344 std::multimap<Value *, Value *> &LoadMoveSet,
345 Instruction *&InsertionPt,
346 Instruction *I, Instruction *J);
348 void combineMetadata(Instruction *K, const Instruction *J);
350 bool vectorizeBB(BasicBlock &BB) {
351 if (!DT->isReachableFromEntry(&BB)) {
352 DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
353 " in " << BB.getParent()->getName() << "\n");
357 DEBUG(if (VTTI) dbgs() << "BBV: using target information\n");
359 bool changed = false;
360 // Iterate a sufficient number of times to merge types of size 1 bit,
361 // then 2 bits, then 4, etc. up to half of the target vector width of the
362 // target vector register.
365 (VTTI || v <= Config.VectorBits) &&
366 (!Config.MaxIter || n <= Config.MaxIter);
368 DEBUG(dbgs() << "BBV: fusing loop #" << n <<
369 " for " << BB.getName() << " in " <<
370 BB.getParent()->getName() << "...\n");
371 if (vectorizePairs(BB))
377 if (changed && !Pow2LenOnly) {
379 for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
380 DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
381 n << " for " << BB.getName() << " in " <<
382 BB.getParent()->getName() << "...\n");
383 if (!vectorizePairs(BB, true)) break;
387 DEBUG(dbgs() << "BBV: done!\n");
391 virtual bool runOnBasicBlock(BasicBlock &BB) {
392 AA = &getAnalysis<AliasAnalysis>();
393 DT = &getAnalysis<DominatorTree>();
394 SE = &getAnalysis<ScalarEvolution>();
395 TD = getAnalysisIfAvailable<DataLayout>();
396 TTI = IgnoreTargetInfo ? 0 :
397 getAnalysisIfAvailable<TargetTransformInfo>();
398 VTTI = TTI ? TTI->getVectorTargetTransformInfo() : 0;
400 return vectorizeBB(BB);
403 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
404 BasicBlockPass::getAnalysisUsage(AU);
405 AU.addRequired<AliasAnalysis>();
406 AU.addRequired<DominatorTree>();
407 AU.addRequired<ScalarEvolution>();
408 AU.addPreserved<AliasAnalysis>();
409 AU.addPreserved<DominatorTree>();
410 AU.addPreserved<ScalarEvolution>();
411 AU.setPreservesCFG();
414 static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
415 assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
416 "Cannot form vector from incompatible scalar types");
417 Type *STy = ElemTy->getScalarType();
420 if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
421 numElem = VTy->getNumElements();
426 if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
427 numElem += VTy->getNumElements();
432 return VectorType::get(STy, numElem);
435 static inline void getInstructionTypes(Instruction *I,
436 Type *&T1, Type *&T2) {
437 if (isa<StoreInst>(I)) {
438 // For stores, it is the value type, not the pointer type that matters
439 // because the value is what will come from a vector register.
441 Value *IVal = cast<StoreInst>(I)->getValueOperand();
442 T1 = IVal->getType();
448 T2 = cast<CastInst>(I)->getSrcTy();
452 if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
453 T2 = SI->getCondition()->getType();
457 // Returns the weight associated with the provided value. A chain of
458 // candidate pairs has a length given by the sum of the weights of its
459 // members (one weight per pair; the weight of each member of the pair
460 // is assumed to be the same). This length is then compared to the
461 // chain-length threshold to determine if a given chain is significant
462 // enough to be vectorized. The length is also used in comparing
463 // candidate chains where longer chains are considered to be better.
464 // Note: when this function returns 0, the resulting instructions are
465 // not actually fused.
466 inline size_t getDepthFactor(Value *V) {
467 // InsertElement and ExtractElement have a depth factor of zero. This is
468 // for two reasons: First, they cannot be usefully fused. Second, because
469 // the pass generates a lot of these, they can confuse the simple metric
470 // used to compare the trees in the next iteration. Thus, giving them a
471 // weight of zero allows the pass to essentially ignore them in
472 // subsequent iterations when looking for vectorization opportunities
473 // while still tracking dependency chains that flow through those
475 if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
478 // Give a load or store half of the required depth so that load/store
479 // pairs will vectorize.
480 if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
481 return Config.ReqChainDepth/2;
486 // This determines the relative offset of two loads or stores, returning
487 // true if the offset could be determined to be some constant value.
488 // For example, if OffsetInElmts == 1, then J accesses the memory directly
489 // after I; if OffsetInElmts == -1 then I accesses the memory
491 bool getPairPtrInfo(Instruction *I, Instruction *J,
492 Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
493 unsigned &IAddressSpace, unsigned &JAddressSpace,
494 int64_t &OffsetInElmts) {
496 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
497 LoadInst *LJ = cast<LoadInst>(J);
498 IPtr = LI->getPointerOperand();
499 JPtr = LJ->getPointerOperand();
500 IAlignment = LI->getAlignment();
501 JAlignment = LJ->getAlignment();
502 IAddressSpace = LI->getPointerAddressSpace();
503 JAddressSpace = LJ->getPointerAddressSpace();
505 StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
506 IPtr = SI->getPointerOperand();
507 JPtr = SJ->getPointerOperand();
508 IAlignment = SI->getAlignment();
509 JAlignment = SJ->getAlignment();
510 IAddressSpace = SI->getPointerAddressSpace();
511 JAddressSpace = SJ->getPointerAddressSpace();
514 const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
515 const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
517 // If this is a trivial offset, then we'll get something like
518 // 1*sizeof(type). With target data, which we need anyway, this will get
519 // constant folded into a number.
520 const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
521 if (const SCEVConstant *ConstOffSCEV =
522 dyn_cast<SCEVConstant>(OffsetSCEV)) {
523 ConstantInt *IntOff = ConstOffSCEV->getValue();
524 int64_t Offset = IntOff->getSExtValue();
526 Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
527 int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
529 Type *VTy2 = cast<PointerType>(JPtr->getType())->getElementType();
530 if (VTy != VTy2 && Offset < 0) {
531 int64_t VTy2TSS = (int64_t) TD->getTypeStoreSize(VTy2);
532 OffsetInElmts = Offset/VTy2TSS;
533 return (abs64(Offset) % VTy2TSS) == 0;
536 OffsetInElmts = Offset/VTyTSS;
537 return (abs64(Offset) % VTyTSS) == 0;
543 // Returns true if the provided CallInst represents an intrinsic that can
545 bool isVectorizableIntrinsic(CallInst* I) {
546 Function *F = I->getCalledFunction();
547 if (!F) return false;
549 unsigned IID = F->getIntrinsicID();
550 if (!IID) return false;
555 case Intrinsic::sqrt:
556 case Intrinsic::powi:
560 case Intrinsic::log2:
561 case Intrinsic::log10:
563 case Intrinsic::exp2:
565 return Config.VectorizeMath;
567 return Config.VectorizeFMA;
571 // Returns true if J is the second element in some pair referenced by
572 // some multimap pair iterator pair.
573 template <typename V>
574 bool isSecondInIteratorPair(V J, std::pair<
575 typename std::multimap<V, V>::iterator,
576 typename std::multimap<V, V>::iterator> PairRange) {
577 for (typename std::multimap<V, V>::iterator K = PairRange.first;
578 K != PairRange.second; ++K)
579 if (K->second == J) return true;
585 // This function implements one vectorization iteration on the provided
586 // basic block. It returns true if the block is changed.
587 bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
589 BasicBlock::iterator Start = BB.getFirstInsertionPt();
591 std::vector<Value *> AllPairableInsts;
592 DenseMap<Value *, Value *> AllChosenPairs;
595 std::vector<Value *> PairableInsts;
596 std::multimap<Value *, Value *> CandidatePairs;
597 DenseMap<ValuePair, int> CandidatePairCostSavings;
598 ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
599 CandidatePairCostSavings,
600 PairableInsts, NonPow2Len);
601 if (PairableInsts.empty()) continue;
603 // Now we have a map of all of the pairable instructions and we need to
604 // select the best possible pairing. A good pairing is one such that the
605 // users of the pair are also paired. This defines a (directed) forest
606 // over the pairs such that two pairs are connected iff the second pair
609 // Note that it only matters that both members of the second pair use some
610 // element of the first pair (to allow for splatting).
612 std::multimap<ValuePair, ValuePair> ConnectedPairs;
613 computeConnectedPairs(CandidatePairs, PairableInsts, ConnectedPairs);
614 if (ConnectedPairs.empty()) continue;
616 // Build the pairable-instruction dependency map
617 DenseSet<ValuePair> PairableInstUsers;
618 buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
620 // There is now a graph of the connected pairs. For each variable, pick
621 // the pairing with the largest tree meeting the depth requirement on at
622 // least one branch. Then select all pairings that are part of that tree
623 // and remove them from the list of available pairings and pairable
626 DenseMap<Value *, Value *> ChosenPairs;
627 choosePairs(CandidatePairs, CandidatePairCostSavings,
628 PairableInsts, ConnectedPairs,
629 PairableInstUsers, ChosenPairs);
631 if (ChosenPairs.empty()) continue;
632 AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
633 PairableInsts.end());
634 AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
635 } while (ShouldContinue);
637 if (AllChosenPairs.empty()) return false;
638 NumFusedOps += AllChosenPairs.size();
640 // A set of pairs has now been selected. It is now necessary to replace the
641 // paired instructions with vector instructions. For this procedure each
642 // operand must be replaced with a vector operand. This vector is formed
643 // by using build_vector on the old operands. The replaced values are then
644 // replaced with a vector_extract on the result. Subsequent optimization
645 // passes should coalesce the build/extract combinations.
647 fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs);
649 // It is important to cleanup here so that future iterations of this
650 // function have less work to do.
651 (void) SimplifyInstructionsInBlock(&BB, TD, AA->getTargetLibraryInfo());
655 // This function returns true if the provided instruction is capable of being
656 // fused into a vector instruction. This determination is based only on the
657 // type and other attributes of the instruction.
658 bool BBVectorize::isInstVectorizable(Instruction *I,
659 bool &IsSimpleLoadStore) {
660 IsSimpleLoadStore = false;
662 if (CallInst *C = dyn_cast<CallInst>(I)) {
663 if (!isVectorizableIntrinsic(C))
665 } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
666 // Vectorize simple loads if possbile:
667 IsSimpleLoadStore = L->isSimple();
668 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
670 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
671 // Vectorize simple stores if possbile:
672 IsSimpleLoadStore = S->isSimple();
673 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
675 } else if (CastInst *C = dyn_cast<CastInst>(I)) {
676 // We can vectorize casts, but not casts of pointer types, etc.
677 if (!Config.VectorizeCasts)
680 Type *SrcTy = C->getSrcTy();
681 if (!SrcTy->isSingleValueType())
684 Type *DestTy = C->getDestTy();
685 if (!DestTy->isSingleValueType())
687 } else if (isa<SelectInst>(I)) {
688 if (!Config.VectorizeSelect)
690 } else if (isa<CmpInst>(I)) {
691 if (!Config.VectorizeCmp)
693 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
694 if (!Config.VectorizeGEP)
697 // Currently, vector GEPs exist only with one index.
698 if (G->getNumIndices() != 1)
700 } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
701 isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
705 // We can't vectorize memory operations without target data
706 if (TD == 0 && IsSimpleLoadStore)
710 getInstructionTypes(I, T1, T2);
712 // Not every type can be vectorized...
713 if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
714 !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
717 if (T1->getScalarSizeInBits() == 1) {
718 if (!Config.VectorizeBools)
721 if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
725 if (T2->getScalarSizeInBits() == 1) {
726 if (!Config.VectorizeBools)
729 if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
733 if (!Config.VectorizeFloats
734 && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
737 // Don't vectorize target-specific types.
738 if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
740 if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
743 if ((!Config.VectorizePointers || TD == 0) &&
744 (T1->getScalarType()->isPointerTy() ||
745 T2->getScalarType()->isPointerTy()))
748 if (!VTTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
749 T2->getPrimitiveSizeInBits() >= Config.VectorBits))
755 // This function returns true if the two provided instructions are compatible
756 // (meaning that they can be fused into a vector instruction). This assumes
757 // that I has already been determined to be vectorizable and that J is not
758 // in the use tree of I.
759 bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
760 bool IsSimpleLoadStore, bool NonPow2Len,
762 DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
763 " <-> " << *J << "\n");
767 // Loads and stores can be merged if they have different alignments,
768 // but are otherwise the same.
769 if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
770 (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
773 Type *IT1, *IT2, *JT1, *JT2;
774 getInstructionTypes(I, IT1, IT2);
775 getInstructionTypes(J, JT1, JT2);
776 unsigned MaxTypeBits = std::max(
777 IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
778 IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
779 if (!VTTI && MaxTypeBits > Config.VectorBits)
782 // FIXME: handle addsub-type operations!
784 if (IsSimpleLoadStore) {
786 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
787 int64_t OffsetInElmts = 0;
788 if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
789 IAddressSpace, JAddressSpace,
790 OffsetInElmts) && abs64(OffsetInElmts) == 1) {
791 unsigned BottomAlignment = IAlignment;
792 if (OffsetInElmts < 0) BottomAlignment = JAlignment;
794 Type *aTypeI = isa<StoreInst>(I) ?
795 cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
796 Type *aTypeJ = isa<StoreInst>(J) ?
797 cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
798 Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
800 if (Config.AlignedOnly) {
801 // An aligned load or store is possible only if the instruction
802 // with the lower offset has an alignment suitable for the
805 unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
806 if (BottomAlignment < VecAlignment)
811 unsigned ICost = VTTI->getMemoryOpCost(I->getOpcode(), I->getType(),
812 IAlignment, IAddressSpace);
813 unsigned JCost = VTTI->getMemoryOpCost(J->getOpcode(), J->getType(),
814 JAlignment, JAddressSpace);
815 unsigned VCost = VTTI->getMemoryOpCost(I->getOpcode(), VType,
818 if (VCost > ICost + JCost)
820 CostSavings = ICost + JCost - VCost;
826 unsigned ICost = VTTI->getInstrCost(I->getOpcode(), IT1, IT2);
827 unsigned JCost = VTTI->getInstrCost(J->getOpcode(), JT1, JT2);
828 Type *VT1 = getVecTypeForPair(IT1, JT1),
829 *VT2 = getVecTypeForPair(IT2, JT2);
830 unsigned VCost = VTTI->getInstrCost(I->getOpcode(), VT1, VT2);
832 if (VCost > ICost + JCost)
834 CostSavings = ICost + JCost - VCost;
837 // The powi intrinsic is special because only the first argument is
838 // vectorized, the second arguments must be equal.
839 CallInst *CI = dyn_cast<CallInst>(I);
841 if (CI && (FI = CI->getCalledFunction()) &&
842 FI->getIntrinsicID() == Intrinsic::powi) {
844 Value *A1I = CI->getArgOperand(1),
845 *A1J = cast<CallInst>(J)->getArgOperand(1);
846 const SCEV *A1ISCEV = SE->getSCEV(A1I),
847 *A1JSCEV = SE->getSCEV(A1J);
848 return (A1ISCEV == A1JSCEV);
854 // Figure out whether or not J uses I and update the users and write-set
855 // structures associated with I. Specifically, Users represents the set of
856 // instructions that depend on I. WriteSet represents the set
857 // of memory locations that are dependent on I. If UpdateUsers is true,
858 // and J uses I, then Users is updated to contain J and WriteSet is updated
859 // to contain any memory locations to which J writes. The function returns
860 // true if J uses I. By default, alias analysis is used to determine
861 // whether J reads from memory that overlaps with a location in WriteSet.
862 // If LoadMoveSet is not null, then it is a previously-computed multimap
863 // where the key is the memory-based user instruction and the value is
864 // the instruction to be compared with I. So, if LoadMoveSet is provided,
865 // then the alias analysis is not used. This is necessary because this
866 // function is called during the process of moving instructions during
867 // vectorization and the results of the alias analysis are not stable during
869 bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
870 AliasSetTracker &WriteSet, Instruction *I,
871 Instruction *J, bool UpdateUsers,
872 std::multimap<Value *, Value *> *LoadMoveSet) {
875 // This instruction may already be marked as a user due, for example, to
876 // being a member of a selected pair.
881 for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
884 if (I == V || Users.count(V)) {
889 if (!UsesI && J->mayReadFromMemory()) {
891 VPIteratorPair JPairRange = LoadMoveSet->equal_range(J);
892 UsesI = isSecondInIteratorPair<Value*>(I, JPairRange);
894 for (AliasSetTracker::iterator W = WriteSet.begin(),
895 WE = WriteSet.end(); W != WE; ++W) {
896 if (W->aliasesUnknownInst(J, *AA)) {
904 if (UsesI && UpdateUsers) {
905 if (J->mayWriteToMemory()) WriteSet.add(J);
912 // This function iterates over all instruction pairs in the provided
913 // basic block and collects all candidate pairs for vectorization.
914 bool BBVectorize::getCandidatePairs(BasicBlock &BB,
915 BasicBlock::iterator &Start,
916 std::multimap<Value *, Value *> &CandidatePairs,
917 DenseMap<ValuePair, int> &CandidatePairCostSavings,
918 std::vector<Value *> &PairableInsts, bool NonPow2Len) {
919 BasicBlock::iterator E = BB.end();
920 if (Start == E) return false;
922 bool ShouldContinue = false, IAfterStart = false;
923 for (BasicBlock::iterator I = Start++; I != E; ++I) {
924 if (I == Start) IAfterStart = true;
926 bool IsSimpleLoadStore;
927 if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
929 // Look for an instruction with which to pair instruction *I...
930 DenseSet<Value *> Users;
931 AliasSetTracker WriteSet(*AA);
932 bool JAfterStart = IAfterStart;
933 BasicBlock::iterator J = llvm::next(I);
934 for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
935 if (J == Start) JAfterStart = true;
937 // Determine if J uses I, if so, exit the loop.
938 bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
939 if (Config.FastDep) {
940 // Note: For this heuristic to be effective, independent operations
941 // must tend to be intermixed. This is likely to be true from some
942 // kinds of grouped loop unrolling (but not the generic LLVM pass),
943 // but otherwise may require some kind of reordering pass.
945 // When using fast dependency analysis,
946 // stop searching after first use:
952 // J does not use I, and comes before the first use of I, so it can be
953 // merged with I if the instructions are compatible.
955 if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
956 CostSavings)) continue;
958 // J is a candidate for merging with I.
959 if (!PairableInsts.size() ||
960 PairableInsts[PairableInsts.size()-1] != I) {
961 PairableInsts.push_back(I);
964 CandidatePairs.insert(ValuePair(I, J));
966 CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
969 // The next call to this function must start after the last instruction
970 // selected during this invocation.
972 Start = llvm::next(J);
973 IAfterStart = JAfterStart = false;
976 DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
977 << *I << " <-> " << *J << " (cost savings: " <<
978 CostSavings << ")\n");
980 // If we have already found too many pairs, break here and this function
981 // will be called again starting after the last instruction selected
982 // during this invocation.
983 if (PairableInsts.size() >= Config.MaxInsts) {
984 ShouldContinue = true;
993 DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
994 << " instructions with candidate pairs\n");
996 return ShouldContinue;
999 // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
1000 // it looks for pairs such that both members have an input which is an
1001 // output of PI or PJ.
1002 void BBVectorize::computePairsConnectedTo(
1003 std::multimap<Value *, Value *> &CandidatePairs,
1004 std::vector<Value *> &PairableInsts,
1005 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1009 // For each possible pairing for this variable, look at the uses of
1010 // the first value...
1011 for (Value::use_iterator I = P.first->use_begin(),
1012 E = P.first->use_end(); I != E; ++I) {
1013 if (isa<LoadInst>(*I)) {
1014 // A pair cannot be connected to a load because the load only takes one
1015 // operand (the address) and it is a scalar even after vectorization.
1017 } else if ((SI = dyn_cast<StoreInst>(*I)) &&
1018 P.first == SI->getPointerOperand()) {
1019 // Similarly, a pair cannot be connected to a store through its
1024 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
1026 // For each use of the first variable, look for uses of the second
1028 for (Value::use_iterator J = P.second->use_begin(),
1029 E2 = P.second->use_end(); J != E2; ++J) {
1030 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1031 P.second == SJ->getPointerOperand())
1034 VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
1037 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
1038 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
1041 if (isSecondInIteratorPair<Value*>(*I, JPairRange))
1042 ConnectedPairs.insert(VPPair(P, ValuePair(*J, *I)));
1045 if (Config.SplatBreaksChain) continue;
1046 // Look for cases where just the first value in the pair is used by
1047 // both members of another pair (splatting).
1048 for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
1049 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1050 P.first == SJ->getPointerOperand())
1053 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
1054 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
1058 if (Config.SplatBreaksChain) return;
1059 // Look for cases where just the second value in the pair is used by
1060 // both members of another pair (splatting).
1061 for (Value::use_iterator I = P.second->use_begin(),
1062 E = P.second->use_end(); I != E; ++I) {
1063 if (isa<LoadInst>(*I))
1065 else if ((SI = dyn_cast<StoreInst>(*I)) &&
1066 P.second == SI->getPointerOperand())
1069 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
1071 for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
1072 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1073 P.second == SJ->getPointerOperand())
1076 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
1077 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
1082 // This function figures out which pairs are connected. Two pairs are
1083 // connected if some output of the first pair forms an input to both members
1084 // of the second pair.
1085 void BBVectorize::computeConnectedPairs(
1086 std::multimap<Value *, Value *> &CandidatePairs,
1087 std::vector<Value *> &PairableInsts,
1088 std::multimap<ValuePair, ValuePair> &ConnectedPairs) {
1090 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1091 PE = PairableInsts.end(); PI != PE; ++PI) {
1092 VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
1094 for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
1095 P != choiceRange.second; ++P)
1096 computePairsConnectedTo(CandidatePairs, PairableInsts,
1097 ConnectedPairs, *P);
1100 DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
1101 << " pair connections.\n");
1104 // This function builds a set of use tuples such that <A, B> is in the set
1105 // if B is in the use tree of A. If B is in the use tree of A, then B
1106 // depends on the output of A.
1107 void BBVectorize::buildDepMap(
1109 std::multimap<Value *, Value *> &CandidatePairs,
1110 std::vector<Value *> &PairableInsts,
1111 DenseSet<ValuePair> &PairableInstUsers) {
1112 DenseSet<Value *> IsInPair;
1113 for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
1114 E = CandidatePairs.end(); C != E; ++C) {
1115 IsInPair.insert(C->first);
1116 IsInPair.insert(C->second);
1119 // Iterate through the basic block, recording all Users of each
1120 // pairable instruction.
1122 BasicBlock::iterator E = BB.end();
1123 for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1124 if (IsInPair.find(I) == IsInPair.end()) continue;
1126 DenseSet<Value *> Users;
1127 AliasSetTracker WriteSet(*AA);
1128 for (BasicBlock::iterator J = llvm::next(I); J != E; ++J)
1129 (void) trackUsesOfI(Users, WriteSet, I, J);
1131 for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1133 PairableInstUsers.insert(ValuePair(I, *U));
1137 // Returns true if an input to pair P is an output of pair Q and also an
1138 // input of pair Q is an output of pair P. If this is the case, then these
1139 // two pairs cannot be simultaneously fused.
1140 bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1141 DenseSet<ValuePair> &PairableInstUsers,
1142 std::multimap<ValuePair, ValuePair> *PairableInstUserMap) {
1143 // Two pairs are in conflict if they are mutual Users of eachother.
1144 bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
1145 PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
1146 PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
1147 PairableInstUsers.count(ValuePair(P.second, Q.second));
1148 bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
1149 PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
1150 PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
1151 PairableInstUsers.count(ValuePair(Q.second, P.second));
1152 if (PairableInstUserMap) {
1153 // FIXME: The expensive part of the cycle check is not so much the cycle
1154 // check itself but this edge insertion procedure. This needs some
1155 // profiling and probably a different data structure (same is true of
1156 // most uses of std::multimap).
1158 VPPIteratorPair QPairRange = PairableInstUserMap->equal_range(Q);
1159 if (!isSecondInIteratorPair(P, QPairRange))
1160 PairableInstUserMap->insert(VPPair(Q, P));
1163 VPPIteratorPair PPairRange = PairableInstUserMap->equal_range(P);
1164 if (!isSecondInIteratorPair(Q, PPairRange))
1165 PairableInstUserMap->insert(VPPair(P, Q));
1169 return (QUsesP && PUsesQ);
1172 // This function walks the use graph of current pairs to see if, starting
1173 // from P, the walk returns to P.
1174 bool BBVectorize::pairWillFormCycle(ValuePair P,
1175 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1176 DenseSet<ValuePair> &CurrentPairs) {
1177 DEBUG(if (DebugCycleCheck)
1178 dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1179 << *P.second << "\n");
1180 // A lookup table of visisted pairs is kept because the PairableInstUserMap
1181 // contains non-direct associations.
1182 DenseSet<ValuePair> Visited;
1183 SmallVector<ValuePair, 32> Q;
1184 // General depth-first post-order traversal:
1187 ValuePair QTop = Q.pop_back_val();
1188 Visited.insert(QTop);
1190 DEBUG(if (DebugCycleCheck)
1191 dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1192 << *QTop.second << "\n");
1193 VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
1194 for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
1195 C != QPairRange.second; ++C) {
1196 if (C->second == P) {
1198 << "BBV: rejected to prevent non-trivial cycle formation: "
1199 << *C->first.first << " <-> " << *C->first.second << "\n");
1203 if (CurrentPairs.count(C->second) && !Visited.count(C->second))
1204 Q.push_back(C->second);
1206 } while (!Q.empty());
1211 // This function builds the initial tree of connected pairs with the
1212 // pair J at the root.
1213 void BBVectorize::buildInitialTreeFor(
1214 std::multimap<Value *, Value *> &CandidatePairs,
1215 std::vector<Value *> &PairableInsts,
1216 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1217 DenseSet<ValuePair> &PairableInstUsers,
1218 DenseMap<Value *, Value *> &ChosenPairs,
1219 DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
1220 // Each of these pairs is viewed as the root node of a Tree. The Tree
1221 // is then walked (depth-first). As this happens, we keep track of
1222 // the pairs that compose the Tree and the maximum depth of the Tree.
1223 SmallVector<ValuePairWithDepth, 32> Q;
1224 // General depth-first post-order traversal:
1225 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1227 ValuePairWithDepth QTop = Q.back();
1229 // Push each child onto the queue:
1230 bool MoreChildren = false;
1231 size_t MaxChildDepth = QTop.second;
1232 VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
1233 for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
1234 k != qtRange.second; ++k) {
1235 // Make sure that this child pair is still a candidate:
1236 bool IsStillCand = false;
1237 VPIteratorPair checkRange =
1238 CandidatePairs.equal_range(k->second.first);
1239 for (std::multimap<Value *, Value *>::iterator m = checkRange.first;
1240 m != checkRange.second; ++m) {
1241 if (m->second == k->second.second) {
1248 DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
1249 if (C == Tree.end()) {
1250 size_t d = getDepthFactor(k->second.first);
1251 Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
1252 MoreChildren = true;
1254 MaxChildDepth = std::max(MaxChildDepth, C->second);
1259 if (!MoreChildren) {
1260 // Record the current pair as part of the Tree:
1261 Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1264 } while (!Q.empty());
1267 // Given some initial tree, prune it by removing conflicting pairs (pairs
1268 // that cannot be simultaneously chosen for vectorization).
1269 void BBVectorize::pruneTreeFor(
1270 std::multimap<Value *, Value *> &CandidatePairs,
1271 std::vector<Value *> &PairableInsts,
1272 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1273 DenseSet<ValuePair> &PairableInstUsers,
1274 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1275 DenseMap<Value *, Value *> &ChosenPairs,
1276 DenseMap<ValuePair, size_t> &Tree,
1277 DenseSet<ValuePair> &PrunedTree, ValuePair J,
1278 bool UseCycleCheck) {
1279 SmallVector<ValuePairWithDepth, 32> Q;
1280 // General depth-first post-order traversal:
1281 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1283 ValuePairWithDepth QTop = Q.pop_back_val();
1284 PrunedTree.insert(QTop.first);
1286 // Visit each child, pruning as necessary...
1287 DenseMap<ValuePair, size_t> BestChildren;
1288 VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
1289 for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
1290 K != QTopRange.second; ++K) {
1291 DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
1292 if (C == Tree.end()) continue;
1294 // This child is in the Tree, now we need to make sure it is the
1295 // best of any conflicting children. There could be multiple
1296 // conflicting children, so first, determine if we're keeping
1297 // this child, then delete conflicting children as necessary.
1299 // It is also necessary to guard against pairing-induced
1300 // dependencies. Consider instructions a .. x .. y .. b
1301 // such that (a,b) are to be fused and (x,y) are to be fused
1302 // but a is an input to x and b is an output from y. This
1303 // means that y cannot be moved after b but x must be moved
1304 // after b for (a,b) to be fused. In other words, after
1305 // fusing (a,b) we have y .. a/b .. x where y is an input
1306 // to a/b and x is an output to a/b: x and y can no longer
1307 // be legally fused. To prevent this condition, we must
1308 // make sure that a child pair added to the Tree is not
1309 // both an input and output of an already-selected pair.
1311 // Pairing-induced dependencies can also form from more complicated
1312 // cycles. The pair vs. pair conflicts are easy to check, and so
1313 // that is done explicitly for "fast rejection", and because for
1314 // child vs. child conflicts, we may prefer to keep the current
1315 // pair in preference to the already-selected child.
1316 DenseSet<ValuePair> CurrentPairs;
1319 for (DenseMap<ValuePair, size_t>::iterator C2
1320 = BestChildren.begin(), E2 = BestChildren.end();
1322 if (C2->first.first == C->first.first ||
1323 C2->first.first == C->first.second ||
1324 C2->first.second == C->first.first ||
1325 C2->first.second == C->first.second ||
1326 pairsConflict(C2->first, C->first, PairableInstUsers,
1327 UseCycleCheck ? &PairableInstUserMap : 0)) {
1328 if (C2->second >= C->second) {
1333 CurrentPairs.insert(C2->first);
1336 if (!CanAdd) continue;
1338 // Even worse, this child could conflict with another node already
1339 // selected for the Tree. If that is the case, ignore this child.
1340 for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1341 E2 = PrunedTree.end(); T != E2; ++T) {
1342 if (T->first == C->first.first ||
1343 T->first == C->first.second ||
1344 T->second == C->first.first ||
1345 T->second == C->first.second ||
1346 pairsConflict(*T, C->first, PairableInstUsers,
1347 UseCycleCheck ? &PairableInstUserMap : 0)) {
1352 CurrentPairs.insert(*T);
1354 if (!CanAdd) continue;
1356 // And check the queue too...
1357 for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1358 E2 = Q.end(); C2 != E2; ++C2) {
1359 if (C2->first.first == C->first.first ||
1360 C2->first.first == C->first.second ||
1361 C2->first.second == C->first.first ||
1362 C2->first.second == C->first.second ||
1363 pairsConflict(C2->first, C->first, PairableInstUsers,
1364 UseCycleCheck ? &PairableInstUserMap : 0)) {
1369 CurrentPairs.insert(C2->first);
1371 if (!CanAdd) continue;
1373 // Last but not least, check for a conflict with any of the
1374 // already-chosen pairs.
1375 for (DenseMap<Value *, Value *>::iterator C2 =
1376 ChosenPairs.begin(), E2 = ChosenPairs.end();
1378 if (pairsConflict(*C2, C->first, PairableInstUsers,
1379 UseCycleCheck ? &PairableInstUserMap : 0)) {
1384 CurrentPairs.insert(*C2);
1386 if (!CanAdd) continue;
1388 // To check for non-trivial cycles formed by the addition of the
1389 // current pair we've formed a list of all relevant pairs, now use a
1390 // graph walk to check for a cycle. We start from the current pair and
1391 // walk the use tree to see if we again reach the current pair. If we
1392 // do, then the current pair is rejected.
1394 // FIXME: It may be more efficient to use a topological-ordering
1395 // algorithm to improve the cycle check. This should be investigated.
1396 if (UseCycleCheck &&
1397 pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1400 // This child can be added, but we may have chosen it in preference
1401 // to an already-selected child. Check for this here, and if a
1402 // conflict is found, then remove the previously-selected child
1403 // before adding this one in its place.
1404 for (DenseMap<ValuePair, size_t>::iterator C2
1405 = BestChildren.begin(); C2 != BestChildren.end();) {
1406 if (C2->first.first == C->first.first ||
1407 C2->first.first == C->first.second ||
1408 C2->first.second == C->first.first ||
1409 C2->first.second == C->first.second ||
1410 pairsConflict(C2->first, C->first, PairableInstUsers))
1411 BestChildren.erase(C2++);
1416 BestChildren.insert(ValuePairWithDepth(C->first, C->second));
1419 for (DenseMap<ValuePair, size_t>::iterator C
1420 = BestChildren.begin(), E2 = BestChildren.end();
1422 size_t DepthF = getDepthFactor(C->first.first);
1423 Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1425 } while (!Q.empty());
1428 // This function finds the best tree of mututally-compatible connected
1429 // pairs, given the choice of root pairs as an iterator range.
1430 void BBVectorize::findBestTreeFor(
1431 std::multimap<Value *, Value *> &CandidatePairs,
1432 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1433 std::vector<Value *> &PairableInsts,
1434 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1435 DenseSet<ValuePair> &PairableInstUsers,
1436 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1437 DenseMap<Value *, Value *> &ChosenPairs,
1438 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1439 int &BestEffSize, VPIteratorPair ChoiceRange,
1440 bool UseCycleCheck) {
1441 for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
1442 J != ChoiceRange.second; ++J) {
1444 // Before going any further, make sure that this pair does not
1445 // conflict with any already-selected pairs (see comment below
1446 // near the Tree pruning for more details).
1447 DenseSet<ValuePair> ChosenPairSet;
1448 bool DoesConflict = false;
1449 for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1450 E = ChosenPairs.end(); C != E; ++C) {
1451 if (pairsConflict(*C, *J, PairableInstUsers,
1452 UseCycleCheck ? &PairableInstUserMap : 0)) {
1453 DoesConflict = true;
1457 ChosenPairSet.insert(*C);
1459 if (DoesConflict) continue;
1461 if (UseCycleCheck &&
1462 pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1465 DenseMap<ValuePair, size_t> Tree;
1466 buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1467 PairableInstUsers, ChosenPairs, Tree, *J);
1469 // Because we'll keep the child with the largest depth, the largest
1470 // depth is still the same in the unpruned Tree.
1471 size_t MaxDepth = Tree.lookup(*J);
1473 DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1474 << *J->first << " <-> " << *J->second << "} of depth " <<
1475 MaxDepth << " and size " << Tree.size() << "\n");
1477 // At this point the Tree has been constructed, but, may contain
1478 // contradictory children (meaning that different children of
1479 // some tree node may be attempting to fuse the same instruction).
1480 // So now we walk the tree again, in the case of a conflict,
1481 // keep only the child with the largest depth. To break a tie,
1482 // favor the first child.
1484 DenseSet<ValuePair> PrunedTree;
1485 pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1486 PairableInstUsers, PairableInstUserMap, ChosenPairs, Tree,
1487 PrunedTree, *J, UseCycleCheck);
1491 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1492 E = PrunedTree.end(); S != E; ++S) {
1493 if (getDepthFactor(S->first))
1494 EffSize += CandidatePairCostSavings.find(*S)->second;
1497 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1498 E = PrunedTree.end(); S != E; ++S)
1499 EffSize += (int) getDepthFactor(S->first);
1502 DEBUG(if (DebugPairSelection)
1503 dbgs() << "BBV: found pruned Tree for pair {"
1504 << *J->first << " <-> " << *J->second << "} of depth " <<
1505 MaxDepth << " and size " << PrunedTree.size() <<
1506 " (effective size: " << EffSize << ")\n");
1507 if (MaxDepth >= Config.ReqChainDepth &&
1508 EffSize > 0 && EffSize > BestEffSize) {
1509 BestMaxDepth = MaxDepth;
1510 BestEffSize = EffSize;
1511 BestTree = PrunedTree;
1516 // Given the list of candidate pairs, this function selects those
1517 // that will be fused into vector instructions.
1518 void BBVectorize::choosePairs(
1519 std::multimap<Value *, Value *> &CandidatePairs,
1520 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1521 std::vector<Value *> &PairableInsts,
1522 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1523 DenseSet<ValuePair> &PairableInstUsers,
1524 DenseMap<Value *, Value *>& ChosenPairs) {
1525 bool UseCycleCheck =
1526 CandidatePairs.size() <= Config.MaxCandPairsForCycleCheck;
1527 std::multimap<ValuePair, ValuePair> PairableInstUserMap;
1528 for (std::vector<Value *>::iterator I = PairableInsts.begin(),
1529 E = PairableInsts.end(); I != E; ++I) {
1530 // The number of possible pairings for this variable:
1531 size_t NumChoices = CandidatePairs.count(*I);
1532 if (!NumChoices) continue;
1534 VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
1536 // The best pair to choose and its tree:
1537 size_t BestMaxDepth = 0;
1538 int BestEffSize = 0;
1539 DenseSet<ValuePair> BestTree;
1540 findBestTreeFor(CandidatePairs, CandidatePairCostSavings,
1541 PairableInsts, ConnectedPairs,
1542 PairableInstUsers, PairableInstUserMap, ChosenPairs,
1543 BestTree, BestMaxDepth, BestEffSize, ChoiceRange,
1546 // A tree has been chosen (or not) at this point. If no tree was
1547 // chosen, then this instruction, I, cannot be paired (and is no longer
1550 DEBUG(if (BestTree.size() > 0)
1551 dbgs() << "BBV: selected pairs in the best tree for: "
1552 << *cast<Instruction>(*I) << "\n");
1554 for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
1555 SE2 = BestTree.end(); S != SE2; ++S) {
1556 // Insert the members of this tree into the list of chosen pairs.
1557 ChosenPairs.insert(ValuePair(S->first, S->second));
1558 DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
1559 *S->second << "\n");
1561 // Remove all candidate pairs that have values in the chosen tree.
1562 for (std::multimap<Value *, Value *>::iterator K =
1563 CandidatePairs.begin(); K != CandidatePairs.end();) {
1564 if (K->first == S->first || K->second == S->first ||
1565 K->second == S->second || K->first == S->second) {
1566 // Don't remove the actual pair chosen so that it can be used
1567 // in subsequent tree selections.
1568 if (!(K->first == S->first && K->second == S->second))
1569 CandidatePairs.erase(K++);
1579 DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
1582 std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
1587 return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
1588 (n > 0 ? "." + utostr(n) : "")).str();
1591 // Returns the value that is to be used as the pointer input to the vector
1592 // instruction that fuses I with J.
1593 Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
1594 Instruction *I, Instruction *J, unsigned o,
1595 bool FlipMemInputs) {
1597 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
1598 int64_t OffsetInElmts;
1600 // Note: the analysis might fail here, that is why FlipMemInputs has
1601 // been precomputed (OffsetInElmts must be unused here).
1602 (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
1603 IAddressSpace, JAddressSpace,
1606 // The pointer value is taken to be the one with the lowest offset.
1608 if (!FlipMemInputs) {
1614 Type *ArgTypeI = cast<PointerType>(IPtr->getType())->getElementType();
1615 Type *ArgTypeJ = cast<PointerType>(JPtr->getType())->getElementType();
1616 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
1617 Type *VArgPtrType = PointerType::get(VArgType,
1618 cast<PointerType>(IPtr->getType())->getAddressSpace());
1619 return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
1620 /* insert before */ FlipMemInputs ? J : I);
1623 void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
1624 unsigned MaskOffset, unsigned NumInElem,
1625 unsigned NumInElem1, unsigned IdxOffset,
1626 std::vector<Constant*> &Mask) {
1627 unsigned NumElem1 = cast<VectorType>(J->getType())->getNumElements();
1628 for (unsigned v = 0; v < NumElem1; ++v) {
1629 int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
1631 Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
1633 unsigned mm = m + (int) IdxOffset;
1634 if (m >= (int) NumInElem1)
1635 mm += (int) NumInElem;
1637 Mask[v+MaskOffset] =
1638 ConstantInt::get(Type::getInt32Ty(Context), mm);
1643 // Returns the value that is to be used as the vector-shuffle mask to the
1644 // vector instruction that fuses I with J.
1645 Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
1646 Instruction *I, Instruction *J) {
1647 // This is the shuffle mask. We need to append the second
1648 // mask to the first, and the numbers need to be adjusted.
1650 Type *ArgTypeI = I->getType();
1651 Type *ArgTypeJ = J->getType();
1652 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
1654 unsigned NumElemI = cast<VectorType>(ArgTypeI)->getNumElements();
1656 // Get the total number of elements in the fused vector type.
1657 // By definition, this must equal the number of elements in
1659 unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
1660 std::vector<Constant*> Mask(NumElem);
1662 Type *OpTypeI = I->getOperand(0)->getType();
1663 unsigned NumInElemI = cast<VectorType>(OpTypeI)->getNumElements();
1664 Type *OpTypeJ = J->getOperand(0)->getType();
1665 unsigned NumInElemJ = cast<VectorType>(OpTypeJ)->getNumElements();
1667 // The fused vector will be:
1668 // -----------------------------------------------------
1669 // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
1670 // -----------------------------------------------------
1671 // from which we'll extract NumElem total elements (where the first NumElemI
1672 // of them come from the mask in I and the remainder come from the mask
1675 // For the mask from the first pair...
1676 fillNewShuffleMask(Context, I, 0, NumInElemJ, NumInElemI,
1679 // For the mask from the second pair...
1680 fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
1683 return ConstantVector::get(Mask);
1686 bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
1687 Instruction *J, unsigned o, Value *&LOp,
1689 Type *ArgTypeL, Type *ArgTypeH,
1691 bool ExpandedIEChain = false;
1692 if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
1693 // If we have a pure insertelement chain, then this can be rewritten
1694 // into a chain that directly builds the larger type.
1695 bool PureChain = true;
1696 InsertElementInst *LIENext = LIE;
1698 if (!isa<UndefValue>(LIENext->getOperand(0)) &&
1699 !isa<InsertElementInst>(LIENext->getOperand(0))) {
1704 dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
1707 SmallVector<Value *, 8> VectElemts(numElemL,
1708 UndefValue::get(ArgTypeL->getScalarType()));
1709 InsertElementInst *LIENext = LIE;
1712 cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
1713 VectElemts[Idx] = LIENext->getOperand(1);
1715 dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
1718 Value *LIEPrev = UndefValue::get(ArgTypeH);
1719 for (unsigned i = 0; i < numElemL; ++i) {
1720 if (isa<UndefValue>(VectElemts[i])) continue;
1721 LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
1722 ConstantInt::get(Type::getInt32Ty(Context),
1724 getReplacementName(I, true, o, i+1));
1725 LIENext->insertBefore(J);
1729 LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
1730 ExpandedIEChain = true;
1734 return ExpandedIEChain;
1737 // Returns the value to be used as the specified operand of the vector
1738 // instruction that fuses I with J.
1739 Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
1740 Instruction *J, unsigned o, bool FlipMemInputs) {
1741 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1742 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1744 // Compute the fused vector type for this operand
1745 Type *ArgTypeI = I->getOperand(o)->getType();
1746 Type *ArgTypeJ = J->getOperand(o)->getType();
1747 VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
1749 Instruction *L = I, *H = J;
1750 Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
1751 if (FlipMemInputs) {
1754 ArgTypeL = ArgTypeJ;
1755 ArgTypeH = ArgTypeI;
1759 if (ArgTypeL->isVectorTy())
1760 numElemL = cast<VectorType>(ArgTypeL)->getNumElements();
1765 if (ArgTypeH->isVectorTy())
1766 numElemH = cast<VectorType>(ArgTypeH)->getNumElements();
1770 Value *LOp = L->getOperand(o);
1771 Value *HOp = H->getOperand(o);
1772 unsigned numElem = VArgType->getNumElements();
1774 // First, we check if we can reuse the "original" vector outputs (if these
1775 // exist). We might need a shuffle.
1776 ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
1777 ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
1778 ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
1779 ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
1781 // FIXME: If we're fusing shuffle instructions, then we can't apply this
1782 // optimization. The input vectors to the shuffle might be a different
1783 // length from the shuffle outputs. Unfortunately, the replacement
1784 // shuffle mask has already been formed, and the mask entries are sensitive
1785 // to the sizes of the inputs.
1786 bool IsSizeChangeShuffle =
1787 isa<ShuffleVectorInst>(L) &&
1788 (LOp->getType() != L->getType() || HOp->getType() != H->getType());
1790 if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
1791 // We can have at most two unique vector inputs.
1792 bool CanUseInputs = true;
1795 I1 = LEE->getOperand(0);
1797 I1 = LSV->getOperand(0);
1798 I2 = LSV->getOperand(1);
1799 if (I2 == I1 || isa<UndefValue>(I2))
1804 Value *I3 = HEE->getOperand(0);
1805 if (!I2 && I3 != I1)
1807 else if (I3 != I1 && I3 != I2)
1808 CanUseInputs = false;
1810 Value *I3 = HSV->getOperand(0);
1811 if (!I2 && I3 != I1)
1813 else if (I3 != I1 && I3 != I2)
1814 CanUseInputs = false;
1817 Value *I4 = HSV->getOperand(1);
1818 if (!isa<UndefValue>(I4)) {
1819 if (!I2 && I4 != I1)
1821 else if (I4 != I1 && I4 != I2)
1822 CanUseInputs = false;
1829 cast<VectorType>(cast<Instruction>(LOp)->getOperand(0)->getType())
1832 cast<VectorType>(cast<Instruction>(HOp)->getOperand(0)->getType())
1835 // We have one or two input vectors. We need to map each index of the
1836 // operands to the index of the original vector.
1837 SmallVector<std::pair<int, int>, 8> II(numElem);
1838 for (unsigned i = 0; i < numElemL; ++i) {
1842 cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
1843 INum = LEE->getOperand(0) == I1 ? 0 : 1;
1845 Idx = LSV->getMaskValue(i);
1846 if (Idx < (int) LOpElem) {
1847 INum = LSV->getOperand(0) == I1 ? 0 : 1;
1850 INum = LSV->getOperand(1) == I1 ? 0 : 1;
1854 II[i] = std::pair<int, int>(Idx, INum);
1856 for (unsigned i = 0; i < numElemH; ++i) {
1860 cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
1861 INum = HEE->getOperand(0) == I1 ? 0 : 1;
1863 Idx = HSV->getMaskValue(i);
1864 if (Idx < (int) HOpElem) {
1865 INum = HSV->getOperand(0) == I1 ? 0 : 1;
1868 INum = HSV->getOperand(1) == I1 ? 0 : 1;
1872 II[i + numElemL] = std::pair<int, int>(Idx, INum);
1875 // We now have an array which tells us from which index of which
1876 // input vector each element of the operand comes.
1877 VectorType *I1T = cast<VectorType>(I1->getType());
1878 unsigned I1Elem = I1T->getNumElements();
1881 // In this case there is only one underlying vector input. Check for
1882 // the trivial case where we can use the input directly.
1883 if (I1Elem == numElem) {
1884 bool ElemInOrder = true;
1885 for (unsigned i = 0; i < numElem; ++i) {
1886 if (II[i].first != (int) i && II[i].first != -1) {
1887 ElemInOrder = false;
1896 // A shuffle is needed.
1897 std::vector<Constant *> Mask(numElem);
1898 for (unsigned i = 0; i < numElem; ++i) {
1899 int Idx = II[i].first;
1901 Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
1903 Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
1907 new ShuffleVectorInst(I1, UndefValue::get(I1T),
1908 ConstantVector::get(Mask),
1909 getReplacementName(I, true, o));
1914 VectorType *I2T = cast<VectorType>(I2->getType());
1915 unsigned I2Elem = I2T->getNumElements();
1917 // This input comes from two distinct vectors. The first step is to
1918 // make sure that both vectors are the same length. If not, the
1919 // smaller one will need to grow before they can be shuffled together.
1920 if (I1Elem < I2Elem) {
1921 std::vector<Constant *> Mask(I2Elem);
1923 for (; v < I1Elem; ++v)
1924 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1925 for (; v < I2Elem; ++v)
1926 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
1928 Instruction *NewI1 =
1929 new ShuffleVectorInst(I1, UndefValue::get(I1T),
1930 ConstantVector::get(Mask),
1931 getReplacementName(I, true, o, 1));
1932 NewI1->insertBefore(J);
1936 } else if (I1Elem > I2Elem) {
1937 std::vector<Constant *> Mask(I1Elem);
1939 for (; v < I2Elem; ++v)
1940 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1941 for (; v < I1Elem; ++v)
1942 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
1944 Instruction *NewI2 =
1945 new ShuffleVectorInst(I2, UndefValue::get(I2T),
1946 ConstantVector::get(Mask),
1947 getReplacementName(I, true, o, 1));
1948 NewI2->insertBefore(J);
1954 // Now that both I1 and I2 are the same length we can shuffle them
1955 // together (and use the result).
1956 std::vector<Constant *> Mask(numElem);
1957 for (unsigned v = 0; v < numElem; ++v) {
1958 if (II[v].first == -1) {
1959 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
1961 int Idx = II[v].first + II[v].second * I1Elem;
1962 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
1966 Instruction *NewOp =
1967 new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
1968 getReplacementName(I, true, o));
1969 NewOp->insertBefore(J);
1974 Type *ArgType = ArgTypeL;
1975 if (numElemL < numElemH) {
1976 if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
1977 ArgTypeL, VArgType, 1)) {
1978 // This is another short-circuit case: we're combining a scalar into
1979 // a vector that is formed by an IE chain. We've just expanded the IE
1980 // chain, now insert the scalar and we're done.
1982 Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
1983 getReplacementName(I, true, o));
1986 } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
1988 // The two vector inputs to the shuffle must be the same length,
1989 // so extend the smaller vector to be the same length as the larger one.
1993 std::vector<Constant *> Mask(numElemH);
1995 for (; v < numElemL; ++v)
1996 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
1997 for (; v < numElemH; ++v)
1998 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2000 NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2001 ConstantVector::get(Mask),
2002 getReplacementName(I, true, o, 1));
2004 NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2005 getReplacementName(I, true, o, 1));
2008 NLOp->insertBefore(J);
2013 } else if (numElemL > numElemH) {
2014 if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2015 ArgTypeH, VArgType)) {
2017 InsertElementInst::Create(LOp, HOp,
2018 ConstantInt::get(Type::getInt32Ty(Context),
2020 getReplacementName(I, true, o));
2023 } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2027 std::vector<Constant *> Mask(numElemL);
2029 for (; v < numElemH; ++v)
2030 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2031 for (; v < numElemL; ++v)
2032 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2034 NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2035 ConstantVector::get(Mask),
2036 getReplacementName(I, true, o, 1));
2038 NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2039 getReplacementName(I, true, o, 1));
2042 NHOp->insertBefore(J);
2047 if (ArgType->isVectorTy()) {
2048 unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
2049 std::vector<Constant*> Mask(numElem);
2050 for (unsigned v = 0; v < numElem; ++v) {
2052 // If the low vector was expanded, we need to skip the extra
2053 // undefined entries.
2054 if (v >= numElemL && numElemH > numElemL)
2055 Idx += (numElemH - numElemL);
2056 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2059 Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2060 ConstantVector::get(Mask),
2061 getReplacementName(I, true, o));
2062 BV->insertBefore(J);
2066 Instruction *BV1 = InsertElementInst::Create(
2067 UndefValue::get(VArgType), LOp, CV0,
2068 getReplacementName(I, true, o, 1));
2069 BV1->insertBefore(I);
2070 Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
2071 getReplacementName(I, true, o, 2));
2072 BV2->insertBefore(J);
2076 // This function creates an array of values that will be used as the inputs
2077 // to the vector instruction that fuses I with J.
2078 void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
2079 Instruction *I, Instruction *J,
2080 SmallVector<Value *, 3> &ReplacedOperands,
2081 bool FlipMemInputs) {
2082 unsigned NumOperands = I->getNumOperands();
2084 for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
2085 // Iterate backward so that we look at the store pointer
2086 // first and know whether or not we need to flip the inputs.
2088 if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
2089 // This is the pointer for a load/store instruction.
2090 ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o,
2093 } else if (isa<CallInst>(I)) {
2094 Function *F = cast<CallInst>(I)->getCalledFunction();
2095 unsigned IID = F->getIntrinsicID();
2096 if (o == NumOperands-1) {
2097 BasicBlock &BB = *I->getParent();
2099 Module *M = BB.getParent()->getParent();
2100 Type *ArgTypeI = I->getType();
2101 Type *ArgTypeJ = J->getType();
2102 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2104 ReplacedOperands[o] = Intrinsic::getDeclaration(M,
2105 (Intrinsic::ID) IID, VArgType);
2107 } else if (IID == Intrinsic::powi && o == 1) {
2108 // The second argument of powi is a single integer and we've already
2109 // checked that both arguments are equal. As a result, we just keep
2110 // I's second argument.
2111 ReplacedOperands[o] = I->getOperand(o);
2114 } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2115 ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2119 ReplacedOperands[o] =
2120 getReplacementInput(Context, I, J, o, FlipMemInputs);
2124 // This function creates two values that represent the outputs of the
2125 // original I and J instructions. These are generally vector shuffles
2126 // or extracts. In many cases, these will end up being unused and, thus,
2127 // eliminated by later passes.
2128 void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2129 Instruction *J, Instruction *K,
2130 Instruction *&InsertionPt,
2131 Instruction *&K1, Instruction *&K2,
2132 bool FlipMemInputs) {
2133 if (isa<StoreInst>(I)) {
2134 AA->replaceWithNewValue(I, K);
2135 AA->replaceWithNewValue(J, K);
2137 Type *IType = I->getType();
2138 Type *JType = J->getType();
2140 VectorType *VType = getVecTypeForPair(IType, JType);
2141 unsigned numElem = VType->getNumElements();
2143 unsigned numElemI, numElemJ;
2144 if (IType->isVectorTy())
2145 numElemI = cast<VectorType>(IType)->getNumElements();
2149 if (JType->isVectorTy())
2150 numElemJ = cast<VectorType>(JType)->getNumElements();
2154 if (IType->isVectorTy()) {
2155 std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
2156 for (unsigned v = 0; v < numElemI; ++v) {
2157 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2158 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
2161 K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2162 ConstantVector::get(
2163 FlipMemInputs ? Mask2 : Mask1),
2164 getReplacementName(K, false, 1));
2166 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2167 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2168 K1 = ExtractElementInst::Create(K, FlipMemInputs ? CV1 : CV0,
2169 getReplacementName(K, false, 1));
2172 if (JType->isVectorTy()) {
2173 std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
2174 for (unsigned v = 0; v < numElemJ; ++v) {
2175 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2176 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
2179 K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2180 ConstantVector::get(
2181 FlipMemInputs ? Mask1 : Mask2),
2182 getReplacementName(K, false, 2));
2184 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2185 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2186 K2 = ExtractElementInst::Create(K, FlipMemInputs ? CV0 : CV1,
2187 getReplacementName(K, false, 2));
2191 K2->insertAfter(K1);
2196 // Move all uses of the function I (including pairing-induced uses) after J.
2197 bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2198 std::multimap<Value *, Value *> &LoadMoveSet,
2199 Instruction *I, Instruction *J) {
2200 // Skip to the first instruction past I.
2201 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2203 DenseSet<Value *> Users;
2204 AliasSetTracker WriteSet(*AA);
2205 for (; cast<Instruction>(L) != J; ++L)
2206 (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet);
2208 assert(cast<Instruction>(L) == J &&
2209 "Tracking has not proceeded far enough to check for dependencies");
2210 // If J is now in the use set of I, then trackUsesOfI will return true
2211 // and we have a dependency cycle (and the fusing operation must abort).
2212 return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSet);
2215 // Move all uses of the function I (including pairing-induced uses) after J.
2216 void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2217 std::multimap<Value *, Value *> &LoadMoveSet,
2218 Instruction *&InsertionPt,
2219 Instruction *I, Instruction *J) {
2220 // Skip to the first instruction past I.
2221 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2223 DenseSet<Value *> Users;
2224 AliasSetTracker WriteSet(*AA);
2225 for (; cast<Instruction>(L) != J;) {
2226 if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet)) {
2227 // Move this instruction
2228 Instruction *InstToMove = L; ++L;
2230 DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2231 " to after " << *InsertionPt << "\n");
2232 InstToMove->removeFromParent();
2233 InstToMove->insertAfter(InsertionPt);
2234 InsertionPt = InstToMove;
2241 // Collect all load instruction that are in the move set of a given first
2242 // pair member. These loads depend on the first instruction, I, and so need
2243 // to be moved after J (the second instruction) when the pair is fused.
2244 void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2245 DenseMap<Value *, Value *> &ChosenPairs,
2246 std::multimap<Value *, Value *> &LoadMoveSet,
2248 // Skip to the first instruction past I.
2249 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2251 DenseSet<Value *> Users;
2252 AliasSetTracker WriteSet(*AA);
2254 // Note: We cannot end the loop when we reach J because J could be moved
2255 // farther down the use chain by another instruction pairing. Also, J
2256 // could be before I if this is an inverted input.
2257 for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
2258 if (trackUsesOfI(Users, WriteSet, I, L)) {
2259 if (L->mayReadFromMemory())
2260 LoadMoveSet.insert(ValuePair(L, I));
2265 // In cases where both load/stores and the computation of their pointers
2266 // are chosen for vectorization, we can end up in a situation where the
2267 // aliasing analysis starts returning different query results as the
2268 // process of fusing instruction pairs continues. Because the algorithm
2269 // relies on finding the same use trees here as were found earlier, we'll
2270 // need to precompute the necessary aliasing information here and then
2271 // manually update it during the fusion process.
2272 void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2273 std::vector<Value *> &PairableInsts,
2274 DenseMap<Value *, Value *> &ChosenPairs,
2275 std::multimap<Value *, Value *> &LoadMoveSet) {
2276 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2277 PIE = PairableInsts.end(); PI != PIE; ++PI) {
2278 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2279 if (P == ChosenPairs.end()) continue;
2281 Instruction *I = cast<Instruction>(P->first);
2282 collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet, I);
2286 // As with the aliasing information, SCEV can also change because of
2287 // vectorization. This information is used to compute relative pointer
2288 // offsets; the necessary information will be cached here prior to
2290 void BBVectorize::collectPtrInfo(std::vector<Value *> &PairableInsts,
2291 DenseMap<Value *, Value *> &ChosenPairs,
2292 DenseSet<Value *> &LowPtrInsts) {
2293 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2294 PIE = PairableInsts.end(); PI != PIE; ++PI) {
2295 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2296 if (P == ChosenPairs.end()) continue;
2298 Instruction *I = cast<Instruction>(P->first);
2299 Instruction *J = cast<Instruction>(P->second);
2301 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
2305 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
2306 int64_t OffsetInElmts;
2307 if (!getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
2308 IAddressSpace, JAddressSpace,
2309 OffsetInElmts) || abs64(OffsetInElmts) != 1)
2310 llvm_unreachable("Pre-fusion pointer analysis failed");
2312 Value *LowPI = (OffsetInElmts > 0) ? I : J;
2313 LowPtrInsts.insert(LowPI);
2317 // When the first instruction in each pair is cloned, it will inherit its
2318 // parent's metadata. This metadata must be combined with that of the other
2319 // instruction in a safe way.
2320 void BBVectorize::combineMetadata(Instruction *K, const Instruction *J) {
2321 SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
2322 K->getAllMetadataOtherThanDebugLoc(Metadata);
2323 for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
2324 unsigned Kind = Metadata[i].first;
2325 MDNode *JMD = J->getMetadata(Kind);
2326 MDNode *KMD = Metadata[i].second;
2330 K->setMetadata(Kind, 0); // Remove unknown metadata
2332 case LLVMContext::MD_tbaa:
2333 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2335 case LLVMContext::MD_fpmath:
2336 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2342 // This function fuses the chosen instruction pairs into vector instructions,
2343 // taking care preserve any needed scalar outputs and, then, it reorders the
2344 // remaining instructions as needed (users of the first member of the pair
2345 // need to be moved to after the location of the second member of the pair
2346 // because the vector instruction is inserted in the location of the pair's
2348 void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2349 std::vector<Value *> &PairableInsts,
2350 DenseMap<Value *, Value *> &ChosenPairs) {
2351 LLVMContext& Context = BB.getContext();
2353 // During the vectorization process, the order of the pairs to be fused
2354 // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
2355 // list. After a pair is fused, the flipped pair is removed from the list.
2356 std::vector<ValuePair> FlippedPairs;
2357 FlippedPairs.reserve(ChosenPairs.size());
2358 for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
2359 E = ChosenPairs.end(); P != E; ++P)
2360 FlippedPairs.push_back(ValuePair(P->second, P->first));
2361 for (std::vector<ValuePair>::iterator P = FlippedPairs.begin(),
2362 E = FlippedPairs.end(); P != E; ++P)
2363 ChosenPairs.insert(*P);
2365 std::multimap<Value *, Value *> LoadMoveSet;
2366 collectLoadMoveSet(BB, PairableInsts, ChosenPairs, LoadMoveSet);
2368 DenseSet<Value *> LowPtrInsts;
2369 collectPtrInfo(PairableInsts, ChosenPairs, LowPtrInsts);
2371 DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
2373 for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
2374 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
2375 if (P == ChosenPairs.end()) {
2380 if (getDepthFactor(P->first) == 0) {
2381 // These instructions are not really fused, but are tracked as though
2382 // they are. Any case in which it would be interesting to fuse them
2383 // will be taken care of by InstCombine.
2389 Instruction *I = cast<Instruction>(P->first),
2390 *J = cast<Instruction>(P->second);
2392 DEBUG(dbgs() << "BBV: fusing: " << *I <<
2393 " <-> " << *J << "\n");
2395 // Remove the pair and flipped pair from the list.
2396 DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
2397 assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
2398 ChosenPairs.erase(FP);
2399 ChosenPairs.erase(P);
2401 if (!canMoveUsesOfIAfterJ(BB, LoadMoveSet, I, J)) {
2402 DEBUG(dbgs() << "BBV: fusion of: " << *I <<
2404 " aborted because of non-trivial dependency cycle\n");
2410 bool FlipMemInputs = false;
2411 if (isa<LoadInst>(I) || isa<StoreInst>(I))
2412 FlipMemInputs = (LowPtrInsts.find(I) == LowPtrInsts.end());
2414 unsigned NumOperands = I->getNumOperands();
2415 SmallVector<Value *, 3> ReplacedOperands(NumOperands);
2416 getReplacementInputsForPair(Context, I, J, ReplacedOperands,
2419 // Make a copy of the original operation, change its type to the vector
2420 // type and replace its operands with the vector operands.
2421 Instruction *K = I->clone();
2422 if (I->hasName()) K->takeName(I);
2424 if (!isa<StoreInst>(K))
2425 K->mutateType(getVecTypeForPair(I->getType(), J->getType()));
2427 combineMetadata(K, J);
2429 for (unsigned o = 0; o < NumOperands; ++o)
2430 K->setOperand(o, ReplacedOperands[o]);
2432 // If we've flipped the memory inputs, make sure that we take the correct
2434 if (FlipMemInputs) {
2435 if (isa<StoreInst>(K))
2436 cast<StoreInst>(K)->setAlignment(cast<StoreInst>(J)->getAlignment());
2438 cast<LoadInst>(K)->setAlignment(cast<LoadInst>(J)->getAlignment());
2443 // Instruction insertion point:
2444 Instruction *InsertionPt = K;
2445 Instruction *K1 = 0, *K2 = 0;
2446 replaceOutputsOfPair(Context, I, J, K, InsertionPt, K1, K2,
2449 // The use tree of the first original instruction must be moved to after
2450 // the location of the second instruction. The entire use tree of the
2451 // first instruction is disjoint from the input tree of the second
2452 // (by definition), and so commutes with it.
2454 moveUsesOfIAfterJ(BB, LoadMoveSet, InsertionPt, I, J);
2456 if (!isa<StoreInst>(I)) {
2457 I->replaceAllUsesWith(K1);
2458 J->replaceAllUsesWith(K2);
2459 AA->replaceWithNewValue(I, K1);
2460 AA->replaceWithNewValue(J, K2);
2463 // Instructions that may read from memory may be in the load move set.
2464 // Once an instruction is fused, we no longer need its move set, and so
2465 // the values of the map never need to be updated. However, when a load
2466 // is fused, we need to merge the entries from both instructions in the
2467 // pair in case those instructions were in the move set of some other
2468 // yet-to-be-fused pair. The loads in question are the keys of the map.
2469 if (I->mayReadFromMemory()) {
2470 std::vector<ValuePair> NewSetMembers;
2471 VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
2472 VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
2473 for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
2474 N != IPairRange.second; ++N)
2475 NewSetMembers.push_back(ValuePair(K, N->second));
2476 for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
2477 N != JPairRange.second; ++N)
2478 NewSetMembers.push_back(ValuePair(K, N->second));
2479 for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
2480 AE = NewSetMembers.end(); A != AE; ++A)
2481 LoadMoveSet.insert(*A);
2484 // Before removing I, set the iterator to the next instruction.
2485 PI = llvm::next(BasicBlock::iterator(I));
2486 if (cast<Instruction>(PI) == J)
2491 I->eraseFromParent();
2492 J->eraseFromParent();
2495 DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
2499 char BBVectorize::ID = 0;
2500 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
2501 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
2502 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2503 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
2504 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2505 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
2507 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
2508 return new BBVectorize(C);
2512 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
2513 BBVectorize BBVectorizer(P, C);
2514 return BBVectorizer.vectorizeBB(BB);
2517 //===----------------------------------------------------------------------===//
2518 VectorizeConfig::VectorizeConfig() {
2519 VectorBits = ::VectorBits;
2520 VectorizeBools = !::NoBools;
2521 VectorizeInts = !::NoInts;
2522 VectorizeFloats = !::NoFloats;
2523 VectorizePointers = !::NoPointers;
2524 VectorizeCasts = !::NoCasts;
2525 VectorizeMath = !::NoMath;
2526 VectorizeFMA = !::NoFMA;
2527 VectorizeSelect = !::NoSelect;
2528 VectorizeCmp = !::NoCmp;
2529 VectorizeGEP = !::NoGEP;
2530 VectorizeMemOps = !::NoMemOps;
2531 AlignedOnly = ::AlignedOnly;
2532 ReqChainDepth= ::ReqChainDepth;
2533 SearchLimit = ::SearchLimit;
2534 MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
2535 SplatBreaksChain = ::SplatBreaksChain;
2536 MaxInsts = ::MaxInsts;
2537 MaxIter = ::MaxIter;
2538 Pow2LenOnly = ::Pow2LenOnly;
2539 NoMemOpBoost = ::NoMemOpBoost;
2540 FastDep = ::FastDep;