LLVM  5.0.0
TargetTransformInfoImpl.h
Go to the documentation of this file.
1 //===- TargetTransformInfoImpl.h --------------------------------*- C++ -*-===//
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 /// \file
10 /// This file provides helpers for the implementation of
11 /// a TargetTransformInfo-conforming class.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H
16 #define LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H
17 
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Function.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/IR/Type.h"
27 
28 namespace llvm {
29 
30 /// \brief Base class for use as a mix-in that aids implementing
31 /// a TargetTransformInfo-compatible class.
33 protected:
35 
36  const DataLayout &DL;
37 
38  explicit TargetTransformInfoImplBase(const DataLayout &DL) : DL(DL) {}
39 
40 public:
41  // Provide value semantics. MSVC requires that we spell all of these out.
43  : DL(Arg.DL) {}
45 
46  const DataLayout &getDataLayout() const { return DL; }
47 
48  unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
49  switch (Opcode) {
50  default:
51  // By default, just classify everything as 'basic'.
52  return TTI::TCC_Basic;
53 
54  case Instruction::GetElementPtr:
55  llvm_unreachable("Use getGEPCost for GEP operations!");
56 
57  case Instruction::BitCast:
58  assert(OpTy && "Cast instructions must provide the operand type");
59  if (Ty == OpTy || (Ty->isPointerTy() && OpTy->isPointerTy()))
60  // Identity and pointer-to-pointer casts are free.
61  return TTI::TCC_Free;
62 
63  // Otherwise, the default basic cost is used.
64  return TTI::TCC_Basic;
65 
66  case Instruction::FDiv:
67  case Instruction::FRem:
68  case Instruction::SDiv:
69  case Instruction::SRem:
70  case Instruction::UDiv:
71  case Instruction::URem:
72  return TTI::TCC_Expensive;
73 
74  case Instruction::IntToPtr: {
75  // An inttoptr cast is free so long as the input is a legal integer type
76  // which doesn't contain values outside the range of a pointer.
77  unsigned OpSize = OpTy->getScalarSizeInBits();
78  if (DL.isLegalInteger(OpSize) &&
79  OpSize <= DL.getPointerTypeSizeInBits(Ty))
80  return TTI::TCC_Free;
81 
82  // Otherwise it's not a no-op.
83  return TTI::TCC_Basic;
84  }
85  case Instruction::PtrToInt: {
86  // A ptrtoint cast is free so long as the result is large enough to store
87  // the pointer, and a legal integer type.
88  unsigned DestSize = Ty->getScalarSizeInBits();
89  if (DL.isLegalInteger(DestSize) &&
90  DestSize >= DL.getPointerTypeSizeInBits(OpTy))
91  return TTI::TCC_Free;
92 
93  // Otherwise it's not a no-op.
94  return TTI::TCC_Basic;
95  }
96  case Instruction::Trunc:
97  // trunc to a native type is free (assuming the target has compare and
98  // shift-right of the same width).
100  return TTI::TCC_Free;
101 
102  return TTI::TCC_Basic;
103  }
104  }
105 
106  int getGEPCost(Type *PointeeType, const Value *Ptr,
107  ArrayRef<const Value *> Operands) {
108  // In the basic model, we just assume that all-constant GEPs will be folded
109  // into their uses via addressing modes.
110  for (unsigned Idx = 0, Size = Operands.size(); Idx != Size; ++Idx)
111  if (!isa<Constant>(Operands[Idx]))
112  return TTI::TCC_Basic;
113 
114  return TTI::TCC_Free;
115  }
116 
118  unsigned &JTSize) {
119  JTSize = 0;
120  return SI.getNumCases();
121  }
122 
123  int getExtCost(const Instruction *I, const Value *Src) {
124  return TTI::TCC_Basic;
125  }
126 
127  unsigned getCallCost(FunctionType *FTy, int NumArgs) {
128  assert(FTy && "FunctionType must be provided to this routine.");
129 
130  // The target-independent implementation just measures the size of the
131  // function by approximating that each argument will take on average one
132  // instruction to prepare.
133 
134  if (NumArgs < 0)
135  // Set the argument number to the number of explicit arguments in the
136  // function.
137  NumArgs = FTy->getNumParams();
138 
139  return TTI::TCC_Basic * (NumArgs + 1);
140  }
141 
142  unsigned getInliningThresholdMultiplier() { return 1; }
143 
144  unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
145  ArrayRef<Type *> ParamTys) {
146  switch (IID) {
147  default:
148  // Intrinsics rarely (if ever) have normal argument setup constraints.
149  // Model them as having a basic instruction cost.
150  // FIXME: This is wrong for libc intrinsics.
151  return TTI::TCC_Basic;
152 
153  case Intrinsic::annotation:
154  case Intrinsic::assume:
155  case Intrinsic::dbg_declare:
156  case Intrinsic::dbg_value:
157  case Intrinsic::invariant_start:
158  case Intrinsic::invariant_end:
159  case Intrinsic::lifetime_start:
160  case Intrinsic::lifetime_end:
161  case Intrinsic::objectsize:
162  case Intrinsic::ptr_annotation:
163  case Intrinsic::var_annotation:
164  case Intrinsic::experimental_gc_result:
165  case Intrinsic::experimental_gc_relocate:
166  case Intrinsic::coro_alloc:
167  case Intrinsic::coro_begin:
168  case Intrinsic::coro_free:
169  case Intrinsic::coro_end:
170  case Intrinsic::coro_frame:
171  case Intrinsic::coro_size:
172  case Intrinsic::coro_suspend:
173  case Intrinsic::coro_param:
174  case Intrinsic::coro_subfn_addr:
175  // These intrinsics don't actually represent code after lowering.
176  return TTI::TCC_Free;
177  }
178  }
179 
180  bool hasBranchDivergence() { return false; }
181 
182  bool isSourceOfDivergence(const Value *V) { return false; }
183 
184  bool isAlwaysUniform(const Value *V) { return false; }
185 
186  unsigned getFlatAddressSpace () {
187  return -1;
188  }
189 
190  bool isLoweredToCall(const Function *F) {
191  // FIXME: These should almost certainly not be handled here, and instead
192  // handled with the help of TLI or the target itself. This was largely
193  // ported from existing analysis heuristics here so that such refactorings
194  // can take place in the future.
195 
196  if (F->isIntrinsic())
197  return false;
198 
199  if (F->hasLocalLinkage() || !F->hasName())
200  return true;
201 
202  StringRef Name = F->getName();
203 
204  // These will all likely lower to a single selection DAG node.
205  if (Name == "copysign" || Name == "copysignf" || Name == "copysignl" ||
206  Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" ||
207  Name == "fmin" || Name == "fminf" || Name == "fminl" ||
208  Name == "fmax" || Name == "fmaxf" || Name == "fmaxl" ||
209  Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" ||
210  Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl")
211  return false;
212 
213  // These are all likely to be optimized into something smaller.
214  if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" ||
215  Name == "exp2l" || Name == "exp2f" || Name == "floor" ||
216  Name == "floorf" || Name == "ceil" || Name == "round" ||
217  Name == "ffs" || Name == "ffsl" || Name == "abs" || Name == "labs" ||
218  Name == "llabs")
219  return false;
220 
221  return true;
222  }
223 
226 
227  bool isLegalAddImmediate(int64_t Imm) { return false; }
228 
229  bool isLegalICmpImmediate(int64_t Imm) { return false; }
230 
231  bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
232  bool HasBaseReg, int64_t Scale,
233  unsigned AddrSpace) {
234  // Guess that only reg and reg+reg addressing is allowed. This heuristic is
235  // taken from the implementation of LSR.
236  return !BaseGV && BaseOffset == 0 && (Scale == 0 || Scale == 1);
237  }
238 
240  return std::tie(C1.NumRegs, C1.AddRecCost, C1.NumIVMuls, C1.NumBaseAdds,
241  C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
242  std::tie(C2.NumRegs, C2.AddRecCost, C2.NumIVMuls, C2.NumBaseAdds,
243  C2.ScaleCost, C2.ImmCost, C2.SetupCost);
244  }
245 
246  bool isLegalMaskedStore(Type *DataType) { return false; }
247 
248  bool isLegalMaskedLoad(Type *DataType) { return false; }
249 
250  bool isLegalMaskedScatter(Type *DataType) { return false; }
251 
252  bool isLegalMaskedGather(Type *DataType) { return false; }
253 
254  bool prefersVectorizedAddressing() { return true; }
255 
256  int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
257  bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
258  // Guess that all legal addressing mode are free.
259  if (isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
260  Scale, AddrSpace))
261  return 0;
262  return -1;
263  }
264 
265  bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) { return true; }
266 
267  bool isTruncateFree(Type *Ty1, Type *Ty2) { return false; }
268 
269  bool isProfitableToHoist(Instruction *I) { return true; }
270 
271  bool isTypeLegal(Type *Ty) { return false; }
272 
273  unsigned getJumpBufAlignment() { return 0; }
274 
275  unsigned getJumpBufSize() { return 0; }
276 
277  bool shouldBuildLookupTables() { return true; }
279 
280  unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
281  return 0;
282  }
283 
285  unsigned VF) { return 0; }
286 
288 
289  bool enableAggressiveInterleaving(bool LoopHasReductions) { return false; }
290 
291  bool expandMemCmp(Instruction *I, unsigned &MaxLoadSize) { return false; }
292 
293  bool enableInterleavedAccessVectorization() { return false; }
294 
295  bool isFPVectorizationPotentiallyUnsafe() { return false; }
296 
298  unsigned BitWidth,
299  unsigned AddressSpace,
300  unsigned Alignment,
301  bool *Fast) { return false; }
302 
303  TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) {
304  return TTI::PSK_Software;
305  }
306 
307  bool haveFastSqrt(Type *Ty) { return false; }
308 
310 
311  int getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
312  Type *Ty) {
313  return 0;
314  }
315 
316  unsigned getIntImmCost(const APInt &Imm, Type *Ty) { return TTI::TCC_Basic; }
317 
318  unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
319  Type *Ty) {
320  return TTI::TCC_Free;
321  }
322 
323  unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
324  Type *Ty) {
325  return TTI::TCC_Free;
326  }
327 
328  unsigned getNumberOfRegisters(bool Vector) { return 8; }
329 
330  unsigned getRegisterBitWidth(bool Vector) const { return 32; }
331 
332  unsigned getMinVectorRegisterBitWidth() { return 128; }
333 
334  bool
336  bool &AllowPromotionWithoutCommonHeader) {
337  AllowPromotionWithoutCommonHeader = false;
338  return false;
339  }
340 
341  unsigned getCacheLineSize() { return 0; }
342 
343  unsigned getPrefetchDistance() { return 0; }
344 
345  unsigned getMinPrefetchStride() { return 1; }
346 
347  unsigned getMaxPrefetchIterationsAhead() { return UINT_MAX; }
348 
349  unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
350 
351  unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
352  TTI::OperandValueKind Opd1Info,
353  TTI::OperandValueKind Opd2Info,
354  TTI::OperandValueProperties Opd1PropInfo,
355  TTI::OperandValueProperties Opd2PropInfo,
357  return 1;
358  }
359 
360  unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index,
361  Type *SubTp) {
362  return 1;
363  }
364 
365  unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
366  const Instruction *I) { return 1; }
367 
368  unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
369  VectorType *VecTy, unsigned Index) {
370  return 1;
371  }
372 
373  unsigned getCFInstrCost(unsigned Opcode) { return 1; }
374 
375  unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
376  const Instruction *I) {
377  return 1;
378  }
379 
380  unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
381  return 1;
382  }
383 
384  unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
385  unsigned AddressSpace, const Instruction *I) {
386  return 1;
387  }
388 
389  unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
390  unsigned AddressSpace) {
391  return 1;
392  }
393 
394  unsigned getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr,
395  bool VariableMask,
396  unsigned Alignment) {
397  return 1;
398  }
399 
400  unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
401  unsigned Factor,
402  ArrayRef<unsigned> Indices,
403  unsigned Alignment,
404  unsigned AddressSpace) {
405  return 1;
406  }
407 
410  unsigned ScalarizationCostPassed) {
411  return 1;
412  }
414  ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) {
415  return 1;
416  }
417 
418  unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
419  return 1;
420  }
421 
422  unsigned getNumberOfParts(Type *Tp) { return 0; }
423 
425  const SCEV *) {
426  return 0;
427  }
428 
429  unsigned getReductionCost(unsigned, Type *, bool) { return 1; }
430 
431  unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { return 0; }
432 
434  return false;
435  }
436 
438  // Note for overrides: You must ensure for all element unordered-atomic
439  // memory intrinsics that all power-of-2 element sizes up to, and
440  // including, the return value of this method have a corresponding
441  // runtime lib call. These runtime lib call definitions can be found
442  // in RuntimeLibcalls.h
443  return 0;
444  }
445 
447  Type *ExpectedType) {
448  return nullptr;
449  }
450 
452  unsigned SrcAlign, unsigned DestAlign) const {
453  return Type::getInt8Ty(Context);
454  }
455 
458  unsigned RemainingBytes,
459  unsigned SrcAlign,
460  unsigned DestAlign) const {
461  for (unsigned i = 0; i != RemainingBytes; ++i)
462  OpsOut.push_back(Type::getInt8Ty(Context));
463  }
464 
465  bool areInlineCompatible(const Function *Caller,
466  const Function *Callee) const {
467  return (Caller->getFnAttribute("target-cpu") ==
468  Callee->getFnAttribute("target-cpu")) &&
469  (Caller->getFnAttribute("target-features") ==
470  Callee->getFnAttribute("target-features"));
471  }
472 
473  unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { return 128; }
474 
475  bool isLegalToVectorizeLoad(LoadInst *LI) const { return true; }
476 
477  bool isLegalToVectorizeStore(StoreInst *SI) const { return true; }
478 
479  bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
480  unsigned Alignment,
481  unsigned AddrSpace) const {
482  return true;
483  }
484 
485  bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
486  unsigned Alignment,
487  unsigned AddrSpace) const {
488  return true;
489  }
490 
491  unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
492  unsigned ChainSizeInBytes,
493  VectorType *VecTy) const {
494  return VF;
495  }
496 
497  unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
498  unsigned ChainSizeInBytes,
499  VectorType *VecTy) const {
500  return VF;
501  }
502 
503  bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
504  TTI::ReductionFlags Flags) const {
505  return false;
506  }
507 
508  bool shouldExpandReduction(const IntrinsicInst *II) const {
509  return true;
510  }
511 
512 protected:
513  // Obtain the minimum required size to hold the value (without the sign)
514  // In case of a vector it returns the min required size for one element.
515  unsigned minRequiredElementSize(const Value* Val, bool &isSigned) {
516  if (isa<ConstantDataVector>(Val) || isa<ConstantVector>(Val)) {
517  const auto* VectorValue = cast<Constant>(Val);
518 
519  // In case of a vector need to pick the max between the min
520  // required size for each element
521  auto *VT = cast<VectorType>(Val->getType());
522 
523  // Assume unsigned elements
524  isSigned = false;
525 
526  // The max required size is the total vector width divided by num
527  // of elements in the vector
528  unsigned MaxRequiredSize = VT->getBitWidth() / VT->getNumElements();
529 
530  unsigned MinRequiredSize = 0;
531  for(unsigned i = 0, e = VT->getNumElements(); i < e; ++i) {
532  if (auto* IntElement =
533  dyn_cast<ConstantInt>(VectorValue->getAggregateElement(i))) {
534  bool signedElement = IntElement->getValue().isNegative();
535  // Get the element min required size.
536  unsigned ElementMinRequiredSize =
537  IntElement->getValue().getMinSignedBits() - 1;
538  // In case one element is signed then all the vector is signed.
539  isSigned |= signedElement;
540  // Save the max required bit size between all the elements.
541  MinRequiredSize = std::max(MinRequiredSize, ElementMinRequiredSize);
542  }
543  else {
544  // not an int constant element
545  return MaxRequiredSize;
546  }
547  }
548  return MinRequiredSize;
549  }
550 
551  if (const auto* CI = dyn_cast<ConstantInt>(Val)) {
552  isSigned = CI->getValue().isNegative();
553  return CI->getValue().getMinSignedBits() - 1;
554  }
555 
556  if (const auto* Cast = dyn_cast<SExtInst>(Val)) {
557  isSigned = true;
558  return Cast->getSrcTy()->getScalarSizeInBits() - 1;
559  }
560 
561  if (const auto* Cast = dyn_cast<ZExtInst>(Val)) {
562  isSigned = false;
563  return Cast->getSrcTy()->getScalarSizeInBits();
564  }
565 
566  isSigned = false;
567  return Val->getType()->getScalarSizeInBits();
568  }
569 
570  bool isStridedAccess(const SCEV *Ptr) {
571  return Ptr && isa<SCEVAddRecExpr>(Ptr);
572  }
573 
575  const SCEV *Ptr) {
576  if (!isStridedAccess(Ptr))
577  return nullptr;
578  const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ptr);
579  return dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*SE));
580  }
581 
583  int64_t MergeDistance) {
584  const SCEVConstant *Step = getConstantStrideStep(SE, Ptr);
585  if (!Step)
586  return false;
587  APInt StrideVal = Step->getAPInt();
588  if (StrideVal.getBitWidth() > 64)
589  return false;
590  // FIXME: need to take absolute value for negtive stride case
591  return StrideVal.getSExtValue() < MergeDistance;
592  }
593 };
594 
595 /// \brief CRTP base class for use as a mix-in that aids implementing
596 /// a TargetTransformInfo-compatible class.
597 template <typename T>
599 private:
601 
602 protected:
604 
605 public:
606  using BaseT::getCallCost;
607 
608  unsigned getCallCost(const Function *F, int NumArgs) {
609  assert(F && "A concrete function must be provided to this routine.");
610 
611  if (NumArgs < 0)
612  // Set the argument number to the number of explicit arguments in the
613  // function.
614  NumArgs = F->arg_size();
615 
616  if (Intrinsic::ID IID = F->getIntrinsicID()) {
617  FunctionType *FTy = F->getFunctionType();
618  SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end());
619  return static_cast<T *>(this)
620  ->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys);
621  }
622 
623  if (!static_cast<T *>(this)->isLoweredToCall(F))
624  return TTI::TCC_Basic; // Give a basic cost if it will be lowered
625  // directly.
626 
627  return static_cast<T *>(this)->getCallCost(F->getFunctionType(), NumArgs);
628  }
629 
630  unsigned getCallCost(const Function *F, ArrayRef<const Value *> Arguments) {
631  // Simply delegate to generic handling of the call.
632  // FIXME: We should use instsimplify or something else to catch calls which
633  // will constant fold with these arguments.
634  return static_cast<T *>(this)->getCallCost(F, Arguments.size());
635  }
636 
637  using BaseT::getGEPCost;
638 
639  int getGEPCost(Type *PointeeType, const Value *Ptr,
640  ArrayRef<const Value *> Operands) {
641  const GlobalValue *BaseGV = nullptr;
642  if (Ptr != nullptr) {
643  // TODO: will remove this when pointers have an opaque type.
645  PointeeType &&
646  "explicit pointee type doesn't match operand's pointee type");
647  BaseGV = dyn_cast<GlobalValue>(Ptr->stripPointerCasts());
648  }
649  bool HasBaseReg = (BaseGV == nullptr);
650  int64_t BaseOffset = 0;
651  int64_t Scale = 0;
652 
653  auto GTI = gep_type_begin(PointeeType, Operands);
654  Type *TargetType;
655  for (auto I = Operands.begin(); I != Operands.end(); ++I, ++GTI) {
656  TargetType = GTI.getIndexedType();
657  // We assume that the cost of Scalar GEP with constant index and the
658  // cost of Vector GEP with splat constant index are the same.
659  const ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
660  if (!ConstIdx)
661  if (auto Splat = getSplatValue(*I))
662  ConstIdx = dyn_cast<ConstantInt>(Splat);
663  if (StructType *STy = GTI.getStructTypeOrNull()) {
664  // For structures the index is always splat or scalar constant
665  assert(ConstIdx && "Unexpected GEP index");
666  uint64_t Field = ConstIdx->getZExtValue();
667  BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field);
668  } else {
669  int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType());
670  if (ConstIdx)
671  BaseOffset += ConstIdx->getSExtValue() * ElementSize;
672  else {
673  // Needs scale register.
674  if (Scale != 0)
675  // No addressing mode takes two scale registers.
676  return TTI::TCC_Basic;
677  Scale = ElementSize;
678  }
679  }
680  }
681 
682  // Assumes the address space is 0 when Ptr is nullptr.
683  unsigned AS =
684  (Ptr == nullptr ? 0 : Ptr->getType()->getPointerAddressSpace());
685  if (static_cast<T *>(this)->isLegalAddressingMode(
686  TargetType, const_cast<GlobalValue *>(BaseGV), BaseOffset,
687  HasBaseReg, Scale, AS))
688  return TTI::TCC_Free;
689  return TTI::TCC_Basic;
690  }
691 
693 
694  unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
695  ArrayRef<const Value *> Arguments) {
696  // Delegate to the generic intrinsic handling code. This mostly provides an
697  // opportunity for targets to (for example) special case the cost of
698  // certain intrinsics based on constants used as arguments.
699  SmallVector<Type *, 8> ParamTys;
700  ParamTys.reserve(Arguments.size());
701  for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
702  ParamTys.push_back(Arguments[Idx]->getType());
703  return static_cast<T *>(this)->getIntrinsicCost(IID, RetTy, ParamTys);
704  }
705 
706  unsigned getUserCost(const User *U, ArrayRef<const Value *> Operands) {
707  if (isa<PHINode>(U))
708  return TTI::TCC_Free; // Model all PHI nodes as free.
709 
710  if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
711  return static_cast<T *>(this)->getGEPCost(GEP->getSourceElementType(),
712  GEP->getPointerOperand(),
713  Operands.drop_front());
714  }
715 
716  if (auto CS = ImmutableCallSite(U)) {
717  const Function *F = CS.getCalledFunction();
718  if (!F) {
719  // Just use the called value type.
720  Type *FTy = CS.getCalledValue()->getType()->getPointerElementType();
721  return static_cast<T *>(this)
722  ->getCallCost(cast<FunctionType>(FTy), CS.arg_size());
723  }
724 
725  SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end());
726  return static_cast<T *>(this)->getCallCost(F, Arguments);
727  }
728 
729  if (const CastInst *CI = dyn_cast<CastInst>(U)) {
730  // Result of a cmp instruction is often extended (to be used by other
731  // cmp instructions, logical or return instructions). These are usually
732  // nop on most sane targets.
733  if (isa<CmpInst>(CI->getOperand(0)))
734  return TTI::TCC_Free;
735  if (isa<SExtInst>(CI) || isa<ZExtInst>(CI) || isa<FPExtInst>(CI))
736  return static_cast<T *>(this)->getExtCost(CI, Operands.back());
737  }
738 
739  return static_cast<T *>(this)->getOperationCost(
740  Operator::getOpcode(U), U->getType(),
741  U->getNumOperands() == 1 ? U->getOperand(0)->getType() : nullptr);
742  }
743 };
744 }
745 
746 #endif
Base class for use as a mix-in that aids implementing a TargetTransformInfo-compatible class...
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
bool isConstantStridedAccessLessThan(ScalarEvolution *SE, const SCEV *Ptr, int64_t MergeDistance)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
size_t arg_size() const
Definition: Function.h:622
LLVMContext & Context
unsigned getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr, bool VariableMask, unsigned Alignment)
bool hasName() const
Definition: Value.h:251
unsigned minRequiredElementSize(const Value *Val, bool &isSigned)
void getUnrollingPreferences(Loop *, ScalarEvolution &, TTI::UnrollingPreferences &)
unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index)
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:527
const Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
unsigned getNumOperands() const
Definition: User.h:176
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
Definition: DataLayout.cpp:612
unsigned getCallCost(const Function *F, ArrayRef< const Value * > Arguments)
The main scalar evolution driver.
iterator end() const
Definition: ArrayRef.h:138
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition: Function.h:172
unsigned getCallCost(const Function *F, int NumArgs)
unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy)
bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset)
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:301
bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace)
unsigned getCostOfKeepingLiveOverCall(ArrayRef< Type * > Tys)
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:262
unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, const Instruction *I)
bool useReductionIntrinsic(unsigned Opcode, Type *Ty, TTI::ReductionFlags Flags) const
An instruction for reading from memory.
Definition: Instructions.h:164
Hexagon Common GEP
unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment, unsigned AddressSpace, const Instruction *I)
void reserve(size_type N)
Definition: SmallVector.h:377
unsigned getIntImmCost(const APInt &Imm, Type *Ty)
int getExtCost(const Instruction *I, const Value *Src)
Type * getPointerElementType() const
Definition: Type.h:373
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:218
void getMemcpyLoopResidualLoweringType(SmallVectorImpl< Type * > &OpsOut, LLVMContext &Context, unsigned RemainingBytes, unsigned SrcAlign, unsigned DestAlign) const
bool expandMemCmp(Instruction *I, unsigned &MaxLoadSize)
CRTP base class for use as a mix-in that aids implementing a TargetTransformInfo-compatible class...
bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info)
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:562
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:560
Class to represent struct types.
Definition: DerivedTypes.h:201
param_iterator param_end() const
Definition: DerivedTypes.h:129
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
int getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands)
unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::OperandValueKind Opd1Info, TTI::OperandValueKind Opd2Info, TTI::OperandValueProperties Opd1PropInfo, TTI::OperandValueProperties Opd2PropInfo, ArrayRef< const Value * > Args)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:149
bool isTruncateFree(Type *Ty1, Type *Ty2)
bool enableAggressiveInterleaving(bool LoopHasReductions)
bool shouldExpandReduction(const IntrinsicInst *II) const
Class to represent function types.
Definition: DerivedTypes.h:103
#define F(x, y, z)
Definition: MD5.cpp:55
This node represents a polynomial recurrence on the trip count of the specified loop.
PopcntSupportKind
Flags indicating the kind of support for population count.
unsigned getOperandsScalarizationOverhead(ArrayRef< const Value * > Args, unsigned VF)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
An instruction for storing to memory.
Definition: Instructions.h:306
bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, unsigned Alignment, unsigned AddrSpace) const
unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy, unsigned Index)
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
const char * Name
unsigned getUserCost(const User *U, ArrayRef< const Value * > Operands)
unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize, unsigned ChainSizeInBytes, VectorType *VecTy) const
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:515
bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, unsigned Alignment, unsigned AddrSpace) const
unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index, Type *SubTp)
Flags describing the kind of vector reduction.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, ArrayRef< Type * > Tys, FastMathFlags FMF, unsigned ScalarizationCostPassed)
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:137
unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, const Instruction *I)
unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, ArrayRef< Value * > Args, FastMathFlags FMF, unsigned VF)
TargetTransformInfoImplBase(const TargetTransformInfoImplBase &Arg)
This is an important base class in LLVM.
Definition: Constant.h:42
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1554
unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
param_iterator param_begin() const
Definition: DerivedTypes.h:128
unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm, Type *Ty)
Expected to fold away in lowering.
unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize)
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1488
iterator begin() const
Definition: ArrayRef.h:137
Value * getOperand(unsigned i) const
Definition: User.h:154
const APInt & getAPInt() const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:221
unsigned getCallCost(FunctionType *FTy, int NumArgs)
const T & back() const
back - Get the last element.
Definition: ArrayRef.h:158
const SCEVConstant * getConstantStrideStep(ScalarEvolution *SE, const SCEV *Ptr)
OperandValueProperties
Additional properties of an operand's values.
unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy, ArrayRef< const Value * > Arguments)
int getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, const APInt &Imm, Type *Ty)
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:405
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:130
unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract)
TargetTransformInfoImplBase(const DataLayout &DL)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
bool areInlineCompatible(const Function *Caller, const Function *Callee) const
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
unsigned getRegisterBitWidth(bool Vector) const
AddressSpace
Definition: NVPTXBaseInfo.h:22
Type * getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length, unsigned SrcAlign, unsigned DestAlign) const
bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth, unsigned AddressSpace, unsigned Alignment, bool *Fast)
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
bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader)
int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace)
Class to represent vector types.
Definition: DerivedTypes.h:393
unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy, ArrayRef< Type * > ParamTys)
Class for arbitrary precision integers.
Definition: APInt.h:69
const DataLayout & getDataLayout() const
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
bool isLegalToVectorizeLoad(LoadInst *LI) const
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition: Operator.h:41
unsigned getReductionCost(unsigned, Type *, bool)
bool isLSRCostLess(TTI::LSRCost &C1, TTI::LSRCost &C2)
unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment, unsigned AddressSpace)
static std::vector< std::string > Flags
Definition: FlagsTest.cpp:8
bool isLegalToVectorizeStore(StoreInst *SI) const
unsigned getCFInstrCost(unsigned Opcode)
This class represents an analyzed expression in the program.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:360
#define C
Definition: LargeTest.cpp:25
Parameters that control the generic loop unrolling transformation.
Establish a view to a call site for examination.
Definition: CallSite.h:687
#define I(x, y, z)
Definition: MD5.cpp:58
Fast - This calling convention attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:43
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
unsigned getAddressComputationCost(Type *Tp, ScalarEvolution *, const SCEV *)
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, unsigned Alignment, unsigned AddressSpace)
bool hasLocalLinkage() const
Definition: GlobalValue.h:416
const unsigned Kind
Multiway switch.
unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize, unsigned ChainSizeInBytes, VectorType *VecTy) const
TargetTransformInfoImplBase(TargetTransformInfoImplBase &&Arg)
Type * getReturnType() const
Definition: DerivedTypes.h:124
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition: ArrayRef.h:188
The cost of a typical 'add' instruction.
LLVM Value Representation.
Definition: Value.h:73
unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm, Type *Ty)
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:532
Convenience struct for specifying and reasoning about fast-math flags.
Definition: Operator.h:160
OperandValueKind
Additional information about an operand's possible values.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
This pass exposes codegen information to IR-level passes.
bool isLegalInteger(uint64_t Width) const
Returns true if the specified type is known to be a native integer type supported by the CPU...
Definition: DataLayout.h:238
int * Ptr
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
unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef< Type * > Tys)
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
Information about a load/store intrinsic defined by the target.
The cost of a 'div' instruction on x86.
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:174
int getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands)
TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit)
Value * getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst, Type *ExpectedType)
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
This class represents a constant integer value.
ShuffleKind
The various kinds of shuffle patterns for vector queries.
gep_type_iterator gep_type_begin(const User *GEP)