LLVM  5.0.0svn
BBVectorize.cpp
Go to the documentation of this file.
1 //===- BBVectorize.cpp - A Basic-Block Vectorizer -------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a basic-block vectorization pass. The algorithm was
11 // inspired by that used by the Vienna MAP Vectorizor by Franchetti and Kral,
12 // et al. It works by looking for chains of pairable operations and then
13 // pairing them.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #define BBV_NAME "bb-vectorize"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/Metadata.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/IR/ValueHandle.h"
47 #include "llvm/Pass.h"
49 #include "llvm/Support/Debug.h"
53 #include <algorithm>
54 using namespace llvm;
55 
56 #define DEBUG_TYPE BBV_NAME
57 
58 static cl::opt<bool>
59 IgnoreTargetInfo("bb-vectorize-ignore-target-info", cl::init(false),
60  cl::Hidden, cl::desc("Ignore target information"));
61 
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"));
65 
66 static cl::opt<bool>
67 UseChainDepthWithTI("bb-vectorize-use-chain-depth", cl::init(false),
68  cl::Hidden, cl::desc("Use the chain depth requirement with"
69  " target information"));
70 
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"));
74 
75 static cl::opt<bool>
76 SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
77  cl::desc("Replicating one element to a pair breaks the chain"));
78 
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"));
82 
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"));
86 
87 static cl::opt<bool>
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"));
90 
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"));
94 
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"));
98 
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"));
103 
104 static cl::opt<bool>
105 NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
106  cl::desc("Don't try to vectorize boolean (i1) values"));
107 
108 static cl::opt<bool>
109 NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
110  cl::desc("Don't try to vectorize integer values"));
111 
112 static cl::opt<bool>
113 NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
114  cl::desc("Don't try to vectorize floating-point values"));
115 
116 // FIXME: This should default to false once pointer vector support works.
117 static cl::opt<bool>
118 NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
119  cl::desc("Don't try to vectorize pointer values"));
120 
121 static cl::opt<bool>
122 NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
123  cl::desc("Don't try to vectorize casting (conversion) operations"));
124 
125 static cl::opt<bool>
126 NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
127  cl::desc("Don't try to vectorize floating-point math intrinsics"));
128 
129 static cl::opt<bool>
130  NoBitManipulation("bb-vectorize-no-bitmanip", cl::init(false), cl::Hidden,
131  cl::desc("Don't try to vectorize BitManipulation intrinsics"));
132 
133 static cl::opt<bool>
134 NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
135  cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
136 
137 static cl::opt<bool>
138 NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
139  cl::desc("Don't try to vectorize select instructions"));
140 
141 static cl::opt<bool>
142 NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
143  cl::desc("Don't try to vectorize comparison instructions"));
144 
145 static cl::opt<bool>
146 NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
147  cl::desc("Don't try to vectorize getelementptr instructions"));
148 
149 static cl::opt<bool>
150 NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
151  cl::desc("Don't try to vectorize loads and stores"));
152 
153 static cl::opt<bool>
154 AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
155  cl::desc("Only generate aligned loads and stores"));
156 
157 static cl::opt<bool>
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"));
161 
162 static cl::opt<bool>
163 FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
164  cl::desc("Use a fast instruction dependency analysis"));
165 
166 #ifndef NDEBUG
167 static cl::opt<bool>
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"));
172 static cl::opt<bool>
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"));
177 static cl::opt<bool>
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"));
182 static cl::opt<bool>
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"));
187 
188 static cl::opt<bool>
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"));
193 #endif
194 
195 STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
196 
197 namespace {
198  struct BBVectorize : public BasicBlockPass {
199  static char ID; // Pass identification, replacement for typeid
200 
201  const VectorizeConfig Config;
202 
203  BBVectorize(const VectorizeConfig &C = VectorizeConfig())
204  : BasicBlockPass(ID), Config(C) {
206  }
207 
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
215  ? nullptr
216  : &P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
217  }
218 
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;
224 
225  AliasAnalysis *AA;
226  DominatorTree *DT;
227  ScalarEvolution *SE;
228  const TargetLibraryInfo *TLI;
229  const TargetTransformInfo *TTI;
230 
231  // FIXME: const correct?
232 
233  bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
234 
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);
241 
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,
247  PairConnectionSwap,
248  PairConnectionSplat
249  };
250 
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);
257 
258  void buildDepMap(BasicBlock &BB,
259  DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
260  std::vector<Value *> &PairableInsts,
261  DenseSet<ValuePair> &PairableInstUsers);
262 
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);
273 
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);
281 
282 
283  bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
284 
285  bool areInstsCompatible(Instruction *I, Instruction *J,
286  bool IsSimpleLoadStore, bool NonPow2Len,
287  int &CostSavings, int &FixedOrder);
288 
289  bool trackUsesOfI(DenseSet<Value *> &Users,
290  AliasSetTracker &WriteSet, Instruction *I,
291  Instruction *J, bool UpdateUsers = true,
292  DenseSet<ValuePair> *LoadMoveSetPairs = nullptr);
293 
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,
300  ValuePair P);
301 
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);
307 
308  bool pairWillFormCycle(ValuePair P,
309  DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUsers,
310  DenseSet<ValuePair> &CurrentPairs);
311 
312  void pruneDAGFor(
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,
321  DenseSet<ValuePair> &PrunedDAG, ValuePair J,
322  bool UseCycleCheck);
323 
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);
332 
333  void findBestDAGFor(
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,
348  bool UseCycleCheck);
349 
350  Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
351  Instruction *J, unsigned o);
352 
353  void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
354  unsigned MaskOffset, unsigned NumInElem,
355  unsigned NumInElem1, unsigned IdxOffset,
356  std::vector<Constant*> &Mask);
357 
358  Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
359  Instruction *J);
360 
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);
365 
366  Value *getReplacementInput(LLVMContext& Context, Instruction *I,
367  Instruction *J, unsigned o, bool IBeforeJ);
368 
369  void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
370  Instruction *J, SmallVectorImpl<Value *> &ReplacedOperands,
371  bool IBeforeJ);
372 
373  void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
374  Instruction *J, Instruction *K,
375  Instruction *&InsertionPt, Instruction *&K1,
376  Instruction *&K2);
377 
378  void collectPairLoadMoveSet(BasicBlock &BB,
379  DenseMap<Value *, Value *> &ChosenPairs,
380  DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
381  DenseSet<ValuePair> &LoadMoveSetPairs,
382  Instruction *I);
383 
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);
389 
390  bool canMoveUsesOfIAfterJ(BasicBlock &BB,
391  DenseSet<ValuePair> &LoadMoveSetPairs,
392  Instruction *I, Instruction *J);
393 
394  void moveUsesOfIAfterJ(BasicBlock &BB,
395  DenseSet<ValuePair> &LoadMoveSetPairs,
396  Instruction *&InsertionPt,
397  Instruction *I, Instruction *J);
398 
399  bool vectorizeBB(BasicBlock &BB) {
400  if (skipBasicBlock(BB))
401  return false;
402  if (!DT->isReachableFromEntry(&BB)) {
403  DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
404  " in " << BB.getParent()->getName() << "\n");
405  return false;
406  }
407 
408  DEBUG(if (TTI) dbgs() << "BBV: using target information\n");
409 
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.
414  unsigned n = 1;
415  for (unsigned v = 2;
416  (TTI || v <= Config.VectorBits) &&
417  (!Config.MaxIter || n <= Config.MaxIter);
418  v *= 2, ++n) {
419  DEBUG(dbgs() << "BBV: fusing loop #" << n <<
420  " for " << BB.getName() << " in " <<
421  BB.getParent()->getName() << "...\n");
422  if (vectorizePairs(BB))
423  changed = true;
424  else
425  break;
426  }
427 
428  if (changed && !Pow2LenOnly) {
429  ++n;
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;
435  }
436  }
437 
438  DEBUG(dbgs() << "BBV: done!\n");
439  return changed;
440  }
441 
442  bool runOnBasicBlock(BasicBlock &BB) override {
443  // OptimizeNone check deferred to vectorizeBB().
444 
445  AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
446  DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
447  SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
448  TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
449  TTI = IgnoreTargetInfo
450  ? nullptr
451  : &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
452  *BB.getParent());
453 
454  return vectorizeBB(BB);
455  }
456 
457  void getAnalysisUsage(AnalysisUsage &AU) const override {
468  AU.setPreservesCFG();
469  }
470 
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();
475 
476  unsigned numElem;
477  if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
478  numElem = VTy->getNumElements();
479  } else {
480  numElem = 1;
481  }
482 
483  if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
484  numElem += VTy->getNumElements();
485  } else {
486  numElem += 1;
487  }
488 
489  return VectorType::get(STy, numElem);
490  }
491 
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.
497 
498  Value *IVal = SI->getValueOperand();
499  T1 = IVal->getType();
500  } else {
501  T1 = I->getType();
502  }
503 
504  if (CastInst *CI = dyn_cast<CastInst>(I))
505  T2 = CI->getSrcTy();
506  else
507  T2 = T1;
508 
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();
515  }
516  }
517 
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
535  // instructions.
536  if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
537  return 0;
538 
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;
543 
544  return 1;
545  }
546 
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,
554  const Instruction *I = nullptr) {
555  switch (Opcode) {
556  default: break;
557  case Instruction::GetElementPtr:
558  // We mark this instruction as zero-cost because scalar GEPs are usually
559  // lowered to the instruction addressing mode. At the moment we don't
560  // generate vector GEPs.
561  return 0;
562  case Instruction::Br:
563  return TTI->getCFInstrCost(Opcode);
564  case Instruction::PHI:
565  return 0;
566  case Instruction::Add:
567  case Instruction::FAdd:
568  case Instruction::Sub:
569  case Instruction::FSub:
570  case Instruction::Mul:
571  case Instruction::FMul:
572  case Instruction::UDiv:
573  case Instruction::SDiv:
574  case Instruction::FDiv:
575  case Instruction::URem:
576  case Instruction::SRem:
577  case Instruction::FRem:
578  case Instruction::Shl:
579  case Instruction::LShr:
580  case Instruction::AShr:
581  case Instruction::And:
582  case Instruction::Or:
583  case Instruction::Xor:
584  return TTI->getArithmeticInstrCost(Opcode, T1, Op1VK, Op2VK);
585  case Instruction::Select:
586  case Instruction::ICmp:
587  case Instruction::FCmp:
588  return TTI->getCmpSelInstrCost(Opcode, T1, T2, I);
589  case Instruction::ZExt:
590  case Instruction::SExt:
591  case Instruction::FPToUI:
592  case Instruction::FPToSI:
593  case Instruction::FPExt:
594  case Instruction::PtrToInt:
595  case Instruction::IntToPtr:
596  case Instruction::SIToFP:
597  case Instruction::UIToFP:
598  case Instruction::Trunc:
599  case Instruction::FPTrunc:
600  case Instruction::BitCast:
601  case Instruction::ShuffleVector:
602  return TTI->getCastInstrCost(Opcode, T1, T2, I);
603  }
604 
605  return 1;
606  }
607 
608  // This determines the relative offset of two loads or stores, returning
609  // true if the offset could be determined to be some constant value.
610  // For example, if OffsetInElmts == 1, then J accesses the memory directly
611  // after I; if OffsetInElmts == -1 then I accesses the memory
612  // directly after J.
613  bool getPairPtrInfo(Instruction *I, Instruction *J,
614  Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
615  unsigned &IAddressSpace, unsigned &JAddressSpace,
616  int64_t &OffsetInElmts, bool ComputeOffset = true) {
617  OffsetInElmts = 0;
618  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
619  LoadInst *LJ = cast<LoadInst>(J);
620  IPtr = LI->getPointerOperand();
621  JPtr = LJ->getPointerOperand();
622  IAlignment = LI->getAlignment();
623  JAlignment = LJ->getAlignment();
624  IAddressSpace = LI->getPointerAddressSpace();
625  JAddressSpace = LJ->getPointerAddressSpace();
626  } else {
627  StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
628  IPtr = SI->getPointerOperand();
629  JPtr = SJ->getPointerOperand();
630  IAlignment = SI->getAlignment();
631  JAlignment = SJ->getAlignment();
632  IAddressSpace = SI->getPointerAddressSpace();
633  JAddressSpace = SJ->getPointerAddressSpace();
634  }
635 
636  if (!ComputeOffset)
637  return true;
638 
639  const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
640  const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
641 
642  // If this is a trivial offset, then we'll get something like
643  // 1*sizeof(type). With target data, which we need anyway, this will get
644  // constant folded into a number.
645  const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
646  if (const SCEVConstant *ConstOffSCEV =
647  dyn_cast<SCEVConstant>(OffsetSCEV)) {
648  ConstantInt *IntOff = ConstOffSCEV->getValue();
649  int64_t Offset = IntOff->getSExtValue();
650  const DataLayout &DL = I->getModule()->getDataLayout();
651  Type *VTy = IPtr->getType()->getPointerElementType();
652  int64_t VTyTSS = (int64_t)DL.getTypeStoreSize(VTy);
653 
654  Type *VTy2 = JPtr->getType()->getPointerElementType();
655  if (VTy != VTy2 && Offset < 0) {
656  int64_t VTy2TSS = (int64_t)DL.getTypeStoreSize(VTy2);
657  OffsetInElmts = Offset/VTy2TSS;
658  return (std::abs(Offset) % VTy2TSS) == 0;
659  }
660 
661  OffsetInElmts = Offset/VTyTSS;
662  return (std::abs(Offset) % VTyTSS) == 0;
663  }
664 
665  return false;
666  }
667 
668  // Returns true if the provided CallInst represents an intrinsic that can
669  // be vectorized.
670  bool isVectorizableIntrinsic(CallInst* I) {
671  Function *F = I->getCalledFunction();
672  if (!F) return false;
673 
674  Intrinsic::ID IID = F->getIntrinsicID();
675  if (!IID) return false;
676 
677  switch(IID) {
678  default:
679  return false;
680  case Intrinsic::sqrt:
681  case Intrinsic::powi:
682  case Intrinsic::sin:
683  case Intrinsic::cos:
684  case Intrinsic::log:
685  case Intrinsic::log2:
686  case Intrinsic::log10:
687  case Intrinsic::exp:
688  case Intrinsic::exp2:
689  case Intrinsic::pow:
690  case Intrinsic::round:
691  case Intrinsic::copysign:
692  case Intrinsic::ceil:
693  case Intrinsic::nearbyint:
694  case Intrinsic::rint:
695  case Intrinsic::trunc:
696  case Intrinsic::floor:
697  case Intrinsic::fabs:
698  case Intrinsic::minnum:
699  case Intrinsic::maxnum:
700  return Config.VectorizeMath;
701  case Intrinsic::bswap:
702  case Intrinsic::ctpop:
703  case Intrinsic::ctlz:
704  case Intrinsic::cttz:
705  return Config.VectorizeBitManipulations;
706  case Intrinsic::fma:
707  case Intrinsic::fmuladd:
708  return Config.VectorizeFMA;
709  }
710  }
711 
712  bool isPureIEChain(InsertElementInst *IE) {
713  InsertElementInst *IENext = IE;
714  do {
715  if (!isa<UndefValue>(IENext->getOperand(0)) &&
716  !isa<InsertElementInst>(IENext->getOperand(0))) {
717  return false;
718  }
719  } while ((IENext =
720  dyn_cast<InsertElementInst>(IENext->getOperand(0))));
721 
722  return true;
723  }
724  };
725 
726  // This function implements one vectorization iteration on the provided
727  // basic block. It returns true if the block is changed.
728  bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
729  bool ShouldContinue;
731 
732  std::vector<Value *> AllPairableInsts;
733  DenseMap<Value *, Value *> AllChosenPairs;
734  DenseSet<ValuePair> AllFixedOrderPairs;
735  DenseMap<VPPair, unsigned> AllPairConnectionTypes;
736  DenseMap<ValuePair, std::vector<ValuePair> > AllConnectedPairs,
737  AllConnectedPairDeps;
738 
739  do {
740  std::vector<Value *> PairableInsts;
742  DenseSet<ValuePair> FixedOrderPairs;
743  DenseMap<ValuePair, int> CandidatePairCostSavings;
744  ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
745  FixedOrderPairs,
746  CandidatePairCostSavings,
747  PairableInsts, NonPow2Len);
748  if (PairableInsts.empty()) continue;
749 
750  // Build the candidate pair set for faster lookups.
751  DenseSet<ValuePair> CandidatePairsSet;
752  for (DenseMap<Value *, std::vector<Value *> >::iterator I =
753  CandidatePairs.begin(), E = CandidatePairs.end(); I != E; ++I)
754  for (std::vector<Value *>::iterator J = I->second.begin(),
755  JE = I->second.end(); J != JE; ++J)
756  CandidatePairsSet.insert(ValuePair(I->first, *J));
757 
758  // Now we have a map of all of the pairable instructions and we need to
759  // select the best possible pairing. A good pairing is one such that the
760  // users of the pair are also paired. This defines a (directed) forest
761  // over the pairs such that two pairs are connected iff the second pair
762  // uses the first.
763 
764  // Note that it only matters that both members of the second pair use some
765  // element of the first pair (to allow for splatting).
766 
768  ConnectedPairDeps;
769  DenseMap<VPPair, unsigned> PairConnectionTypes;
770  computeConnectedPairs(CandidatePairs, CandidatePairsSet,
771  PairableInsts, ConnectedPairs, PairConnectionTypes);
772  if (ConnectedPairs.empty()) continue;
773 
774  for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
775  I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
776  I != IE; ++I)
777  for (std::vector<ValuePair>::iterator J = I->second.begin(),
778  JE = I->second.end(); J != JE; ++J)
779  ConnectedPairDeps[*J].push_back(I->first);
780 
781  // Build the pairable-instruction dependency map
782  DenseSet<ValuePair> PairableInstUsers;
783  buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
784 
785  // There is now a graph of the connected pairs. For each variable, pick
786  // the pairing with the largest dag meeting the depth requirement on at
787  // least one branch. Then select all pairings that are part of that dag
788  // and remove them from the list of available pairings and pairable
789  // variables.
790 
791  DenseMap<Value *, Value *> ChosenPairs;
792  choosePairs(CandidatePairs, CandidatePairsSet,
793  CandidatePairCostSavings,
794  PairableInsts, FixedOrderPairs, PairConnectionTypes,
795  ConnectedPairs, ConnectedPairDeps,
796  PairableInstUsers, ChosenPairs);
797 
798  if (ChosenPairs.empty()) continue;
799  AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
800  PairableInsts.end());
801  AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
802 
803  // Only for the chosen pairs, propagate information on fixed-order pairs,
804  // pair connections, and their types to the data structures used by the
805  // pair fusion procedures.
806  for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
807  IE = ChosenPairs.end(); I != IE; ++I) {
808  if (FixedOrderPairs.count(*I))
809  AllFixedOrderPairs.insert(*I);
810  else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
811  AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
812 
813  for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
814  J != IE; ++J) {
816  PairConnectionTypes.find(VPPair(*I, *J));
817  if (K != PairConnectionTypes.end()) {
818  AllPairConnectionTypes.insert(*K);
819  } else {
820  K = PairConnectionTypes.find(VPPair(*J, *I));
821  if (K != PairConnectionTypes.end())
822  AllPairConnectionTypes.insert(*K);
823  }
824  }
825  }
826 
827  for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
828  I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
829  I != IE; ++I)
830  for (std::vector<ValuePair>::iterator J = I->second.begin(),
831  JE = I->second.end(); J != JE; ++J)
832  if (AllPairConnectionTypes.count(VPPair(I->first, *J))) {
833  AllConnectedPairs[I->first].push_back(*J);
834  AllConnectedPairDeps[*J].push_back(I->first);
835  }
836  } while (ShouldContinue);
837 
838  if (AllChosenPairs.empty()) return false;
839  NumFusedOps += AllChosenPairs.size();
840 
841  // A set of pairs has now been selected. It is now necessary to replace the
842  // paired instructions with vector instructions. For this procedure each
843  // operand must be replaced with a vector operand. This vector is formed
844  // by using build_vector on the old operands. The replaced values are then
845  // replaced with a vector_extract on the result. Subsequent optimization
846  // passes should coalesce the build/extract combinations.
847 
848  fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
849  AllPairConnectionTypes,
850  AllConnectedPairs, AllConnectedPairDeps);
851 
852  // It is important to cleanup here so that future iterations of this
853  // function have less work to do.
854  (void)SimplifyInstructionsInBlock(&BB, TLI);
855  return true;
856  }
857 
858  // This function returns true if the provided instruction is capable of being
859  // fused into a vector instruction. This determination is based only on the
860  // type and other attributes of the instruction.
861  bool BBVectorize::isInstVectorizable(Instruction *I,
862  bool &IsSimpleLoadStore) {
863  IsSimpleLoadStore = false;
864 
865  if (CallInst *C = dyn_cast<CallInst>(I)) {
866  if (!isVectorizableIntrinsic(C))
867  return false;
868  } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
869  // Vectorize simple loads if possbile:
870  IsSimpleLoadStore = L->isSimple();
871  if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
872  return false;
873  } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
874  // Vectorize simple stores if possbile:
875  IsSimpleLoadStore = S->isSimple();
876  if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
877  return false;
878  } else if (CastInst *C = dyn_cast<CastInst>(I)) {
879  // We can vectorize casts, but not casts of pointer types, etc.
880  if (!Config.VectorizeCasts)
881  return false;
882 
883  Type *SrcTy = C->getSrcTy();
884  if (!SrcTy->isSingleValueType())
885  return false;
886 
887  Type *DestTy = C->getDestTy();
888  if (!DestTy->isSingleValueType())
889  return false;
890  } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
891  if (!Config.VectorizeSelect)
892  return false;
893  // We can vectorize a select if either all operands are scalars,
894  // or all operands are vectors. Trying to "widen" a select between
895  // vectors that has a scalar condition results in a malformed select.
896  // FIXME: We could probably be smarter about this by rewriting the select
897  // with different types instead.
898  return (SI->getCondition()->getType()->isVectorTy() ==
899  SI->getTrueValue()->getType()->isVectorTy());
900  } else if (isa<CmpInst>(I)) {
901  if (!Config.VectorizeCmp)
902  return false;
903  } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
904  if (!Config.VectorizeGEP)
905  return false;
906 
907  // Currently, vector GEPs exist only with one index.
908  if (G->getNumIndices() != 1)
909  return false;
910  } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
911  isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
912  return false;
913  }
914 
915  Type *T1, *T2;
916  getInstructionTypes(I, T1, T2);
917 
918  // Not every type can be vectorized...
919  if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
921  return false;
922 
923  if (T1->getScalarSizeInBits() == 1) {
924  if (!Config.VectorizeBools)
925  return false;
926  } else {
927  if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
928  return false;
929  }
930 
931  if (T2->getScalarSizeInBits() == 1) {
932  if (!Config.VectorizeBools)
933  return false;
934  } else {
935  if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
936  return false;
937  }
938 
939  if (!Config.VectorizeFloats
940  && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
941  return false;
942 
943  // Don't vectorize target-specific types.
944  if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
945  return false;
946  if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
947  return false;
948 
949  if (!Config.VectorizePointers && (T1->getScalarType()->isPointerTy() ||
950  T2->getScalarType()->isPointerTy()))
951  return false;
952 
953  if (!TTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
954  T2->getPrimitiveSizeInBits() >= Config.VectorBits))
955  return false;
956 
957  return true;
958  }
959 
960  // This function returns true if the two provided instructions are compatible
961  // (meaning that they can be fused into a vector instruction). This assumes
962  // that I has already been determined to be vectorizable and that J is not
963  // in the use dag of I.
964  bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
965  bool IsSimpleLoadStore, bool NonPow2Len,
966  int &CostSavings, int &FixedOrder) {
967  DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
968  " <-> " << *J << "\n");
969 
970  CostSavings = 0;
971  FixedOrder = 0;
972 
973  // Loads and stores can be merged if they have different alignments,
974  // but are otherwise the same.
976  (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
977  return false;
978 
979  Type *IT1, *IT2, *JT1, *JT2;
980  getInstructionTypes(I, IT1, IT2);
981  getInstructionTypes(J, JT1, JT2);
982  unsigned MaxTypeBits = std::max(
985  if (!TTI && MaxTypeBits > Config.VectorBits)
986  return false;
987 
988  // FIXME: handle addsub-type operations!
989 
990  if (IsSimpleLoadStore) {
991  Value *IPtr, *JPtr;
992  unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
993  int64_t OffsetInElmts = 0;
994  if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
995  IAddressSpace, JAddressSpace, OffsetInElmts) &&
996  std::abs(OffsetInElmts) == 1) {
997  FixedOrder = (int) OffsetInElmts;
998  unsigned BottomAlignment = IAlignment;
999  if (OffsetInElmts < 0) BottomAlignment = JAlignment;
1000 
1001  Type *aTypeI = isa<StoreInst>(I) ?
1002  cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
1003  Type *aTypeJ = isa<StoreInst>(J) ?
1004  cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
1005  Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
1006 
1007  if (Config.AlignedOnly) {
1008  // An aligned load or store is possible only if the instruction
1009  // with the lower offset has an alignment suitable for the
1010  // vector type.
1011  const DataLayout &DL = I->getModule()->getDataLayout();
1012  unsigned VecAlignment = DL.getPrefTypeAlignment(VType);
1013  if (BottomAlignment < VecAlignment)
1014  return false;
1015  }
1016 
1017  if (TTI) {
1018  unsigned ICost = TTI->getMemoryOpCost(I->getOpcode(), aTypeI,
1019  IAlignment, IAddressSpace);
1020  unsigned JCost = TTI->getMemoryOpCost(J->getOpcode(), aTypeJ,
1021  JAlignment, JAddressSpace);
1022  unsigned VCost = TTI->getMemoryOpCost(I->getOpcode(), VType,
1023  BottomAlignment,
1024  IAddressSpace);
1025 
1026  ICost += TTI->getAddressComputationCost(aTypeI);
1027  JCost += TTI->getAddressComputationCost(aTypeJ);
1028  VCost += TTI->getAddressComputationCost(VType);
1029 
1030  if (VCost > ICost + JCost)
1031  return false;
1032 
1033  // We don't want to fuse to a type that will be split, even
1034  // if the two input types will also be split and there is no other
1035  // associated cost.
1036  unsigned VParts = TTI->getNumberOfParts(VType);
1037  if (VParts > 1)
1038  return false;
1039  else if (!VParts && VCost == ICost + JCost)
1040  return false;
1041 
1042  CostSavings = ICost + JCost - VCost;
1043  }
1044  } else {
1045  return false;
1046  }
1047  } else if (TTI) {
1052  unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2, Op1VK, Op2VK, I);
1053  unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2, Op1VK, Op2VK, J);
1054  Type *VT1 = getVecTypeForPair(IT1, JT1),
1055  *VT2 = getVecTypeForPair(IT2, JT2);
1056 
1057  // On some targets (example X86) the cost of a vector shift may vary
1058  // depending on whether the second operand is a Uniform or
1059  // NonUniform Constant.
1060  switch (I->getOpcode()) {
1061  default : break;
1062  case Instruction::Shl:
1063  case Instruction::LShr:
1064  case Instruction::AShr:
1065 
1066  // If both I and J are scalar shifts by constant, then the
1067  // merged vector shift count would be either a constant splat value
1068  // or a non-uniform vector of constants.
1069  if (ConstantInt *CII = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070  if (ConstantInt *CIJ = dyn_cast<ConstantInt>(J->getOperand(1)))
1071  Op2VK = CII == CIJ ? TargetTransformInfo::OK_UniformConstantValue :
1073  } else {
1074  // Check for a splat of a constant or for a non uniform vector
1075  // of constants.
1076  Value *IOp = I->getOperand(1);
1077  Value *JOp = J->getOperand(1);
1078  if ((isa<ConstantVector>(IOp) || isa<ConstantDataVector>(IOp)) &&
1079  (isa<ConstantVector>(JOp) || isa<ConstantDataVector>(JOp))) {
1081  Constant *SplatValue = cast<Constant>(IOp)->getSplatValue();
1082  if (SplatValue != nullptr &&
1083  SplatValue == cast<Constant>(JOp)->getSplatValue())
1085  }
1086  }
1087  }
1088 
1089  // Note that this procedure is incorrect for insert and extract element
1090  // instructions (because combining these often results in a shuffle),
1091  // but this cost is ignored (because insert and extract element
1092  // instructions are assigned a zero depth factor and are not really
1093  // fused in general).
1094  unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2, Op1VK, Op2VK, I);
1095 
1096  if (VCost > ICost + JCost)
1097  return false;
1098 
1099  // We don't want to fuse to a type that will be split, even
1100  // if the two input types will also be split and there is no other
1101  // associated cost.
1102  unsigned VParts1 = TTI->getNumberOfParts(VT1),
1103  VParts2 = TTI->getNumberOfParts(VT2);
1104  if (VParts1 > 1 || VParts2 > 1)
1105  return false;
1106  else if ((!VParts1 || !VParts2) && VCost == ICost + JCost)
1107  return false;
1108 
1109  CostSavings = ICost + JCost - VCost;
1110  }
1111 
1112  // The powi,ctlz,cttz intrinsics are special because only the first
1113  // argument is vectorized, the second arguments must be equal.
1114  CallInst *CI = dyn_cast<CallInst>(I);
1115  Function *FI;
1116  if (CI && (FI = CI->getCalledFunction())) {
1117  Intrinsic::ID IID = FI->getIntrinsicID();
1118  if (IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
1119  IID == Intrinsic::cttz) {
1120  Value *A1I = CI->getArgOperand(1),
1121  *A1J = cast<CallInst>(J)->getArgOperand(1);
1122  const SCEV *A1ISCEV = SE->getSCEV(A1I),
1123  *A1JSCEV = SE->getSCEV(A1J);
1124  return (A1ISCEV == A1JSCEV);
1125  }
1126 
1127  if (IID && TTI) {
1128  FastMathFlags FMFCI;
1129  if (auto *FPMOCI = dyn_cast<FPMathOperator>(CI))
1130  FMFCI = FPMOCI->getFastMathFlags();
1132  unsigned ICost = TTI->getIntrinsicInstrCost(IID, IT1, IArgs, FMFCI);
1133 
1134  CallInst *CJ = cast<CallInst>(J);
1135 
1136  FastMathFlags FMFCJ;
1137  if (auto *FPMOCJ = dyn_cast<FPMathOperator>(CJ))
1138  FMFCJ = FPMOCJ->getFastMathFlags();
1139 
1141  unsigned JCost = TTI->getIntrinsicInstrCost(IID, JT1, JArgs, FMFCJ);
1142 
1143  assert(CI->getNumArgOperands() == CJ->getNumArgOperands() &&
1144  "Intrinsic argument counts differ");
1146  SmallVector<Value *, 4> VecArgs;
1147  for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1148  if ((IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
1149  IID == Intrinsic::cttz) && i == 1) {
1150  Tys.push_back(CI->getArgOperand(i)->getType());
1151  VecArgs.push_back(CI->getArgOperand(i));
1152  }
1153  else {
1154  Tys.push_back(getVecTypeForPair(CI->getArgOperand(i)->getType(),
1155  CJ->getArgOperand(i)->getType()));
1156  // Add both operands, and then count their scalarization overhead
1157  // with VF 1.
1158  VecArgs.push_back(CI->getArgOperand(i));
1159  VecArgs.push_back(CJ->getArgOperand(i));
1160  }
1161  }
1162 
1163  // Compute the scalarization cost here with the original operands (to
1164  // check for uniqueness etc), and then call getIntrinsicInstrCost()
1165  // with the constructed vector types.
1166  Type *RetTy = getVecTypeForPair(IT1, JT1);
1167  unsigned ScalarizationCost = 0;
1168  if (!RetTy->isVoidTy())
1169  ScalarizationCost += TTI->getScalarizationOverhead(RetTy, true, false);
1170  ScalarizationCost += TTI->getOperandsScalarizationOverhead(VecArgs, 1);
1171 
1172  FastMathFlags FMFV = FMFCI;
1173  FMFV &= FMFCJ;
1174  unsigned VCost = TTI->getIntrinsicInstrCost(IID, RetTy, Tys, FMFV,
1175  ScalarizationCost);
1176 
1177  if (VCost > ICost + JCost)
1178  return false;
1179 
1180  // We don't want to fuse to a type that will be split, even
1181  // if the two input types will also be split and there is no other
1182  // associated cost.
1183  unsigned RetParts = TTI->getNumberOfParts(RetTy);
1184  if (RetParts > 1)
1185  return false;
1186  else if (!RetParts && VCost == ICost + JCost)
1187  return false;
1188 
1189  for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
1190  if (!Tys[i]->isVectorTy())
1191  continue;
1192 
1193  unsigned NumParts = TTI->getNumberOfParts(Tys[i]);
1194  if (NumParts > 1)
1195  return false;
1196  else if (!NumParts && VCost == ICost + JCost)
1197  return false;
1198  }
1199 
1200  CostSavings = ICost + JCost - VCost;
1201  }
1202  }
1203 
1204  return true;
1205  }
1206 
1207  // Figure out whether or not J uses I and update the users and write-set
1208  // structures associated with I. Specifically, Users represents the set of
1209  // instructions that depend on I. WriteSet represents the set
1210  // of memory locations that are dependent on I. If UpdateUsers is true,
1211  // and J uses I, then Users is updated to contain J and WriteSet is updated
1212  // to contain any memory locations to which J writes. The function returns
1213  // true if J uses I. By default, alias analysis is used to determine
1214  // whether J reads from memory that overlaps with a location in WriteSet.
1215  // If LoadMoveSet is not null, then it is a previously-computed map
1216  // where the key is the memory-based user instruction and the value is
1217  // the instruction to be compared with I. So, if LoadMoveSet is provided,
1218  // then the alias analysis is not used. This is necessary because this
1219  // function is called during the process of moving instructions during
1220  // vectorization and the results of the alias analysis are not stable during
1221  // that process.
1222  bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
1223  AliasSetTracker &WriteSet, Instruction *I,
1224  Instruction *J, bool UpdateUsers,
1225  DenseSet<ValuePair> *LoadMoveSetPairs) {
1226  bool UsesI = false;
1227 
1228  // This instruction may already be marked as a user due, for example, to
1229  // being a member of a selected pair.
1230  if (Users.count(J))
1231  UsesI = true;
1232 
1233  if (!UsesI)
1234  for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
1235  JU != JE; ++JU) {
1236  Value *V = *JU;
1237  if (I == V || Users.count(V)) {
1238  UsesI = true;
1239  break;
1240  }
1241  }
1242  if (!UsesI && J->mayReadFromMemory()) {
1243  if (LoadMoveSetPairs) {
1244  UsesI = LoadMoveSetPairs->count(ValuePair(J, I));
1245  } else {
1246  for (AliasSetTracker::iterator W = WriteSet.begin(),
1247  WE = WriteSet.end(); W != WE; ++W) {
1248  if (W->aliasesUnknownInst(J, *AA)) {
1249  UsesI = true;
1250  break;
1251  }
1252  }
1253  }
1254  }
1255 
1256  if (UsesI && UpdateUsers) {
1257  if (J->mayWriteToMemory()) WriteSet.add(J);
1258  Users.insert(J);
1259  }
1260 
1261  return UsesI;
1262  }
1263 
1264  // This function iterates over all instruction pairs in the provided
1265  // basic block and collects all candidate pairs for vectorization.
1266  bool BBVectorize::getCandidatePairs(BasicBlock &BB,
1267  BasicBlock::iterator &Start,
1268  DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1269  DenseSet<ValuePair> &FixedOrderPairs,
1270  DenseMap<ValuePair, int> &CandidatePairCostSavings,
1271  std::vector<Value *> &PairableInsts, bool NonPow2Len) {
1272  size_t TotalPairs = 0;
1273  BasicBlock::iterator E = BB.end();
1274  if (Start == E) return false;
1275 
1276  bool ShouldContinue = false, IAfterStart = false;
1277  for (BasicBlock::iterator I = Start++; I != E; ++I) {
1278  if (I == Start) IAfterStart = true;
1279 
1280  bool IsSimpleLoadStore;
1281  if (!isInstVectorizable(&*I, IsSimpleLoadStore))
1282  continue;
1283 
1284  // Look for an instruction with which to pair instruction *I...
1286  AliasSetTracker WriteSet(*AA);
1287  if (I->mayWriteToMemory())
1288  WriteSet.add(&*I);
1289 
1290  bool JAfterStart = IAfterStart;
1291  BasicBlock::iterator J = std::next(I);
1292  for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
1293  if (J == Start)
1294  JAfterStart = true;
1295 
1296  // Determine if J uses I, if so, exit the loop.
1297  bool UsesI = trackUsesOfI(Users, WriteSet, &*I, &*J, !Config.FastDep);
1298  if (Config.FastDep) {
1299  // Note: For this heuristic to be effective, independent operations
1300  // must tend to be intermixed. This is likely to be true from some
1301  // kinds of grouped loop unrolling (but not the generic LLVM pass),
1302  // but otherwise may require some kind of reordering pass.
1303 
1304  // When using fast dependency analysis,
1305  // stop searching after first use:
1306  if (UsesI) break;
1307  } else {
1308  if (UsesI) continue;
1309  }
1310 
1311  // J does not use I, and comes before the first use of I, so it can be
1312  // merged with I if the instructions are compatible.
1313  int CostSavings, FixedOrder;
1314  if (!areInstsCompatible(&*I, &*J, IsSimpleLoadStore, NonPow2Len,
1315  CostSavings, FixedOrder))
1316  continue;
1317 
1318  // J is a candidate for merging with I.
1319  if (PairableInsts.empty() ||
1320  PairableInsts[PairableInsts.size() - 1] != &*I) {
1321  PairableInsts.push_back(&*I);
1322  }
1323 
1324  CandidatePairs[&*I].push_back(&*J);
1325  ++TotalPairs;
1326  if (TTI)
1327  CandidatePairCostSavings.insert(
1328  ValuePairWithCost(ValuePair(&*I, &*J), CostSavings));
1329 
1330  if (FixedOrder == 1)
1331  FixedOrderPairs.insert(ValuePair(&*I, &*J));
1332  else if (FixedOrder == -1)
1333  FixedOrderPairs.insert(ValuePair(&*J, &*I));
1334 
1335  // The next call to this function must start after the last instruction
1336  // selected during this invocation.
1337  if (JAfterStart) {
1338  Start = std::next(J);
1339  IAfterStart = JAfterStart = false;
1340  }
1341 
1342  DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
1343  << *I << " <-> " << *J << " (cost savings: " <<
1344  CostSavings << ")\n");
1345 
1346  // If we have already found too many pairs, break here and this function
1347  // will be called again starting after the last instruction selected
1348  // during this invocation.
1349  if (PairableInsts.size() >= Config.MaxInsts ||
1350  TotalPairs >= Config.MaxPairs) {
1351  ShouldContinue = true;
1352  break;
1353  }
1354  }
1355 
1356  if (ShouldContinue)
1357  break;
1358  }
1359 
1360  DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
1361  << " instructions with candidate pairs\n");
1362 
1363  return ShouldContinue;
1364  }
1365 
1366  // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
1367  // it looks for pairs such that both members have an input which is an
1368  // output of PI or PJ.
1369  void BBVectorize::computePairsConnectedTo(
1370  DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1371  DenseSet<ValuePair> &CandidatePairsSet,
1372  std::vector<Value *> &PairableInsts,
1373  DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1374  DenseMap<VPPair, unsigned> &PairConnectionTypes,
1375  ValuePair P) {
1376  StoreInst *SI, *SJ;
1377 
1378  // For each possible pairing for this variable, look at the uses of
1379  // the first value...
1380  for (Value::user_iterator I = P.first->user_begin(),
1381  E = P.first->user_end();
1382  I != E; ++I) {
1383  User *UI = *I;
1384  if (isa<LoadInst>(UI)) {
1385  // A pair cannot be connected to a load because the load only takes one
1386  // operand (the address) and it is a scalar even after vectorization.
1387  continue;
1388  } else if ((SI = dyn_cast<StoreInst>(UI)) &&
1389  P.first == SI->getPointerOperand()) {
1390  // Similarly, a pair cannot be connected to a store through its
1391  // pointer operand.
1392  continue;
1393  }
1394 
1395  // For each use of the first variable, look for uses of the second
1396  // variable...
1397  for (User *UJ : P.second->users()) {
1398  if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1399  P.second == SJ->getPointerOperand())
1400  continue;
1401 
1402  // Look for <I, J>:
1403  if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1404  VPPair VP(P, ValuePair(UI, UJ));
1405  ConnectedPairs[VP.first].push_back(VP.second);
1406  PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
1407  }
1408 
1409  // Look for <J, I>:
1410  if (CandidatePairsSet.count(ValuePair(UJ, UI))) {
1411  VPPair VP(P, ValuePair(UJ, UI));
1412  ConnectedPairs[VP.first].push_back(VP.second);
1413  PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
1414  }
1415  }
1416 
1417  if (Config.SplatBreaksChain) continue;
1418  // Look for cases where just the first value in the pair is used by
1419  // both members of another pair (splatting).
1420  for (Value::user_iterator J = P.first->user_begin(); J != E; ++J) {
1421  User *UJ = *J;
1422  if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1423  P.first == SJ->getPointerOperand())
1424  continue;
1425 
1426  if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1427  VPPair VP(P, ValuePair(UI, UJ));
1428  ConnectedPairs[VP.first].push_back(VP.second);
1429  PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1430  }
1431  }
1432  }
1433 
1434  if (Config.SplatBreaksChain) return;
1435  // Look for cases where just the second value in the pair is used by
1436  // both members of another pair (splatting).
1437  for (Value::user_iterator I = P.second->user_begin(),
1438  E = P.second->user_end();
1439  I != E; ++I) {
1440  User *UI = *I;
1441  if (isa<LoadInst>(UI))
1442  continue;
1443  else if ((SI = dyn_cast<StoreInst>(UI)) &&
1444  P.second == SI->getPointerOperand())
1445  continue;
1446 
1447  for (Value::user_iterator J = P.second->user_begin(); J != E; ++J) {
1448  User *UJ = *J;
1449  if ((SJ = dyn_cast<StoreInst>(UJ)) &&
1450  P.second == SJ->getPointerOperand())
1451  continue;
1452 
1453  if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
1454  VPPair VP(P, ValuePair(UI, UJ));
1455  ConnectedPairs[VP.first].push_back(VP.second);
1456  PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
1457  }
1458  }
1459  }
1460  }
1461 
1462  // This function figures out which pairs are connected. Two pairs are
1463  // connected if some output of the first pair forms an input to both members
1464  // of the second pair.
1465  void BBVectorize::computeConnectedPairs(
1466  DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1467  DenseSet<ValuePair> &CandidatePairsSet,
1468  std::vector<Value *> &PairableInsts,
1469  DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1470  DenseMap<VPPair, unsigned> &PairConnectionTypes) {
1471  for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
1472  PE = PairableInsts.end(); PI != PE; ++PI) {
1474  CandidatePairs.find(*PI);
1475  if (PP == CandidatePairs.end())
1476  continue;
1477 
1478  for (std::vector<Value *>::iterator P = PP->second.begin(),
1479  E = PP->second.end(); P != E; ++P)
1480  computePairsConnectedTo(CandidatePairs, CandidatePairsSet,
1481  PairableInsts, ConnectedPairs,
1482  PairConnectionTypes, ValuePair(*PI, *P));
1483  }
1484 
1485  DEBUG(size_t TotalPairs = 0;
1486  for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator I =
1487  ConnectedPairs.begin(), IE = ConnectedPairs.end(); I != IE; ++I)
1488  TotalPairs += I->second.size();
1489  dbgs() << "BBV: found " << TotalPairs
1490  << " pair connections.\n");
1491  }
1492 
1493  // This function builds a set of use tuples such that <A, B> is in the set
1494  // if B is in the use dag of A. If B is in the use dag of A, then B
1495  // depends on the output of A.
1496  void BBVectorize::buildDepMap(
1497  BasicBlock &BB,
1498  DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1499  std::vector<Value *> &PairableInsts,
1500  DenseSet<ValuePair> &PairableInstUsers) {
1501  DenseSet<Value *> IsInPair;
1502  for (DenseMap<Value *, std::vector<Value *> >::iterator C =
1503  CandidatePairs.begin(), E = CandidatePairs.end(); C != E; ++C) {
1504  IsInPair.insert(C->first);
1505  IsInPair.insert(C->second.begin(), C->second.end());
1506  }
1507 
1508  // Iterate through the basic block, recording all users of each
1509  // pairable instruction.
1510 
1511  BasicBlock::iterator E = BB.end(), EL =
1512  BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
1513  for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
1514  if (IsInPair.find(&*I) == IsInPair.end())
1515  continue;
1516 
1518  AliasSetTracker WriteSet(*AA);
1519  if (I->mayWriteToMemory())
1520  WriteSet.add(&*I);
1521 
1522  for (BasicBlock::iterator J = std::next(I); J != E; ++J) {
1523  (void)trackUsesOfI(Users, WriteSet, &*I, &*J);
1524 
1525  if (J == EL)
1526  break;
1527  }
1528 
1529  for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
1530  U != E; ++U) {
1531  if (IsInPair.find(*U) == IsInPair.end()) continue;
1532  PairableInstUsers.insert(ValuePair(&*I, *U));
1533  }
1534 
1535  if (I == EL)
1536  break;
1537  }
1538  }
1539 
1540  // Returns true if an input to pair P is an output of pair Q and also an
1541  // input of pair Q is an output of pair P. If this is the case, then these
1542  // two pairs cannot be simultaneously fused.
1543  bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
1544  DenseSet<ValuePair> &PairableInstUsers,
1545  DenseMap<ValuePair, std::vector<ValuePair> > *PairableInstUserMap,
1546  DenseSet<VPPair> *PairableInstUserPairSet) {
1547  // Two pairs are in conflict if they are mutual Users of eachother.
1548  bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
1549  PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
1550  PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
1551  PairableInstUsers.count(ValuePair(P.second, Q.second));
1552  bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
1553  PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
1554  PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
1555  PairableInstUsers.count(ValuePair(Q.second, P.second));
1556  if (PairableInstUserMap) {
1557  // FIXME: The expensive part of the cycle check is not so much the cycle
1558  // check itself but this edge insertion procedure. This needs some
1559  // profiling and probably a different data structure.
1560  if (PUsesQ) {
1561  if (PairableInstUserPairSet->insert(VPPair(Q, P)).second)
1562  (*PairableInstUserMap)[Q].push_back(P);
1563  }
1564  if (QUsesP) {
1565  if (PairableInstUserPairSet->insert(VPPair(P, Q)).second)
1566  (*PairableInstUserMap)[P].push_back(Q);
1567  }
1568  }
1569 
1570  return (QUsesP && PUsesQ);
1571  }
1572 
1573  // This function walks the use graph of current pairs to see if, starting
1574  // from P, the walk returns to P.
1575  bool BBVectorize::pairWillFormCycle(ValuePair P,
1576  DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1577  DenseSet<ValuePair> &CurrentPairs) {
1578  DEBUG(if (DebugCycleCheck)
1579  dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
1580  << *P.second << "\n");
1581  // A lookup table of visisted pairs is kept because the PairableInstUserMap
1582  // contains non-direct associations.
1583  DenseSet<ValuePair> Visited;
1585  // General depth-first post-order traversal:
1586  Q.push_back(P);
1587  do {
1588  ValuePair QTop = Q.pop_back_val();
1589  Visited.insert(QTop);
1590 
1591  DEBUG(if (DebugCycleCheck)
1592  dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
1593  << *QTop.second << "\n");
1595  PairableInstUserMap.find(QTop);
1596  if (QQ == PairableInstUserMap.end())
1597  continue;
1598 
1599  for (std::vector<ValuePair>::iterator C = QQ->second.begin(),
1600  CE = QQ->second.end(); C != CE; ++C) {
1601  if (*C == P) {
1602  DEBUG(dbgs()
1603  << "BBV: rejected to prevent non-trivial cycle formation: "
1604  << QTop.first << " <-> " << C->second << "\n");
1605  return true;
1606  }
1607 
1608  if (CurrentPairs.count(*C) && !Visited.count(*C))
1609  Q.push_back(*C);
1610  }
1611  } while (!Q.empty());
1612 
1613  return false;
1614  }
1615 
1616  // This function builds the initial dag of connected pairs with the
1617  // pair J at the root.
1618  void BBVectorize::buildInitialDAGFor(
1619  DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1620  DenseSet<ValuePair> &CandidatePairsSet,
1621  std::vector<Value *> &PairableInsts,
1622  DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1623  DenseSet<ValuePair> &PairableInstUsers,
1624  DenseMap<Value *, Value *> &ChosenPairs,
1625  DenseMap<ValuePair, size_t> &DAG, ValuePair J) {
1626  // Each of these pairs is viewed as the root node of a DAG. The DAG
1627  // is then walked (depth-first). As this happens, we keep track of
1628  // the pairs that compose the DAG and the maximum depth of the DAG.
1630  // General depth-first post-order traversal:
1631  Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1632  do {
1633  ValuePairWithDepth QTop = Q.back();
1634 
1635  // Push each child onto the queue:
1636  bool MoreChildren = false;
1637  size_t MaxChildDepth = QTop.second;
1639  ConnectedPairs.find(QTop.first);
1640  if (QQ != ConnectedPairs.end())
1641  for (std::vector<ValuePair>::iterator k = QQ->second.begin(),
1642  ke = QQ->second.end(); k != ke; ++k) {
1643  // Make sure that this child pair is still a candidate:
1644  if (CandidatePairsSet.count(*k)) {
1646  if (C == DAG.end()) {
1647  size_t d = getDepthFactor(k->first);
1648  Q.push_back(ValuePairWithDepth(*k, QTop.second+d));
1649  MoreChildren = true;
1650  } else {
1651  MaxChildDepth = std::max(MaxChildDepth, C->second);
1652  }
1653  }
1654  }
1655 
1656  if (!MoreChildren) {
1657  // Record the current pair as part of the DAG:
1658  DAG.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
1659  Q.pop_back();
1660  }
1661  } while (!Q.empty());
1662  }
1663 
1664  // Given some initial dag, prune it by removing conflicting pairs (pairs
1665  // that cannot be simultaneously chosen for vectorization).
1666  void BBVectorize::pruneDAGFor(
1667  DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1668  std::vector<Value *> &PairableInsts,
1669  DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1670  DenseSet<ValuePair> &PairableInstUsers,
1671  DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1672  DenseSet<VPPair> &PairableInstUserPairSet,
1673  DenseMap<Value *, Value *> &ChosenPairs,
1675  DenseSet<ValuePair> &PrunedDAG, ValuePair J,
1676  bool UseCycleCheck) {
1678  // General depth-first post-order traversal:
1679  Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
1680  do {
1681  ValuePairWithDepth QTop = Q.pop_back_val();
1682  PrunedDAG.insert(QTop.first);
1683 
1684  // Visit each child, pruning as necessary...
1687  ConnectedPairs.find(QTop.first);
1688  if (QQ == ConnectedPairs.end())
1689  continue;
1690 
1691  for (std::vector<ValuePair>::iterator K = QQ->second.begin(),
1692  KE = QQ->second.end(); K != KE; ++K) {
1694  if (C == DAG.end()) continue;
1695 
1696  // This child is in the DAG, now we need to make sure it is the
1697  // best of any conflicting children. There could be multiple
1698  // conflicting children, so first, determine if we're keeping
1699  // this child, then delete conflicting children as necessary.
1700 
1701  // It is also necessary to guard against pairing-induced
1702  // dependencies. Consider instructions a .. x .. y .. b
1703  // such that (a,b) are to be fused and (x,y) are to be fused
1704  // but a is an input to x and b is an output from y. This
1705  // means that y cannot be moved after b but x must be moved
1706  // after b for (a,b) to be fused. In other words, after
1707  // fusing (a,b) we have y .. a/b .. x where y is an input
1708  // to a/b and x is an output to a/b: x and y can no longer
1709  // be legally fused. To prevent this condition, we must
1710  // make sure that a child pair added to the DAG is not
1711  // both an input and output of an already-selected pair.
1712 
1713  // Pairing-induced dependencies can also form from more complicated
1714  // cycles. The pair vs. pair conflicts are easy to check, and so
1715  // that is done explicitly for "fast rejection", and because for
1716  // child vs. child conflicts, we may prefer to keep the current
1717  // pair in preference to the already-selected child.
1718  DenseSet<ValuePair> CurrentPairs;
1719 
1720  bool CanAdd = true;
1722  = BestChildren.begin(), E2 = BestChildren.end();
1723  C2 != E2; ++C2) {
1724  if (C2->first.first == C->first.first ||
1725  C2->first.first == C->first.second ||
1726  C2->first.second == C->first.first ||
1727  C2->first.second == C->first.second ||
1728  pairsConflict(C2->first, C->first, PairableInstUsers,
1729  UseCycleCheck ? &PairableInstUserMap : nullptr,
1730  UseCycleCheck ? &PairableInstUserPairSet
1731  : nullptr)) {
1732  if (C2->second >= C->second) {
1733  CanAdd = false;
1734  break;
1735  }
1736 
1737  CurrentPairs.insert(C2->first);
1738  }
1739  }
1740  if (!CanAdd) continue;
1741 
1742  // Even worse, this child could conflict with another node already
1743  // selected for the DAG. If that is the case, ignore this child.
1744  for (DenseSet<ValuePair>::iterator T = PrunedDAG.begin(),
1745  E2 = PrunedDAG.end(); T != E2; ++T) {
1746  if (T->first == C->first.first ||
1747  T->first == C->first.second ||
1748  T->second == C->first.first ||
1749  T->second == C->first.second ||
1750  pairsConflict(*T, C->first, PairableInstUsers,
1751  UseCycleCheck ? &PairableInstUserMap : nullptr,
1752  UseCycleCheck ? &PairableInstUserPairSet
1753  : nullptr)) {
1754  CanAdd = false;
1755  break;
1756  }
1757 
1758  CurrentPairs.insert(*T);
1759  }
1760  if (!CanAdd) continue;
1761 
1762  // And check the queue too...
1764  E2 = Q.end(); C2 != E2; ++C2) {
1765  if (C2->first.first == C->first.first ||
1766  C2->first.first == C->first.second ||
1767  C2->first.second == C->first.first ||
1768  C2->first.second == C->first.second ||
1769  pairsConflict(C2->first, C->first, PairableInstUsers,
1770  UseCycleCheck ? &PairableInstUserMap : nullptr,
1771  UseCycleCheck ? &PairableInstUserPairSet
1772  : nullptr)) {
1773  CanAdd = false;
1774  break;
1775  }
1776 
1777  CurrentPairs.insert(C2->first);
1778  }
1779  if (!CanAdd) continue;
1780 
1781  // Last but not least, check for a conflict with any of the
1782  // already-chosen pairs.
1784  ChosenPairs.begin(), E2 = ChosenPairs.end();
1785  C2 != E2; ++C2) {
1786  if (pairsConflict(*C2, C->first, PairableInstUsers,
1787  UseCycleCheck ? &PairableInstUserMap : nullptr,
1788  UseCycleCheck ? &PairableInstUserPairSet
1789  : nullptr)) {
1790  CanAdd = false;
1791  break;
1792  }
1793 
1794  CurrentPairs.insert(*C2);
1795  }
1796  if (!CanAdd) continue;
1797 
1798  // To check for non-trivial cycles formed by the addition of the
1799  // current pair we've formed a list of all relevant pairs, now use a
1800  // graph walk to check for a cycle. We start from the current pair and
1801  // walk the use dag to see if we again reach the current pair. If we
1802  // do, then the current pair is rejected.
1803 
1804  // FIXME: It may be more efficient to use a topological-ordering
1805  // algorithm to improve the cycle check. This should be investigated.
1806  if (UseCycleCheck &&
1807  pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
1808  continue;
1809 
1810  // This child can be added, but we may have chosen it in preference
1811  // to an already-selected child. Check for this here, and if a
1812  // conflict is found, then remove the previously-selected child
1813  // before adding this one in its place.
1815  = BestChildren.begin(); C2 != BestChildren.end();) {
1816  if (C2->first.first == C->first.first ||
1817  C2->first.first == C->first.second ||
1818  C2->first.second == C->first.first ||
1819  C2->first.second == C->first.second ||
1820  pairsConflict(C2->first, C->first, PairableInstUsers))
1821  C2 = BestChildren.erase(C2);
1822  else
1823  ++C2;
1824  }
1825 
1826  BestChildren.push_back(ValuePairWithDepth(C->first, C->second));
1827  }
1828 
1830  = BestChildren.begin(), E2 = BestChildren.end();
1831  C != E2; ++C) {
1832  size_t DepthF = getDepthFactor(C->first.first);
1833  Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
1834  }
1835  } while (!Q.empty());
1836  }
1837 
1838  // This function finds the best dag of mututally-compatible connected
1839  // pairs, given the choice of root pairs as an iterator range.
1840  void BBVectorize::findBestDAGFor(
1841  DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
1842  DenseSet<ValuePair> &CandidatePairsSet,
1843  DenseMap<ValuePair, int> &CandidatePairCostSavings,
1844  std::vector<Value *> &PairableInsts,
1845  DenseSet<ValuePair> &FixedOrderPairs,
1846  DenseMap<VPPair, unsigned> &PairConnectionTypes,
1847  DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
1848  DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
1849  DenseSet<ValuePair> &PairableInstUsers,
1850  DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
1851  DenseSet<VPPair> &PairableInstUserPairSet,
1852  DenseMap<Value *, Value *> &ChosenPairs,
1853  DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
1854  int &BestEffSize, Value *II, std::vector<Value *>&JJ,
1855  bool UseCycleCheck) {
1856  for (std::vector<Value *>::iterator J = JJ.begin(), JE = JJ.end();
1857  J != JE; ++J) {
1858  ValuePair IJ(II, *J);
1859  if (!CandidatePairsSet.count(IJ))
1860  continue;
1861 
1862  // Before going any further, make sure that this pair does not
1863  // conflict with any already-selected pairs (see comment below
1864  // near the DAG pruning for more details).
1865  DenseSet<ValuePair> ChosenPairSet;
1866  bool DoesConflict = false;
1867  for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
1868  E = ChosenPairs.end(); C != E; ++C) {
1869  if (pairsConflict(*C, IJ, PairableInstUsers,
1870  UseCycleCheck ? &PairableInstUserMap : nullptr,
1871  UseCycleCheck ? &PairableInstUserPairSet : nullptr)) {
1872  DoesConflict = true;
1873  break;
1874  }
1875 
1876  ChosenPairSet.insert(*C);
1877  }
1878  if (DoesConflict) continue;
1879 
1880  if (UseCycleCheck &&
1881  pairWillFormCycle(IJ, PairableInstUserMap, ChosenPairSet))
1882  continue;
1883 
1885  buildInitialDAGFor(CandidatePairs, CandidatePairsSet,
1886  PairableInsts, ConnectedPairs,
1887  PairableInstUsers, ChosenPairs, DAG, IJ);
1888 
1889  // Because we'll keep the child with the largest depth, the largest
1890  // depth is still the same in the unpruned DAG.
1891  size_t MaxDepth = DAG.lookup(IJ);
1892 
1893  DEBUG(if (DebugPairSelection) dbgs() << "BBV: found DAG for pair {"
1894  << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
1895  MaxDepth << " and size " << DAG.size() << "\n");
1896 
1897  // At this point the DAG has been constructed, but, may contain
1898  // contradictory children (meaning that different children of
1899  // some dag node may be attempting to fuse the same instruction).
1900  // So now we walk the dag again, in the case of a conflict,
1901  // keep only the child with the largest depth. To break a tie,
1902  // favor the first child.
1903 
1904  DenseSet<ValuePair> PrunedDAG;
1905  pruneDAGFor(CandidatePairs, PairableInsts, ConnectedPairs,
1906  PairableInstUsers, PairableInstUserMap,
1907  PairableInstUserPairSet,
1908  ChosenPairs, DAG, PrunedDAG, IJ, UseCycleCheck);
1909 
1910  int EffSize = 0;
1911  if (TTI) {
1912  DenseSet<Value *> PrunedDAGInstrs;
1913  for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
1914  E = PrunedDAG.end(); S != E; ++S) {
1915  PrunedDAGInstrs.insert(S->first);
1916  PrunedDAGInstrs.insert(S->second);
1917  }
1918 
1919  // The set of pairs that have already contributed to the total cost.
1920  DenseSet<ValuePair> IncomingPairs;
1921 
1922  // If the cost model were perfect, this might not be necessary; but we
1923  // need to make sure that we don't get stuck vectorizing our own
1924  // shuffle chains.
1925  bool HasNontrivialInsts = false;
1926 
1927  // The node weights represent the cost savings associated with
1928  // fusing the pair of instructions.
1929  for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
1930  E = PrunedDAG.end(); S != E; ++S) {
1931  if (!isa<ShuffleVectorInst>(S->first) &&
1932  !isa<InsertElementInst>(S->first) &&
1933  !isa<ExtractElementInst>(S->first))
1934  HasNontrivialInsts = true;
1935 
1936  bool FlipOrder = false;
1937 
1938  if (getDepthFactor(S->first)) {
1939  int ESContrib = CandidatePairCostSavings.find(*S)->second;
1940  DEBUG(if (DebugPairSelection) dbgs() << "\tweight {"
1941  << *S->first << " <-> " << *S->second << "} = " <<
1942  ESContrib << "\n");
1943  EffSize += ESContrib;
1944  }
1945 
1946  // The edge weights contribute in a negative sense: they represent
1947  // the cost of shuffles.
1949  ConnectedPairDeps.find(*S);
1950  if (SS != ConnectedPairDeps.end()) {
1951  unsigned NumDepsDirect = 0, NumDepsSwap = 0;
1952  for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1953  TE = SS->second.end(); T != TE; ++T) {
1954  VPPair Q(*S, *T);
1955  if (!PrunedDAG.count(Q.second))
1956  continue;
1958  PairConnectionTypes.find(VPPair(Q.second, Q.first));
1959  assert(R != PairConnectionTypes.end() &&
1960  "Cannot find pair connection type");
1961  if (R->second == PairConnectionDirect)
1962  ++NumDepsDirect;
1963  else if (R->second == PairConnectionSwap)
1964  ++NumDepsSwap;
1965  }
1966 
1967  // If there are more swaps than direct connections, then
1968  // the pair order will be flipped during fusion. So the real
1969  // number of swaps is the minimum number.
1970  FlipOrder = !FixedOrderPairs.count(*S) &&
1971  ((NumDepsSwap > NumDepsDirect) ||
1972  FixedOrderPairs.count(ValuePair(S->second, S->first)));
1973 
1974  for (std::vector<ValuePair>::iterator T = SS->second.begin(),
1975  TE = SS->second.end(); T != TE; ++T) {
1976  VPPair Q(*S, *T);
1977  if (!PrunedDAG.count(Q.second))
1978  continue;
1980  PairConnectionTypes.find(VPPair(Q.second, Q.first));
1981  assert(R != PairConnectionTypes.end() &&
1982  "Cannot find pair connection type");
1983  Type *Ty1 = Q.second.first->getType(),
1984  *Ty2 = Q.second.second->getType();
1985  Type *VTy = getVecTypeForPair(Ty1, Ty2);
1986  if ((R->second == PairConnectionDirect && FlipOrder) ||
1987  (R->second == PairConnectionSwap && !FlipOrder) ||
1988  R->second == PairConnectionSplat) {
1989  int ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
1990  VTy, VTy);
1991 
1992  if (VTy->getVectorNumElements() == 2) {
1993  if (R->second == PairConnectionSplat)
1994  ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1996  else
1997  ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
1999  }
2000 
2001  DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
2002  *Q.second.first << " <-> " << *Q.second.second <<
2003  "} -> {" <<
2004  *S->first << " <-> " << *S->second << "} = " <<
2005  ESContrib << "\n");
2006  EffSize -= ESContrib;
2007  }
2008  }
2009  }
2010 
2011  // Compute the cost of outgoing edges. We assume that edges outgoing
2012  // to shuffles, inserts or extracts can be merged, and so contribute
2013  // no additional cost.
2014  if (!S->first->getType()->isVoidTy()) {
2015  Type *Ty1 = S->first->getType(),
2016  *Ty2 = S->second->getType();
2017  Type *VTy = getVecTypeForPair(Ty1, Ty2);
2018 
2019  bool NeedsExtraction = false;
2020  for (User *U : S->first->users()) {
2021  if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
2022  // Shuffle can be folded if it has no other input
2023  if (isa<UndefValue>(SI->getOperand(1)))
2024  continue;
2025  }
2026  if (isa<ExtractElementInst>(U))
2027  continue;
2028  if (PrunedDAGInstrs.count(U))
2029  continue;
2030  NeedsExtraction = true;
2031  break;
2032  }
2033 
2034  if (NeedsExtraction) {
2035  int ESContrib;
2036  if (Ty1->isVectorTy()) {
2037  ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2038  Ty1, VTy);
2039  ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2041  } else
2042  ESContrib = (int) TTI->getVectorInstrCost(
2043  Instruction::ExtractElement, VTy, 0);
2044 
2045  DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
2046  *S->first << "} = " << ESContrib << "\n");
2047  EffSize -= ESContrib;
2048  }
2049 
2050  NeedsExtraction = false;
2051  for (User *U : S->second->users()) {
2052  if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
2053  // Shuffle can be folded if it has no other input
2054  if (isa<UndefValue>(SI->getOperand(1)))
2055  continue;
2056  }
2057  if (isa<ExtractElementInst>(U))
2058  continue;
2059  if (PrunedDAGInstrs.count(U))
2060  continue;
2061  NeedsExtraction = true;
2062  break;
2063  }
2064 
2065  if (NeedsExtraction) {
2066  int ESContrib;
2067  if (Ty2->isVectorTy()) {
2068  ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2069  Ty2, VTy);
2070  ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2072  Ty1->isVectorTy() ? Ty1->getVectorNumElements() : 1, Ty2));
2073  } else
2074  ESContrib = (int) TTI->getVectorInstrCost(
2075  Instruction::ExtractElement, VTy, 1);
2076  DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
2077  *S->second << "} = " << ESContrib << "\n");
2078  EffSize -= ESContrib;
2079  }
2080  }
2081 
2082  // Compute the cost of incoming edges.
2083  if (!isa<LoadInst>(S->first) && !isa<StoreInst>(S->first)) {
2084  Instruction *S1 = cast<Instruction>(S->first),
2085  *S2 = cast<Instruction>(S->second);
2086  for (unsigned o = 0; o < S1->getNumOperands(); ++o) {
2087  Value *O1 = S1->getOperand(o), *O2 = S2->getOperand(o);
2088 
2089  // Combining constants into vector constants (or small vector
2090  // constants into larger ones are assumed free).
2091  if (isa<Constant>(O1) && isa<Constant>(O2))
2092  continue;
2093 
2094  if (FlipOrder)
2095  std::swap(O1, O2);
2096 
2097  ValuePair VP = ValuePair(O1, O2);
2098  ValuePair VPR = ValuePair(O2, O1);
2099 
2100  // Internal edges are not handled here.
2101  if (PrunedDAG.count(VP) || PrunedDAG.count(VPR))
2102  continue;
2103 
2104  Type *Ty1 = O1->getType(),
2105  *Ty2 = O2->getType();
2106  Type *VTy = getVecTypeForPair(Ty1, Ty2);
2107 
2108  // Combining vector operations of the same type is also assumed
2109  // folded with other operations.
2110  if (Ty1 == Ty2) {
2111  // If both are insert elements, then both can be widened.
2113  *IEO2 = dyn_cast<InsertElementInst>(O2);
2114  if (IEO1 && IEO2 && isPureIEChain(IEO1) && isPureIEChain(IEO2))
2115  continue;
2116  // If both are extract elements, and both have the same input
2117  // type, then they can be replaced with a shuffle
2119  *EIO2 = dyn_cast<ExtractElementInst>(O2);
2120  if (EIO1 && EIO2 &&
2121  EIO1->getOperand(0)->getType() ==
2122  EIO2->getOperand(0)->getType())
2123  continue;
2124  // If both are a shuffle with equal operand types and only two
2125  // unqiue operands, then they can be replaced with a single
2126  // shuffle
2128  *SIO2 = dyn_cast<ShuffleVectorInst>(O2);
2129  if (SIO1 && SIO2 &&
2130  SIO1->getOperand(0)->getType() ==
2131  SIO2->getOperand(0)->getType()) {
2132  SmallSet<Value *, 4> SIOps;
2133  SIOps.insert(SIO1->getOperand(0));
2134  SIOps.insert(SIO1->getOperand(1));
2135  SIOps.insert(SIO2->getOperand(0));
2136  SIOps.insert(SIO2->getOperand(1));
2137  if (SIOps.size() <= 2)
2138  continue;
2139  }
2140  }
2141 
2142  int ESContrib;
2143  // This pair has already been formed.
2144  if (IncomingPairs.count(VP)) {
2145  continue;
2146  } else if (IncomingPairs.count(VPR)) {
2147  ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2148  VTy, VTy);
2149 
2150  if (VTy->getVectorNumElements() == 2)
2151  ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
2153  } else if (!Ty1->isVectorTy() && !Ty2->isVectorTy()) {
2154  ESContrib = (int) TTI->getVectorInstrCost(
2155  Instruction::InsertElement, VTy, 0);
2156  ESContrib += (int) TTI->getVectorInstrCost(
2157  Instruction::InsertElement, VTy, 1);
2158  } else if (!Ty1->isVectorTy()) {
2159  // O1 needs to be inserted into a vector of size O2, and then
2160  // both need to be shuffled together.
2161  ESContrib = (int) TTI->getVectorInstrCost(
2162  Instruction::InsertElement, Ty2, 0);
2163  ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2164  VTy, Ty2);
2165  } else if (!Ty2->isVectorTy()) {
2166  // O2 needs to be inserted into a vector of size O1, and then
2167  // both need to be shuffled together.
2168  ESContrib = (int) TTI->getVectorInstrCost(
2169  Instruction::InsertElement, Ty1, 0);
2170  ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2171  VTy, Ty1);
2172  } else {
2173  Type *TyBig = Ty1, *TySmall = Ty2;
2174  if (Ty2->getVectorNumElements() > Ty1->getVectorNumElements())
2175  std::swap(TyBig, TySmall);
2176 
2177  ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
2178  VTy, TyBig);
2179  if (TyBig != TySmall)
2180  ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
2181  TyBig, TySmall);
2182  }
2183 
2184  DEBUG(if (DebugPairSelection) dbgs() << "\tcost {"
2185  << *O1 << " <-> " << *O2 << "} = " <<
2186  ESContrib << "\n");
2187  EffSize -= ESContrib;
2188  IncomingPairs.insert(VP);
2189  }
2190  }
2191  }
2192 
2193  if (!HasNontrivialInsts) {
2194  DEBUG(if (DebugPairSelection) dbgs() <<
2195  "\tNo non-trivial instructions in DAG;"
2196  " override to zero effective size\n");
2197  EffSize = 0;
2198  }
2199  } else {
2200  for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
2201  E = PrunedDAG.end(); S != E; ++S)
2202  EffSize += (int) getDepthFactor(S->first);
2203  }
2204 
2206  dbgs() << "BBV: found pruned DAG for pair {"
2207  << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
2208  MaxDepth << " and size " << PrunedDAG.size() <<
2209  " (effective size: " << EffSize << ")\n");
2210  if (((TTI && !UseChainDepthWithTI) ||
2211  MaxDepth >= Config.ReqChainDepth) &&
2212  EffSize > 0 && EffSize > BestEffSize) {
2213  BestMaxDepth = MaxDepth;
2214  BestEffSize = EffSize;
2215  BestDAG = PrunedDAG;
2216  }
2217  }
2218  }
2219 
2220  // Given the list of candidate pairs, this function selects those
2221  // that will be fused into vector instructions.
2222  void BBVectorize::choosePairs(
2223  DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
2224  DenseSet<ValuePair> &CandidatePairsSet,
2225  DenseMap<ValuePair, int> &CandidatePairCostSavings,
2226  std::vector<Value *> &PairableInsts,
2227  DenseSet<ValuePair> &FixedOrderPairs,
2228  DenseMap<VPPair, unsigned> &PairConnectionTypes,
2229  DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
2230  DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
2231  DenseSet<ValuePair> &PairableInstUsers,
2232  DenseMap<Value *, Value *>& ChosenPairs) {
2233  bool UseCycleCheck =
2234  CandidatePairsSet.size() <= Config.MaxCandPairsForCycleCheck;
2235 
2236  DenseMap<Value *, std::vector<Value *> > CandidatePairs2;
2237  for (DenseSet<ValuePair>::iterator I = CandidatePairsSet.begin(),
2238  E = CandidatePairsSet.end(); I != E; ++I) {
2239  std::vector<Value *> &JJ = CandidatePairs2[I->second];
2240  if (JJ.empty()) JJ.reserve(32);
2241  JJ.push_back(I->first);
2242  }
2243 
2244  DenseMap<ValuePair, std::vector<ValuePair> > PairableInstUserMap;
2245  DenseSet<VPPair> PairableInstUserPairSet;
2246  for (std::vector<Value *>::iterator I = PairableInsts.begin(),
2247  E = PairableInsts.end(); I != E; ++I) {
2248  // The number of possible pairings for this variable:
2249  size_t NumChoices = CandidatePairs.lookup(*I).size();
2250  if (!NumChoices) continue;
2251 
2252  std::vector<Value *> &JJ = CandidatePairs[*I];
2253 
2254  // The best pair to choose and its dag:
2255  size_t BestMaxDepth = 0;
2256  int BestEffSize = 0;
2257  DenseSet<ValuePair> BestDAG;
2258  findBestDAGFor(CandidatePairs, CandidatePairsSet,
2259  CandidatePairCostSavings,
2260  PairableInsts, FixedOrderPairs, PairConnectionTypes,
2261  ConnectedPairs, ConnectedPairDeps,
2262  PairableInstUsers, PairableInstUserMap,
2263  PairableInstUserPairSet, ChosenPairs,
2264  BestDAG, BestMaxDepth, BestEffSize, *I, JJ,
2265  UseCycleCheck);
2266 
2267  if (BestDAG.empty())
2268  continue;
2269 
2270  // A dag has been chosen (or not) at this point. If no dag was
2271  // chosen, then this instruction, I, cannot be paired (and is no longer
2272  // considered).
2273 
2274  DEBUG(dbgs() << "BBV: selected pairs in the best DAG for: "
2275  << *cast<Instruction>(*I) << "\n");
2276 
2277  for (DenseSet<ValuePair>::iterator S = BestDAG.begin(),
2278  SE2 = BestDAG.end(); S != SE2; ++S) {
2279  // Insert the members of this dag into the list of chosen pairs.
2280  ChosenPairs.insert(ValuePair(S->first, S->second));
2281  DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
2282  *S->second << "\n");
2283 
2284  // Remove all candidate pairs that have values in the chosen dag.
2285  std::vector<Value *> &KK = CandidatePairs[S->first];
2286  for (std::vector<Value *>::iterator K = KK.begin(), KE = KK.end();
2287  K != KE; ++K) {
2288  if (*K == S->second)
2289  continue;
2290 
2291  CandidatePairsSet.erase(ValuePair(S->first, *K));
2292  }
2293 
2294  std::vector<Value *> &LL = CandidatePairs2[S->second];
2295  for (std::vector<Value *>::iterator L = LL.begin(), LE = LL.end();
2296  L != LE; ++L) {
2297  if (*L == S->first)
2298  continue;
2299 
2300  CandidatePairsSet.erase(ValuePair(*L, S->second));
2301  }
2302 
2303  std::vector<Value *> &MM = CandidatePairs[S->second];
2304  for (std::vector<Value *>::iterator M = MM.begin(), ME = MM.end();
2305  M != ME; ++M) {
2306  assert(*M != S->first && "Flipped pair in candidate list?");
2307  CandidatePairsSet.erase(ValuePair(S->second, *M));
2308  }
2309 
2310  std::vector<Value *> &NN = CandidatePairs2[S->first];
2311  for (std::vector<Value *>::iterator N = NN.begin(), NE = NN.end();
2312  N != NE; ++N) {
2313  assert(*N != S->second && "Flipped pair in candidate list?");
2314  CandidatePairsSet.erase(ValuePair(*N, S->first));
2315  }
2316  }
2317  }
2318 
2319  DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
2320  }
2321 
2322  std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
2323  unsigned n = 0) {
2324  if (!I->hasName())
2325  return "";
2326 
2327  return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
2328  (n > 0 ? "." + utostr(n) : "")).str();
2329  }
2330 
2331  // Returns the value that is to be used as the pointer input to the vector
2332  // instruction that fuses I with J.
2333  Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
2334  Instruction *I, Instruction *J, unsigned o) {
2335  Value *IPtr, *JPtr;
2336  unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
2337  int64_t OffsetInElmts;
2338 
2339  // Note: the analysis might fail here, that is why the pair order has
2340  // been precomputed (OffsetInElmts must be unused here).
2341  (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
2342  IAddressSpace, JAddressSpace,
2343  OffsetInElmts, false);
2344 
2345  // The pointer value is taken to be the one with the lowest offset.
2346  Value *VPtr = IPtr;
2347 
2348  Type *ArgTypeI = IPtr->getType()->getPointerElementType();
2349  Type *ArgTypeJ = JPtr->getType()->getPointerElementType();
2350  Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2351  Type *VArgPtrType
2352  = PointerType::get(VArgType,
2353  IPtr->getType()->getPointerAddressSpace());
2354  return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
2355  /* insert before */ I);
2356  }
2357 
2358  void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
2359  unsigned MaskOffset, unsigned NumInElem,
2360  unsigned NumInElem1, unsigned IdxOffset,
2361  std::vector<Constant*> &Mask) {
2362  unsigned NumElem1 = J->getType()->getVectorNumElements();
2363  for (unsigned v = 0; v < NumElem1; ++v) {
2364  int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
2365  if (m < 0) {
2366  Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
2367  } else {
2368  unsigned mm = m + (int) IdxOffset;
2369  if (m >= (int) NumInElem1)
2370  mm += (int) NumInElem;
2371 
2372  Mask[v+MaskOffset] =
2373  ConstantInt::get(Type::getInt32Ty(Context), mm);
2374  }
2375  }
2376  }
2377 
2378  // Returns the value that is to be used as the vector-shuffle mask to the
2379  // vector instruction that fuses I with J.
2380  Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
2381  Instruction *I, Instruction *J) {
2382  // This is the shuffle mask. We need to append the second
2383  // mask to the first, and the numbers need to be adjusted.
2384 
2385  Type *ArgTypeI = I->getType();
2386  Type *ArgTypeJ = J->getType();
2387  Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2388 
2389  unsigned NumElemI = ArgTypeI->getVectorNumElements();
2390 
2391  // Get the total number of elements in the fused vector type.
2392  // By definition, this must equal the number of elements in
2393  // the final mask.
2394  unsigned NumElem = VArgType->getVectorNumElements();
2395  std::vector<Constant*> Mask(NumElem);
2396 
2397  Type *OpTypeI = I->getOperand(0)->getType();
2398  unsigned NumInElemI = OpTypeI->getVectorNumElements();
2399  Type *OpTypeJ = J->getOperand(0)->getType();
2400  unsigned NumInElemJ = OpTypeJ->getVectorNumElements();
2401 
2402  // The fused vector will be:
2403  // -----------------------------------------------------
2404  // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
2405  // -----------------------------------------------------
2406  // from which we'll extract NumElem total elements (where the first NumElemI
2407  // of them come from the mask in I and the remainder come from the mask
2408  // in J.
2409 
2410  // For the mask from the first pair...
2411  fillNewShuffleMask(Context, I, 0, NumInElemJ, NumInElemI,
2412  0, Mask);
2413 
2414  // For the mask from the second pair...
2415  fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
2416  NumInElemI, Mask);
2417 
2418  return ConstantVector::get(Mask);
2419  }
2420 
2421  bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
2422  Instruction *J, unsigned o, Value *&LOp,
2423  unsigned numElemL,
2424  Type *ArgTypeL, Type *ArgTypeH,
2425  bool IBeforeJ, unsigned IdxOff) {
2426  bool ExpandedIEChain = false;
2427  if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
2428  // If we have a pure insertelement chain, then this can be rewritten
2429  // into a chain that directly builds the larger type.
2430  if (isPureIEChain(LIE)) {
2431  SmallVector<Value *, 8> VectElemts(numElemL,
2432  UndefValue::get(ArgTypeL->getScalarType()));
2433  InsertElementInst *LIENext = LIE;
2434  do {
2435  unsigned Idx =
2436  cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
2437  VectElemts[Idx] = LIENext->getOperand(1);
2438  } while ((LIENext =
2439  dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
2440 
2441  LIENext = nullptr;
2442  Value *LIEPrev = UndefValue::get(ArgTypeH);
2443  for (unsigned i = 0; i < numElemL; ++i) {
2444  if (isa<UndefValue>(VectElemts[i])) continue;
2445  LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
2447  i + IdxOff),
2448  getReplacementName(IBeforeJ ? I : J,
2449  true, o, i+1));
2450  LIENext->insertBefore(IBeforeJ ? J : I);
2451  LIEPrev = LIENext;
2452  }
2453 
2454  LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
2455  ExpandedIEChain = true;
2456  }
2457  }
2458 
2459  return ExpandedIEChain;
2460  }
2461 
2462  static unsigned getNumScalarElements(Type *Ty) {
2463  if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
2464  return VecTy->getNumElements();
2465  return 1;
2466  }
2467 
2468  // Returns the value to be used as the specified operand of the vector
2469  // instruction that fuses I with J.
2470  Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
2471  Instruction *J, unsigned o, bool IBeforeJ) {
2472  Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2473  Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
2474 
2475  // Compute the fused vector type for this operand
2476  Type *ArgTypeI = I->getOperand(o)->getType();
2477  Type *ArgTypeJ = J->getOperand(o)->getType();
2478  VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2479 
2480  Instruction *L = I, *H = J;
2481  Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
2482 
2483  unsigned numElemL = getNumScalarElements(ArgTypeL);
2484  unsigned numElemH = getNumScalarElements(ArgTypeH);
2485 
2486  Value *LOp = L->getOperand(o);
2487  Value *HOp = H->getOperand(o);
2488  unsigned numElem = VArgType->getNumElements();
2489 
2490  // First, we check if we can reuse the "original" vector outputs (if these
2491  // exist). We might need a shuffle.
2496 
2497  // FIXME: If we're fusing shuffle instructions, then we can't apply this
2498  // optimization. The input vectors to the shuffle might be a different
2499  // length from the shuffle outputs. Unfortunately, the replacement
2500  // shuffle mask has already been formed, and the mask entries are sensitive
2501  // to the sizes of the inputs.
2502  bool IsSizeChangeShuffle =
2503  isa<ShuffleVectorInst>(L) &&
2504  (LOp->getType() != L->getType() || HOp->getType() != H->getType());
2505 
2506  if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
2507  // We can have at most two unique vector inputs.
2508  bool CanUseInputs = true;
2509  Value *I1, *I2 = nullptr;
2510  if (LEE) {
2511  I1 = LEE->getOperand(0);
2512  } else {
2513  I1 = LSV->getOperand(0);
2514  I2 = LSV->getOperand(1);
2515  if (I2 == I1 || isa<UndefValue>(I2))
2516  I2 = nullptr;
2517  }
2518 
2519  if (HEE) {
2520  Value *I3 = HEE->getOperand(0);
2521  if (!I2 && I3 != I1)
2522  I2 = I3;
2523  else if (I3 != I1 && I3 != I2)
2524  CanUseInputs = false;
2525  } else {
2526  Value *I3 = HSV->getOperand(0);
2527  if (!I2 && I3 != I1)
2528  I2 = I3;
2529  else if (I3 != I1 && I3 != I2)
2530  CanUseInputs = false;
2531 
2532  if (CanUseInputs) {
2533  Value *I4 = HSV->getOperand(1);
2534  if (!isa<UndefValue>(I4)) {
2535  if (!I2 && I4 != I1)
2536  I2 = I4;
2537  else if (I4 != I1 && I4 != I2)
2538  CanUseInputs = false;
2539  }
2540  }
2541  }
2542 
2543  if (CanUseInputs) {
2544  unsigned LOpElem =
2545  cast<Instruction>(LOp)->getOperand(0)->getType()
2546  ->getVectorNumElements();
2547 
2548  unsigned HOpElem =
2549  cast<Instruction>(HOp)->getOperand(0)->getType()
2550  ->getVectorNumElements();
2551 
2552  // We have one or two input vectors. We need to map each index of the
2553  // operands to the index of the original vector.
2554  SmallVector<std::pair<int, int>, 8> II(numElem);
2555  for (unsigned i = 0; i < numElemL; ++i) {
2556  int Idx, INum;
2557  if (LEE) {
2558  Idx =
2559  cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
2560  INum = LEE->getOperand(0) == I1 ? 0 : 1;
2561  } else {
2562  Idx = LSV->getMaskValue(i);
2563  if (Idx < (int) LOpElem) {
2564  INum = LSV->getOperand(0) == I1 ? 0 : 1;
2565  } else {
2566  Idx -= LOpElem;
2567  INum = LSV->getOperand(1) == I1 ? 0 : 1;
2568  }
2569  }
2570 
2571  II[i] = std::pair<int, int>(Idx, INum);
2572  }
2573  for (unsigned i = 0; i < numElemH; ++i) {
2574  int Idx, INum;
2575  if (HEE) {
2576  Idx =
2577  cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
2578  INum = HEE->getOperand(0) == I1 ? 0 : 1;
2579  } else {
2580  Idx = HSV->getMaskValue(i);
2581  if (Idx < (int) HOpElem) {
2582  INum = HSV->getOperand(0) == I1 ? 0 : 1;
2583  } else {
2584  Idx -= HOpElem;
2585  INum = HSV->getOperand(1) == I1 ? 0 : 1;
2586  }
2587  }
2588 
2589  II[i + numElemL] = std::pair<int, int>(Idx, INum);
2590  }
2591 
2592  // We now have an array which tells us from which index of which
2593  // input vector each element of the operand comes.
2594  VectorType *I1T = cast<VectorType>(I1->getType());
2595  unsigned I1Elem = I1T->getNumElements();
2596 
2597  if (!I2) {
2598  // In this case there is only one underlying vector input. Check for
2599  // the trivial case where we can use the input directly.
2600  if (I1Elem == numElem) {
2601  bool ElemInOrder = true;
2602  for (unsigned i = 0; i < numElem; ++i) {
2603  if (II[i].first != (int) i && II[i].first != -1) {
2604  ElemInOrder = false;
2605  break;
2606  }
2607  }
2608 
2609  if (ElemInOrder)
2610  return I1;
2611  }
2612 
2613  // A shuffle is needed.
2614  std::vector<Constant *> Mask(numElem);
2615  for (unsigned i = 0; i < numElem; ++i) {
2616  int Idx = II[i].first;
2617  if (Idx == -1)
2618  Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
2619  else
2620  Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2621  }
2622 
2623  Instruction *S =
2624  new ShuffleVectorInst(I1, UndefValue::get(I1T),
2625  ConstantVector::get(Mask),
2626  getReplacementName(IBeforeJ ? I : J,
2627  true, o));
2628  S->insertBefore(IBeforeJ ? J : I);
2629  return S;
2630  }
2631 
2632  VectorType *I2T = cast<VectorType>(I2->getType());
2633  unsigned I2Elem = I2T->getNumElements();
2634 
2635  // This input comes from two distinct vectors. The first step is to
2636  // make sure that both vectors are the same length. If not, the
2637  // smaller one will need to grow before they can be shuffled together.
2638  if (I1Elem < I2Elem) {
2639  std::vector<Constant *> Mask(I2Elem);
2640  unsigned v = 0;
2641  for (; v < I1Elem; ++v)
2642  Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2643  for (; v < I2Elem; ++v)
2644  Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2645 
2646  Instruction *NewI1 =
2647  new ShuffleVectorInst(I1, UndefValue::get(I1T),
2648  ConstantVector::get(Mask),
2649  getReplacementName(IBeforeJ ? I : J,
2650  true, o, 1));
2651  NewI1->insertBefore(IBeforeJ ? J : I);
2652  I1 = NewI1;
2653  I1Elem = I2Elem;
2654  } else if (I1Elem > I2Elem) {
2655  std::vector<Constant *> Mask(I1Elem);
2656  unsigned v = 0;
2657  for (; v < I2Elem; ++v)
2658  Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2659  for (; v < I1Elem; ++v)
2660  Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2661 
2662  Instruction *NewI2 =
2663  new ShuffleVectorInst(I2, UndefValue::get(I2T),
2664  ConstantVector::get(Mask),
2665  getReplacementName(IBeforeJ ? I : J,
2666  true, o, 1));
2667  NewI2->insertBefore(IBeforeJ ? J : I);
2668  I2 = NewI2;
2669  }
2670 
2671  // Now that both I1 and I2 are the same length we can shuffle them
2672  // together (and use the result).
2673  std::vector<Constant *> Mask(numElem);
2674  for (unsigned v = 0; v < numElem; ++v) {
2675  if (II[v].first == -1) {
2676  Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2677  } else {
2678  int Idx = II[v].first + II[v].second * I1Elem;
2679  Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2680  }
2681  }
2682 
2683  Instruction *NewOp =
2684  new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
2685  getReplacementName(IBeforeJ ? I : J, true, o));
2686  NewOp->insertBefore(IBeforeJ ? J : I);
2687  return NewOp;
2688  }
2689  }
2690 
2691  Type *ArgType = ArgTypeL;
2692  if (numElemL < numElemH) {
2693  if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
2694  ArgTypeL, VArgType, IBeforeJ, 1)) {
2695  // This is another short-circuit case: we're combining a scalar into
2696  // a vector that is formed by an IE chain. We've just expanded the IE
2697  // chain, now insert the scalar and we're done.
2698 
2699  Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
2700  getReplacementName(IBeforeJ ? I : J, true, o));
2701  S->insertBefore(IBeforeJ ? J : I);
2702  return S;
2703  } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
2704  ArgTypeH, IBeforeJ)) {
2705  // The two vector inputs to the shuffle must be the same length,
2706  // so extend the smaller vector to be the same length as the larger one.
2707  Instruction *NLOp;
2708  if (numElemL > 1) {
2709 
2710  std::vector<Constant *> Mask(numElemH);
2711  unsigned v = 0;
2712  for (; v < numElemL; ++v)
2713  Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2714  for (; v < numElemH; ++v)
2715  Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2716 
2717  NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
2718  ConstantVector::get(Mask),
2719  getReplacementName(IBeforeJ ? I : J,
2720  true, o, 1));
2721  } else {
2722  NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
2723  getReplacementName(IBeforeJ ? I : J,
2724  true, o, 1));
2725  }
2726 
2727  NLOp->insertBefore(IBeforeJ ? J : I);
2728  LOp = NLOp;
2729  }
2730 
2731  ArgType = ArgTypeH;
2732  } else if (numElemL > numElemH) {
2733  if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
2734  ArgTypeH, VArgType, IBeforeJ)) {
2735  Instruction *S =
2736  InsertElementInst::Create(LOp, HOp,
2738  numElemL),
2739  getReplacementName(IBeforeJ ? I : J,
2740  true, o));
2741  S->insertBefore(IBeforeJ ? J : I);
2742  return S;
2743  } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
2744  ArgTypeL, IBeforeJ)) {
2745  Instruction *NHOp;
2746  if (numElemH > 1) {
2747  std::vector<Constant *> Mask(numElemL);
2748  unsigned v = 0;
2749  for (; v < numElemH; ++v)
2750  Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2751  for (; v < numElemL; ++v)
2752  Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
2753 
2754  NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
2755  ConstantVector::get(Mask),
2756  getReplacementName(IBeforeJ ? I : J,
2757  true, o, 1));
2758  } else {
2759  NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
2760  getReplacementName(IBeforeJ ? I : J,
2761  true, o, 1));
2762  }
2763 
2764  NHOp->insertBefore(IBeforeJ ? J : I);
2765  HOp = NHOp;
2766  }
2767  }
2768 
2769  if (ArgType->isVectorTy()) {
2770  unsigned numElem = VArgType->getVectorNumElements();
2771  std::vector<Constant*> Mask(numElem);
2772  for (unsigned v = 0; v < numElem; ++v) {
2773  unsigned Idx = v;
2774  // If the low vector was expanded, we need to skip the extra
2775  // undefined entries.
2776  if (v >= numElemL && numElemH > numElemL)
2777  Idx += (numElemH - numElemL);
2778  Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
2779  }
2780 
2781  Instruction *BV = new ShuffleVectorInst(LOp, HOp,
2782  ConstantVector::get(Mask),
2783  getReplacementName(IBeforeJ ? I : J, true, o));
2784  BV->insertBefore(IBeforeJ ? J : I);
2785  return BV;
2786  }
2787 
2789  UndefValue::get(VArgType), LOp, CV0,
2790  getReplacementName(IBeforeJ ? I : J,
2791  true, o, 1));
2792  BV1->insertBefore(IBeforeJ ? J : I);
2793  Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
2794  getReplacementName(IBeforeJ ? I : J,
2795  true, o, 2));
2796  BV2->insertBefore(IBeforeJ ? J : I);
2797  return BV2;
2798  }
2799 
2800  // This function creates an array of values that will be used as the inputs
2801  // to the vector instruction that fuses I with J.
2802  void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
2803  Instruction *I, Instruction *J,
2804  SmallVectorImpl<Value *> &ReplacedOperands,
2805  bool IBeforeJ) {
2806  unsigned NumOperands = I->getNumOperands();
2807 
2808  for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
2809  // Iterate backward so that we look at the store pointer
2810  // first and know whether or not we need to flip the inputs.
2811 
2812  if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
2813  // This is the pointer for a load/store instruction.
2814  ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
2815  continue;
2816  } else if (isa<CallInst>(I)) {
2817  Function *F = cast<CallInst>(I)->getCalledFunction();
2818  Intrinsic::ID IID = F->getIntrinsicID();
2819  if (o == NumOperands-1) {
2820  BasicBlock &BB = *I->getParent();
2821 
2822  Module *M = BB.getParent()->getParent();
2823  Type *ArgTypeI = I->getType();
2824  Type *ArgTypeJ = J->getType();
2825  Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
2826 
2827  ReplacedOperands[o] = Intrinsic::getDeclaration(M, IID, VArgType);
2828  continue;
2829  } else if ((IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
2830  IID == Intrinsic::cttz) && o == 1) {
2831  // The second argument of powi/ctlz/cttz is a single integer/constant
2832  // and we've already checked that both arguments are equal.
2833  // As a result, we just keep I's second argument.
2834  ReplacedOperands[o] = I->getOperand(o);
2835  continue;
2836  }
2837  } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
2838  ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
2839  continue;
2840  }
2841 
2842  ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
2843  }
2844  }
2845 
2846  // This function creates two values that represent the outputs of the
2847  // original I and J instructions. These are generally vector shuffles
2848  // or extracts. In many cases, these will end up being unused and, thus,
2849  // eliminated by later passes.
2850  void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
2851  Instruction *J, Instruction *K,
2852  Instruction *&InsertionPt,
2853  Instruction *&K1, Instruction *&K2) {
2854  if (isa<StoreInst>(I))
2855  return;
2856 
2857  Type *IType = I->getType();
2858  Type *JType = J->getType();
2859 
2860  VectorType *VType = getVecTypeForPair(IType, JType);
2861  unsigned numElem = VType->getNumElements();
2862 
2863  unsigned numElemI = getNumScalarElements(IType);
2864  unsigned numElemJ = getNumScalarElements(JType);
2865 
2866  if (IType->isVectorTy()) {
2867  std::vector<Constant *> Mask1(numElemI), Mask2(numElemI);
2868  for (unsigned v = 0; v < numElemI; ++v) {
2869  Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2870  Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ + v);
2871  }
2872 
2873  K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
2874  ConstantVector::get(Mask1),
2875  getReplacementName(K, false, 1));
2876  } else {
2877  Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
2878  K1 = ExtractElementInst::Create(K, CV0, getReplacementName(K, false, 1));
2879  }
2880 
2881  if (JType->isVectorTy()) {
2882  std::vector<Constant *> Mask1(numElemJ), Mask2(numElemJ);
2883  for (unsigned v = 0; v < numElemJ; ++v) {
2884  Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
2885  Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI + v);
2886  }
2887 
2888  K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
2889  ConstantVector::get(Mask2),
2890  getReplacementName(K, false, 2));
2891  } else {
2892  Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem - 1);
2893  K2 = ExtractElementInst::Create(K, CV1, getReplacementName(K, false, 2));
2894  }
2895 
2896  K1->insertAfter(K);
2897  K2->insertAfter(K1);
2898  InsertionPt = K2;
2899  }
2900 
2901  // Move all uses of the function I (including pairing-induced uses) after J.
2902  bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
2903  DenseSet<ValuePair> &LoadMoveSetPairs,
2904  Instruction *I, Instruction *J) {
2905  // Skip to the first instruction past I.
2906  BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2907 
2909  AliasSetTracker WriteSet(*AA);
2910  if (I->mayWriteToMemory()) WriteSet.add(I);
2911 
2912  for (; cast<Instruction>(L) != J; ++L)
2913  (void)trackUsesOfI(Users, WriteSet, I, &*L, true, &LoadMoveSetPairs);
2914 
2915  assert(cast<Instruction>(L) == J &&
2916  "Tracking has not proceeded far enough to check for dependencies");
2917  // If J is now in the use set of I, then trackUsesOfI will return true
2918  // and we have a dependency cycle (and the fusing operation must abort).
2919  return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSetPairs);
2920  }
2921 
2922  // Move all uses of the function I (including pairing-induced uses) after J.
2923  void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
2924  DenseSet<ValuePair> &LoadMoveSetPairs,
2925  Instruction *&InsertionPt,
2926  Instruction *I, Instruction *J) {
2927  // Skip to the first instruction past I.
2928  BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2929 
2931  AliasSetTracker WriteSet(*AA);
2932  if (I->mayWriteToMemory()) WriteSet.add(I);
2933 
2934  for (; cast<Instruction>(L) != J;) {
2935  if (trackUsesOfI(Users, WriteSet, I, &*L, true, &LoadMoveSetPairs)) {
2936  // Move this instruction
2937  Instruction *InstToMove = &*L++;
2938 
2939  DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
2940  " to after " << *InsertionPt << "\n");
2941  InstToMove->removeFromParent();
2942  InstToMove->insertAfter(InsertionPt);
2943  InsertionPt = InstToMove;
2944  } else {
2945  ++L;
2946  }
2947  }
2948  }
2949 
2950  // Collect all load instruction that are in the move set of a given first
2951  // pair member. These loads depend on the first instruction, I, and so need
2952  // to be moved after J (the second instruction) when the pair is fused.
2953  void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
2954  DenseMap<Value *, Value *> &ChosenPairs,
2955  DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2956  DenseSet<ValuePair> &LoadMoveSetPairs,
2957  Instruction *I) {
2958  // Skip to the first instruction past I.
2959  BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
2960 
2962  AliasSetTracker WriteSet(*AA);
2963  if (I->mayWriteToMemory()) WriteSet.add(I);
2964 
2965  // Note: We cannot end the loop when we reach J because J could be moved
2966  // farther down the use chain by another instruction pairing. Also, J
2967  // could be before I if this is an inverted input.
2968  for (BasicBlock::iterator E = BB.end(); L != E; ++L) {
2969  if (trackUsesOfI(Users, WriteSet, I, &*L)) {
2970  if (L->mayReadFromMemory()) {
2971  LoadMoveSet[&*L].push_back(I);
2972  LoadMoveSetPairs.insert(ValuePair(&*L, I));
2973  }
2974  }
2975  }
2976  }
2977 
2978  // In cases where both load/stores and the computation of their pointers
2979  // are chosen for vectorization, we can end up in a situation where the
2980  // aliasing analysis starts returning different query results as the
2981  // process of fusing instruction pairs continues. Because the algorithm
2982  // relies on finding the same use dags here as were found earlier, we'll
2983  // need to precompute the necessary aliasing information here and then
2984  // manually update it during the fusion process.
2985  void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
2986  std::vector<Value *> &PairableInsts,
2987  DenseMap<Value *, Value *> &ChosenPairs,
2988  DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
2989  DenseSet<ValuePair> &LoadMoveSetPairs) {
2990  for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
2991  PIE = PairableInsts.end(); PI != PIE; ++PI) {
2992  DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
2993  if (P == ChosenPairs.end()) continue;
2994 
2995  Instruction *I = cast<Instruction>(P->first);
2996  collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet,
2997  LoadMoveSetPairs, I);
2998  }
2999  }
3000 
3001  // This function fuses the chosen instruction pairs into vector instructions,
3002  // taking care preserve any needed scalar outputs and, then, it reorders the
3003  // remaining instructions as needed (users of the first member of the pair
3004  // need to be moved to after the location of the second member of the pair
3005  // because the vector instruction is inserted in the location of the pair's
3006  // second member).
3007  void BBVectorize::fuseChosenPairs(BasicBlock &BB,
3008  std::vector<Value *> &PairableInsts,
3009  DenseMap<Value *, Value *> &ChosenPairs,
3010  DenseSet<ValuePair> &FixedOrderPairs,
3011  DenseMap<VPPair, unsigned> &PairConnectionTypes,
3012  DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
3013  DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps) {
3014  LLVMContext& Context = BB.getContext();
3015 
3016  // During the vectorization process, the order of the pairs to be fused
3017  // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
3018  // list. After a pair is fused, the flipped pair is removed from the list.
3019  DenseSet<ValuePair> FlippedPairs;
3020  for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
3021  E = ChosenPairs.end(); P != E; ++P)
3022  FlippedPairs.insert(ValuePair(P->second, P->first));
3023  for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
3024  E = FlippedPairs.end(); P != E; ++P)
3025  ChosenPairs.insert(*P);
3026 
3028  DenseSet<ValuePair> LoadMoveSetPairs;
3029  collectLoadMoveSet(BB, PairableInsts, ChosenPairs,
3030  LoadMoveSet, LoadMoveSetPairs);
3031 
3032  DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
3033 
3034  for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
3035  DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(&*PI);
3036  if (P == ChosenPairs.end()) {
3037  ++PI;
3038  continue;
3039  }
3040 
3041  if (getDepthFactor(P->first) == 0) {
3042  // These instructions are not really fused, but are tracked as though
3043  // they are. Any case in which it would be interesting to fuse them
3044  // will be taken care of by InstCombine.
3045  --NumFusedOps;
3046  ++PI;
3047  continue;
3048  }
3049 
3050  Instruction *I = cast<Instruction>(P->first),
3051  *J = cast<Instruction>(P->second);
3052 
3053  DEBUG(dbgs() << "BBV: fusing: " << *I <<
3054  " <-> " << *J << "\n");
3055 
3056  // Remove the pair and flipped pair from the list.
3057  DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
3058  assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
3059  ChosenPairs.erase(FP);
3060  ChosenPairs.erase(P);
3061 
3062  if (!canMoveUsesOfIAfterJ(BB, LoadMoveSetPairs, I, J)) {
3063  DEBUG(dbgs() << "BBV: fusion of: " << *I <<
3064  " <-> " << *J <<
3065  " aborted because of non-trivial dependency cycle\n");
3066  --NumFusedOps;
3067  ++PI;
3068  continue;
3069  }
3070 
3071  // If the pair must have the other order, then flip it.
3072  bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
3073  if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
3074  // This pair does not have a fixed order, and so we might want to
3075  // flip it if that will yield fewer shuffles. We count the number
3076  // of dependencies connected via swaps, and those directly connected,
3077  // and flip the order if the number of swaps is greater.
3078  bool OrigOrder = true;
3080  ConnectedPairDeps.find(ValuePair(I, J));
3081  if (IJ == ConnectedPairDeps.end()) {
3082  IJ = ConnectedPairDeps.find(ValuePair(J, I));
3083  OrigOrder = false;
3084  }
3085 
3086  if (IJ != ConnectedPairDeps.end()) {
3087  unsigned NumDepsDirect = 0, NumDepsSwap = 0;
3088  for (std::vector<ValuePair>::iterator T = IJ->second.begin(),
3089  TE = IJ->second.end(); T != TE; ++T) {
3090  VPPair Q(IJ->first, *T);
3092  PairConnectionTypes.find(VPPair(Q.second, Q.first));
3093  assert(R != PairConnectionTypes.end() &&
3094  "Cannot find pair connection type");
3095  if (R->second == PairConnectionDirect)
3096  ++NumDepsDirect;
3097  else if (R->second == PairConnectionSwap)
3098  ++NumDepsSwap;
3099  }
3100 
3101  if (!OrigOrder)
3102  std::swap(NumDepsDirect, NumDepsSwap);
3103 
3104  if (NumDepsSwap > NumDepsDirect) {
3105  FlipPairOrder = true;
3106  DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
3107  " <-> " << *J << "\n");
3108  }
3109  }
3110  }
3111 
3112  Instruction *L = I, *H = J;
3113  if (FlipPairOrder)
3114  std::swap(H, L);
3115 
3116  // If the pair being fused uses the opposite order from that in the pair
3117  // connection map, then we need to flip the types.
3119  ConnectedPairs.find(ValuePair(H, L));
3120  if (HL != ConnectedPairs.end())
3121  for (std::vector<ValuePair>::iterator T = HL->second.begin(),
3122  TE = HL->second.end(); T != TE; ++T) {
3123  VPPair Q(HL->first, *T);
3124  DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(Q);
3125  assert(R != PairConnectionTypes.end() &&
3126  "Cannot find pair connection type");
3127  if (R->second == PairConnectionDirect)
3128  R->second = PairConnectionSwap;
3129  else if (R->second == PairConnectionSwap)
3130  R->second = PairConnectionDirect;
3131  }
3132 
3133  bool LBeforeH = !FlipPairOrder;
3134  unsigned NumOperands = I->getNumOperands();
3135  SmallVector<Value *, 3> ReplacedOperands(NumOperands);
3136  getReplacementInputsForPair(Context, L, H, ReplacedOperands,
3137  LBeforeH);
3138 
3139  // Make a copy of the original operation, change its type to the vector
3140  // type and replace its operands with the vector operands.
3141  Instruction *K = L->clone();
3142  if (L->hasName())
3143  K->takeName(L);
3144  else if (H->hasName())
3145  K->takeName(H);
3146 
3147  if (auto CS = CallSite(K)) {
3149  FunctionType *Old = CS.getFunctionType();
3150  unsigned NumOld = Old->getNumParams();
3151  assert(NumOld <= ReplacedOperands.size());
3152  for (unsigned i = 0; i != NumOld; ++i)
3153  Tys.push_back(ReplacedOperands[i]->getType());
3154  CS.mutateFunctionType(
3155  FunctionType::get(getVecTypeForPair(L->getType(), H->getType()),
3156  Tys, Old->isVarArg()));
3157  } else if (!isa<StoreInst>(K))
3158  K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
3159 
3160  unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
3163  combineMetadata(K, H, KnownIDs);
3164  K->andIRFlags(H);
3165 
3166  for (unsigned o = 0; o < NumOperands; ++o)
3167  K->setOperand(o, ReplacedOperands[o]);
3168 
3169  K->insertAfter(J);
3170 
3171  // Instruction insertion point:
3172  Instruction *InsertionPt = K;
3173  Instruction *K1 = nullptr, *K2 = nullptr;
3174  replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
3175 
3176  // The use dag of the first original instruction must be moved to after
3177  // the location of the second instruction. The entire use dag of the
3178  // first instruction is disjoint from the input dag of the second
3179  // (by definition), and so commutes with it.
3180 
3181  moveUsesOfIAfterJ(BB, LoadMoveSetPairs, InsertionPt, I, J);
3182 
3183  if (!isa<StoreInst>(I)) {
3184  L->replaceAllUsesWith(K1);
3185  H->replaceAllUsesWith(K2);
3186  }
3187 
3188  // Instructions that may read from memory may be in the load move set.
3189  // Once an instruction is fused, we no longer need its move set, and so
3190  // the values of the map never need to be updated. However, when a load
3191  // is fused, we need to merge the entries from both instructions in the
3192  // pair in case those instructions were in the move set of some other
3193  // yet-to-be-fused pair. The loads in question are the keys of the map.
3194  if (I->mayReadFromMemory()) {
3195  std::vector<ValuePair> NewSetMembers;
3197  LoadMoveSet.find(I);
3198  if (II != LoadMoveSet.end())
3199  for (std::vector<Value *>::iterator N = II->second.begin(),
3200  NE = II->second.end(); N != NE; ++N)
3201  NewSetMembers.push_back(ValuePair(K, *N));
3203  LoadMoveSet.find(J);
3204  if (JJ != LoadMoveSet.end())
3205  for (std::vector<Value *>::iterator N = JJ->second.begin(),
3206  NE = JJ->second.end(); N != NE; ++N)
3207  NewSetMembers.push_back(ValuePair(K, *N));
3208  for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
3209  AE = NewSetMembers.end(); A != AE; ++A) {
3210  LoadMoveSet[A->first].push_back(A->second);
3211  LoadMoveSetPairs.insert(*A);
3212  }
3213  }
3214 
3215  // Before removing I, set the iterator to the next instruction.
3216  PI = std::next(BasicBlock::iterator(I));
3217  if (cast<Instruction>(PI) == J)
3218  ++PI;
3219 
3220  SE->forgetValue(I);
3221  SE->forgetValue(J);
3222  I->eraseFromParent();
3223  J->eraseFromParent();
3224 
3225  DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
3226  BB << "\n");
3227  }
3228 
3229  DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
3230  }
3231 }
3232 
3233 char BBVectorize::ID = 0;
3234 static const char bb_vectorize_name[] = "Basic-Block Vectorization";
3235 INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3244 INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
3245 
3247  return new BBVectorize(C);
3248 }
3249 
3250 bool
3252  BBVectorize BBVectorizer(P, *BB.getParent(), C);
3253  return BBVectorizer.vectorizeBB(BB);
3254 }
3255 
3256 //===----------------------------------------------------------------------===//
3259  VectorizeBools = !::NoBools;
3260  VectorizeInts = !::NoInts;
3261  VectorizeFloats = !::NoFloats;
3262  VectorizePointers = !::NoPointers;
3263  VectorizeCasts = !::NoCasts;
3264  VectorizeMath = !::NoMath;
3265  VectorizeBitManipulations = !::NoBitManipulation;
3266  VectorizeFMA = !::NoFMA;
3267  VectorizeSelect = !::NoSelect;
3268  VectorizeCmp = !::NoCmp;
3269  VectorizeGEP = !::NoGEP;
3270  VectorizeMemOps = !::NoMemOps;
3276  MaxInsts = ::MaxInsts;
3277  MaxPairs = ::MaxPairs;
3278  MaxIter = ::MaxIter;
3281  FastDep = ::FastDep;
3282 }
Legacy wrapper pass to provide the GlobalsAAResult object.
static cl::opt< bool > DebugInstructionExamination("bb-vectorize-debug-instruction-examination", cl::init(false), cl::Hidden, cl::desc("When debugging is enabled, output information on the" " instruction-examination process"))
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:81
uint64_t CallInst * C
bool VectorizeFMA
Vectorize the fused-multiply-add intrinsic.
Definition: Vectorize.h:54
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:69
void push_back(const T &Elt)
Definition: SmallVector.h:211
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
static cl::opt< unsigned > MaxPairs("bb-vectorize-max-pairs-per-group", cl::init(3000), cl::Hidden, cl::desc("The maximum number of candidate instruction pairs per group"))
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:850
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static cl::opt< bool > UseChainDepthWithTI("bb-vectorize-use-chain-depth", cl::init(false), cl::Hidden, cl::desc("Use the chain depth requirement with" " target information"))
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
LLVMContext & Context
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const
This function determines if the specified instruction executes the same operation as the current one...
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
This is the interface for a simple mod/ref and alias analysis over globals.
const_iterator end() const
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
const Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
Implements a dense probed hash-table based set.
Definition: DenseSet.h:221
The main scalar evolution driver.
This class represents a function call, abstracting a target machine&#39;s calling convention.
void initializeBBVectorizePass(PassRegistry &)
This file contains the declarations for metadata subclasses.
static bool runOnBasicBlock(BasicBlock &BB)
static cl::opt< bool > NoMemOpBoost("bb-vectorize-no-mem-op-boost", cl::init(false), cl::Hidden, cl::desc("Don't boost the chain-depth contribution of loads and stores"))
static cl::opt< bool > DebugCycleCheck("bb-vectorize-debug-cycle-check", cl::init(false), cl::Hidden, cl::desc("When debugging is enabled, output information on the" " cycle-checking process"))
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:617
static uint64_t round(uint64_t Acc, uint64_t Input)
Definition: xxhash.cpp:57
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
static cl::opt< bool > IgnoreTargetInfo("bb-vectorize-ignore-target-info", cl::init(false), cl::Hidden, cl::desc("Ignore target information"))
This instruction constructs a fixed permutation of two input vectors.
bool VectorizeMath
Vectorize floating-point math intrinsics.
Definition: Vectorize.h:48
STATISTIC(NumFunctions, "Total number of functions")
bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
Definition: Local.cpp:504
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
An instruction for reading from memory.
Definition: Instructions.h:169
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:221
iv Induction Variable Users
Definition: IVUsers.cpp:51
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition: Type.h:159
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:33
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:272
op_iterator op_begin()
Definition: User.h:214
static cl::opt< unsigned > VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden, cl::desc("The size of the native vector registers"))
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:176
AnalysisUsage & addRequired()
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
This is the interface for a SCEV-based alias analysis.
static cl::opt< bool > AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden, cl::desc("Only generate aligned loads and stores"))
This class represents the LLVM &#39;select&#39; instruction.
Type * getPointerElementType() const
Definition: Type.h:367
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
unsigned MaxCandPairsForCycleCheck
The maximum number of candidate pairs with which to use a full cycle check.
Definition: Vectorize.h:82
unsigned getNumArgOperands() const
Return the number of call arguments.
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:560
int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, const Instruction *I=nullptr) const
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
Check for equivalence ignoring load/store alignment.
Definition: Instruction.h:536
uint64_t getNumElements() const
Definition: DerivedTypes.h:359
static cl::opt< unsigned > MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden, cl::desc("The maximum number of pairable instructions per group"))
static const char bb_vectorize_name[]
static cl::opt< unsigned > MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200), cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use" " a full cycle check"))
Instruction * clone() const
Create a copy of &#39;this&#39; instruction that is identical in all ways except the following: ...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:406
Class to represent function types.
Definition: DerivedTypes.h:103
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:84
#define F(x, y, z)
Definition: MD5.cpp:55
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const
Check for equivalence treating a type and a vector of that type as equivalent.
Definition: Instruction.h:539
static cl::opt< bool > NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden, cl::desc("Don't try to vectorize floating-point math intrinsics"))
#define T
static cl::opt< bool > NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden, cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"))
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:608
void andIRFlags(const Value *V)
Logical &#39;and&#39; of any supported wrapping, exact, and fast-math flags of V and this instruction...
bool isVarArg() const
Definition: DerivedTypes.h:123
This class represents a no-op cast from one type to another.
static std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:160
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:138
int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, ArrayRef< Value *> Args, FastMathFlags FMF, unsigned VF=1) const
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:121
An instruction for storing to memory.
Definition: Instructions.h:307
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:203
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:428
int getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index=-1) const
Reverse the order of the vector.
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:290
bool VectorizePointers
Vectorize pointer values.
Definition: Vectorize.h:42
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:115
int getAddressComputationCost(Type *Ty, ScalarEvolution *SE=nullptr, const SCEV *Ptr=nullptr) const
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:975
bool VectorizeCmp
Vectorize comparison instructions.
Definition: Vectorize.h:60
Value * getOperand(unsigned i) const
Definition: User.h:154
unsigned MaxIter
The maximum number of pairing iterations.
Definition: Vectorize.h:94
bool VectorizeMemOps
Vectorize loads and stores.
Definition: Vectorize.h:66
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return &#39;this&#39;.
Definition: Type.h:295
static cl::opt< bool > FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden, cl::desc("Use a fast instruction dependency analysis"))
ExtractSubvector Index indicates start offset.
static cl::opt< bool > NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden, cl::desc("Don't try to vectorize comparison instructions"))
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: Type.h:141
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:831
#define P(N)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:404
This instruction inserts a single (scalar) element into a VectorType value.
Wrapper pass for TargetTransformInfo.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:200
bool AlignedOnly
Only generate aligned loads and stores.
Definition: Vectorize.h:69
static cl::opt< bool > NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden, cl::desc("Don't try to vectorize floating-point values"))
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
Definition: Instruction.cpp:75
bool hasName() const
Definition: Value.h:251
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
static cl::opt< unsigned > SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden, cl::desc("The maximum search distance for instruction pairs"))
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:50
static cl::opt< bool > PrintAfterEveryPair("bb-vectorize-debug-print-after-every-pair", cl::init(false), cl::Hidden, cl::desc("When debugging is enabled, dump the basic block after" " every pair is fused"))
unsigned getNumberOfParts(Type *Tp) const
This is an important base class in LLVM.
Definition: Constant.h:42
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
bool SplatBreaksChain
Replicating one element to a pair breaks the chain.
Definition: Vectorize.h:85
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:36
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:215
#define H(x, y, z)
Definition: MD5.cpp:57
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
#define A
Definition: LargeTest.cpp:12
static cl::opt< bool > NoBitManipulation("bb-vectorize-no-bitmanip", cl::init(false), cl::Hidden, cl::desc("Don't try to vectorize BitManipulation intrinsics"))
size_type size() const
Definition: SmallSet.h:60
unsigned getPrefTypeAlignment(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
Definition: DataLayout.cpp:690
int getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy=nullptr, const Instruction *I=nullptr) const
Represent the analysis usage information of a pass.
op_iterator op_end()
Definition: User.h:216
bool isBinaryOp() const
Definition: Instruction.h:125
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:297
Value * getPointerOperand()
Definition: Instructions.h:276
unsigned SearchLimit
The maximum search distance for instruction pairs.
Definition: Vectorize.h:78
bool isX86_MMXTy() const
Return true if this is X86 MMX.
Definition: Type.h:182
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again...
Definition: DenseMap.h:91
static cl::opt< bool > NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden, cl::desc("Don't try to vectorize casting (conversion) operations"))
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:81
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1304
iterator erase(const_iterator CI)
Definition: SmallVector.h:446
static cl::opt< unsigned > MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden, cl::desc("The maximum number of pairing iterations"))
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE maxNum semantics.
Definition: APFloat.h:1223
unsigned first
BasicBlockPass class - This class is used to implement most local optimizations.
Definition: Pass.h:335
unsigned MaxPairs
The maximum number of candidate instruction pairs per group.
Definition: Vectorize.h:91
const unsigned MaxDepth
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
Definition: User.h:176
#define E
Definition: LargeTest.cpp:27
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
Legacy wrapper pass to provide the SCEVAAResult object.
bool VectorizeFloats
Vectorize floating-point values.
Definition: Vectorize.h:39
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
iterator end()
Definition: BasicBlock.h:254
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:130
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
static cl::opt< bool > SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden, cl::desc("Replicating one element to a pair breaks the chain"))
bool vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C=VectorizeConfig())
Vectorize the BasicBlock.
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:48
const size_t N
static cl::opt< bool > NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden, cl::desc("Don't try to vectorize loads and stores"))
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:382
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:544
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:278
static cl::opt< bool > NoPointers("bb-vectorize-no-pointers", cl::init(true), cl::Hidden, cl::desc("Don't try to vectorize pointer values"))
static cl::opt< bool > DebugCandidateSelection("bb-vectorize-debug-candidate-selection", cl::init(false), cl::Hidden, cl::desc("When debugging is enabled, output information on the" " candidate-selection process"))
void add(Value *Ptr, uint64_t Size, const AAMDNodes &AAInfo)
These methods are used to add different types of instructions to the alias sets.
static const Function * getCalledFunction(const Value *V, bool LookThroughBitCast, bool &IsNoBuiltin)
bool FastDep
Use a fast instruction dependency analysis.
Definition: Vectorize.h:103
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition: Function.h:167
Vectorize configuration.
Definition: Vectorize.h:25
void setOperand(unsigned i, Value *Val)
Definition: User.h:159
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
unsigned getVectorNumElements() const
Definition: DerivedTypes.h:462
Class to represent vector types.
Definition: DerivedTypes.h:393
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:57
static cl::opt< bool > NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden, cl::desc("Don't try to vectorize getelementptr instructions"))
typename SuperClass::iterator iterator
Definition: SmallVector.h:325
iterator_range< user_iterator > users()
Definition: Value.h:395
static cl::opt< bool > NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden, cl::desc("Don't try to vectorize boolean (i1) values"))
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:91
bool VectorizeCasts
Vectorize casting (conversion) operations.
Definition: Vectorize.h:45
#define BBV_NAME
Definition: BBVectorize.cpp:17
BasicBlockPass * createBBVectorizePass(const VectorizeConfig &C=VectorizeConfig())
bool VectorizeBools
Vectorize boolean values.
Definition: Vectorize.h:33
bool isX86_FP80Ty() const
Return true if this is x86 long double.
Definition: Type.h:153
void removeFromParent()
This method unlinks &#39;this&#39; from the containing basic block, but does not delete it.
Definition: Instruction.cpp:65
static cl::opt< unsigned > ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden, cl::desc("The required chain depth for vectorization"))
unsigned ReqChainDepth
The required chain depth for vectorization.
Definition: Vectorize.h:75
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
unsigned MaxInsts
The maximum number of pairable instructions per group.
Definition: Vectorize.h:88
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:232
This class represents an analyzed expression in the program.
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
static cl::opt< HelpPrinterWrapper, true, parser< bool > > HOp("help", cl::desc("Display available options (-help-hidden for more)"), cl::location(WrappedNormalPrinter), cl::ValueDisallowed, cl::cat(GenericCategory), cl::sub(*AllSubCommands))
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
static cl::opt< bool > NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden, cl::desc("Don't try to vectorize integer values"))
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:218
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
Definition: Instruction.cpp:81
bool NoMemOpBoost
Don&#39;t boost the chain-depth contribution of loads and stores.
Definition: Vectorize.h:100
#define I(x, y, z)
Definition: MD5.cpp:58
user_iterator_impl< User > user_iterator
Definition: Value.h:364
bool VectorizeGEP
Vectorize getelementptr instructions.
Definition: Vectorize.h:63
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition: APFloat.h:1198
bool mayReadFromMemory() const
Return true if this instruction may read memory.
iterator find(const_arg_type_t< ValueT > V)
Definition: DenseSet.h:165
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
This instruction extracts a single (scalar) element from a VectorType value.
int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index=0, Type *SubTp=nullptr) const
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:91
int getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info=OK_AnyValue, OperandValueKind Opd2Info=OK_AnyValue, OperandValueProperties Opd1PropInfo=OP_None, OperandValueProperties Opd2PropInfo=OP_None, ArrayRef< const Value *> Args=ArrayRef< const Value *>()) const
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:126
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:353
const_iterator begin() const
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition: Value.h:598
VectorizeConfig()
Initialize the VectorizeConfig from command line options.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:166
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:185
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:282
iterator_range< op_iterator > arg_operands()
Iteration adapter for range-for loops.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Definition: Value.h:371
aarch64 promote const
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition: Type.h:241
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:115
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:545
LLVM Value Representation.
Definition: Value.h:73
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:388
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:593
bool VectorizeInts
Vectorize integer values.
Definition: Vectorize.h:36
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:81
Broadcast element 0 to all other elements.
static cl::opt< bool > Pow2LenOnly("bb-vectorize-pow2-len-only", cl::init(false), cl::Hidden, cl::desc("Don't try to form non-2^n-length vectors"))
#define DEBUG(X)
Definition: Debug.h:118
int getCFInstrCost(unsigned Opcode) const
bool VectorizeBitManipulations
Vectorize bit intrinsics.
Definition: Vectorize.h:51
unsigned getOperandsScalarizationOverhead(ArrayRef< const Value *> Args, unsigned VF) const
Convenience struct for specifying and reasoning about fast-math flags.
Definition: Operator.h:160
OperandValueKind
Additional information about an operand&#39;s possible values.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:244
This pass exposes codegen information to IR-level passes.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
bool VectorizeSelect
Vectorize select instructions.
Definition: Vectorize.h:57
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:157
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment, unsigned AddressSpace, const Instruction *I=nullptr) const
Value * getPointerOperand()
Definition: Instructions.h:400
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs)
Combine the metadata of two instructions so that K can replace J.
Definition: Local.cpp:1702
static Constant * get(ArrayRef< Constant *> V)
Definition: Constants.cpp:968
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE minNum semantics.
Definition: APFloat.h:1212
static cl::opt< bool > NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden, cl::desc("Don't try to vectorize select instructions"))
#define T1
static cl::opt< bool > DebugPairSelection("bb-vectorize-debug-pair-selection", cl::init(false), cl::Hidden, cl::desc("When debugging is enabled, output information on the" " pair-selection process"))
unsigned VectorBits
The size of the native vector registers.
Definition: Vectorize.h:30
const BasicBlock * getParent() const
Definition: Instruction.h:66
This class represents a constant integer value.