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 #include "llvm/Transforms/Vectorize.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AliasSetTracker.h"
28 #include "llvm/Analysis/GlobalsModRef.h"
29 #include "llvm/Analysis/ScalarEvolution.h"
30 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
31 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
32 #include "llvm/Analysis/TargetLibraryInfo.h"
33 #include "llvm/Analysis/TargetTransformInfo.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Dominators.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/IntrinsicInst.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/LLVMContext.h"
44 #include "llvm/IR/Metadata.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/IR/ValueHandle.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Transforms/Utils/Local.h"
56 #define DEBUG_TYPE BBV_NAME
59 IgnoreTargetInfo("bb-vectorize-ignore-target-info", cl::init(false),
60 cl::Hidden, cl::desc("Ignore target information"));
62 static cl::opt<unsigned>
63 ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
64 cl::desc("The required chain depth for vectorization"));
67 UseChainDepthWithTI("bb-vectorize-use-chain-depth", cl::init(false),
68 cl::Hidden, cl::desc("Use the chain depth requirement with"
69 " target information"));
71 static cl::opt<unsigned>
72 SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
73 cl::desc("The maximum search distance for instruction pairs"));
76 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
77 cl::desc("Replicating one element to a pair breaks the chain"));
79 static cl::opt<unsigned>
80 VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
81 cl::desc("The size of the native vector registers"));
83 static cl::opt<unsigned>
84 MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
85 cl::desc("The maximum number of pairing iterations"));
88 Pow2LenOnly("bb-vectorize-pow2-len-only", cl::init(false), cl::Hidden,
89 cl::desc("Don't try to form non-2^n-length vectors"));
91 static cl::opt<unsigned>
92 MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
93 cl::desc("The maximum number of pairable instructions per group"));
95 static cl::opt<unsigned>
96 MaxPairs("bb-vectorize-max-pairs-per-group", cl::init(3000), cl::Hidden,
97 cl::desc("The maximum number of candidate instruction pairs per group"));
99 static cl::opt<unsigned>
100 MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
101 cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
102 " a full cycle check"));
105 NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
106 cl::desc("Don't try to vectorize boolean (i1) values"));
109 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
110 cl::desc("Don't try to vectorize integer values"));
113 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
114 cl::desc("Don't try to vectorize floating-point values"));
116 // FIXME: This should default to false once pointer vector support works.
118 NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
119 cl::desc("Don't try to vectorize pointer values"));
122 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
123 cl::desc("Don't try to vectorize casting (conversion) operations"));
126 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
127 cl::desc("Don't try to vectorize floating-point math intrinsics"));
130 NoBitManipulation("bb-vectorize-no-bitmanip", cl::init(false), cl::Hidden,
131 cl::desc("Don't try to vectorize BitManipulation intrinsics"));
134 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
135 cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
138 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
139 cl::desc("Don't try to vectorize select instructions"));
142 NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
143 cl::desc("Don't try to vectorize comparison instructions"));
146 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
147 cl::desc("Don't try to vectorize getelementptr instructions"));
150 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
151 cl::desc("Don't try to vectorize loads and stores"));
154 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
155 cl::desc("Only generate aligned loads and stores"));
158 NoMemOpBoost("bb-vectorize-no-mem-op-boost",
159 cl::init(false), cl::Hidden,
160 cl::desc("Don't boost the chain-depth contribution of loads and stores"));
163 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
164 cl::desc("Use a fast instruction dependency analysis"));
168 DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
169 cl::init(false), cl::Hidden,
170 cl::desc("When debugging is enabled, output information on the"
171 " instruction-examination process"));
173 DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
174 cl::init(false), cl::Hidden,
175 cl::desc("When debugging is enabled, output information on the"
176 " candidate-selection process"));
178 DebugPairSelection("bb-vectorize-debug-pair-selection",
179 cl::init(false), cl::Hidden,
180 cl::desc("When debugging is enabled, output information on the"
181 " pair-selection process"));
183 DebugCycleCheck("bb-vectorize-debug-cycle-check",
184 cl::init(false), cl::Hidden,
185 cl::desc("When debugging is enabled, output information on the"
186 " cycle-checking process"));
189 PrintAfterEveryPair("bb-vectorize-debug-print-after-every-pair",
190 cl::init(false), cl::Hidden,
191 cl::desc("When debugging is enabled, dump the basic block after"
192 " every pair is fused"));
195 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
198 struct BBVectorize : public BasicBlockPass {
199 static char ID; // Pass identification, replacement for typeid
201 const VectorizeConfig Config;
203 BBVectorize(const VectorizeConfig &C = VectorizeConfig())
204 : BasicBlockPass(ID), Config(C) {
205 initializeBBVectorizePass(*PassRegistry::getPassRegistry());
208 BBVectorize(Pass *P, Function &F, const VectorizeConfig &C)
209 : BasicBlockPass(ID), Config(C) {
210 AA = &P->getAnalysis<AAResultsWrapperPass>().getAAResults();
211 DT = &P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
212 SE = &P->getAnalysis<ScalarEvolutionWrapperPass>().getSE();
213 TLI = &P->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
214 TTI = IgnoreTargetInfo
216 : &P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
219 typedef std::pair<Value *, Value *> ValuePair;
220 typedef std::pair<ValuePair, int> ValuePairWithCost;
221 typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
222 typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
223 typedef std::pair<VPPair, unsigned> VPPairWithType;
228 const TargetLibraryInfo *TLI;
229 const TargetTransformInfo *TTI;
231 // FIXME: const correct?
233 bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
235 bool getCandidatePairs(BasicBlock &BB,
236 BasicBlock::iterator &Start,
237 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
238 DenseSet<ValuePair> &FixedOrderPairs,
239 DenseMap<ValuePair, int> &CandidatePairCostSavings,
240 std::vector<Value *> &PairableInsts, bool NonPow2Len);
242 // FIXME: The current implementation does not account for pairs that
243 // are connected in multiple ways. For example:
244 // C1 = A1 / A2; C2 = A2 / A1 (which may be both direct and a swap)
245 enum PairConnectionType {
246 PairConnectionDirect,
251 void computeConnectedPairs(
252 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
253 DenseSet<ValuePair> &CandidatePairsSet,
254 std::vector<Value *> &PairableInsts,
255 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
256 DenseMap<VPPair, unsigned> &PairConnectionTypes);
258 void buildDepMap(BasicBlock &BB,
259 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
260 std::vector<Value *> &PairableInsts,
261 DenseSet<ValuePair> &PairableInstUsers);
263 void choosePairs(DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
264 DenseSet<ValuePair> &CandidatePairsSet,
265 DenseMap<ValuePair, int> &CandidatePairCostSavings,
266 std::vector<Value *> &PairableInsts,
267 DenseSet<ValuePair> &FixedOrderPairs,
268 DenseMap<VPPair, unsigned> &PairConnectionTypes,
269 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
270 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
271 DenseSet<ValuePair> &PairableInstUsers,
272 DenseMap<Value *, Value *>& ChosenPairs);
274 void fuseChosenPairs(BasicBlock &BB,
275 std::vector<Value *> &PairableInsts,
276 DenseMap<Value *, Value *>& ChosenPairs,
277 DenseSet<ValuePair> &FixedOrderPairs,
278 DenseMap<VPPair, unsigned> &PairConnectionTypes,
279 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
280 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps);
283 bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
285 bool areInstsCompatible(Instruction *I, Instruction *J,
286 bool IsSimpleLoadStore, bool NonPow2Len,
287 int &CostSavings, int &FixedOrder);
289 bool trackUsesOfI(DenseSet<Value *> &Users,
290 AliasSetTracker &WriteSet, Instruction *I,
291 Instruction *J, bool UpdateUsers = true,
292 DenseSet<ValuePair> *LoadMoveSetPairs = nullptr);
294 void computePairsConnectedTo(
295 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
296 DenseSet<ValuePair> &CandidatePairsSet,
297 std::vector<Value *> &PairableInsts,
298 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
299 DenseMap<VPPair, unsigned> &PairConnectionTypes,
302 bool pairsConflict(ValuePair P, ValuePair Q,
303 DenseSet<ValuePair> &PairableInstUsers,
304 DenseMap<ValuePair, std::vector<ValuePair> >
305 *PairableInstUserMap = nullptr,
306 DenseSet<VPPair> *PairableInstUserPairSet = nullptr);
308 bool pairWillFormCycle(ValuePair P,
309 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUsers,
310 DenseSet<ValuePair> &CurrentPairs);
313 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
314 std::vector<Value *> &PairableInsts,
315 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
316 DenseSet<ValuePair> &PairableInstUsers,
317 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
318 DenseSet<VPPair> &PairableInstUserPairSet,
319 DenseMap<Value *, Value *> &ChosenPairs,
320 DenseMap<ValuePair, size_t> &DAG,
321 DenseSet<ValuePair> &PrunedDAG, ValuePair J,
324 void buildInitialDAGFor(
325 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
326 DenseSet<ValuePair> &CandidatePairsSet,
327 std::vector<Value *> &PairableInsts,
328 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
329 DenseSet<ValuePair> &PairableInstUsers,
330 DenseMap<Value *, Value *> &ChosenPairs,
331 DenseMap<ValuePair, size_t> &DAG, ValuePair J);
334 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
335 DenseSet<ValuePair> &CandidatePairsSet,
336 DenseMap<ValuePair, int> &CandidatePairCostSavings,
337 std::vector<Value *> &PairableInsts,
338 DenseSet<ValuePair> &FixedOrderPairs,
339 DenseMap<VPPair, unsigned> &PairConnectionTypes,
340 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
341 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
342 DenseSet<ValuePair> &PairableInstUsers,
343 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
344 DenseSet<VPPair> &PairableInstUserPairSet,
345 DenseMap<Value *, Value *> &ChosenPairs,
346 DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
347 int &BestEffSize, Value *II, std::vector<Value *>&JJ,
350 Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
351 Instruction *J, unsigned o);
353 void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
354 unsigned MaskOffset, unsigned NumInElem,
355 unsigned NumInElem1, unsigned IdxOffset,
356 std::vector<Constant*> &Mask);
358 Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
361 bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
362 unsigned o, Value *&LOp, unsigned numElemL,
363 Type *ArgTypeL, Type *ArgTypeR, bool IBeforeJ,
364 unsigned IdxOff = 0);
366 Value *getReplacementInput(LLVMContext& Context, Instruction *I,
367 Instruction *J, unsigned o, bool IBeforeJ);
369 void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
370 Instruction *J, SmallVectorImpl<Value *> &ReplacedOperands,
373 void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
374 Instruction *J, Instruction *K,
375 Instruction *&InsertionPt, Instruction *&K1,
378 void collectPairLoadMoveSet(BasicBlock &BB,
379 DenseMap<Value *, Value *> &ChosenPairs,
380 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
381 DenseSet<ValuePair> &LoadMoveSetPairs,
384 void collectLoadMoveSet(BasicBlock &BB,
385 std::vector<Value *> &PairableInsts,
386 DenseMap<Value *, Value *> &ChosenPairs,
387 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
388 DenseSet<ValuePair> &LoadMoveSetPairs);
390 bool canMoveUsesOfIAfterJ(BasicBlock &BB,
391 DenseSet<ValuePair> &LoadMoveSetPairs,
392 Instruction *I, Instruction *J);
394 void moveUsesOfIAfterJ(BasicBlock &BB,
395 DenseSet<ValuePair> &LoadMoveSetPairs,
396 Instruction *&InsertionPt,
397 Instruction *I, Instruction *J);
399 bool vectorizeBB(BasicBlock &BB) {
400 if (skipOptnoneFunction(BB))
402 if (!DT->isReachableFromEntry(&BB)) {
403 DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
404 " in " << BB.getParent()->getName() << "\n");
408 DEBUG(if (TTI) dbgs() << "BBV: using target information\n");
410 bool changed = false;
411 // Iterate a sufficient number of times to merge types of size 1 bit,
412 // then 2 bits, then 4, etc. up to half of the target vector width of the
413 // target vector register.
416 (TTI || v <= Config.VectorBits) &&
417 (!Config.MaxIter || n <= Config.MaxIter);
419 DEBUG(dbgs() << "BBV: fusing loop #" << n <<
420 " for " << BB.getName() << " in " <<
421 BB.getParent()->getName() << "...\n");
422 if (vectorizePairs(BB))
428 if (changed && !Pow2LenOnly) {
430 for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
431 DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
432 n << " for " << BB.getName() << " in " <<
433 BB.getParent()->getName() << "...\n");
434 if (!vectorizePairs(BB, true)) break;
438 DEBUG(dbgs() << "BBV: done!\n");
442 bool runOnBasicBlock(BasicBlock &BB) override {
443 // OptimizeNone check deferred to vectorizeBB().
445 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
446 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
447 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
448 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
449 TTI = IgnoreTargetInfo
451 : &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
454 return vectorizeBB(BB);
457 void getAnalysisUsage(AnalysisUsage &AU) const override {
458 BasicBlockPass::getAnalysisUsage(AU);
459 AU.addRequired<AAResultsWrapperPass>();
460 AU.addRequired<DominatorTreeWrapperPass>();
461 AU.addRequired<ScalarEvolutionWrapperPass>();
462 AU.addRequired<TargetLibraryInfoWrapperPass>();
463 AU.addRequired<TargetTransformInfoWrapperPass>();
464 AU.addPreserved<DominatorTreeWrapperPass>();
465 AU.addPreserved<GlobalsAAWrapperPass>();
466 AU.addPreserved<ScalarEvolutionWrapperPass>();
467 AU.addPreserved<SCEVAAWrapperPass>();
468 AU.setPreservesCFG();
471 static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
472 assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
473 "Cannot form vector from incompatible scalar types");
474 Type *STy = ElemTy->getScalarType();
477 if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
478 numElem = VTy->getNumElements();
483 if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
484 numElem += VTy->getNumElements();
489 return VectorType::get(STy, numElem);
492 static inline void getInstructionTypes(Instruction *I,
493 Type *&T1, Type *&T2) {
494 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
495 // For stores, it is the value type, not the pointer type that matters
496 // because the value is what will come from a vector register.
498 Value *IVal = SI->getValueOperand();
499 T1 = IVal->getType();
504 if (CastInst *CI = dyn_cast<CastInst>(I))
509 if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
510 T2 = SI->getCondition()->getType();
511 } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
512 T2 = SI->getOperand(0)->getType();
513 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
514 T2 = CI->getOperand(0)->getType();
518 // Returns the weight associated with the provided value. A chain of
519 // candidate pairs has a length given by the sum of the weights of its
520 // members (one weight per pair; the weight of each member of the pair
521 // is assumed to be the same). This length is then compared to the
522 // chain-length threshold to determine if a given chain is significant
523 // enough to be vectorized. The length is also used in comparing
524 // candidate chains where longer chains are considered to be better.
525 // Note: when this function returns 0, the resulting instructions are
526 // not actually fused.
527 inline size_t getDepthFactor(Value *V) {
528 // InsertElement and ExtractElement have a depth factor of zero. This is
529 // for two reasons: First, they cannot be usefully fused. Second, because
530 // the pass generates a lot of these, they can confuse the simple metric
531 // used to compare the dags in the next iteration. Thus, giving them a
532 // weight of zero allows the pass to essentially ignore them in
533 // subsequent iterations when looking for vectorization opportunities
534 // while still tracking dependency chains that flow through those
536 if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
539 // Give a load or store half of the required depth so that load/store
540 // pairs will vectorize.
541 if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
542 return Config.ReqChainDepth/2;
547 // Returns the cost of the provided instruction using TTI.
548 // This does not handle loads and stores.
549 unsigned getInstrCost(unsigned Opcode, Type *T1, Type *T2,
550 TargetTransformInfo::OperandValueKind Op1VK =
551 TargetTransformInfo::OK_AnyValue,
552 TargetTransformInfo::OperandValueKind Op2VK =
553 TargetTransformInfo::OK_AnyValue) {
556 case Instruction::GetElementPtr:
557 // We mark this instruction as zero-cost because scalar GEPs are usually
558 // lowered to the instruction addressing mode. At the moment we don't
559 // generate vector GEPs.
561 case Instruction::Br:
562 return TTI->getCFInstrCost(Opcode);
563 case Instruction::PHI:
565 case Instruction::Add:
566 case Instruction::FAdd:
567 case Instruction::Sub:
568 case Instruction::FSub:
569 case Instruction::Mul:
570 case Instruction::FMul:
571 case Instruction::UDiv:
572 case Instruction::SDiv:
573 case Instruction::FDiv:
574 case Instruction::URem:
575 case Instruction::SRem:
576 case Instruction::FRem:
577 case Instruction::Shl:
578 case Instruction::LShr:
579 case Instruction::AShr:
580 case Instruction::And:
581 case Instruction::Or:
582 case Instruction::Xor:
583 return TTI->getArithmeticInstrCost(Opcode, T1, Op1VK, Op2VK);
584 case Instruction::Select:
585 case Instruction::ICmp:
586 case Instruction::FCmp:
587 return TTI->getCmpSelInstrCost(Opcode, T1, T2);
588 case Instruction::ZExt:
589 case Instruction::SExt:
590 case Instruction::FPToUI:
591 case Instruction::FPToSI:
592 case Instruction::FPExt:
593 case Instruction::PtrToInt:
594 case Instruction::IntToPtr:
595 case Instruction::SIToFP:
596 case Instruction::UIToFP:
597 case Instruction::Trunc:
598 case Instruction::FPTrunc:
599 case Instruction::BitCast:
600 case Instruction::ShuffleVector:
601 return TTI->getCastInstrCost(Opcode, T1, T2);
607 // This determines the relative offset of two loads or stores, returning
608 // true if the offset could be determined to be some constant value.
609 // For example, if OffsetInElmts == 1, then J accesses the memory directly
610 // after I; if OffsetInElmts == -1 then I accesses the memory
612 bool getPairPtrInfo(Instruction *I, Instruction *J,
613 Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
614 unsigned &IAddressSpace, unsigned &JAddressSpace,
615 int64_t &OffsetInElmts, bool ComputeOffset = true) {
617 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
618 LoadInst *LJ = cast<LoadInst>(J);
619 IPtr = LI->getPointerOperand();
620 JPtr = LJ->getPointerOperand();
621 IAlignment = LI->getAlignment();
622 JAlignment = LJ->getAlignment();
623 IAddressSpace = LI->getPointerAddressSpace();
624 JAddressSpace = LJ->getPointerAddressSpace();
626 StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
627 IPtr = SI->getPointerOperand();
628 JPtr = SJ->getPointerOperand();
629 IAlignment = SI->getAlignment();
630 JAlignment = SJ->getAlignment();
631 IAddressSpace = SI->getPointerAddressSpace();
632 JAddressSpace = SJ->getPointerAddressSpace();
638 const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
639 const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
641 // If this is a trivial offset, then we'll get something like
642 // 1*sizeof(type). With target data, which we need anyway, this will get
643 // constant folded into a number.
644 const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
645 if (const SCEVConstant *ConstOffSCEV =
646 dyn_cast<SCEVConstant>(OffsetSCEV)) {
647 ConstantInt *IntOff = ConstOffSCEV->getValue();
648 int64_t Offset = IntOff->getSExtValue();
649 const DataLayout &DL = I->getModule()->getDataLayout();
650 Type *VTy = IPtr->getType()->getPointerElementType();
651 int64_t VTyTSS = (int64_t)DL.getTypeStoreSize(VTy);
653 Type *VTy2 = JPtr->getType()->getPointerElementType();
654 if (VTy != VTy2 && Offset < 0) {
655 int64_t VTy2TSS = (int64_t)DL.getTypeStoreSize(VTy2);
656 OffsetInElmts = Offset/VTy2TSS;
657 return (std::abs(Offset) % VTy2TSS) == 0;
660 OffsetInElmts = Offset/VTyTSS;
661 return (std::abs(Offset) % VTyTSS) == 0;
667 // Returns true if the provided CallInst represents an intrinsic that can
669 bool isVectorizableIntrinsic(CallInst* I) {
670 Function *F = I->getCalledFunction();
671 if (!F) return false;
673 Intrinsic::ID IID = F->getIntrinsicID();
674 if (!IID) return false;
679 case Intrinsic::sqrt:
680 case Intrinsic::powi:
684 case Intrinsic::log2:
685 case Intrinsic::log10:
687 case Intrinsic::exp2:
689 case Intrinsic::round:
690 case Intrinsic::copysign:
691 case Intrinsic::ceil:
692 case Intrinsic::nearbyint:
693 case Intrinsic::rint:
694 case Intrinsic::trunc:
695 case Intrinsic::floor:
696 case Intrinsic::fabs:
697 case Intrinsic::minnum:
698 case Intrinsic::maxnum:
699 return Config.VectorizeMath;
700 case Intrinsic::bswap:
701 case Intrinsic::ctpop:
702 case Intrinsic::ctlz:
703 case Intrinsic::cttz:
704 return Config.VectorizeBitManipulations;
706 case Intrinsic::fmuladd:
707 return Config.VectorizeFMA;
711 bool isPureIEChain(InsertElementInst *IE) {
712 InsertElementInst *IENext = IE;
714 if (!isa<UndefValue>(IENext->getOperand(0)) &&
715 !isa<InsertElementInst>(IENext->getOperand(0))) {
719 dyn_cast<InsertElementInst>(IENext->getOperand(0))));
725 // This function implements one vectorization iteration on the provided
726 // basic block. It returns true if the block is changed.
727 bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
729 BasicBlock::iterator Start = BB.getFirstInsertionPt();
731 std::vector<Value *> AllPairableInsts;
732 DenseMap<Value *, Value *> AllChosenPairs;
733 DenseSet<ValuePair> AllFixedOrderPairs;
734 DenseMap<VPPair, unsigned> AllPairConnectionTypes;
735 DenseMap<ValuePair, std::vector<ValuePair> > AllConnectedPairs,
736 AllConnectedPairDeps;
739 std::vector<Value *> PairableInsts;
740 DenseMap<Value *, std::vector<Value *> > CandidatePairs;
741 DenseSet<ValuePair> FixedOrderPairs;
742 DenseMap<ValuePair, int> CandidatePairCostSavings;
743 ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
745 CandidatePairCostSavings,
746 PairableInsts, NonPow2Len);
747 if (PairableInsts.empty()) continue;
749 // Build the candidate pair set for faster lookups.
750 DenseSet<ValuePair> CandidatePairsSet;
751 for (DenseMap<Value *, std::vector<Value *> >::iterator I =
752 CandidatePairs.begin(), E = CandidatePairs.end(); I != E; ++I)
753 for (std::vector<Value *>::iterator J = I->second.begin(),
754 JE = I->second.end(); J != JE; ++J)
755 CandidatePairsSet.insert(ValuePair(I->first, *J));
757 // Now we have a map of all of the pairable instructions and we need to
758 // select the best possible pairing. A good pairing is one such that the
759 // users of the pair are also paired. This defines a (directed) forest
760 // over the pairs such that two pairs are connected iff the second pair
763 // Note that it only matters that both members of the second pair use some
764 // element of the first pair (to allow for splatting).
766 DenseMap<ValuePair, std::vector<ValuePair> > ConnectedPairs,
768 DenseMap<VPPair, unsigned> PairConnectionTypes;
769 computeConnectedPairs(CandidatePairs, CandidatePairsSet,
770 PairableInsts, ConnectedPairs, PairConnectionTypes);
771 if (ConnectedPairs.empty()) continue;
773 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
774 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
776 for (std::vector<ValuePair>::iterator J = I->second.begin(),
777 JE = I->second.end(); J != JE; ++J)
778 ConnectedPairDeps[*J].push_back(I->first);
780 // Build the pairable-instruction dependency map
781 DenseSet<ValuePair> PairableInstUsers;
782 buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
784 // There is now a graph of the connected pairs. For each variable, pick
785 // the pairing with the largest dag meeting the depth requirement on at
786 // least one branch. Then select all pairings that are part of that dag
787 // and remove them from the list of available pairings and pairable
790 DenseMap<Value *, Value *> ChosenPairs;
791 choosePairs(CandidatePairs, CandidatePairsSet,
792 CandidatePairCostSavings,
793 PairableInsts, FixedOrderPairs, PairConnectionTypes,
794 ConnectedPairs, ConnectedPairDeps,
795 PairableInstUsers, ChosenPairs);
797 if (ChosenPairs.empty()) continue;
798 AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
799 PairableInsts.end());
800 AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
802 // Only for the chosen pairs, propagate information on fixed-order pairs,
803 // pair connections, and their types to the data structures used by the
804 // pair fusion procedures.
805 for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
806 IE = ChosenPairs.end(); I != IE; ++I) {
807 if (FixedOrderPairs.count(*I))
808 AllFixedOrderPairs.insert(*I);
809 else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
810 AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
812 for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
814 DenseMap<VPPair, unsigned>::iterator K =
815 PairConnectionTypes.find(VPPair(*I, *J));
816 if (K != PairConnectionTypes.end()) {
817 AllPairConnectionTypes.insert(*K);
819 K = PairConnectionTypes.find(VPPair(*J, *I));
820 if (K != PairConnectionTypes.end())
821 AllPairConnectionTypes.insert(*K);
826 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
827 I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
829 for (std::vector<ValuePair>::iterator J = I->second.begin(),
830 JE = I->second.end(); J != JE; ++J)
831 if (AllPairConnectionTypes.count(VPPair(I->first, *J))) {
832 AllConnectedPairs[I->first].push_back(*J);
833 AllConnectedPairDeps[*J].push_back(I->first);
835 } while (ShouldContinue);
837 if (AllChosenPairs.empty()) return false;
838 NumFusedOps += AllChosenPairs.size();
840 // A set of pairs has now been selected. It is now necessary to replace the
841 // paired instructions with vector instructions. For this procedure each
842 // operand must be replaced with a vector operand. This vector is formed
843 // by using build_vector on the old operands. The replaced values are then
844 // replaced with a vector_extract on the result. Subsequent optimization
845 // passes should coalesce the build/extract combinations.
847 fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
848 AllPairConnectionTypes,
849 AllConnectedPairs, AllConnectedPairDeps);
851 // It is important to cleanup here so that future iterations of this
852 // function have less work to do.
853 (void)SimplifyInstructionsInBlock(&BB, TLI);
857 // This function returns true if the provided instruction is capable of being
858 // fused into a vector instruction. This determination is based only on the
859 // type and other attributes of the instruction.
860 bool BBVectorize::isInstVectorizable(Instruction *I,
861 bool &IsSimpleLoadStore) {
862 IsSimpleLoadStore = false;
864 if (CallInst *C = dyn_cast<CallInst>(I)) {
865 if (!isVectorizableIntrinsic(C))
867 } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
868 // Vectorize simple loads if possbile:
869 IsSimpleLoadStore = L->isSimple();
870 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
872 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
873 // Vectorize simple stores if possbile:
874 IsSimpleLoadStore = S->isSimple();
875 if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
877 } else if (CastInst *C = dyn_cast<CastInst>(I)) {
878 // We can vectorize casts, but not casts of pointer types, etc.
879 if (!Config.VectorizeCasts)
882 Type *SrcTy = C->getSrcTy();
883 if (!SrcTy->isSingleValueType())
886 Type *DestTy = C->getDestTy();
887 if (!DestTy->isSingleValueType())
889 } else if (isa<SelectInst>(I)) {
890 if (!Config.VectorizeSelect)
892 } else if (isa<CmpInst>(I)) {
893 if (!Config.VectorizeCmp)
895 } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
896 if (!Config.VectorizeGEP)
899 // Currently, vector GEPs exist only with one index.
900 if (G->getNumIndices() != 1)
902 } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
903 isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
908 getInstructionTypes(I, T1, T2);
910 // Not every type can be vectorized...
911 if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
912 !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
915 if (T1->getScalarSizeInBits() == 1) {
916 if (!Config.VectorizeBools)
919 if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
923 if (T2->getScalarSizeInBits() == 1) {
924 if (!Config.VectorizeBools)
927 if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
931 if (!Config.VectorizeFloats
932 && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
935 // Don't vectorize target-specific types.
936 if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
938 if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
941 if (!Config.VectorizePointers && (T1->getScalarType()->isPointerTy() ||
942 T2->getScalarType()->isPointerTy()))
945 if (!TTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
946 T2->getPrimitiveSizeInBits() >= Config.VectorBits))
952 // This function returns true if the two provided instructions are compatible
953 // (meaning that they can be fused into a vector instruction). This assumes
954 // that I has already been determined to be vectorizable and that J is not
955 // in the use dag of I.
956 bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
957 bool IsSimpleLoadStore, bool NonPow2Len,
958 int &CostSavings, int &FixedOrder) {
959 DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
960 " <-> " << *J << "\n");
965 // Loads and stores can be merged if they have different alignments,
966 // but are otherwise the same.
967 if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
968 (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
971 Type *IT1, *IT2, *JT1, *JT2;
972 getInstructionTypes(I, IT1, IT2);
973 getInstructionTypes(J, JT1, JT2);
974 unsigned MaxTypeBits = std::max(
975 IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
976 IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
977 if (!TTI && MaxTypeBits > Config.VectorBits)
980 // FIXME: handle addsub-type operations!
982 if (IsSimpleLoadStore) {
984 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
985 int64_t OffsetInElmts = 0;
986 if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
987 IAddressSpace, JAddressSpace, OffsetInElmts) &&
988 std::abs(OffsetInElmts) == 1) {
989 FixedOrder = (int) OffsetInElmts;
990 unsigned BottomAlignment = IAlignment;
991 if (OffsetInElmts < 0) BottomAlignment = JAlignment;
993 Type *aTypeI = isa<StoreInst>(I) ?
994 cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
995 Type *aTypeJ = isa<StoreInst>(J) ?
996 cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
997 Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
999 if (Config.AlignedOnly) {
1000 // An aligned load or store is possible only if the instruction
1001 // with the lower offset has an alignment suitable for the
1003 const DataLayout &DL = I->getModule()->getDataLayout();
1004 unsigned VecAlignment = DL.getPrefTypeAlignment(VType);
1005 if (BottomAlignment < VecAlignment)
1010 unsigned ICost = TTI->getMemoryOpCost(I->getOpcode(), aTypeI,
1011 IAlignment, IAddressSpace);
1012 unsigned JCost = TTI->getMemoryOpCost(J->getOpcode(), aTypeJ,
1013 JAlignment, JAddressSpace);
1014 unsigned VCost = TTI->getMemoryOpCost(I->getOpcode(), VType,
1018 ICost += TTI->getAddressComputationCost(aTypeI);
1019 JCost += TTI->getAddressComputationCost(aTypeJ);
1020 VCost += TTI->getAddressComputationCost(VType);
1022 if (VCost > ICost + JCost)
1025 // We don't want to fuse to a type that will be split, even
1026 // if the two input types will also be split and there is no other
1028 unsigned VParts = TTI->getNumberOfParts(VType);
1031 else if (!VParts && VCost == ICost + JCost)
1034 CostSavings = ICost + JCost - VCost;
1040 unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
1041 unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
1042 Type *VT1 = getVecTypeForPair(IT1, JT1),
1043 *VT2 = getVecTypeForPair(IT2, JT2);
1044 TargetTransformInfo::OperandValueKind Op1VK =
1045 TargetTransformInfo::OK_AnyValue;
1046 TargetTransformInfo::OperandValueKind Op2VK =
1047 TargetTransformInfo::OK_AnyValue;
1049 // On some targets (example X86) the cost of a vector shift may vary
1050 // depending on whether the second operand is a Uniform or
1051 // NonUniform Constant.
1052 switch (I->getOpcode()) {
1054 case Instruction::Shl:
1055 case Instruction::LShr:
1056 case Instruction::AShr:
1058 // If both I and J are scalar shifts by constant, then the
1059 // merged vector shift count would be either a constant splat value
1060 // or a non-uniform vector of constants.
1061 if (ConstantInt *CII = dyn_cast<ConstantInt>(I->getOperand(1))) {
1062 if (ConstantInt *CIJ = dyn_cast<ConstantInt>(J->getOperand(1)))
1063 Op2VK = CII == CIJ ? TargetTransformInfo::OK_UniformConstantValue :
1064 TargetTransformInfo::OK_NonUniformConstantValue;
1066 // Check for a splat of a constant or for a non uniform vector
1068 Value *IOp = I->getOperand(1);
1069 Value *JOp = J->getOperand(1);
1070 if ((isa<ConstantVector>(IOp) || isa<ConstantDataVector>(IOp)) &&
1071 (isa<ConstantVector>(JOp) || isa<ConstantDataVector>(JOp))) {
1072 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1073 Constant *SplatValue = cast<Constant>(IOp)->getSplatValue();
1074 if (SplatValue != nullptr &&
1075 SplatValue == cast<Constant>(JOp)->getSplatValue())
1076 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
1081 // Note that this procedure is incorrect for insert and extract element
1082 // instructions (because combining these often results in a shuffle),
1083 // but this cost is ignored (because insert and extract element
1084 // instructions are assigned a zero depth factor and are not really
1085 // fused in general).
1086 unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2, Op1VK, Op2VK);
1088 if (VCost > ICost + JCost)
1091 // We don't want to fuse to a type that will be split, even
1092 // if the two input types will also be split and there is no other
1094 unsigned VParts1 = TTI->getNumberOfParts(VT1),
1095 VParts2 = TTI->getNumberOfParts(VT2);
1096 if (VParts1 > 1 || VParts2 > 1)
1098 else if ((!VParts1 || !VParts2) && VCost == ICost + JCost)
1101 CostSavings = ICost + JCost - VCost;
1104 // The powi,ctlz,cttz intrinsics are special because only the first
1105 // argument is vectorized, the second arguments must be equal.
1106 CallInst *CI = dyn_cast<CallInst>(I);
1108 if (CI && (FI = CI->getCalledFunction())) {
1109 Intrinsic::ID IID = FI->getIntrinsicID();
1110 if (IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
1111 IID == Intrinsic::cttz) {
1112 Value *A1I = CI->getArgOperand(1),
1113 *A1J = cast<CallInst>(J)->getArgOperand(1);
1114 const SCEV *A1ISCEV = SE->getSCEV(A1I),
1115 *A1JSCEV = SE->getSCEV(A1J);
1116 return (A1ISCEV == A1JSCEV);
1120 SmallVector<Type*, 4> Tys;
1121 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
1122 Tys.push_back(CI->getArgOperand(i)->getType());
1123 unsigned ICost = TTI->getIntrinsicInstrCost(IID, IT1, Tys);
1126 CallInst *CJ = cast<CallInst>(J);
1127 for (unsigned i = 0, ie = CJ->getNumArgOperands(); i != ie; ++i)
1128 Tys.push_back(CJ->getArgOperand(i)->getType());
1129 unsigned JCost = TTI->getIntrinsicInstrCost(IID, JT1, Tys);
1132 assert(CI->getNumArgOperands() == CJ->getNumArgOperands() &&
1133 "Intrinsic argument counts differ");
1134 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1135 if ((IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
1136 IID == Intrinsic::cttz) && i == 1)
1137 Tys.push_back(CI->getArgOperand(i)->getType());
1139 Tys.push_back(getVecTypeForPair(CI->getArgOperand(i)->getType(),
1140 CJ->getArgOperand(i)->getType()));
1143 Type *RetTy = getVecTypeForPair(IT1, JT1);
1144 unsigned VCost = TTI->getIntrinsicInstrCost(IID, RetTy, Tys);
1146 if (VCost > ICost + JCost)
1149 // We don't want to fuse to a type that will be split, even
1150 // if the two input types will also be split and there is no other
1152 unsigned RetParts = TTI->getNumberOfParts(RetTy);
1155 else if (!RetParts && VCost == ICost + JCost)
1158 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1159 if (!Tys[i]->isVectorTy())
1162 unsigned NumParts = TTI->getNumberOfParts(Tys[i]);
1165 else if (!NumParts && VCost == ICost + JCost)
1169 CostSavings = ICost + JCost - VCost;
1176 // Figure out whether or not J uses I and update the users and write-set
1177 // structures associated with I. Specifically, Users represents the set of
1178 // instructions that depend on I. WriteSet represents the set
1179 // of memory locations that are dependent on I. If UpdateUsers is true,
1180 // and J uses I, then Users is updated to contain J and WriteSet is updated
1181 // to contain any memory locations to which J writes. The function returns
1182 // true if J uses I. By default, alias analysis is used to determine
1183 // whether J reads from memory that overlaps with a location in WriteSet.
1184 // If LoadMoveSet is not null, then it is a previously-computed map
1185 // where the key is the memory-based user instruction and the value is
1186 // the instruction to be compared with I. So, if LoadMoveSet is provided,
1187 // then the alias analysis is not used. This is necessary because this
1188 // function is called during the process of moving instructions during
1189 // vectorization and the results of the alias analysis are not stable during
1191 bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
1192 AliasSetTracker &WriteSet, Instruction *I,
1193 Instruction *J, bool UpdateUsers,
1194 DenseSet<ValuePair> *LoadMoveSetPairs) {
1197 // This instruction may already be marked as a user due, for example, to
1198 // being a member of a selected pair.
1203 for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
1206 if (I == V || Users.count(V)) {
1211 if (!UsesI && J->mayReadFromMemory()) {
1212 if (LoadMoveSetPairs) {
1213 UsesI = LoadMoveSetPairs->count(ValuePair(J, I));
1215 for (AliasSetTracker::iterator W = WriteSet.begin(),
1216 WE = WriteSet.end(); W != WE; ++W) {
1217 if (W->aliasesUnknownInst(J, *AA)) {
1225 if (UsesI && UpdateUsers) {
1226 if (J->mayWriteToMemory()) WriteSet.add(J);
1233 // This function iterates over all instruction pairs in the provided
1234 // basic block and collects all candidate pairs for vectorization.
1235 bool BBVectorize::getCandidatePairs(BasicBlock &BB,
1236 BasicBlock::iterator &Start,
1237 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1238 DenseSet<ValuePair> &FixedOrderPairs,
1239 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1240 std::vector<Value *> &PairableInsts, bool NonPow2Len) {
1241 size_t TotalPairs = 0;
1242 BasicBlock::iterator E = BB.end();
1243 if (Start == E) return false;
1245 bool ShouldContinue = false, IAfterStart = false;
1246 for (BasicBlock::iterator I = Start++; I != E; ++I) {
1247 if (I == Start) IAfterStart = true;
1249 bool IsSimpleLoadStore;
1250 if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
1252 // Look for an instruction with which to pair instruction *I...
1253 DenseSet<Value *> Users;
1254 AliasSetTracker WriteSet(*AA);
1255 if (I->mayWriteToMemory()) WriteSet.add(I);
1257 bool JAfterStart = IAfterStart;
1258 BasicBlock::iterator J = std::next(I);
1259 for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
1260 if (J == Start) JAfterStart = true;
1262 // Determine if J uses I, if so, exit the loop.
1263 bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
1264 if (Config.FastDep) {
1265 // Note: For this heuristic to be effective, independent operations
1266 // must tend to be intermixed. This is likely to be true from some
1267 // kinds of grouped loop unrolling (but not the generic LLVM pass),
1268 // but otherwise may require some kind of reordering pass.
1270 // When using fast dependency analysis,
1271 // stop searching after first use:
1274 if (UsesI) continue;
1277 // J does not use I, and comes before the first use of I, so it can be
1278 // merged with I if the instructions are compatible.
1279 int CostSavings, FixedOrder;
1280 if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
1281 CostSavings, FixedOrder)) continue;
1283 // J is a candidate for merging with I.
1284 if (PairableInsts.empty() ||
1285 PairableInsts[PairableInsts.size()-1] != I) {
1286 PairableInsts.push_back(I);
1289 CandidatePairs[I].push_back(J);
1292 CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
1295 if (FixedOrder == 1)
1296 FixedOrderPairs.insert(ValuePair(I, J));
1297 else if (FixedOrder == -1)
1298 FixedOrderPairs.insert(ValuePair(J, I));
1300 // The next call to this function must start after the last instruction
1301 // selected during this invocation.
1303 Start = std::next(J);
1304 IAfterStart = JAfterStart = false;
1307 DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
1308 << *I << " <-> " << *J << " (cost savings: " <<
1309 CostSavings << ")\n");
1311 // If we have already found too many pairs, break here and this function
1312 // will be called again starting after the last instruction selected
1313 // during this invocation.
1314 if (PairableInsts.size() >= Config.MaxInsts ||
1315 TotalPairs >= Config.MaxPairs) {
1316 ShouldContinue = true;
1325 DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
1326 << " instructions with candidate pairs\n");
1328 return ShouldContinue;
1331 // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
1332 // it looks for pairs such that both members have an input which is an
1333 // output of PI or PJ.
1334 void BBVectorize::computePairsConnectedTo(
1335 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1336 DenseSet<ValuePair> &CandidatePairsSet,
1337 std::vector<Value *> &PairableInsts,
1338 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1339 DenseMap<VPPair, unsigned> &PairConnectionTypes,
1343 // For each possible pairing for this variable, look at the uses of
1344 // the first value...
1345 for (Value::user_iterator I = P.first->user_begin(),
1346 E = P.first->user_end();
1349 if (isa<LoadInst>(UI)) {
1350 // A pair cannot be connected to a load because the load only takes one
1351 // operand (the address) and it is a scalar even after vectorization.
1353 } else if ((SI = dyn_cast<StoreInst>(UI)) &&
1354 P.first == SI->getPointerOperand()) {
1355 // Similarly, a pair cannot be connected to a store through its
1360 // For each use of the first variable, look for uses of the second
1362 for (User *UJ : P.second->users()) {
1363 if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1364 P.second == SJ->getPointerOperand())
1368 if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1369 VPPair VP(P, ValuePair(UI, UJ));
1370 ConnectedPairs[VP.first].push_back(VP.second);
1371 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
1375 if (CandidatePairsSet.count(ValuePair(UJ, UI))) {
1376 VPPair VP(P, ValuePair(UJ, UI));
1377 ConnectedPairs[VP.first].push_back(VP.second);
1378 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
1382 if (Config.SplatBreaksChain) continue;
1383 // Look for cases where just the first value in the pair is used by
1384 // both members of another pair (splatting).
1385 for (Value::user_iterator J = P.first->user_begin(); J != E; ++J) {
1387 if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1388 P.first == SJ->getPointerOperand())
1391 if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1392 VPPair VP(P, ValuePair(UI, UJ));
1393 ConnectedPairs[VP.first].push_back(VP.second);
1394 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1399 if (Config.SplatBreaksChain) return;
1400 // Look for cases where just the second value in the pair is used by
1401 // both members of another pair (splatting).
1402 for (Value::user_iterator I = P.second->user_begin(),
1403 E = P.second->user_end();
1406 if (isa<LoadInst>(UI))
1408 else if ((SI = dyn_cast<StoreInst>(UI)) &&
1409 P.second == SI->getPointerOperand())
1412 for (Value::user_iterator J = P.second->user_begin(); J != E; ++J) {
1414 if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1415 P.second == SJ->getPointerOperand())
1418 if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1419 VPPair VP(P, ValuePair(UI, UJ));
1420 ConnectedPairs[VP.first].push_back(VP.second);
1421 PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1427 // This function figures out which pairs are connected. Two pairs are
1428 // connected if some output of the first pair forms an input to both members
1429 // of the second pair.
1430 void BBVectorize::computeConnectedPairs(
1431 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1432 DenseSet<ValuePair> &CandidatePairsSet,
1433 std::vector<Value *> &PairableInsts,
1434 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1435 DenseMap<VPPair, unsigned> &PairConnectionTypes) {
1436 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1437 PE = PairableInsts.end(); PI != PE; ++PI) {
1438 DenseMap<Value *, std::vector<Value *> >::iterator PP =
1439 CandidatePairs.find(*PI);
1440 if (PP == CandidatePairs.end())
1443 for (std::vector<Value *>::iterator P = PP->second.begin(),
1444 E = PP->second.end(); P != E; ++P)
1445 computePairsConnectedTo(CandidatePairs, CandidatePairsSet,
1446 PairableInsts, ConnectedPairs,
1447 PairConnectionTypes, ValuePair(*PI, *P));
1450 DEBUG(size_t TotalPairs = 0;
1451 for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator I =
1452 ConnectedPairs.begin(), IE = ConnectedPairs.end(); I != IE; ++I)
1453 TotalPairs += I->second.size();
1454 dbgs() << "BBV: found " << TotalPairs
1455 << " pair connections.\n");
1458 // This function builds a set of use tuples such that <A, B> is in the set
1459 // if B is in the use dag of A. If B is in the use dag of A, then B
1460 // depends on the output of A.
1461 void BBVectorize::buildDepMap(
1463 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1464 std::vector<Value *> &PairableInsts,
1465 DenseSet<ValuePair> &PairableInstUsers) {
1466 DenseSet<Value *> IsInPair;
1467 for (DenseMap<Value *, std::vector<Value *> >::iterator C =
1468 CandidatePairs.begin(), E = CandidatePairs.end(); C != E; ++C) {
1469 IsInPair.insert(C->first);
1470 IsInPair.insert(C->second.begin(), C->second.end());
1473 // Iterate through the basic block, recording all users of each
1474 // pairable instruction.
1476 BasicBlock::iterator E = BB.end(), EL =
1477 BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
1478 for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1479 if (IsInPair.find(I) == IsInPair.end()) continue;
1481 DenseSet<Value *> Users;
1482 AliasSetTracker WriteSet(*AA);
1483 if (I->mayWriteToMemory()) WriteSet.add(I);
1485 for (BasicBlock::iterator J = std::next(I); J != E; ++J) {
1486 (void) trackUsesOfI(Users, WriteSet, I, J);
1492 for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1494 if (IsInPair.find(*U) == IsInPair.end()) continue;
1495 PairableInstUsers.insert(ValuePair(I, *U));
1503 // Returns true if an input to pair P is an output of pair Q and also an
1504 // input of pair Q is an output of pair P. If this is the case, then these
1505 // two pairs cannot be simultaneously fused.
1506 bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1507 DenseSet<ValuePair> &PairableInstUsers,
1508 DenseMap<ValuePair, std::vector<ValuePair> > *PairableInstUserMap,
1509 DenseSet<VPPair> *PairableInstUserPairSet) {
1510 // Two pairs are in conflict if they are mutual Users of eachother.
1511 bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
1512 PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
1513 PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
1514 PairableInstUsers.count(ValuePair(P.second, Q.second));
1515 bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
1516 PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
1517 PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
1518 PairableInstUsers.count(ValuePair(Q.second, P.second));
1519 if (PairableInstUserMap) {
1520 // FIXME: The expensive part of the cycle check is not so much the cycle
1521 // check itself but this edge insertion procedure. This needs some
1522 // profiling and probably a different data structure.
1524 if (PairableInstUserPairSet->insert(VPPair(Q, P)).second)
1525 (*PairableInstUserMap)[Q].push_back(P);
1528 if (PairableInstUserPairSet->insert(VPPair(P, Q)).second)
1529 (*PairableInstUserMap)[P].push_back(Q);
1533 return (QUsesP && PUsesQ);
1536 // This function walks the use graph of current pairs to see if, starting
1537 // from P, the walk returns to P.
1538 bool BBVectorize::pairWillFormCycle(ValuePair P,
1539 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1540 DenseSet<ValuePair> &CurrentPairs) {
1541 DEBUG(if (DebugCycleCheck)
1542 dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1543 << *P.second << "\n");
1544 // A lookup table of visisted pairs is kept because the PairableInstUserMap
1545 // contains non-direct associations.
1546 DenseSet<ValuePair> Visited;
1547 SmallVector<ValuePair, 32> Q;
1548 // General depth-first post-order traversal:
1551 ValuePair QTop = Q.pop_back_val();
1552 Visited.insert(QTop);
1554 DEBUG(if (DebugCycleCheck)
1555 dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1556 << *QTop.second << "\n");
1557 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1558 PairableInstUserMap.find(QTop);
1559 if (QQ == PairableInstUserMap.end())
1562 for (std::vector<ValuePair>::iterator C = QQ->second.begin(),
1563 CE = QQ->second.end(); C != CE; ++C) {
1566 << "BBV: rejected to prevent non-trivial cycle formation: "
1567 << QTop.first << " <-> " << C->second << "\n");
1571 if (CurrentPairs.count(*C) && !Visited.count(*C))
1574 } while (!Q.empty());
1579 // This function builds the initial dag of connected pairs with the
1580 // pair J at the root.
1581 void BBVectorize::buildInitialDAGFor(
1582 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1583 DenseSet<ValuePair> &CandidatePairsSet,
1584 std::vector<Value *> &PairableInsts,
1585 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1586 DenseSet<ValuePair> &PairableInstUsers,
1587 DenseMap<Value *, Value *> &ChosenPairs,
1588 DenseMap<ValuePair, size_t> &DAG, ValuePair J) {
1589 // Each of these pairs is viewed as the root node of a DAG. The DAG
1590 // is then walked (depth-first). As this happens, we keep track of
1591 // the pairs that compose the DAG and the maximum depth of the DAG.
1592 SmallVector<ValuePairWithDepth, 32> Q;
1593 // General depth-first post-order traversal:
1594 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1596 ValuePairWithDepth QTop = Q.back();
1598 // Push each child onto the queue:
1599 bool MoreChildren = false;
1600 size_t MaxChildDepth = QTop.second;
1601 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1602 ConnectedPairs.find(QTop.first);
1603 if (QQ != ConnectedPairs.end())
1604 for (std::vector<ValuePair>::iterator k = QQ->second.begin(),
1605 ke = QQ->second.end(); k != ke; ++k) {
1606 // Make sure that this child pair is still a candidate:
1607 if (CandidatePairsSet.count(*k)) {
1608 DenseMap<ValuePair, size_t>::iterator C = DAG.find(*k);
1609 if (C == DAG.end()) {
1610 size_t d = getDepthFactor(k->first);
1611 Q.push_back(ValuePairWithDepth(*k, QTop.second+d));
1612 MoreChildren = true;
1614 MaxChildDepth = std::max(MaxChildDepth, C->second);
1619 if (!MoreChildren) {
1620 // Record the current pair as part of the DAG:
1621 DAG.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1624 } while (!Q.empty());
1627 // Given some initial dag, prune it by removing conflicting pairs (pairs
1628 // that cannot be simultaneously chosen for vectorization).
1629 void BBVectorize::pruneDAGFor(
1630 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1631 std::vector<Value *> &PairableInsts,
1632 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1633 DenseSet<ValuePair> &PairableInstUsers,
1634 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1635 DenseSet<VPPair> &PairableInstUserPairSet,
1636 DenseMap<Value *, Value *> &ChosenPairs,
1637 DenseMap<ValuePair, size_t> &DAG,
1638 DenseSet<ValuePair> &PrunedDAG, ValuePair J,
1639 bool UseCycleCheck) {
1640 SmallVector<ValuePairWithDepth, 32> Q;
1641 // General depth-first post-order traversal:
1642 Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1644 ValuePairWithDepth QTop = Q.pop_back_val();
1645 PrunedDAG.insert(QTop.first);
1647 // Visit each child, pruning as necessary...
1648 SmallVector<ValuePairWithDepth, 8> BestChildren;
1649 DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
1650 ConnectedPairs.find(QTop.first);
1651 if (QQ == ConnectedPairs.end())
1654 for (std::vector<ValuePair>::iterator K = QQ->second.begin(),
1655 KE = QQ->second.end(); K != KE; ++K) {
1656 DenseMap<ValuePair, size_t>::iterator C = DAG.find(*K);
1657 if (C == DAG.end()) continue;
1659 // This child is in the DAG, now we need to make sure it is the
1660 // best of any conflicting children. There could be multiple
1661 // conflicting children, so first, determine if we're keeping
1662 // this child, then delete conflicting children as necessary.
1664 // It is also necessary to guard against pairing-induced
1665 // dependencies. Consider instructions a .. x .. y .. b
1666 // such that (a,b) are to be fused and (x,y) are to be fused
1667 // but a is an input to x and b is an output from y. This
1668 // means that y cannot be moved after b but x must be moved
1669 // after b for (a,b) to be fused. In other words, after
1670 // fusing (a,b) we have y .. a/b .. x where y is an input
1671 // to a/b and x is an output to a/b: x and y can no longer
1672 // be legally fused. To prevent this condition, we must
1673 // make sure that a child pair added to the DAG is not
1674 // both an input and output of an already-selected pair.
1676 // Pairing-induced dependencies can also form from more complicated
1677 // cycles. The pair vs. pair conflicts are easy to check, and so
1678 // that is done explicitly for "fast rejection", and because for
1679 // child vs. child conflicts, we may prefer to keep the current
1680 // pair in preference to the already-selected child.
1681 DenseSet<ValuePair> CurrentPairs;
1684 for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
1685 = BestChildren.begin(), E2 = BestChildren.end();
1687 if (C2->first.first == C->first.first ||
1688 C2->first.first == C->first.second ||
1689 C2->first.second == C->first.first ||
1690 C2->first.second == C->first.second ||
1691 pairsConflict(C2->first, C->first, PairableInstUsers,
1692 UseCycleCheck ? &PairableInstUserMap : nullptr,
1693 UseCycleCheck ? &PairableInstUserPairSet
1695 if (C2->second >= C->second) {
1700 CurrentPairs.insert(C2->first);
1703 if (!CanAdd) continue;
1705 // Even worse, this child could conflict with another node already
1706 // selected for the DAG. If that is the case, ignore this child.
1707 for (DenseSet<ValuePair>::iterator T = PrunedDAG.begin(),
1708 E2 = PrunedDAG.end(); T != E2; ++T) {
1709 if (T->first == C->first.first ||
1710 T->first == C->first.second ||
1711 T->second == C->first.first ||
1712 T->second == C->first.second ||
1713 pairsConflict(*T, C->first, PairableInstUsers,
1714 UseCycleCheck ? &PairableInstUserMap : nullptr,
1715 UseCycleCheck ? &PairableInstUserPairSet
1721 CurrentPairs.insert(*T);
1723 if (!CanAdd) continue;
1725 // And check the queue too...
1726 for (SmallVectorImpl<ValuePairWithDepth>::iterator C2 = Q.begin(),
1727 E2 = Q.end(); C2 != E2; ++C2) {
1728 if (C2->first.first == C->first.first ||
1729 C2->first.first == C->first.second ||
1730 C2->first.second == C->first.first ||
1731 C2->first.second == C->first.second ||
1732 pairsConflict(C2->first, C->first, PairableInstUsers,
1733 UseCycleCheck ? &PairableInstUserMap : nullptr,
1734 UseCycleCheck ? &PairableInstUserPairSet
1740 CurrentPairs.insert(C2->first);
1742 if (!CanAdd) continue;
1744 // Last but not least, check for a conflict with any of the
1745 // already-chosen pairs.
1746 for (DenseMap<Value *, Value *>::iterator C2 =
1747 ChosenPairs.begin(), E2 = ChosenPairs.end();
1749 if (pairsConflict(*C2, C->first, PairableInstUsers,
1750 UseCycleCheck ? &PairableInstUserMap : nullptr,
1751 UseCycleCheck ? &PairableInstUserPairSet
1757 CurrentPairs.insert(*C2);
1759 if (!CanAdd) continue;
1761 // To check for non-trivial cycles formed by the addition of the
1762 // current pair we've formed a list of all relevant pairs, now use a
1763 // graph walk to check for a cycle. We start from the current pair and
1764 // walk the use dag to see if we again reach the current pair. If we
1765 // do, then the current pair is rejected.
1767 // FIXME: It may be more efficient to use a topological-ordering
1768 // algorithm to improve the cycle check. This should be investigated.
1769 if (UseCycleCheck &&
1770 pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1773 // This child can be added, but we may have chosen it in preference
1774 // to an already-selected child. Check for this here, and if a
1775 // conflict is found, then remove the previously-selected child
1776 // before adding this one in its place.
1777 for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
1778 = BestChildren.begin(); C2 != BestChildren.end();) {
1779 if (C2->first.first == C->first.first ||
1780 C2->first.first == C->first.second ||
1781 C2->first.second == C->first.first ||
1782 C2->first.second == C->first.second ||
1783 pairsConflict(C2->first, C->first, PairableInstUsers))
1784 C2 = BestChildren.erase(C2);
1789 BestChildren.push_back(ValuePairWithDepth(C->first, C->second));
1792 for (SmallVectorImpl<ValuePairWithDepth>::iterator C
1793 = BestChildren.begin(), E2 = BestChildren.end();
1795 size_t DepthF = getDepthFactor(C->first.first);
1796 Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1798 } while (!Q.empty());
1801 // This function finds the best dag of mututally-compatible connected
1802 // pairs, given the choice of root pairs as an iterator range.
1803 void BBVectorize::findBestDAGFor(
1804 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1805 DenseSet<ValuePair> &CandidatePairsSet,
1806 DenseMap<ValuePair, int> &CandidatePairCostSavings,
1807 std::vector<Value *> &PairableInsts,
1808 DenseSet<ValuePair> &FixedOrderPairs,
1809 DenseMap<VPPair, unsigned> &PairConnectionTypes,
1810 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1811 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
1812 DenseSet<ValuePair> &PairableInstUsers,
1813 DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1814 DenseSet<VPPair> &PairableInstUserPairSet,
1815 DenseMap<Value *, Value *> &ChosenPairs,
1816 DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
1817 int &BestEffSize, Value *II, std::vector<Value *>&JJ,
1818 bool UseCycleCheck) {
1819 for (std::vector<Value *>::iterator J = JJ.begin(), JE = JJ.end();
1821 ValuePair IJ(II, *J);
1822 if (!CandidatePairsSet.count(IJ))
1825 // Before going any further, make sure that this pair does not
1826 // conflict with any already-selected pairs (see comment below
1827 // near the DAG pruning for more details).
1828 DenseSet<ValuePair> ChosenPairSet;
1829 bool DoesConflict = false;
1830 for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1831 E = ChosenPairs.end(); C != E; ++C) {
1832 if (pairsConflict(*C, IJ, PairableInstUsers,
1833 UseCycleCheck ? &PairableInstUserMap : nullptr,
1834 UseCycleCheck ? &PairableInstUserPairSet : nullptr)) {
1835 DoesConflict = true;
1839 ChosenPairSet.insert(*C);
1841 if (DoesConflict) continue;
1843 if (UseCycleCheck &&
1844 pairWillFormCycle(IJ, PairableInstUserMap, ChosenPairSet))
1847 DenseMap<ValuePair, size_t> DAG;
1848 buildInitialDAGFor(CandidatePairs, CandidatePairsSet,
1849 PairableInsts, ConnectedPairs,
1850 PairableInstUsers, ChosenPairs, DAG, IJ);
1852 // Because we'll keep the child with the largest depth, the largest
1853 // depth is still the same in the unpruned DAG.
1854 size_t MaxDepth = DAG.lookup(IJ);
1856 DEBUG(if (DebugPairSelection) dbgs() << "BBV: found DAG for pair {"
1857 << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
1858 MaxDepth << " and size " << DAG.size() << "\n");
1860 // At this point the DAG has been constructed, but, may contain
1861 // contradictory children (meaning that different children of
1862 // some dag node may be attempting to fuse the same instruction).
1863 // So now we walk the dag again, in the case of a conflict,
1864 // keep only the child with the largest depth. To break a tie,
1865 // favor the first child.
1867 DenseSet<ValuePair> PrunedDAG;
1868 pruneDAGFor(CandidatePairs, PairableInsts, ConnectedPairs,
1869 PairableInstUsers, PairableInstUserMap,
1870 PairableInstUserPairSet,
1871 ChosenPairs, DAG, PrunedDAG, IJ, UseCycleCheck);
1875 DenseSet<Value *> PrunedDAGInstrs;
1876 for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
1877 E = PrunedDAG.end(); S != E; ++S) {
1878 PrunedDAGInstrs.insert(S->first);
1879 PrunedDAGInstrs.insert(S->second);
1882 // The set of pairs that have already contributed to the total cost.
1883 DenseSet<ValuePair> IncomingPairs;
1885 // If the cost model were perfect, this might not be necessary; but we
1886 // need to make sure that we don't get stuck vectorizing our own
1888 bool HasNontrivialInsts = false;
1890 // The node weights represent the cost savings associated with
1891 // fusing the pair of instructions.
1892 for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
1893 E = PrunedDAG.end(); S != E; ++S) {
1894 if (!isa<ShuffleVectorInst>(S->first) &&
1895 !isa<InsertElementInst>(S->first) &&
1896 !isa<ExtractElementInst>(S->first))
1897 HasNontrivialInsts = true;
1899 bool FlipOrder = false;
1901 if (getDepthFactor(S->first)) {
1902 int ESContrib = CandidatePairCostSavings.find(*S)->second;
1903 DEBUG(if (DebugPairSelection) dbgs() << "\tweight {"
1904 << *S->first << " <-> " << *S->second << "} = " <<
1906 EffSize += ESContrib;
1909 // The edge weights contribute in a negative sense: they represent
1910 // the cost of shuffles.
1911 DenseMap<ValuePair, std::vector<ValuePair> >::iterator SS =
1912 ConnectedPairDeps.find(*S);
1913 if (SS != ConnectedPairDeps.end()) {
1914 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
1915 for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1916 TE = SS->second.end(); T != TE; ++T) {
1918 if (!PrunedDAG.count(Q.second))
1920 DenseMap<VPPair, unsigned>::iterator R =
1921 PairConnectionTypes.find(VPPair(Q.second, Q.first));
1922 assert(R != PairConnectionTypes.end() &&
1923 "Cannot find pair connection type");
1924 if (R->second == PairConnectionDirect)
1926 else if (R->second == PairConnectionSwap)
1930 // If there are more swaps than direct connections, then
1931 // the pair order will be flipped during fusion. So the real
1932 // number of swaps is the minimum number.
1933 FlipOrder = !FixedOrderPairs.count(*S) &&
1934 ((NumDepsSwap > NumDepsDirect) ||
1935 FixedOrderPairs.count(ValuePair(S->second, S->first)));
1937 for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1938 TE = SS->second.end(); T != TE; ++T) {
1940 if (!PrunedDAG.count(Q.second))
1942 DenseMap<VPPair, unsigned>::iterator R =
1943 PairConnectionTypes.find(VPPair(Q.second, Q.first));
1944 assert(R != PairConnectionTypes.end() &&
1945 "Cannot find pair connection type");
1946 Type *Ty1 = Q.second.first->getType(),
1947 *Ty2 = Q.second.second->getType();
1948 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1949 if ((R->second == PairConnectionDirect && FlipOrder) ||
1950 (R->second == PairConnectionSwap && !FlipOrder) ||
1951 R->second == PairConnectionSplat) {
1952 int ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1955 if (VTy->getVectorNumElements() == 2) {
1956 if (R->second == PairConnectionSplat)
1957 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1958 TargetTransformInfo::SK_Broadcast, VTy));
1960 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1961 TargetTransformInfo::SK_Reverse, VTy));
1964 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
1965 *Q.second.first << " <-> " << *Q.second.second <<
1967 *S->first << " <-> " << *S->second << "} = " <<
1969 EffSize -= ESContrib;
1974 // Compute the cost of outgoing edges. We assume that edges outgoing
1975 // to shuffles, inserts or extracts can be merged, and so contribute
1976 // no additional cost.
1977 if (!S->first->getType()->isVoidTy()) {
1978 Type *Ty1 = S->first->getType(),
1979 *Ty2 = S->second->getType();
1980 Type *VTy = getVecTypeForPair(Ty1, Ty2);
1982 bool NeedsExtraction = false;
1983 for (User *U : S->first->users()) {
1984 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
1985 // Shuffle can be folded if it has no other input
1986 if (isa<UndefValue>(SI->getOperand(1)))
1989 if (isa<ExtractElementInst>(U))
1991 if (PrunedDAGInstrs.count(U))
1993 NeedsExtraction = true;
1997 if (NeedsExtraction) {
1999 if (Ty1->isVectorTy()) {
2000 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2002 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2003 TargetTransformInfo::SK_ExtractSubvector, VTy, 0, Ty1));
2005 ESContrib = (int) TTI->getVectorInstrCost(
2006 Instruction::ExtractElement, VTy, 0);
2008 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
2009 *S->first << "} = " << ESContrib << "\n");
2010 EffSize -= ESContrib;
2013 NeedsExtraction = false;
2014 for (User *U : S->second->users()) {
2015 if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
2016 // Shuffle can be folded if it has no other input
2017 if (isa<UndefValue>(SI->getOperand(1)))
2020 if (isa<ExtractElementInst>(U))
2022 if (PrunedDAGInstrs.count(U))
2024 NeedsExtraction = true;
2028 if (NeedsExtraction) {
2030 if (Ty2->isVectorTy()) {
2031 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2033 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2034 TargetTransformInfo::SK_ExtractSubvector, VTy,
2035 Ty1->isVectorTy() ? Ty1->getVectorNumElements() : 1, Ty2));
2037 ESContrib = (int) TTI->getVectorInstrCost(
2038 Instruction::ExtractElement, VTy, 1);
2039 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
2040 *S->second << "} = " << ESContrib << "\n");
2041 EffSize -= ESContrib;
2045 // Compute the cost of incoming edges.
2046 if (!isa<LoadInst>(S->first) && !isa<StoreInst>(S->first)) {
2047 Instruction *S1 = cast<Instruction>(S->first),
2048 *S2 = cast<Instruction>(S->second);
2049 for (unsigned o = 0; o < S1->getNumOperands(); ++o) {
2050 Value *O1 = S1->getOperand(o), *O2 = S2->getOperand(o);
2052 // Combining constants into vector constants (or small vector
2053 // constants into larger ones are assumed free).
2054 if (isa<Constant>(O1) && isa<Constant>(O2))
2060 ValuePair VP = ValuePair(O1, O2);
2061 ValuePair VPR = ValuePair(O2, O1);
2063 // Internal edges are not handled here.
2064 if (PrunedDAG.count(VP) || PrunedDAG.count(VPR))
2067 Type *Ty1 = O1->getType(),
2068 *Ty2 = O2->getType();
2069 Type *VTy = getVecTypeForPair(Ty1, Ty2);
2071 // Combining vector operations of the same type is also assumed
2072 // folded with other operations.
2074 // If both are insert elements, then both can be widened.
2075 InsertElementInst *IEO1 = dyn_cast<InsertElementInst>(O1),
2076 *IEO2 = dyn_cast<InsertElementInst>(O2);
2077 if (IEO1 && IEO2 && isPureIEChain(IEO1) && isPureIEChain(IEO2))
2079 // If both are extract elements, and both have the same input
2080 // type, then they can be replaced with a shuffle
2081 ExtractElementInst *EIO1 = dyn_cast<ExtractElementInst>(O1),
2082 *EIO2 = dyn_cast<ExtractElementInst>(O2);
2084 EIO1->getOperand(0)->getType() ==
2085 EIO2->getOperand(0)->getType())
2087 // If both are a shuffle with equal operand types and only two
2088 // unqiue operands, then they can be replaced with a single
2090 ShuffleVectorInst *SIO1 = dyn_cast<ShuffleVectorInst>(O1),
2091 *SIO2 = dyn_cast<ShuffleVectorInst>(O2);
2093 SIO1->getOperand(0)->getType() ==
2094 SIO2->getOperand(0)->getType()) {
2095 SmallSet<Value *, 4> SIOps;
2096 SIOps.insert(SIO1->getOperand(0));
2097 SIOps.insert(SIO1->getOperand(1));
2098 SIOps.insert(SIO2->getOperand(0));
2099 SIOps.insert(SIO2->getOperand(1));
2100 if (SIOps.size() <= 2)
2106 // This pair has already been formed.
2107 if (IncomingPairs.count(VP)) {
2109 } else if (IncomingPairs.count(VPR)) {
2110 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2113 if (VTy->getVectorNumElements() == 2)
2114 ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2115 TargetTransformInfo::SK_Reverse, VTy));
2116 } else if (!Ty1->isVectorTy() && !Ty2->isVectorTy()) {
2117 ESContrib = (int) TTI->getVectorInstrCost(
2118 Instruction::InsertElement, VTy, 0);
2119 ESContrib += (int) TTI->getVectorInstrCost(
2120 Instruction::InsertElement, VTy, 1);
2121 } else if (!Ty1->isVectorTy()) {
2122 // O1 needs to be inserted into a vector of size O2, and then
2123 // both need to be shuffled together.
2124 ESContrib = (int) TTI->getVectorInstrCost(
2125 Instruction::InsertElement, Ty2, 0);
2126 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2128 } else if (!Ty2->isVectorTy()) {
2129 // O2 needs to be inserted into a vector of size O1, and then
2130 // both need to be shuffled together.
2131 ESContrib = (int) TTI->getVectorInstrCost(
2132 Instruction::InsertElement, Ty1, 0);
2133 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2136 Type *TyBig = Ty1, *TySmall = Ty2;
2137 if (Ty2->getVectorNumElements() > Ty1->getVectorNumElements())
2138 std::swap(TyBig, TySmall);
2140 ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2142 if (TyBig != TySmall)
2143 ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2147 DEBUG(if (DebugPairSelection) dbgs() << "\tcost {"
2148 << *O1 << " <-> " << *O2 << "} = " <<
2150 EffSize -= ESContrib;
2151 IncomingPairs.insert(VP);
2156 if (!HasNontrivialInsts) {
2157 DEBUG(if (DebugPairSelection) dbgs() <<
2158 "\tNo non-trivial instructions in DAG;"
2159 " override to zero effective size\n");
2163 for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
2164 E = PrunedDAG.end(); S != E; ++S)
2165 EffSize += (int) getDepthFactor(S->first);
2168 DEBUG(if (DebugPairSelection)
2169 dbgs() << "BBV: found pruned DAG for pair {"
2170 << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
2171 MaxDepth << " and size " << PrunedDAG.size() <<
2172 " (effective size: " << EffSize << ")\n");
2173 if (((TTI && !UseChainDepthWithTI) ||
2174 MaxDepth >= Config.ReqChainDepth) &&
2175 EffSize > 0 && EffSize > BestEffSize) {
2176 BestMaxDepth = MaxDepth;
2177 BestEffSize = EffSize;
2178 BestDAG = PrunedDAG;
2183 // Given the list of candidate pairs, this function selects those
2184 // that will be fused into vector instructions.
2185 void BBVectorize::choosePairs(
2186 DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
2187 DenseSet<ValuePair> &CandidatePairsSet,
2188 DenseMap<ValuePair, int> &CandidatePairCostSavings,
2189 std::vector<Value *> &PairableInsts,
2190 DenseSet<ValuePair> &FixedOrderPairs,
2191 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2192 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
2193 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
2194 DenseSet<ValuePair> &PairableInstUsers,
2195 DenseMap<Value *, Value *>& ChosenPairs) {
2196 bool UseCycleCheck =
2197 CandidatePairsSet.size() <= Config.MaxCandPairsForCycleCheck;
2199 DenseMap<Value *, std::vector<Value *> > CandidatePairs2;
2200 for (DenseSet<ValuePair>::iterator I = CandidatePairsSet.begin(),
2201 E = CandidatePairsSet.end(); I != E; ++I) {
2202 std::vector<Value *> &JJ = CandidatePairs2[I->second];
2203 if (JJ.empty()) JJ.reserve(32);
2204 JJ.push_back(I->first);
2207 DenseMap<ValuePair, std::vector<ValuePair> > PairableInstUserMap;
2208 DenseSet<VPPair> PairableInstUserPairSet;
2209 for (std::vector<Value *>::iterator I = PairableInsts.begin(),
2210 E = PairableInsts.end(); I != E; ++I) {
2211 // The number of possible pairings for this variable:
2212 size_t NumChoices = CandidatePairs.lookup(*I).size();
2213 if (!NumChoices) continue;
2215 std::vector<Value *> &JJ = CandidatePairs[*I];
2217 // The best pair to choose and its dag:
2218 size_t BestMaxDepth = 0;
2219 int BestEffSize = 0;
2220 DenseSet<ValuePair> BestDAG;
2221 findBestDAGFor(CandidatePairs, CandidatePairsSet,
2222 CandidatePairCostSavings,
2223 PairableInsts, FixedOrderPairs, PairConnectionTypes,
2224 ConnectedPairs, ConnectedPairDeps,
2225 PairableInstUsers, PairableInstUserMap,
2226 PairableInstUserPairSet, ChosenPairs,
2227 BestDAG, BestMaxDepth, BestEffSize, *I, JJ,
2230 if (BestDAG.empty())
2233 // A dag has been chosen (or not) at this point. If no dag was
2234 // chosen, then this instruction, I, cannot be paired (and is no longer
2237 DEBUG(dbgs() << "BBV: selected pairs in the best DAG for: "
2238 << *cast<Instruction>(*I) << "\n");
2240 for (DenseSet<ValuePair>::iterator S = BestDAG.begin(),
2241 SE2 = BestDAG.end(); S != SE2; ++S) {
2242 // Insert the members of this dag into the list of chosen pairs.
2243 ChosenPairs.insert(ValuePair(S->first, S->second));
2244 DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
2245 *S->second << "\n");
2247 // Remove all candidate pairs that have values in the chosen dag.
2248 std::vector<Value *> &KK = CandidatePairs[S->first];
2249 for (std::vector<Value *>::iterator K = KK.begin(), KE = KK.end();
2251 if (*K == S->second)
2254 CandidatePairsSet.erase(ValuePair(S->first, *K));
2257 std::vector<Value *> &LL = CandidatePairs2[S->second];
2258 for (std::vector<Value *>::iterator L = LL.begin(), LE = LL.end();
2263 CandidatePairsSet.erase(ValuePair(*L, S->second));
2266 std::vector<Value *> &MM = CandidatePairs[S->second];
2267 for (std::vector<Value *>::iterator M = MM.begin(), ME = MM.end();
2269 assert(*M != S->first && "Flipped pair in candidate list?");
2270 CandidatePairsSet.erase(ValuePair(S->second, *M));
2273 std::vector<Value *> &NN = CandidatePairs2[S->first];
2274 for (std::vector<Value *>::iterator N = NN.begin(), NE = NN.end();
2276 assert(*N != S->second && "Flipped pair in candidate list?");
2277 CandidatePairsSet.erase(ValuePair(*N, S->first));
2282 DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
2285 std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
2290 return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
2291 (n > 0 ? "." + utostr(n) : "")).str();
2294 // Returns the value that is to be used as the pointer input to the vector
2295 // instruction that fuses I with J.
2296 Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
2297 Instruction *I, Instruction *J, unsigned o) {
2299 unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
2300 int64_t OffsetInElmts;
2302 // Note: the analysis might fail here, that is why the pair order has
2303 // been precomputed (OffsetInElmts must be unused here).
2304 (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
2305 IAddressSpace, JAddressSpace,
2306 OffsetInElmts, false);
2308 // The pointer value is taken to be the one with the lowest offset.
2311 Type *ArgTypeI = IPtr->getType()->getPointerElementType();
2312 Type *ArgTypeJ = JPtr->getType()->getPointerElementType();
2313 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2315 = PointerType::get(VArgType,
2316 IPtr->getType()->getPointerAddressSpace());
2317 return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
2318 /* insert before */ I);
2321 void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
2322 unsigned MaskOffset, unsigned NumInElem,
2323 unsigned NumInElem1, unsigned IdxOffset,
2324 std::vector<Constant*> &Mask) {
2325 unsigned NumElem1 = J->getType()->getVectorNumElements();
2326 for (unsigned v = 0; v < NumElem1; ++v) {
2327 int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
2329 Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
2331 unsigned mm = m + (int) IdxOffset;
2332 if (m >= (int) NumInElem1)
2333 mm += (int) NumInElem;
2335 Mask[v+MaskOffset] =
2336 ConstantInt::get(Type::getInt32Ty(Context), mm);
2341 // Returns the value that is to be used as the vector-shuffle mask to the
2342 // vector instruction that fuses I with J.
2343 Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
2344 Instruction *I, Instruction *J) {
2345 // This is the shuffle mask. We need to append the second
2346 // mask to the first, and the numbers need to be adjusted.
2348 Type *ArgTypeI = I->getType();
2349 Type *ArgTypeJ = J->getType();
2350 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2352 unsigned NumElemI = ArgTypeI->getVectorNumElements();
2354 // Get the total number of elements in the fused vector type.
2355 // By definition, this must equal the number of elements in
2357 unsigned NumElem = VArgType->getVectorNumElements();
2358 std::vector<Constant*> Mask(NumElem);
2360 Type *OpTypeI = I->getOperand(0)->getType();
2361 unsigned NumInElemI = OpTypeI->getVectorNumElements();
2362 Type *OpTypeJ = J->getOperand(0)->getType();
2363 unsigned NumInElemJ = OpTypeJ->getVectorNumElements();
2365 // The fused vector will be:
2366 // -----------------------------------------------------
2367 // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
2368 // -----------------------------------------------------
2369 // from which we'll extract NumElem total elements (where the first NumElemI
2370 // of them come from the mask in I and the remainder come from the mask
2373 // For the mask from the first pair...
2374 fillNewShuffleMask(Context, I, 0, NumInElemJ, NumInElemI,
2377 // For the mask from the second pair...
2378 fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
2381 return ConstantVector::get(Mask);
2384 bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
2385 Instruction *J, unsigned o, Value *&LOp,
2387 Type *ArgTypeL, Type *ArgTypeH,
2388 bool IBeforeJ, unsigned IdxOff) {
2389 bool ExpandedIEChain = false;
2390 if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
2391 // If we have a pure insertelement chain, then this can be rewritten
2392 // into a chain that directly builds the larger type.
2393 if (isPureIEChain(LIE)) {
2394 SmallVector<Value *, 8> VectElemts(numElemL,
2395 UndefValue::get(ArgTypeL->getScalarType()));
2396 InsertElementInst *LIENext = LIE;
2399 cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
2400 VectElemts[Idx] = LIENext->getOperand(1);
2402 dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
2405 Value *LIEPrev = UndefValue::get(ArgTypeH);
2406 for (unsigned i = 0; i < numElemL; ++i) {
2407 if (isa<UndefValue>(VectElemts[i])) continue;
2408 LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
2409 ConstantInt::get(Type::getInt32Ty(Context),
2411 getReplacementName(IBeforeJ ? I : J,
2413 LIENext->insertBefore(IBeforeJ ? J : I);
2417 LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
2418 ExpandedIEChain = true;
2422 return ExpandedIEChain;
2425 static unsigned getNumScalarElements(Type *Ty) {
2426 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
2427 return VecTy->getNumElements();
2431 // Returns the value to be used as the specified operand of the vector
2432 // instruction that fuses I with J.
2433 Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
2434 Instruction *J, unsigned o, bool IBeforeJ) {
2435 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2436 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
2438 // Compute the fused vector type for this operand
2439 Type *ArgTypeI = I->getOperand(o)->getType();
2440 Type *ArgTypeJ = J->getOperand(o)->getType();
2441 VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2443 Instruction *L = I, *H = J;
2444 Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
2446 unsigned numElemL = getNumScalarElements(ArgTypeL);
2447 unsigned numElemH = getNumScalarElements(ArgTypeH);
2449 Value *LOp = L->getOperand(o);
2450 Value *HOp = H->getOperand(o);
2451 unsigned numElem = VArgType->getNumElements();
2453 // First, we check if we can reuse the "original" vector outputs (if these
2454 // exist). We might need a shuffle.
2455 ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
2456 ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
2457 ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
2458 ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
2460 // FIXME: If we're fusing shuffle instructions, then we can't apply this
2461 // optimization. The input vectors to the shuffle might be a different
2462 // length from the shuffle outputs. Unfortunately, the replacement
2463 // shuffle mask has already been formed, and the mask entries are sensitive
2464 // to the sizes of the inputs.
2465 bool IsSizeChangeShuffle =
2466 isa<ShuffleVectorInst>(L) &&
2467 (LOp->getType() != L->getType() || HOp->getType() != H->getType());
2469 if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
2470 // We can have at most two unique vector inputs.
2471 bool CanUseInputs = true;
2472 Value *I1, *I2 = nullptr;
2474 I1 = LEE->getOperand(0);
2476 I1 = LSV->getOperand(0);
2477 I2 = LSV->getOperand(1);
2478 if (I2 == I1 || isa<UndefValue>(I2))
2483 Value *I3 = HEE->getOperand(0);
2484 if (!I2 && I3 != I1)
2486 else if (I3 != I1 && I3 != I2)
2487 CanUseInputs = false;
2489 Value *I3 = HSV->getOperand(0);
2490 if (!I2 && I3 != I1)
2492 else if (I3 != I1 && I3 != I2)
2493 CanUseInputs = false;
2496 Value *I4 = HSV->getOperand(1);
2497 if (!isa<UndefValue>(I4)) {
2498 if (!I2 && I4 != I1)
2500 else if (I4 != I1 && I4 != I2)
2501 CanUseInputs = false;
2508 cast<Instruction>(LOp)->getOperand(0)->getType()
2509 ->getVectorNumElements();
2512 cast<Instruction>(HOp)->getOperand(0)->getType()
2513 ->getVectorNumElements();
2515 // We have one or two input vectors. We need to map each index of the
2516 // operands to the index of the original vector.
2517 SmallVector<std::pair<int, int>, 8> II(numElem);
2518 for (unsigned i = 0; i < numElemL; ++i) {
2522 cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
2523 INum = LEE->getOperand(0) == I1 ? 0 : 1;
2525 Idx = LSV->getMaskValue(i);
2526 if (Idx < (int) LOpElem) {
2527 INum = LSV->getOperand(0) == I1 ? 0 : 1;
2530 INum = LSV->getOperand(1) == I1 ? 0 : 1;
2534 II[i] = std::pair<int, int>(Idx, INum);
2536 for (unsigned i = 0; i < numElemH; ++i) {
2540 cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
2541 INum = HEE->getOperand(0) == I1 ? 0 : 1;
2543 Idx = HSV->getMaskValue(i);
2544 if (Idx < (int) HOpElem) {
2545 INum = HSV->getOperand(0) == I1 ? 0 : 1;
2548 INum = HSV->getOperand(1) == I1 ? 0 : 1;
2552 II[i + numElemL] = std::pair<int, int>(Idx, INum);
2555 // We now have an array which tells us from which index of which
2556 // input vector each element of the operand comes.
2557 VectorType *I1T = cast<VectorType>(I1->getType());
2558 unsigned I1Elem = I1T->getNumElements();
2561 // In this case there is only one underlying vector input. Check for
2562 // the trivial case where we can use the input directly.
2563 if (I1Elem == numElem) {
2564 bool ElemInOrder = true;
2565 for (unsigned i = 0; i < numElem; ++i) {
2566 if (II[i].first != (int) i && II[i].first != -1) {
2567 ElemInOrder = false;
2576 // A shuffle is needed.
2577 std::vector<Constant *> Mask(numElem);
2578 for (unsigned i = 0; i < numElem; ++i) {
2579 int Idx = II[i].first;
2581 Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
2583 Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2587 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2588 ConstantVector::get(Mask),
2589 getReplacementName(IBeforeJ ? I : J,
2591 S->insertBefore(IBeforeJ ? J : I);
2595 VectorType *I2T = cast<VectorType>(I2->getType());
2596 unsigned I2Elem = I2T->getNumElements();
2598 // This input comes from two distinct vectors. The first step is to
2599 // make sure that both vectors are the same length. If not, the
2600 // smaller one will need to grow before they can be shuffled together.
2601 if (I1Elem < I2Elem) {
2602 std::vector<Constant *> Mask(I2Elem);
2604 for (; v < I1Elem; ++v)
2605 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2606 for (; v < I2Elem; ++v)
2607 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2609 Instruction *NewI1 =
2610 new ShuffleVectorInst(I1, UndefValue::get(I1T),
2611 ConstantVector::get(Mask),
2612 getReplacementName(IBeforeJ ? I : J,
2614 NewI1->insertBefore(IBeforeJ ? J : I);
2617 } else if (I1Elem > I2Elem) {
2618 std::vector<Constant *> Mask(I1Elem);
2620 for (; v < I2Elem; ++v)
2621 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2622 for (; v < I1Elem; ++v)
2623 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2625 Instruction *NewI2 =
2626 new ShuffleVectorInst(I2, UndefValue::get(I2T),
2627 ConstantVector::get(Mask),
2628 getReplacementName(IBeforeJ ? I : J,
2630 NewI2->insertBefore(IBeforeJ ? J : I);
2634 // Now that both I1 and I2 are the same length we can shuffle them
2635 // together (and use the result).
2636 std::vector<Constant *> Mask(numElem);
2637 for (unsigned v = 0; v < numElem; ++v) {
2638 if (II[v].first == -1) {
2639 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2641 int Idx = II[v].first + II[v].second * I1Elem;
2642 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2646 Instruction *NewOp =
2647 new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
2648 getReplacementName(IBeforeJ ? I : J, true, o));
2649 NewOp->insertBefore(IBeforeJ ? J : I);
2654 Type *ArgType = ArgTypeL;
2655 if (numElemL < numElemH) {
2656 if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
2657 ArgTypeL, VArgType, IBeforeJ, 1)) {
2658 // This is another short-circuit case: we're combining a scalar into
2659 // a vector that is formed by an IE chain. We've just expanded the IE
2660 // chain, now insert the scalar and we're done.
2662 Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
2663 getReplacementName(IBeforeJ ? I : J, true, o));
2664 S->insertBefore(IBeforeJ ? J : I);
2666 } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
2667 ArgTypeH, IBeforeJ)) {
2668 // The two vector inputs to the shuffle must be the same length,
2669 // so extend the smaller vector to be the same length as the larger one.
2673 std::vector<Constant *> Mask(numElemH);
2675 for (; v < numElemL; ++v)
2676 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2677 for (; v < numElemH; ++v)
2678 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2680 NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2681 ConstantVector::get(Mask),
2682 getReplacementName(IBeforeJ ? I : J,
2685 NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2686 getReplacementName(IBeforeJ ? I : J,
2690 NLOp->insertBefore(IBeforeJ ? J : I);
2695 } else if (numElemL > numElemH) {
2696 if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2697 ArgTypeH, VArgType, IBeforeJ)) {
2699 InsertElementInst::Create(LOp, HOp,
2700 ConstantInt::get(Type::getInt32Ty(Context),
2702 getReplacementName(IBeforeJ ? I : J,
2704 S->insertBefore(IBeforeJ ? J : I);
2706 } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2707 ArgTypeL, IBeforeJ)) {
2710 std::vector<Constant *> Mask(numElemL);
2712 for (; v < numElemH; ++v)
2713 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2714 for (; v < numElemL; ++v)
2715 Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2717 NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2718 ConstantVector::get(Mask),
2719 getReplacementName(IBeforeJ ? I : J,
2722 NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2723 getReplacementName(IBeforeJ ? I : J,
2727 NHOp->insertBefore(IBeforeJ ? J : I);
2732 if (ArgType->isVectorTy()) {
2733 unsigned numElem = VArgType->getVectorNumElements();
2734 std::vector<Constant*> Mask(numElem);
2735 for (unsigned v = 0; v < numElem; ++v) {
2737 // If the low vector was expanded, we need to skip the extra
2738 // undefined entries.
2739 if (v >= numElemL && numElemH > numElemL)
2740 Idx += (numElemH - numElemL);
2741 Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2744 Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2745 ConstantVector::get(Mask),
2746 getReplacementName(IBeforeJ ? I : J, true, o));
2747 BV->insertBefore(IBeforeJ ? J : I);
2751 Instruction *BV1 = InsertElementInst::Create(
2752 UndefValue::get(VArgType), LOp, CV0,
2753 getReplacementName(IBeforeJ ? I : J,
2755 BV1->insertBefore(IBeforeJ ? J : I);
2756 Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
2757 getReplacementName(IBeforeJ ? I : J,
2759 BV2->insertBefore(IBeforeJ ? J : I);
2763 // This function creates an array of values that will be used as the inputs
2764 // to the vector instruction that fuses I with J.
2765 void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
2766 Instruction *I, Instruction *J,
2767 SmallVectorImpl<Value *> &ReplacedOperands,
2769 unsigned NumOperands = I->getNumOperands();
2771 for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
2772 // Iterate backward so that we look at the store pointer
2773 // first and know whether or not we need to flip the inputs.
2775 if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
2776 // This is the pointer for a load/store instruction.
2777 ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
2779 } else if (isa<CallInst>(I)) {
2780 Function *F = cast<CallInst>(I)->getCalledFunction();
2781 Intrinsic::ID IID = F->getIntrinsicID();
2782 if (o == NumOperands-1) {
2783 BasicBlock &BB = *I->getParent();
2785 Module *M = BB.getParent()->getParent();
2786 Type *ArgTypeI = I->getType();
2787 Type *ArgTypeJ = J->getType();
2788 Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2790 ReplacedOperands[o] = Intrinsic::getDeclaration(M, IID, VArgType);
2792 } else if ((IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
2793 IID == Intrinsic::cttz) && o == 1) {
2794 // The second argument of powi/ctlz/cttz is a single integer/constant
2795 // and we've already checked that both arguments are equal.
2796 // As a result, we just keep I's second argument.
2797 ReplacedOperands[o] = I->getOperand(o);
2800 } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2801 ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2805 ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
2809 // This function creates two values that represent the outputs of the
2810 // original I and J instructions. These are generally vector shuffles
2811 // or extracts. In many cases, these will end up being unused and, thus,
2812 // eliminated by later passes.
2813 void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2814 Instruction *J, Instruction *K,
2815 Instruction *&InsertionPt,
2816 Instruction *&K1, Instruction *&K2) {
2817 if (isa<StoreInst>(I))
2820 Type *IType = I->getType();
2821 Type *JType = J->getType();
2823 VectorType *VType = getVecTypeForPair(IType, JType);
2824 unsigned numElem = VType->getNumElements();
2826 unsigned numElemI = getNumScalarElements(IType);
2827 unsigned numElemJ = getNumScalarElements(JType);
2829 if (IType->isVectorTy()) {
2830 std::vector<Constant *> Mask1(numElemI), Mask2(numElemI);
2831 for (unsigned v = 0; v < numElemI; ++v) {
2832 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2833 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ + v);
2836 K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2837 ConstantVector::get(Mask1),
2838 getReplacementName(K, false, 1));
2840 Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2841 K1 = ExtractElementInst::Create(K, CV0, getReplacementName(K, false, 1));
2844 if (JType->isVectorTy()) {
2845 std::vector<Constant *> Mask1(numElemJ), Mask2(numElemJ);
2846 for (unsigned v = 0; v < numElemJ; ++v) {
2847 Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2848 Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI + v);
2851 K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2852 ConstantVector::get(Mask2),
2853 getReplacementName(K, false, 2));
2855 Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem - 1);
2856 K2 = ExtractElementInst::Create(K, CV1, getReplacementName(K, false, 2));
2860 K2->insertAfter(K1);
2864 // Move all uses of the function I (including pairing-induced uses) after J.
2865 bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2866 DenseSet<ValuePair> &LoadMoveSetPairs,
2867 Instruction *I, Instruction *J) {
2868 // Skip to the first instruction past I.
2869 BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2871 DenseSet<Value *> Users;
2872 AliasSetTracker WriteSet(*AA);
2873 if (I->mayWriteToMemory()) WriteSet.add(I);
2875 for (; cast<Instruction>(L) != J; ++L)
2876 (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
2878 assert(cast<Instruction>(L) == J &&
2879 "Tracking has not proceeded far enough to check for dependencies");
2880 // If J is now in the use set of I, then trackUsesOfI will return true
2881 // and we have a dependency cycle (and the fusing operation must abort).
2882 return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSetPairs);
2885 // Move all uses of the function I (including pairing-induced uses) after J.
2886 void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2887 DenseSet<ValuePair> &LoadMoveSetPairs,
2888 Instruction *&InsertionPt,
2889 Instruction *I, Instruction *J) {
2890 // Skip to the first instruction past I.
2891 BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2893 DenseSet<Value *> Users;
2894 AliasSetTracker WriteSet(*AA);
2895 if (I->mayWriteToMemory()) WriteSet.add(I);
2897 for (; cast<Instruction>(L) != J;) {
2898 if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
2899 // Move this instruction
2900 Instruction *InstToMove = L; ++L;
2902 DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2903 " to after " << *InsertionPt << "\n");
2904 InstToMove->removeFromParent();
2905 InstToMove->insertAfter(InsertionPt);
2906 InsertionPt = InstToMove;
2913 // Collect all load instruction that are in the move set of a given first
2914 // pair member. These loads depend on the first instruction, I, and so need
2915 // to be moved after J (the second instruction) when the pair is fused.
2916 void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2917 DenseMap<Value *, Value *> &ChosenPairs,
2918 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2919 DenseSet<ValuePair> &LoadMoveSetPairs,
2921 // Skip to the first instruction past I.
2922 BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2924 DenseSet<Value *> Users;
2925 AliasSetTracker WriteSet(*AA);
2926 if (I->mayWriteToMemory()) WriteSet.add(I);
2928 // Note: We cannot end the loop when we reach J because J could be moved
2929 // farther down the use chain by another instruction pairing. Also, J
2930 // could be before I if this is an inverted input.
2931 for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
2932 if (trackUsesOfI(Users, WriteSet, I, L)) {
2933 if (L->mayReadFromMemory()) {
2934 LoadMoveSet[L].push_back(I);
2935 LoadMoveSetPairs.insert(ValuePair(L, I));
2941 // In cases where both load/stores and the computation of their pointers
2942 // are chosen for vectorization, we can end up in a situation where the
2943 // aliasing analysis starts returning different query results as the
2944 // process of fusing instruction pairs continues. Because the algorithm
2945 // relies on finding the same use dags here as were found earlier, we'll
2946 // need to precompute the necessary aliasing information here and then
2947 // manually update it during the fusion process.
2948 void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2949 std::vector<Value *> &PairableInsts,
2950 DenseMap<Value *, Value *> &ChosenPairs,
2951 DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2952 DenseSet<ValuePair> &LoadMoveSetPairs) {
2953 for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2954 PIE = PairableInsts.end(); PI != PIE; ++PI) {
2955 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2956 if (P == ChosenPairs.end()) continue;
2958 Instruction *I = cast<Instruction>(P->first);
2959 collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet,
2960 LoadMoveSetPairs, I);
2964 // This function fuses the chosen instruction pairs into vector instructions,
2965 // taking care preserve any needed scalar outputs and, then, it reorders the
2966 // remaining instructions as needed (users of the first member of the pair
2967 // need to be moved to after the location of the second member of the pair
2968 // because the vector instruction is inserted in the location of the pair's
2970 void BBVectorize::fuseChosenPairs(BasicBlock &BB,
2971 std::vector<Value *> &PairableInsts,
2972 DenseMap<Value *, Value *> &ChosenPairs,
2973 DenseSet<ValuePair> &FixedOrderPairs,
2974 DenseMap<VPPair, unsigned> &PairConnectionTypes,
2975 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
2976 DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps) {
2977 LLVMContext& Context = BB.getContext();
2979 // During the vectorization process, the order of the pairs to be fused
2980 // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
2981 // list. After a pair is fused, the flipped pair is removed from the list.
2982 DenseSet<ValuePair> FlippedPairs;
2983 for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
2984 E = ChosenPairs.end(); P != E; ++P)
2985 FlippedPairs.insert(ValuePair(P->second, P->first));
2986 for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
2987 E = FlippedPairs.end(); P != E; ++P)
2988 ChosenPairs.insert(*P);
2990 DenseMap<Value *, std::vector<Value *> > LoadMoveSet;
2991 DenseSet<ValuePair> LoadMoveSetPairs;
2992 collectLoadMoveSet(BB, PairableInsts, ChosenPairs,
2993 LoadMoveSet, LoadMoveSetPairs);
2995 DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
2997 for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
2998 DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
2999 if (P == ChosenPairs.end()) {
3004 if (getDepthFactor(P->first) == 0) {
3005 // These instructions are not really fused, but are tracked as though
3006 // they are. Any case in which it would be interesting to fuse them
3007 // will be taken care of by InstCombine.
3013 Instruction *I = cast<Instruction>(P->first),
3014 *J = cast<Instruction>(P->second);
3016 DEBUG(dbgs() << "BBV: fusing: " << *I <<
3017 " <-> " << *J << "\n");
3019 // Remove the pair and flipped pair from the list.
3020 DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
3021 assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
3022 ChosenPairs.erase(FP);
3023 ChosenPairs.erase(P);
3025 if (!canMoveUsesOfIAfterJ(BB, LoadMoveSetPairs, I, J)) {
3026 DEBUG(dbgs() << "BBV: fusion of: " << *I <<
3028 " aborted because of non-trivial dependency cycle\n");
3034 // If the pair must have the other order, then flip it.
3035 bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
3036 if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
3037 // This pair does not have a fixed order, and so we might want to
3038 // flip it if that will yield fewer shuffles. We count the number
3039 // of dependencies connected via swaps, and those directly connected,
3040 // and flip the order if the number of swaps is greater.
3041 bool OrigOrder = true;
3042 DenseMap<ValuePair, std::vector<ValuePair> >::iterator IJ =
3043 ConnectedPairDeps.find(ValuePair(I, J));
3044 if (IJ == ConnectedPairDeps.end()) {
3045 IJ = ConnectedPairDeps.find(ValuePair(J, I));
3049 if (IJ != ConnectedPairDeps.end()) {
3050 unsigned NumDepsDirect = 0, NumDepsSwap = 0;
3051 for (std::vector<ValuePair>::iterator T = IJ->second.begin(),
3052 TE = IJ->second.end(); T != TE; ++T) {
3053 VPPair Q(IJ->first, *T);
3054 DenseMap<VPPair, unsigned>::iterator R =
3055 PairConnectionTypes.find(VPPair(Q.second, Q.first));
3056 assert(R != PairConnectionTypes.end() &&
3057 "Cannot find pair connection type");
3058 if (R->second == PairConnectionDirect)
3060 else if (R->second == PairConnectionSwap)
3065 std::swap(NumDepsDirect, NumDepsSwap);
3067 if (NumDepsSwap > NumDepsDirect) {
3068 FlipPairOrder = true;
3069 DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
3070 " <-> " << *J << "\n");
3075 Instruction *L = I, *H = J;
3079 // If the pair being fused uses the opposite order from that in the pair
3080 // connection map, then we need to flip the types.
3081 DenseMap<ValuePair, std::vector<ValuePair> >::iterator HL =
3082 ConnectedPairs.find(ValuePair(H, L));
3083 if (HL != ConnectedPairs.end())
3084 for (std::vector<ValuePair>::iterator T = HL->second.begin(),
3085 TE = HL->second.end(); T != TE; ++T) {
3086 VPPair Q(HL->first, *T);
3087 DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(Q);
3088 assert(R != PairConnectionTypes.end() &&
3089 "Cannot find pair connection type");
3090 if (R->second == PairConnectionDirect)
3091 R->second = PairConnectionSwap;
3092 else if (R->second == PairConnectionSwap)
3093 R->second = PairConnectionDirect;
3096 bool LBeforeH = !FlipPairOrder;
3097 unsigned NumOperands = I->getNumOperands();
3098 SmallVector<Value *, 3> ReplacedOperands(NumOperands);
3099 getReplacementInputsForPair(Context, L, H, ReplacedOperands,
3102 // Make a copy of the original operation, change its type to the vector
3103 // type and replace its operands with the vector operands.
3104 Instruction *K = L->clone();
3107 else if (H->hasName())
3110 if (auto CS = CallSite(K)) {
3111 SmallVector<Type *, 3> Tys;
3112 FunctionType *Old = CS.getFunctionType();
3113 unsigned NumOld = Old->getNumParams();
3114 assert(NumOld <= ReplacedOperands.size());
3115 for (unsigned i = 0; i != NumOld; ++i)
3116 Tys.push_back(ReplacedOperands[i]->getType());
3117 CS.mutateFunctionType(
3118 FunctionType::get(getVecTypeForPair(L->getType(), H->getType()),
3119 Tys, Old->isVarArg()));
3120 } else if (!isa<StoreInst>(K))
3121 K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
3123 unsigned KnownIDs[] = {
3124 LLVMContext::MD_tbaa,
3125 LLVMContext::MD_alias_scope,
3126 LLVMContext::MD_noalias,
3127 LLVMContext::MD_fpmath
3129 combineMetadata(K, H, KnownIDs);
3130 K->intersectOptionalDataWith(H);
3132 for (unsigned o = 0; o < NumOperands; ++o)
3133 K->setOperand(o, ReplacedOperands[o]);
3137 // Instruction insertion point:
3138 Instruction *InsertionPt = K;
3139 Instruction *K1 = nullptr, *K2 = nullptr;
3140 replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
3142 // The use dag of the first original instruction must be moved to after
3143 // the location of the second instruction. The entire use dag of the
3144 // first instruction is disjoint from the input dag of the second
3145 // (by definition), and so commutes with it.
3147 moveUsesOfIAfterJ(BB, LoadMoveSetPairs, InsertionPt, I, J);
3149 if (!isa<StoreInst>(I)) {
3150 L->replaceAllUsesWith(K1);
3151 H->replaceAllUsesWith(K2);
3154 // Instructions that may read from memory may be in the load move set.
3155 // Once an instruction is fused, we no longer need its move set, and so
3156 // the values of the map never need to be updated. However, when a load
3157 // is fused, we need to merge the entries from both instructions in the
3158 // pair in case those instructions were in the move set of some other
3159 // yet-to-be-fused pair. The loads in question are the keys of the map.
3160 if (I->mayReadFromMemory()) {
3161 std::vector<ValuePair> NewSetMembers;
3162 DenseMap<Value *, std::vector<Value *> >::iterator II =
3163 LoadMoveSet.find(I);
3164 if (II != LoadMoveSet.end())
3165 for (std::vector<Value *>::iterator N = II->second.begin(),
3166 NE = II->second.end(); N != NE; ++N)
3167 NewSetMembers.push_back(ValuePair(K, *N));
3168 DenseMap<Value *, std::vector<Value *> >::iterator JJ =
3169 LoadMoveSet.find(J);
3170 if (JJ != LoadMoveSet.end())
3171 for (std::vector<Value *>::iterator N = JJ->second.begin(),
3172 NE = JJ->second.end(); N != NE; ++N)
3173 NewSetMembers.push_back(ValuePair(K, *N));
3174 for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
3175 AE = NewSetMembers.end(); A != AE; ++A) {
3176 LoadMoveSet[A->first].push_back(A->second);
3177 LoadMoveSetPairs.insert(*A);
3181 // Before removing I, set the iterator to the next instruction.
3182 PI = std::next(BasicBlock::iterator(I));
3183 if (cast<Instruction>(PI) == J)
3188 I->eraseFromParent();
3189 J->eraseFromParent();
3191 DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
3195 DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
3199 char BBVectorize::ID = 0;
3200 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
3201 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3202 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3203 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3204 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3205 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
3206 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3207 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
3208 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3209 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
3210 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3212 BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
3213 return new BBVectorize(C);
3217 llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
3218 BBVectorize BBVectorizer(P, *BB.getParent(), C);
3219 return BBVectorizer.vectorizeBB(BB);
3222 //===----------------------------------------------------------------------===//
3223 VectorizeConfig::VectorizeConfig() {
3224 VectorBits = ::VectorBits;
3225 VectorizeBools = !::NoBools;
3226 VectorizeInts = !::NoInts;
3227 VectorizeFloats = !::NoFloats;
3228 VectorizePointers = !::NoPointers;
3229 VectorizeCasts = !::NoCasts;
3230 VectorizeMath = !::NoMath;
3231 VectorizeBitManipulations = !::NoBitManipulation;
3232 VectorizeFMA = !::NoFMA;
3233 VectorizeSelect = !::NoSelect;
3234 VectorizeCmp = !::NoCmp;
3235 VectorizeGEP = !::NoGEP;
3236 VectorizeMemOps = !::NoMemOps;
3237 AlignedOnly = ::AlignedOnly;
3238 ReqChainDepth= ::ReqChainDepth;
3239 SearchLimit = ::SearchLimit;
3240 MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
3241 SplatBreaksChain = ::SplatBreaksChain;
3242 MaxInsts = ::MaxInsts;
3243 MaxPairs = ::MaxPairs;
3244 MaxIter = ::MaxIter;
3245 Pow2LenOnly = ::Pow2LenOnly;
3246 NoMemOpBoost = ::NoMemOpBoost;
3247 FastDep = ::FastDep;