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 // Returns the cost of the provided instruction using VTTI.
488 // This does not handle loads and stores.
489 unsigned getInstrCost(unsigned Opcode, Type *T1, Type *T2) {
492 case Instruction::GetElementPtr:
493 // We mark this instruction as zero-cost because scalar GEPs are usually
494 // lowered to the intruction addressing mode. At the moment we don't
495 // generate vector GEPs.
497 case Instruction::Br:
498 return VTTI->getCFInstrCost(Opcode);
499 case Instruction::PHI:
501 case Instruction::Add:
502 case Instruction::FAdd:
503 case Instruction::Sub:
504 case Instruction::FSub:
505 case Instruction::Mul:
506 case Instruction::FMul:
507 case Instruction::UDiv:
508 case Instruction::SDiv:
509 case Instruction::FDiv:
510 case Instruction::URem:
511 case Instruction::SRem:
512 case Instruction::FRem:
513 case Instruction::Shl:
514 case Instruction::LShr:
515 case Instruction::AShr:
516 case Instruction::And:
517 case Instruction::Or:
518 case Instruction::Xor:
519 return VTTI->getArithmeticInstrCost(Opcode, T1);
520 case Instruction::Select:
521 case Instruction::ICmp:
522 case Instruction::FCmp:
523 return VTTI->getCmpSelInstrCost(Opcode, T1, T2);
524 case Instruction::ZExt:
525 case Instruction::SExt:
526 case Instruction::FPToUI:
527 case Instruction::FPToSI:
528 case Instruction::FPExt:
529 case Instruction::PtrToInt:
530 case Instruction::IntToPtr:
531 case Instruction::SIToFP:
532 case Instruction::UIToFP:
533 case Instruction::Trunc:
534 case Instruction::FPTrunc:
535 case Instruction::BitCast:
536 return VTTI->getCastInstrCost(Opcode, T1, T2);
542 // This determines the relative offset of two loads or stores, returning
543 // true if the offset could be determined to be some constant value.
544 // For example, if OffsetInElmts == 1, then J accesses the memory directly
545 // after I; if OffsetInElmts == -1 then I accesses the memory
547 bool getPairPtrInfo(Instruction *I, Instruction *J,
548 Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
549 unsigned &IAddressSpace, unsigned &JAddressSpace,
550 int64_t &OffsetInElmts) {
552 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
553 LoadInst *LJ = cast<LoadInst>(J);
554 IPtr = LI->getPointerOperand();
555 JPtr = LJ->getPointerOperand();
556 IAlignment = LI->getAlignment();
557 JAlignment = LJ->getAlignment();
558 IAddressSpace = LI->getPointerAddressSpace();
559 JAddressSpace = LJ->getPointerAddressSpace();
561 StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
562 IPtr = SI->getPointerOperand();
563 JPtr = SJ->getPointerOperand();
564 IAlignment = SI->getAlignment();
565 JAlignment = SJ->getAlignment();
566 IAddressSpace = SI->getPointerAddressSpace();
567 JAddressSpace = SJ->getPointerAddressSpace();
570 const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
571 const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
573 // If this is a trivial offset, then we'll get something like
574 // 1*sizeof(type). With target data, which we need anyway, this will get
575 // constant folded into a number.
576 const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
577 if (const SCEVConstant *ConstOffSCEV =
578 dyn_cast<SCEVConstant>(OffsetSCEV)) {
579 ConstantInt *IntOff = ConstOffSCEV->getValue();
580 int64_t Offset = IntOff->getSExtValue();
582 Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
583 int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
585 Type *VTy2 = cast<PointerType>(JPtr->getType())->getElementType();
586 if (VTy != VTy2 && Offset < 0) {
587 int64_t VTy2TSS = (int64_t) TD->getTypeStoreSize(VTy2);
588 OffsetInElmts = Offset/VTy2TSS;
589 return (abs64(Offset) % VTy2TSS) == 0;
592 OffsetInElmts = Offset/VTyTSS;
593 return (abs64(Offset) % VTyTSS) == 0;
599 // Returns true if the provided CallInst represents an intrinsic that can
601 bool isVectorizableIntrinsic(CallInst* I) {
602 Function *F = I->getCalledFunction();
603 if (!F) return false;
605 unsigned IID = F->getIntrinsicID();
606 if (!IID) return false;
611 case Intrinsic::sqrt:
612 case Intrinsic::powi:
616 case Intrinsic::log2:
617 case Intrinsic::log10:
619 case Intrinsic::exp2:
621 return Config.VectorizeMath;
623 return Config.VectorizeFMA;
627 // Returns true if J is the second element in some pair referenced by
628 // some multimap pair iterator pair.
629 template <typename V>
630 bool isSecondInIteratorPair(V J, std::pair<
631 typename std::multimap<V, V>::iterator,
632 typename std::multimap<V, V>::iterator> PairRange) {
633 for (typename std::multimap<V, V>::iterator K = PairRange.first;
634 K != PairRange.second; ++K)
635 if (K->second == J) return true;
641 // This function implements one vectorization iteration on the provided
642 // basic block. It returns true if the block is changed.
643 bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
645 BasicBlock::iterator Start = BB.getFirstInsertionPt();
647 std::vector<Value *> AllPairableInsts;
648 DenseMap<Value *, Value *> AllChosenPairs;
651 std::vector<Value *> PairableInsts;
652 std::multimap<Value *, Value *> CandidatePairs;
653 DenseMap<ValuePair, int> CandidatePairCostSavings;
654 ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
655 CandidatePairCostSavings,
656 PairableInsts, NonPow2Len);
657 if (PairableInsts.empty()) continue;
659 // Now we have a map of all of the pairable instructions and we need to
660 // select the best possible pairing. A good pairing is one such that the
661 // users of the pair are also paired. This defines a (directed) forest
662 // over the pairs such that two pairs are connected iff the second pair
665 // Note that it only matters that both members of the second pair use some
666 // element of the first pair (to allow for splatting).
668 std::multimap<ValuePair, ValuePair> ConnectedPairs;
669 computeConnectedPairs(CandidatePairs, PairableInsts, ConnectedPairs);
670 if (ConnectedPairs.empty()) continue;
672 // Build the pairable-instruction dependency map
673 DenseSet<ValuePair> PairableInstUsers;
674 buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
676 // There is now a graph of the connected pairs. For each variable, pick
677 // the pairing with the largest tree meeting the depth requirement on at
678 // least one branch. Then select all pairings that are part of that tree
679 // and remove them from the list of available pairings and pairable
682 DenseMap<Value *, Value *> ChosenPairs;
683 choosePairs(CandidatePairs, CandidatePairCostSavings,
684 PairableInsts, ConnectedPairs,
685 PairableInstUsers, ChosenPairs);
687 if (ChosenPairs.empty()) continue;
688 AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
689 PairableInsts.end());
690 AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
691 } while (ShouldContinue);
693 if (AllChosenPairs.empty()) return false;
694 NumFusedOps += AllChosenPairs.size();
696 // A set of pairs has now been selected. It is now necessary to replace the
697 // paired instructions with vector instructions. For this procedure each
698 // operand must be replaced with a vector operand. This vector is formed
699 // by using build_vector on the old operands. The replaced values are then
700 // replaced with a vector_extract on the result. Subsequent optimization
701 // passes should coalesce the build/extract combinations.
703 fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs);
705 // It is important to cleanup here so that future iterations of this
706 // function have less work to do.
707 (void) SimplifyInstructionsInBlock(&BB, TD, AA->getTargetLibraryInfo());
711 // This function returns true if the provided instruction is capable of being
712 // fused into a vector instruction. This determination is based only on the
713 // type and other attributes of the instruction.
714 bool BBVectorize::isInstVectorizable(Instruction *I,
715 bool &IsSimpleLoadStore) {
716 IsSimpleLoadStore = false;
718 if (CallInst *C = dyn_cast<CallInst>(I)) {
719 if (!isVectorizableIntrinsic(C))
721 } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
722 // Vectorize simple loads if possbile:
723 IsSimpleLoadStore = L->isSimple();
724 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
726 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
727 // Vectorize simple stores if possbile:
728 IsSimpleLoadStore = S->isSimple();
729 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
731 } else if (CastInst *C = dyn_cast<CastInst>(I)) {
732 // We can vectorize casts, but not casts of pointer types, etc.
733 if (!Config.VectorizeCasts)
736 Type *SrcTy = C->getSrcTy();
737 if (!SrcTy->isSingleValueType())
740 Type *DestTy = C->getDestTy();
741 if (!DestTy->isSingleValueType())
743 } else if (isa<SelectInst>(I)) {
744 if (!Config.VectorizeSelect)
746 } else if (isa<CmpInst>(I)) {
747 if (!Config.VectorizeCmp)
749 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
750 if (!Config.VectorizeGEP)
753 // Currently, vector GEPs exist only with one index.
754 if (G->getNumIndices() != 1)
756 } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
757 isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
761 // We can't vectorize memory operations without target data
762 if (TD == 0 && IsSimpleLoadStore)
766 getInstructionTypes(I, T1, T2);
768 // Not every type can be vectorized...
769 if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
770 !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
773 if (T1->getScalarSizeInBits() == 1) {
774 if (!Config.VectorizeBools)
777 if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
781 if (T2->getScalarSizeInBits() == 1) {
782 if (!Config.VectorizeBools)
785 if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
789 if (!Config.VectorizeFloats
790 && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
793 // Don't vectorize target-specific types.
794 if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
796 if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
799 if ((!Config.VectorizePointers || TD == 0) &&
800 (T1->getScalarType()->isPointerTy() ||
801 T2->getScalarType()->isPointerTy()))
804 if (!VTTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
805 T2->getPrimitiveSizeInBits() >= Config.VectorBits))
811 // This function returns true if the two provided instructions are compatible
812 // (meaning that they can be fused into a vector instruction). This assumes
813 // that I has already been determined to be vectorizable and that J is not
814 // in the use tree of I.
815 bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
816 bool IsSimpleLoadStore, bool NonPow2Len,
818 DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
819 " <-> " << *J << "\n");
823 // Loads and stores can be merged if they have different alignments,
824 // but are otherwise the same.
825 if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
826 (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
829 Type *IT1, *IT2, *JT1, *JT2;
830 getInstructionTypes(I, IT1, IT2);
831 getInstructionTypes(J, JT1, JT2);
832 unsigned MaxTypeBits = std::max(
833 IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
834 IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
835 if (!VTTI && MaxTypeBits > Config.VectorBits)
838 // FIXME: handle addsub-type operations!
840 if (IsSimpleLoadStore) {
842 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
843 int64_t OffsetInElmts = 0;
844 if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
845 IAddressSpace, JAddressSpace,
846 OffsetInElmts) && abs64(OffsetInElmts) == 1) {
847 unsigned BottomAlignment = IAlignment;
848 if (OffsetInElmts < 0) BottomAlignment = JAlignment;
850 Type *aTypeI = isa<StoreInst>(I) ?
851 cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
852 Type *aTypeJ = isa<StoreInst>(J) ?
853 cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
854 Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
856 if (Config.AlignedOnly) {
857 // An aligned load or store is possible only if the instruction
858 // with the lower offset has an alignment suitable for the
861 unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
862 if (BottomAlignment < VecAlignment)
867 unsigned ICost = VTTI->getMemoryOpCost(I->getOpcode(), I->getType(),
868 IAlignment, IAddressSpace);
869 unsigned JCost = VTTI->getMemoryOpCost(J->getOpcode(), J->getType(),
870 JAlignment, JAddressSpace);
871 unsigned VCost = VTTI->getMemoryOpCost(I->getOpcode(), VType,
874 if (VCost > ICost + JCost)
877 // We don't want to fuse to a type that will be split, even
878 // if the two input types will also be split and there is no other
880 unsigned VParts = VTTI->getNumberOfParts(VType);
883 else if (!VParts && VCost == ICost + JCost)
886 CostSavings = ICost + JCost - VCost;
892 unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
893 unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
894 Type *VT1 = getVecTypeForPair(IT1, JT1),
895 *VT2 = getVecTypeForPair(IT2, JT2);
896 unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2);
898 if (VCost > ICost + JCost)
901 // We don't want to fuse to a type that will be split, even
902 // if the two input types will also be split and there is no other
904 unsigned VParts = VTTI->getNumberOfParts(VT1);
907 else if (!VParts && VCost == ICost + JCost)
910 CostSavings = ICost + JCost - VCost;
913 // The powi intrinsic is special because only the first argument is
914 // vectorized, the second arguments must be equal.
915 CallInst *CI = dyn_cast<CallInst>(I);
917 if (CI && (FI = CI->getCalledFunction()) &&
918 FI->getIntrinsicID() == Intrinsic::powi) {
920 Value *A1I = CI->getArgOperand(1),
921 *A1J = cast<CallInst>(J)->getArgOperand(1);
922 const SCEV *A1ISCEV = SE->getSCEV(A1I),
923 *A1JSCEV = SE->getSCEV(A1J);
924 return (A1ISCEV == A1JSCEV);
930 // Figure out whether or not J uses I and update the users and write-set
931 // structures associated with I. Specifically, Users represents the set of
932 // instructions that depend on I. WriteSet represents the set
933 // of memory locations that are dependent on I. If UpdateUsers is true,
934 // and J uses I, then Users is updated to contain J and WriteSet is updated
935 // to contain any memory locations to which J writes. The function returns
936 // true if J uses I. By default, alias analysis is used to determine
937 // whether J reads from memory that overlaps with a location in WriteSet.
938 // If LoadMoveSet is not null, then it is a previously-computed multimap
939 // where the key is the memory-based user instruction and the value is
940 // the instruction to be compared with I. So, if LoadMoveSet is provided,
941 // then the alias analysis is not used. This is necessary because this
942 // function is called during the process of moving instructions during
943 // vectorization and the results of the alias analysis are not stable during
945 bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
946 AliasSetTracker &WriteSet, Instruction *I,
947 Instruction *J, bool UpdateUsers,
948 std::multimap<Value *, Value *> *LoadMoveSet) {
951 // This instruction may already be marked as a user due, for example, to
952 // being a member of a selected pair.
957 for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
960 if (I == V || Users.count(V)) {
965 if (!UsesI && J->mayReadFromMemory()) {
967 VPIteratorPair JPairRange = LoadMoveSet->equal_range(J);
968 UsesI = isSecondInIteratorPair<Value*>(I, JPairRange);
970 for (AliasSetTracker::iterator W = WriteSet.begin(),
971 WE = WriteSet.end(); W != WE; ++W) {
972 if (W->aliasesUnknownInst(J, *AA)) {
980 if (UsesI && UpdateUsers) {
981 if (J->mayWriteToMemory()) WriteSet.add(J);
988 // This function iterates over all instruction pairs in the provided
989 // basic block and collects all candidate pairs for vectorization.
990 bool BBVectorize::getCandidatePairs(BasicBlock &BB,
991 BasicBlock::iterator &Start,
992 std::multimap<Value *, Value *> &CandidatePairs,
993 DenseMap<ValuePair, int> &CandidatePairCostSavings,
994 std::vector<Value *> &PairableInsts, bool NonPow2Len) {
995 BasicBlock::iterator E = BB.end();
996 if (Start == E) return false;
998 bool ShouldContinue = false, IAfterStart = false;
999 for (BasicBlock::iterator I = Start++; I != E; ++I) {
1000 if (I == Start) IAfterStart = true;
1002 bool IsSimpleLoadStore;
1003 if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
1005 // Look for an instruction with which to pair instruction *I...
1006 DenseSet<Value *> Users;
1007 AliasSetTracker WriteSet(*AA);
1008 bool JAfterStart = IAfterStart;
1009 BasicBlock::iterator J = llvm::next(I);
1010 for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
1011 if (J == Start) JAfterStart = true;
1013 // Determine if J uses I, if so, exit the loop.
1014 bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
1015 if (Config.FastDep) {
1016 // Note: For this heuristic to be effective, independent operations
1017 // must tend to be intermixed. This is likely to be true from some
1018 // kinds of grouped loop unrolling (but not the generic LLVM pass),
1019 // but otherwise may require some kind of reordering pass.
1021 // When using fast dependency analysis,
1022 // stop searching after first use:
1025 if (UsesI) continue;
1028 // J does not use I, and comes before the first use of I, so it can be
1029 // merged with I if the instructions are compatible.
1031 if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
1032 CostSavings)) continue;
1034 // J is a candidate for merging with I.
1035 if (!PairableInsts.size() ||
1036 PairableInsts[PairableInsts.size()-1] != I) {
1037 PairableInsts.push_back(I);
1040 CandidatePairs.insert(ValuePair(I, J));
1042 CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
1045 // The next call to this function must start after the last instruction
1046 // selected during this invocation.
1048 Start = llvm::next(J);
1049 IAfterStart = JAfterStart = false;
1052 DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
1053 << *I << " <-> " << *J << " (cost savings: " <<
1054 CostSavings << ")\n");
1056 // If we have already found too many pairs, break here and this function
1057 // will be called again starting after the last instruction selected
1058 // during this invocation.
1059 if (PairableInsts.size() >= Config.MaxInsts) {
1060 ShouldContinue = true;
1069 DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
1070 << " instructions with candidate pairs\n");
1072 return ShouldContinue;
1075 // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
1076 // it looks for pairs such that both members have an input which is an
1077 // output of PI or PJ.
1078 void BBVectorize::computePairsConnectedTo(
1079 std::multimap<Value *, Value *> &CandidatePairs,
1080 std::vector<Value *> &PairableInsts,
1081 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1085 // For each possible pairing for this variable, look at the uses of
1086 // the first value...
1087 for (Value::use_iterator I = P.first->use_begin(),
1088 E = P.first->use_end(); I != E; ++I) {
1089 if (isa<LoadInst>(*I)) {
1090 // A pair cannot be connected to a load because the load only takes one
1091 // operand (the address) and it is a scalar even after vectorization.
1093 } else if ((SI = dyn_cast<StoreInst>(*I)) &&
1094 P.first == SI->getPointerOperand()) {
1095 // Similarly, a pair cannot be connected to a store through its
1100 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
1102 // For each use of the first variable, look for uses of the second
1104 for (Value::use_iterator J = P.second->use_begin(),
1105 E2 = P.second->use_end(); J != E2; ++J) {
1106 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1107 P.second == SJ->getPointerOperand())
1110 VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
1113 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
1114 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
1117 if (isSecondInIteratorPair<Value*>(*I, JPairRange))
1118 ConnectedPairs.insert(VPPair(P, ValuePair(*J, *I)));
1121 if (Config.SplatBreaksChain) continue;
1122 // Look for cases where just the first value in the pair is used by
1123 // both members of another pair (splatting).
1124 for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
1125 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1126 P.first == SJ->getPointerOperand())
1129 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
1130 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
1134 if (Config.SplatBreaksChain) return;
1135 // Look for cases where just the second value in the pair is used by
1136 // both members of another pair (splatting).
1137 for (Value::use_iterator I = P.second->use_begin(),
1138 E = P.second->use_end(); I != E; ++I) {
1139 if (isa<LoadInst>(*I))
1141 else if ((SI = dyn_cast<StoreInst>(*I)) &&
1142 P.second == SI->getPointerOperand())
1145 VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
1147 for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
1148 if ((SJ = dyn_cast<StoreInst>(*J)) &&
1149 P.second == SJ->getPointerOperand())
1152 if (isSecondInIteratorPair<Value*>(*J, IPairRange))
1153 ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
1158 // This function figures out which pairs are connected. Two pairs are
1159 // connected if some output of the first pair forms an input to both members
1160 // of the second pair.
1161 void BBVectorize::computeConnectedPairs(
1162 std::multimap<Value *, Value *> &CandidatePairs,
1163 std::vector<Value *> &PairableInsts,
1164 std::multimap<ValuePair, ValuePair> &ConnectedPairs) {
1166 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1167 PE = PairableInsts.end(); PI != PE; ++PI) {
1168 VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
1170 for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
1171 P != choiceRange.second; ++P)
1172 computePairsConnectedTo(CandidatePairs, PairableInsts,
1173 ConnectedPairs, *P);
1176 DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
1177 << " pair connections.\n");
1180 // This function builds a set of use tuples such that <A, B> is in the set
1181 // if B is in the use tree of A. If B is in the use tree of A, then B
1182 // depends on the output of A.
1183 void BBVectorize::buildDepMap(
1185 std::multimap<Value *, Value *> &CandidatePairs,
1186 std::vector<Value *> &PairableInsts,
1187 DenseSet<ValuePair> &PairableInstUsers) {
1188 DenseSet<Value *> IsInPair;
1189 for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
1190 E = CandidatePairs.end(); C != E; ++C) {
1191 IsInPair.insert(C->first);
1192 IsInPair.insert(C->second);
1195 // Iterate through the basic block, recording all Users of each
1196 // pairable instruction.
1198 BasicBlock::iterator E = BB.end();
1199 for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1200 if (IsInPair.find(I) == IsInPair.end()) continue;
1202 DenseSet<Value *> Users;
1203 AliasSetTracker WriteSet(*AA);
1204 for (BasicBlock::iterator J = llvm::next(I); J != E; ++J)
1205 (void) trackUsesOfI(Users, WriteSet, I, J);
1207 for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1209 PairableInstUsers.insert(ValuePair(I, *U));
1213 // Returns true if an input to pair P is an output of pair Q and also an
1214 // input of pair Q is an output of pair P. If this is the case, then these
1215 // two pairs cannot be simultaneously fused.
1216 bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1217 DenseSet<ValuePair> &PairableInstUsers,
1218 std::multimap<ValuePair, ValuePair> *PairableInstUserMap) {
1219 // Two pairs are in conflict if they are mutual Users of eachother.
1220 bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
1221 PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
1222 PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
1223 PairableInstUsers.count(ValuePair(P.second, Q.second));
1224 bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
1225 PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
1226 PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
1227 PairableInstUsers.count(ValuePair(Q.second, P.second));
1228 if (PairableInstUserMap) {
1229 // FIXME: The expensive part of the cycle check is not so much the cycle
1230 // check itself but this edge insertion procedure. This needs some
1231 // profiling and probably a different data structure (same is true of
1232 // most uses of std::multimap).
1234 VPPIteratorPair QPairRange = PairableInstUserMap->equal_range(Q);
1235 if (!isSecondInIteratorPair(P, QPairRange))
1236 PairableInstUserMap->insert(VPPair(Q, P));
1239 VPPIteratorPair PPairRange = PairableInstUserMap->equal_range(P);
1240 if (!isSecondInIteratorPair(Q, PPairRange))
1241 PairableInstUserMap->insert(VPPair(P, Q));
1245 return (QUsesP && PUsesQ);
1248 // This function walks the use graph of current pairs to see if, starting
1249 // from P, the walk returns to P.
1250 bool BBVectorize::pairWillFormCycle(ValuePair P,
1251 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1252 DenseSet<ValuePair> &CurrentPairs) {
1253 DEBUG(if (DebugCycleCheck)
1254 dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1255 << *P.second << "\n");
1256 // A lookup table of visisted pairs is kept because the PairableInstUserMap
1257 // contains non-direct associations.
1258 DenseSet<ValuePair> Visited;
1259 SmallVector<ValuePair, 32> Q;
1260 // General depth-first post-order traversal:
1263 ValuePair QTop = Q.pop_back_val();
1264 Visited.insert(QTop);
1266 DEBUG(if (DebugCycleCheck)
1267 dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1268 << *QTop.second << "\n");
1269 VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
1270 for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
1271 C != QPairRange.second; ++C) {
1272 if (C->second == P) {
1274 << "BBV: rejected to prevent non-trivial cycle formation: "
1275 << *C->first.first << " <-> " << *C->first.second << "\n");
1279 if (CurrentPairs.count(C->second) && !Visited.count(C->second))
1280 Q.push_back(C->second);
1282 } while (!Q.empty());
1287 // This function builds the initial tree of connected pairs with the
1288 // pair J at the root.
1289 void BBVectorize::buildInitialTreeFor(
1290 std::multimap<Value *, Value *> &CandidatePairs,
1291 std::vector<Value *> &PairableInsts,
1292 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1293 DenseSet<ValuePair> &PairableInstUsers,
1294 DenseMap<Value *, Value *> &ChosenPairs,
1295 DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
1296 // Each of these pairs is viewed as the root node of a Tree. The Tree
1297 // is then walked (depth-first). As this happens, we keep track of
1298 // the pairs that compose the Tree and the maximum depth of the Tree.
1299 SmallVector<ValuePairWithDepth, 32> Q;
1300 // General depth-first post-order traversal:
1301 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1303 ValuePairWithDepth QTop = Q.back();
1305 // Push each child onto the queue:
1306 bool MoreChildren = false;
1307 size_t MaxChildDepth = QTop.second;
1308 VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
1309 for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
1310 k != qtRange.second; ++k) {
1311 // Make sure that this child pair is still a candidate:
1312 bool IsStillCand = false;
1313 VPIteratorPair checkRange =
1314 CandidatePairs.equal_range(k->second.first);
1315 for (std::multimap<Value *, Value *>::iterator m = checkRange.first;
1316 m != checkRange.second; ++m) {
1317 if (m->second == k->second.second) {
1324 DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
1325 if (C == Tree.end()) {
1326 size_t d = getDepthFactor(k->second.first);
1327 Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
1328 MoreChildren = true;
1330 MaxChildDepth = std::max(MaxChildDepth, C->second);
1335 if (!MoreChildren) {
1336 // Record the current pair as part of the Tree:
1337 Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1340 } while (!Q.empty());
1343 // Given some initial tree, prune it by removing conflicting pairs (pairs
1344 // that cannot be simultaneously chosen for vectorization).
1345 void BBVectorize::pruneTreeFor(
1346 std::multimap<Value *, Value *> &CandidatePairs,
1347 std::vector<Value *> &PairableInsts,
1348 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1349 DenseSet<ValuePair> &PairableInstUsers,
1350 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1351 DenseMap<Value *, Value *> &ChosenPairs,
1352 DenseMap<ValuePair, size_t> &Tree,
1353 DenseSet<ValuePair> &PrunedTree, ValuePair J,
1354 bool UseCycleCheck) {
1355 SmallVector<ValuePairWithDepth, 32> Q;
1356 // General depth-first post-order traversal:
1357 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1359 ValuePairWithDepth QTop = Q.pop_back_val();
1360 PrunedTree.insert(QTop.first);
1362 // Visit each child, pruning as necessary...
1363 DenseMap<ValuePair, size_t> BestChildren;
1364 VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
1365 for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
1366 K != QTopRange.second; ++K) {
1367 DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
1368 if (C == Tree.end()) continue;
1370 // This child is in the Tree, now we need to make sure it is the
1371 // best of any conflicting children. There could be multiple
1372 // conflicting children, so first, determine if we're keeping
1373 // this child, then delete conflicting children as necessary.
1375 // It is also necessary to guard against pairing-induced
1376 // dependencies. Consider instructions a .. x .. y .. b
1377 // such that (a,b) are to be fused and (x,y) are to be fused
1378 // but a is an input to x and b is an output from y. This
1379 // means that y cannot be moved after b but x must be moved
1380 // after b for (a,b) to be fused. In other words, after
1381 // fusing (a,b) we have y .. a/b .. x where y is an input
1382 // to a/b and x is an output to a/b: x and y can no longer
1383 // be legally fused. To prevent this condition, we must
1384 // make sure that a child pair added to the Tree is not
1385 // both an input and output of an already-selected pair.
1387 // Pairing-induced dependencies can also form from more complicated
1388 // cycles. The pair vs. pair conflicts are easy to check, and so
1389 // that is done explicitly for "fast rejection", and because for
1390 // child vs. child conflicts, we may prefer to keep the current
1391 // pair in preference to the already-selected child.
1392 DenseSet<ValuePair> CurrentPairs;
1395 for (DenseMap<ValuePair, size_t>::iterator C2
1396 = BestChildren.begin(), E2 = BestChildren.end();
1398 if (C2->first.first == C->first.first ||
1399 C2->first.first == C->first.second ||
1400 C2->first.second == C->first.first ||
1401 C2->first.second == C->first.second ||
1402 pairsConflict(C2->first, C->first, PairableInstUsers,
1403 UseCycleCheck ? &PairableInstUserMap : 0)) {
1404 if (C2->second >= C->second) {
1409 CurrentPairs.insert(C2->first);
1412 if (!CanAdd) continue;
1414 // Even worse, this child could conflict with another node already
1415 // selected for the Tree. If that is the case, ignore this child.
1416 for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
1417 E2 = PrunedTree.end(); T != E2; ++T) {
1418 if (T->first == C->first.first ||
1419 T->first == C->first.second ||
1420 T->second == C->first.first ||
1421 T->second == C->first.second ||
1422 pairsConflict(*T, C->first, PairableInstUsers,
1423 UseCycleCheck ? &PairableInstUserMap : 0)) {
1428 CurrentPairs.insert(*T);
1430 if (!CanAdd) continue;
1432 // And check the queue too...
1433 for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
1434 E2 = Q.end(); C2 != E2; ++C2) {
1435 if (C2->first.first == C->first.first ||
1436 C2->first.first == C->first.second ||
1437 C2->first.second == C->first.first ||
1438 C2->first.second == C->first.second ||
1439 pairsConflict(C2->first, C->first, PairableInstUsers,
1440 UseCycleCheck ? &PairableInstUserMap : 0)) {
1445 CurrentPairs.insert(C2->first);
1447 if (!CanAdd) continue;
1449 // Last but not least, check for a conflict with any of the
1450 // already-chosen pairs.
1451 for (DenseMap<Value *, Value *>::iterator C2 =
1452 ChosenPairs.begin(), E2 = ChosenPairs.end();
1454 if (pairsConflict(*C2, C->first, PairableInstUsers,
1455 UseCycleCheck ? &PairableInstUserMap : 0)) {
1460 CurrentPairs.insert(*C2);
1462 if (!CanAdd) continue;
1464 // To check for non-trivial cycles formed by the addition of the
1465 // current pair we've formed a list of all relevant pairs, now use a
1466 // graph walk to check for a cycle. We start from the current pair and
1467 // walk the use tree to see if we again reach the current pair. If we
1468 // do, then the current pair is rejected.
1470 // FIXME: It may be more efficient to use a topological-ordering
1471 // algorithm to improve the cycle check. This should be investigated.
1472 if (UseCycleCheck &&
1473 pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1476 // This child can be added, but we may have chosen it in preference
1477 // to an already-selected child. Check for this here, and if a
1478 // conflict is found, then remove the previously-selected child
1479 // before adding this one in its place.
1480 for (DenseMap<ValuePair, size_t>::iterator C2
1481 = BestChildren.begin(); C2 != BestChildren.end();) {
1482 if (C2->first.first == C->first.first ||
1483 C2->first.first == C->first.second ||
1484 C2->first.second == C->first.first ||
1485 C2->first.second == C->first.second ||
1486 pairsConflict(C2->first, C->first, PairableInstUsers))
1487 BestChildren.erase(C2++);
1492 BestChildren.insert(ValuePairWithDepth(C->first, C->second));
1495 for (DenseMap<ValuePair, size_t>::iterator C
1496 = BestChildren.begin(), E2 = BestChildren.end();
1498 size_t DepthF = getDepthFactor(C->first.first);
1499 Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1501 } while (!Q.empty());
1504 // This function finds the best tree of mututally-compatible connected
1505 // pairs, given the choice of root pairs as an iterator range.
1506 void BBVectorize::findBestTreeFor(
1507 std::multimap<Value *, Value *> &CandidatePairs,
1508 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1509 std::vector<Value *> &PairableInsts,
1510 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1511 DenseSet<ValuePair> &PairableInstUsers,
1512 std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
1513 DenseMap<Value *, Value *> &ChosenPairs,
1514 DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
1515 int &BestEffSize, VPIteratorPair ChoiceRange,
1516 bool UseCycleCheck) {
1517 for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
1518 J != ChoiceRange.second; ++J) {
1520 // Before going any further, make sure that this pair does not
1521 // conflict with any already-selected pairs (see comment below
1522 // near the Tree pruning for more details).
1523 DenseSet<ValuePair> ChosenPairSet;
1524 bool DoesConflict = false;
1525 for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1526 E = ChosenPairs.end(); C != E; ++C) {
1527 if (pairsConflict(*C, *J, PairableInstUsers,
1528 UseCycleCheck ? &PairableInstUserMap : 0)) {
1529 DoesConflict = true;
1533 ChosenPairSet.insert(*C);
1535 if (DoesConflict) continue;
1537 if (UseCycleCheck &&
1538 pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
1541 DenseMap<ValuePair, size_t> Tree;
1542 buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1543 PairableInstUsers, ChosenPairs, Tree, *J);
1545 // Because we'll keep the child with the largest depth, the largest
1546 // depth is still the same in the unpruned Tree.
1547 size_t MaxDepth = Tree.lookup(*J);
1549 DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
1550 << *J->first << " <-> " << *J->second << "} of depth " <<
1551 MaxDepth << " and size " << Tree.size() << "\n");
1553 // At this point the Tree has been constructed, but, may contain
1554 // contradictory children (meaning that different children of
1555 // some tree node may be attempting to fuse the same instruction).
1556 // So now we walk the tree again, in the case of a conflict,
1557 // keep only the child with the largest depth. To break a tie,
1558 // favor the first child.
1560 DenseSet<ValuePair> PrunedTree;
1561 pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
1562 PairableInstUsers, PairableInstUserMap, ChosenPairs, Tree,
1563 PrunedTree, *J, UseCycleCheck);
1567 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1568 E = PrunedTree.end(); S != E; ++S) {
1569 if (getDepthFactor(S->first))
1570 EffSize += CandidatePairCostSavings.find(*S)->second;
1573 for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
1574 E = PrunedTree.end(); S != E; ++S)
1575 EffSize += (int) getDepthFactor(S->first);
1578 DEBUG(if (DebugPairSelection)
1579 dbgs() << "BBV: found pruned Tree for pair {"
1580 << *J->first << " <-> " << *J->second << "} of depth " <<
1581 MaxDepth << " and size " << PrunedTree.size() <<
1582 " (effective size: " << EffSize << ")\n");
1583 if (MaxDepth >= Config.ReqChainDepth &&
1584 EffSize > 0 && EffSize > BestEffSize) {
1585 BestMaxDepth = MaxDepth;
1586 BestEffSize = EffSize;
1587 BestTree = PrunedTree;
1592 // Given the list of candidate pairs, this function selects those
1593 // that will be fused into vector instructions.
1594 void BBVectorize::choosePairs(
1595 std::multimap<Value *, Value *> &CandidatePairs,
1596 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1597 std::vector<Value *> &PairableInsts,
1598 std::multimap<ValuePair, ValuePair> &ConnectedPairs,
1599 DenseSet<ValuePair> &PairableInstUsers,
1600 DenseMap<Value *, Value *>& ChosenPairs) {
1601 bool UseCycleCheck =
1602 CandidatePairs.size() <= Config.MaxCandPairsForCycleCheck;
1603 std::multimap<ValuePair, ValuePair> PairableInstUserMap;
1604 for (std::vector<Value *>::iterator I = PairableInsts.begin(),
1605 E = PairableInsts.end(); I != E; ++I) {
1606 // The number of possible pairings for this variable:
1607 size_t NumChoices = CandidatePairs.count(*I);
1608 if (!NumChoices) continue;
1610 VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
1612 // The best pair to choose and its tree:
1613 size_t BestMaxDepth = 0;
1614 int BestEffSize = 0;
1615 DenseSet<ValuePair> BestTree;
1616 findBestTreeFor(CandidatePairs, CandidatePairCostSavings,
1617 PairableInsts, ConnectedPairs,
1618 PairableInstUsers, PairableInstUserMap, ChosenPairs,
1619 BestTree, BestMaxDepth, BestEffSize, ChoiceRange,
1622 // A tree has been chosen (or not) at this point. If no tree was
1623 // chosen, then this instruction, I, cannot be paired (and is no longer
1626 DEBUG(if (BestTree.size() > 0)
1627 dbgs() << "BBV: selected pairs in the best tree for: "
1628 << *cast<Instruction>(*I) << "\n");
1630 for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
1631 SE2 = BestTree.end(); S != SE2; ++S) {
1632 // Insert the members of this tree into the list of chosen pairs.
1633 ChosenPairs.insert(ValuePair(S->first, S->second));
1634 DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
1635 *S->second << "\n");
1637 // Remove all candidate pairs that have values in the chosen tree.
1638 for (std::multimap<Value *, Value *>::iterator K =
1639 CandidatePairs.begin(); K != CandidatePairs.end();) {
1640 if (K->first == S->first || K->second == S->first ||
1641 K->second == S->second || K->first == S->second) {
1642 // Don't remove the actual pair chosen so that it can be used
1643 // in subsequent tree selections.
1644 if (!(K->first == S->first && K->second == S->second))
1645 CandidatePairs.erase(K++);
1655 DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
1658 std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
1663 return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
1664 (n > 0 ? "." + utostr(n) : "")).str();
1667 // Returns the value that is to be used as the pointer input to the vector
1668 // instruction that fuses I with J.
1669 Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
1670 Instruction *I, Instruction *J, unsigned o,
1671 bool FlipMemInputs) {
1673 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
1674 int64_t OffsetInElmts;
1676 // Note: the analysis might fail here, that is why FlipMemInputs has
1677 // been precomputed (OffsetInElmts must be unused here).
1678 (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
1679 IAddressSpace, JAddressSpace,
1682 // The pointer value is taken to be the one with the lowest offset.
1684 if (!FlipMemInputs) {
1690 Type *ArgTypeI = cast<PointerType>(IPtr->getType())->getElementType();
1691 Type *ArgTypeJ = cast<PointerType>(JPtr->getType())->getElementType();
1692 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
1693 Type *VArgPtrType = PointerType::get(VArgType,
1694 cast<PointerType>(IPtr->getType())->getAddressSpace());
1695 return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
1696 /* insert before */ FlipMemInputs ? J : I);
1699 void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
1700 unsigned MaskOffset, unsigned NumInElem,
1701 unsigned NumInElem1, unsigned IdxOffset,
1702 std::vector<Constant*> &Mask) {
1703 unsigned NumElem1 = cast<VectorType>(J->getType())->getNumElements();
1704 for (unsigned v = 0; v < NumElem1; ++v) {
1705 int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
1707 Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
1709 unsigned mm = m + (int) IdxOffset;
1710 if (m >= (int) NumInElem1)
1711 mm += (int) NumInElem;
1713 Mask[v+MaskOffset] =
1714 ConstantInt::get(Type::getInt32Ty(Context), mm);
1719 // Returns the value that is to be used as the vector-shuffle mask to the
1720 // vector instruction that fuses I with J.
1721 Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
1722 Instruction *I, Instruction *J) {
1723 // This is the shuffle mask. We need to append the second
1724 // mask to the first, and the numbers need to be adjusted.
1726 Type *ArgTypeI = I->getType();
1727 Type *ArgTypeJ = J->getType();
1728 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
1730 unsigned NumElemI = cast<VectorType>(ArgTypeI)->getNumElements();
1732 // Get the total number of elements in the fused vector type.
1733 // By definition, this must equal the number of elements in
1735 unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
1736 std::vector<Constant*> Mask(NumElem);
1738 Type *OpTypeI = I->getOperand(0)->getType();
1739 unsigned NumInElemI = cast<VectorType>(OpTypeI)->getNumElements();
1740 Type *OpTypeJ = J->getOperand(0)->getType();
1741 unsigned NumInElemJ = cast<VectorType>(OpTypeJ)->getNumElements();
1743 // The fused vector will be:
1744 // -----------------------------------------------------
1745 // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
1746 // -----------------------------------------------------
1747 // from which we'll extract NumElem total elements (where the first NumElemI
1748 // of them come from the mask in I and the remainder come from the mask
1751 // For the mask from the first pair...
1752 fillNewShuffleMask(Context, I, 0, NumInElemJ, NumInElemI,
1755 // For the mask from the second pair...
1756 fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
1759 return ConstantVector::get(Mask);
1762 bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
1763 Instruction *J, unsigned o, Value *&LOp,
1765 Type *ArgTypeL, Type *ArgTypeH,
1767 bool ExpandedIEChain = false;
1768 if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
1769 // If we have a pure insertelement chain, then this can be rewritten
1770 // into a chain that directly builds the larger type.
1771 bool PureChain = true;
1772 InsertElementInst *LIENext = LIE;
1774 if (!isa<UndefValue>(LIENext->getOperand(0)) &&
1775 !isa<InsertElementInst>(LIENext->getOperand(0))) {
1780 dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
1783 SmallVector<Value *, 8> VectElemts(numElemL,
1784 UndefValue::get(ArgTypeL->getScalarType()));
1785 InsertElementInst *LIENext = LIE;
1788 cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
1789 VectElemts[Idx] = LIENext->getOperand(1);
1791 dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
1794 Value *LIEPrev = UndefValue::get(ArgTypeH);
1795 for (unsigned i = 0; i < numElemL; ++i) {
1796 if (isa<UndefValue>(VectElemts[i])) continue;
1797 LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
1798 ConstantInt::get(Type::getInt32Ty(Context),
1800 getReplacementName(I, true, o, i+1));
1801 LIENext->insertBefore(J);
1805 LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
1806 ExpandedIEChain = true;
1810 return ExpandedIEChain;
1813 // Returns the value to be used as the specified operand of the vector
1814 // instruction that fuses I with J.
1815 Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
1816 Instruction *J, unsigned o, bool FlipMemInputs) {
1817 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
1818 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
1820 // Compute the fused vector type for this operand
1821 Type *ArgTypeI = I->getOperand(o)->getType();
1822 Type *ArgTypeJ = J->getOperand(o)->getType();
1823 VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
1825 Instruction *L = I, *H = J;
1826 Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
1827 if (FlipMemInputs) {
1830 ArgTypeL = ArgTypeJ;
1831 ArgTypeH = ArgTypeI;
1835 if (ArgTypeL->isVectorTy())
1836 numElemL = cast<VectorType>(ArgTypeL)->getNumElements();
1841 if (ArgTypeH->isVectorTy())
1842 numElemH = cast<VectorType>(ArgTypeH)->getNumElements();
1846 Value *LOp = L->getOperand(o);
1847 Value *HOp = H->getOperand(o);
1848 unsigned numElem = VArgType->getNumElements();
1850 // First, we check if we can reuse the "original" vector outputs (if these
1851 // exist). We might need a shuffle.
1852 ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
1853 ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
1854 ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
1855 ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
1857 // FIXME: If we're fusing shuffle instructions, then we can't apply this
1858 // optimization. The input vectors to the shuffle might be a different
1859 // length from the shuffle outputs. Unfortunately, the replacement
1860 // shuffle mask has already been formed, and the mask entries are sensitive
1861 // to the sizes of the inputs.
1862 bool IsSizeChangeShuffle =
1863 isa<ShuffleVectorInst>(L) &&
1864 (LOp->getType() != L->getType() || HOp->getType() != H->getType());
1866 if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
1867 // We can have at most two unique vector inputs.
1868 bool CanUseInputs = true;
1871 I1 = LEE->getOperand(0);
1873 I1 = LSV->getOperand(0);
1874 I2 = LSV->getOperand(1);
1875 if (I2 == I1 || isa<UndefValue>(I2))
1880 Value *I3 = HEE->getOperand(0);
1881 if (!I2 && I3 != I1)
1883 else if (I3 != I1 && I3 != I2)
1884 CanUseInputs = false;
1886 Value *I3 = HSV->getOperand(0);
1887 if (!I2 && I3 != I1)
1889 else if (I3 != I1 && I3 != I2)
1890 CanUseInputs = false;
1893 Value *I4 = HSV->getOperand(1);
1894 if (!isa<UndefValue>(I4)) {
1895 if (!I2 && I4 != I1)
1897 else if (I4 != I1 && I4 != I2)
1898 CanUseInputs = false;
1905 cast<VectorType>(cast<Instruction>(LOp)->getOperand(0)->getType())
1908 cast<VectorType>(cast<Instruction>(HOp)->getOperand(0)->getType())
1911 // We have one or two input vectors. We need to map each index of the
1912 // operands to the index of the original vector.
1913 SmallVector<std::pair<int, int>, 8> II(numElem);
1914 for (unsigned i = 0; i < numElemL; ++i) {
1918 cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
1919 INum = LEE->getOperand(0) == I1 ? 0 : 1;
1921 Idx = LSV->getMaskValue(i);
1922 if (Idx < (int) LOpElem) {
1923 INum = LSV->getOperand(0) == I1 ? 0 : 1;
1926 INum = LSV->getOperand(1) == I1 ? 0 : 1;
1930 II[i] = std::pair<int, int>(Idx, INum);
1932 for (unsigned i = 0; i < numElemH; ++i) {
1936 cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
1937 INum = HEE->getOperand(0) == I1 ? 0 : 1;
1939 Idx = HSV->getMaskValue(i);
1940 if (Idx < (int) HOpElem) {
1941 INum = HSV->getOperand(0) == I1 ? 0 : 1;
1944 INum = HSV->getOperand(1) == I1 ? 0 : 1;
1948 II[i + numElemL] = std::pair<int, int>(Idx, INum);
1951 // We now have an array which tells us from which index of which
1952 // input vector each element of the operand comes.
1953 VectorType *I1T = cast<VectorType>(I1->getType());
1954 unsigned I1Elem = I1T->getNumElements();
1957 // In this case there is only one underlying vector input. Check for
1958 // the trivial case where we can use the input directly.
1959 if (I1Elem == numElem) {
1960 bool ElemInOrder = true;
1961 for (unsigned i = 0; i < numElem; ++i) {
1962 if (II[i].first != (int) i && II[i].first != -1) {
1963 ElemInOrder = false;
1972 // A shuffle is needed.
1973 std::vector<Constant *> Mask(numElem);
1974 for (unsigned i = 0; i < numElem; ++i) {
1975 int Idx = II[i].first;
1977 Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
1979 Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
1983 new ShuffleVectorInst(I1, UndefValue::get(I1T),
1984 ConstantVector::get(Mask),
1985 getReplacementName(I, true, o));
1990 VectorType *I2T = cast<VectorType>(I2->getType());
1991 unsigned I2Elem = I2T->getNumElements();
1993 // This input comes from two distinct vectors. The first step is to
1994 // make sure that both vectors are the same length. If not, the
1995 // smaller one will need to grow before they can be shuffled together.
1996 if (I1Elem < I2Elem) {
1997 std::vector<Constant *> Mask(I2Elem);
1999 for (; v < I1Elem; ++v)
2000 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2001 for (; v < I2Elem; ++v)
2002 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2004 Instruction *NewI1 =
2005 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2006 ConstantVector::get(Mask),
2007 getReplacementName(I, true, o, 1));
2008 NewI1->insertBefore(J);
2012 } else if (I1Elem > I2Elem) {
2013 std::vector<Constant *> Mask(I1Elem);
2015 for (; v < I2Elem; ++v)
2016 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2017 for (; v < I1Elem; ++v)
2018 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2020 Instruction *NewI2 =
2021 new ShuffleVectorInst(I2, UndefValue::get(I2T),
2022 ConstantVector::get(Mask),
2023 getReplacementName(I, true, o, 1));
2024 NewI2->insertBefore(J);
2030 // Now that both I1 and I2 are the same length we can shuffle them
2031 // together (and use the result).
2032 std::vector<Constant *> Mask(numElem);
2033 for (unsigned v = 0; v < numElem; ++v) {
2034 if (II[v].first == -1) {
2035 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2037 int Idx = II[v].first + II[v].second * I1Elem;
2038 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2042 Instruction *NewOp =
2043 new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
2044 getReplacementName(I, true, o));
2045 NewOp->insertBefore(J);
2050 Type *ArgType = ArgTypeL;
2051 if (numElemL < numElemH) {
2052 if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
2053 ArgTypeL, VArgType, 1)) {
2054 // This is another short-circuit case: we're combining a scalar into
2055 // a vector that is formed by an IE chain. We've just expanded the IE
2056 // chain, now insert the scalar and we're done.
2058 Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
2059 getReplacementName(I, true, o));
2062 } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
2064 // The two vector inputs to the shuffle must be the same length,
2065 // so extend the smaller vector to be the same length as the larger one.
2069 std::vector<Constant *> Mask(numElemH);
2071 for (; v < numElemL; ++v)
2072 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2073 for (; v < numElemH; ++v)
2074 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2076 NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2077 ConstantVector::get(Mask),
2078 getReplacementName(I, true, o, 1));
2080 NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2081 getReplacementName(I, true, o, 1));
2084 NLOp->insertBefore(J);
2089 } else if (numElemL > numElemH) {
2090 if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2091 ArgTypeH, VArgType)) {
2093 InsertElementInst::Create(LOp, HOp,
2094 ConstantInt::get(Type::getInt32Ty(Context),
2096 getReplacementName(I, true, o));
2099 } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2103 std::vector<Constant *> Mask(numElemL);
2105 for (; v < numElemH; ++v)
2106 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2107 for (; v < numElemL; ++v)
2108 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2110 NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2111 ConstantVector::get(Mask),
2112 getReplacementName(I, true, o, 1));
2114 NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2115 getReplacementName(I, true, o, 1));
2118 NHOp->insertBefore(J);
2123 if (ArgType->isVectorTy()) {
2124 unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
2125 std::vector<Constant*> Mask(numElem);
2126 for (unsigned v = 0; v < numElem; ++v) {
2128 // If the low vector was expanded, we need to skip the extra
2129 // undefined entries.
2130 if (v >= numElemL && numElemH > numElemL)
2131 Idx += (numElemH - numElemL);
2132 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2135 Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2136 ConstantVector::get(Mask),
2137 getReplacementName(I, true, o));
2138 BV->insertBefore(J);
2142 Instruction *BV1 = InsertElementInst::Create(
2143 UndefValue::get(VArgType), LOp, CV0,
2144 getReplacementName(I, true, o, 1));
2145 BV1->insertBefore(I);
2146 Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
2147 getReplacementName(I, true, o, 2));
2148 BV2->insertBefore(J);
2152 // This function creates an array of values that will be used as the inputs
2153 // to the vector instruction that fuses I with J.
2154 void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
2155 Instruction *I, Instruction *J,
2156 SmallVector<Value *, 3> &ReplacedOperands,
2157 bool FlipMemInputs) {
2158 unsigned NumOperands = I->getNumOperands();
2160 for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
2161 // Iterate backward so that we look at the store pointer
2162 // first and know whether or not we need to flip the inputs.
2164 if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
2165 // This is the pointer for a load/store instruction.
2166 ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o,
2169 } else if (isa<CallInst>(I)) {
2170 Function *F = cast<CallInst>(I)->getCalledFunction();
2171 unsigned IID = F->getIntrinsicID();
2172 if (o == NumOperands-1) {
2173 BasicBlock &BB = *I->getParent();
2175 Module *M = BB.getParent()->getParent();
2176 Type *ArgTypeI = I->getType();
2177 Type *ArgTypeJ = J->getType();
2178 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2180 ReplacedOperands[o] = Intrinsic::getDeclaration(M,
2181 (Intrinsic::ID) IID, VArgType);
2183 } else if (IID == Intrinsic::powi && o == 1) {
2184 // The second argument of powi is a single integer and we've already
2185 // checked that both arguments are equal. As a result, we just keep
2186 // I's second argument.
2187 ReplacedOperands[o] = I->getOperand(o);
2190 } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2191 ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2195 ReplacedOperands[o] =
2196 getReplacementInput(Context, I, J, o, FlipMemInputs);
2200 // This function creates two values that represent the outputs of the
2201 // original I and J instructions. These are generally vector shuffles
2202 // or extracts. In many cases, these will end up being unused and, thus,
2203 // eliminated by later passes.
2204 void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2205 Instruction *J, Instruction *K,
2206 Instruction *&InsertionPt,
2207 Instruction *&K1, Instruction *&K2,
2208 bool FlipMemInputs) {
2209 if (isa<StoreInst>(I)) {
2210 AA->replaceWithNewValue(I, K);
2211 AA->replaceWithNewValue(J, K);
2213 Type *IType = I->getType();
2214 Type *JType = J->getType();
2216 VectorType *VType = getVecTypeForPair(IType, JType);
2217 unsigned numElem = VType->getNumElements();
2219 unsigned numElemI, numElemJ;
2220 if (IType->isVectorTy())
2221 numElemI = cast<VectorType>(IType)->getNumElements();
2225 if (JType->isVectorTy())
2226 numElemJ = cast<VectorType>(JType)->getNumElements();
2230 if (IType->isVectorTy()) {
2231 std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
2232 for (unsigned v = 0; v < numElemI; ++v) {
2233 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2234 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
2237 K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2238 ConstantVector::get(
2239 FlipMemInputs ? Mask2 : Mask1),
2240 getReplacementName(K, false, 1));
2242 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2243 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2244 K1 = ExtractElementInst::Create(K, FlipMemInputs ? CV1 : CV0,
2245 getReplacementName(K, false, 1));
2248 if (JType->isVectorTy()) {
2249 std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
2250 for (unsigned v = 0; v < numElemJ; ++v) {
2251 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2252 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
2255 K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2256 ConstantVector::get(
2257 FlipMemInputs ? Mask1 : Mask2),
2258 getReplacementName(K, false, 2));
2260 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2261 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
2262 K2 = ExtractElementInst::Create(K, FlipMemInputs ? CV0 : CV1,
2263 getReplacementName(K, false, 2));
2267 K2->insertAfter(K1);
2272 // Move all uses of the function I (including pairing-induced uses) after J.
2273 bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2274 std::multimap<Value *, Value *> &LoadMoveSet,
2275 Instruction *I, Instruction *J) {
2276 // Skip to the first instruction past I.
2277 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2279 DenseSet<Value *> Users;
2280 AliasSetTracker WriteSet(*AA);
2281 for (; cast<Instruction>(L) != J; ++L)
2282 (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet);
2284 assert(cast<Instruction>(L) == J &&
2285 "Tracking has not proceeded far enough to check for dependencies");
2286 // If J is now in the use set of I, then trackUsesOfI will return true
2287 // and we have a dependency cycle (and the fusing operation must abort).
2288 return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSet);
2291 // Move all uses of the function I (including pairing-induced uses) after J.
2292 void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2293 std::multimap<Value *, Value *> &LoadMoveSet,
2294 Instruction *&InsertionPt,
2295 Instruction *I, Instruction *J) {
2296 // Skip to the first instruction past I.
2297 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2299 DenseSet<Value *> Users;
2300 AliasSetTracker WriteSet(*AA);
2301 for (; cast<Instruction>(L) != J;) {
2302 if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet)) {
2303 // Move this instruction
2304 Instruction *InstToMove = L; ++L;
2306 DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2307 " to after " << *InsertionPt << "\n");
2308 InstToMove->removeFromParent();
2309 InstToMove->insertAfter(InsertionPt);
2310 InsertionPt = InstToMove;
2317 // Collect all load instruction that are in the move set of a given first
2318 // pair member. These loads depend on the first instruction, I, and so need
2319 // to be moved after J (the second instruction) when the pair is fused.
2320 void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2321 DenseMap<Value *, Value *> &ChosenPairs,
2322 std::multimap<Value *, Value *> &LoadMoveSet,
2324 // Skip to the first instruction past I.
2325 BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
2327 DenseSet<Value *> Users;
2328 AliasSetTracker WriteSet(*AA);
2330 // Note: We cannot end the loop when we reach J because J could be moved
2331 // farther down the use chain by another instruction pairing. Also, J
2332 // could be before I if this is an inverted input.
2333 for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
2334 if (trackUsesOfI(Users, WriteSet, I, L)) {
2335 if (L->mayReadFromMemory())
2336 LoadMoveSet.insert(ValuePair(L, I));
2341 // In cases where both load/stores and the computation of their pointers
2342 // are chosen for vectorization, we can end up in a situation where the
2343 // aliasing analysis starts returning different query results as the
2344 // process of fusing instruction pairs continues. Because the algorithm
2345 // relies on finding the same use trees here as were found earlier, we'll
2346 // need to precompute the necessary aliasing information here and then
2347 // manually update it during the fusion process.
2348 void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2349 std::vector<Value *> &PairableInsts,
2350 DenseMap<Value *, Value *> &ChosenPairs,
2351 std::multimap<Value *, Value *> &LoadMoveSet) {
2352 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2353 PIE = PairableInsts.end(); PI != PIE; ++PI) {
2354 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2355 if (P == ChosenPairs.end()) continue;
2357 Instruction *I = cast<Instruction>(P->first);
2358 collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet, I);
2362 // As with the aliasing information, SCEV can also change because of
2363 // vectorization. This information is used to compute relative pointer
2364 // offsets; the necessary information will be cached here prior to
2366 void BBVectorize::collectPtrInfo(std::vector<Value *> &PairableInsts,
2367 DenseMap<Value *, Value *> &ChosenPairs,
2368 DenseSet<Value *> &LowPtrInsts) {
2369 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2370 PIE = PairableInsts.end(); PI != PIE; ++PI) {
2371 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2372 if (P == ChosenPairs.end()) continue;
2374 Instruction *I = cast<Instruction>(P->first);
2375 Instruction *J = cast<Instruction>(P->second);
2377 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
2381 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
2382 int64_t OffsetInElmts;
2383 if (!getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
2384 IAddressSpace, JAddressSpace,
2385 OffsetInElmts) || abs64(OffsetInElmts) != 1)
2386 llvm_unreachable("Pre-fusion pointer analysis failed");
2388 Value *LowPI = (OffsetInElmts > 0) ? I : J;
2389 LowPtrInsts.insert(LowPI);
2393 // When the first instruction in each pair is cloned, it will inherit its
2394 // parent's metadata. This metadata must be combined with that of the other
2395 // instruction in a safe way.
2396 void BBVectorize::combineMetadata(Instruction *K, const Instruction *J) {
2397 SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
2398 K->getAllMetadataOtherThanDebugLoc(Metadata);
2399 for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
2400 unsigned Kind = Metadata[i].first;
2401 MDNode *JMD = J->getMetadata(Kind);
2402 MDNode *KMD = Metadata[i].second;
2406 K->setMetadata(Kind, 0); // Remove unknown metadata
2408 case LLVMContext::MD_tbaa:
2409 K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2411 case LLVMContext::MD_fpmath:
2412 K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2418 // This function fuses the chosen instruction pairs into vector instructions,
2419 // taking care preserve any needed scalar outputs and, then, it reorders the
2420 // remaining instructions as needed (users of the first member of the pair
2421 // need to be moved to after the location of the second member of the pair
2422 // because the vector instruction is inserted in the location of the pair's
2424 void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2425 std::vector<Value *> &PairableInsts,
2426 DenseMap<Value *, Value *> &ChosenPairs) {
2427 LLVMContext& Context = BB.getContext();
2429 // During the vectorization process, the order of the pairs to be fused
2430 // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
2431 // list. After a pair is fused, the flipped pair is removed from the list.
2432 std::vector<ValuePair> FlippedPairs;
2433 FlippedPairs.reserve(ChosenPairs.size());
2434 for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
2435 E = ChosenPairs.end(); P != E; ++P)
2436 FlippedPairs.push_back(ValuePair(P->second, P->first));
2437 for (std::vector<ValuePair>::iterator P = FlippedPairs.begin(),
2438 E = FlippedPairs.end(); P != E; ++P)
2439 ChosenPairs.insert(*P);
2441 std::multimap<Value *, Value *> LoadMoveSet;
2442 collectLoadMoveSet(BB, PairableInsts, ChosenPairs, LoadMoveSet);
2444 DenseSet<Value *> LowPtrInsts;
2445 collectPtrInfo(PairableInsts, ChosenPairs, LowPtrInsts);
2447 DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
2449 for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
2450 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
2451 if (P == ChosenPairs.end()) {
2456 if (getDepthFactor(P->first) == 0) {
2457 // These instructions are not really fused, but are tracked as though
2458 // they are. Any case in which it would be interesting to fuse them
2459 // will be taken care of by InstCombine.
2465 Instruction *I = cast<Instruction>(P->first),
2466 *J = cast<Instruction>(P->second);
2468 DEBUG(dbgs() << "BBV: fusing: " << *I <<
2469 " <-> " << *J << "\n");
2471 // Remove the pair and flipped pair from the list.
2472 DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
2473 assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
2474 ChosenPairs.erase(FP);
2475 ChosenPairs.erase(P);
2477 if (!canMoveUsesOfIAfterJ(BB, LoadMoveSet, I, J)) {
2478 DEBUG(dbgs() << "BBV: fusion of: " << *I <<
2480 " aborted because of non-trivial dependency cycle\n");
2486 bool FlipMemInputs = false;
2487 if (isa<LoadInst>(I) || isa<StoreInst>(I))
2488 FlipMemInputs = (LowPtrInsts.find(I) == LowPtrInsts.end());
2490 unsigned NumOperands = I->getNumOperands();
2491 SmallVector<Value *, 3> ReplacedOperands(NumOperands);
2492 getReplacementInputsForPair(Context, I, J, ReplacedOperands,
2495 // Make a copy of the original operation, change its type to the vector
2496 // type and replace its operands with the vector operands.
2497 Instruction *K = I->clone();
2498 if (I->hasName()) K->takeName(I);
2500 if (!isa<StoreInst>(K))
2501 K->mutateType(getVecTypeForPair(I->getType(), J->getType()));
2503 combineMetadata(K, J);
2505 for (unsigned o = 0; o < NumOperands; ++o)
2506 K->setOperand(o, ReplacedOperands[o]);
2508 // If we've flipped the memory inputs, make sure that we take the correct
2510 if (FlipMemInputs) {
2511 if (isa<StoreInst>(K))
2512 cast<StoreInst>(K)->setAlignment(cast<StoreInst>(J)->getAlignment());
2514 cast<LoadInst>(K)->setAlignment(cast<LoadInst>(J)->getAlignment());
2519 // Instruction insertion point:
2520 Instruction *InsertionPt = K;
2521 Instruction *K1 = 0, *K2 = 0;
2522 replaceOutputsOfPair(Context, I, J, K, InsertionPt, K1, K2,
2525 // The use tree of the first original instruction must be moved to after
2526 // the location of the second instruction. The entire use tree of the
2527 // first instruction is disjoint from the input tree of the second
2528 // (by definition), and so commutes with it.
2530 moveUsesOfIAfterJ(BB, LoadMoveSet, InsertionPt, I, J);
2532 if (!isa<StoreInst>(I)) {
2533 I->replaceAllUsesWith(K1);
2534 J->replaceAllUsesWith(K2);
2535 AA->replaceWithNewValue(I, K1);
2536 AA->replaceWithNewValue(J, K2);
2539 // Instructions that may read from memory may be in the load move set.
2540 // Once an instruction is fused, we no longer need its move set, and so
2541 // the values of the map never need to be updated. However, when a load
2542 // is fused, we need to merge the entries from both instructions in the
2543 // pair in case those instructions were in the move set of some other
2544 // yet-to-be-fused pair. The loads in question are the keys of the map.
2545 if (I->mayReadFromMemory()) {
2546 std::vector<ValuePair> NewSetMembers;
2547 VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
2548 VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
2549 for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
2550 N != IPairRange.second; ++N)
2551 NewSetMembers.push_back(ValuePair(K, N->second));
2552 for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
2553 N != JPairRange.second; ++N)
2554 NewSetMembers.push_back(ValuePair(K, N->second));
2555 for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
2556 AE = NewSetMembers.end(); A != AE; ++A)
2557 LoadMoveSet.insert(*A);
2560 // Before removing I, set the iterator to the next instruction.
2561 PI = llvm::next(BasicBlock::iterator(I));
2562 if (cast<Instruction>(PI) == J)
2567 I->eraseFromParent();
2568 J->eraseFromParent();
2571 DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
2575 char BBVectorize::ID = 0;
2576 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
2577 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
2578 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2579 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
2580 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2581 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
2583 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
2584 return new BBVectorize(C);
2588 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
2589 BBVectorize BBVectorizer(P, C);
2590 return BBVectorizer.vectorizeBB(BB);
2593 //===----------------------------------------------------------------------===//
2594 VectorizeConfig::VectorizeConfig() {
2595 VectorBits = ::VectorBits;
2596 VectorizeBools = !::NoBools;
2597 VectorizeInts = !::NoInts;
2598 VectorizeFloats = !::NoFloats;
2599 VectorizePointers = !::NoPointers;
2600 VectorizeCasts = !::NoCasts;
2601 VectorizeMath = !::NoMath;
2602 VectorizeFMA = !::NoFMA;
2603 VectorizeSelect = !::NoSelect;
2604 VectorizeCmp = !::NoCmp;
2605 VectorizeGEP = !::NoGEP;
2606 VectorizeMemOps = !::NoMemOps;
2607 AlignedOnly = ::AlignedOnly;
2608 ReqChainDepth= ::ReqChainDepth;
2609 SearchLimit = ::SearchLimit;
2610 MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
2611 SplatBreaksChain = ::SplatBreaksChain;
2612 MaxInsts = ::MaxInsts;
2613 MaxIter = ::MaxIter;
2614 Pow2LenOnly = ::Pow2LenOnly;
2615 NoMemOpBoost = ::NoMemOpBoost;
2616 FastDep = ::FastDep;