LLVM  8.0.0svn
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 /// 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).
99  if (DL.isLegalInteger(DL.getTypeSizeInBits(Ty)))
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::sideeffect:
156  case Intrinsic::dbg_declare:
157  case Intrinsic::dbg_value:
158  case Intrinsic::dbg_label:
159  case Intrinsic::invariant_start:
160  case Intrinsic::invariant_end:
161  case Intrinsic::launder_invariant_group:
162  case Intrinsic::strip_invariant_group:
163  case Intrinsic::lifetime_start:
164  case Intrinsic::lifetime_end:
165  case Intrinsic::objectsize:
166  case Intrinsic::ptr_annotation:
167  case Intrinsic::var_annotation:
168  case Intrinsic::experimental_gc_result:
169  case Intrinsic::experimental_gc_relocate:
170  case Intrinsic::coro_alloc:
171  case Intrinsic::coro_begin:
172  case Intrinsic::coro_free:
173  case Intrinsic::coro_end:
174  case Intrinsic::coro_frame:
175  case Intrinsic::coro_size:
176  case Intrinsic::coro_suspend:
177  case Intrinsic::coro_param:
178  case Intrinsic::coro_subfn_addr:
179  // These intrinsics don't actually represent code after lowering.
180  return TTI::TCC_Free;
181  }
182  }
183 
184  bool hasBranchDivergence() { return false; }
185 
186  bool isSourceOfDivergence(const Value *V) { return false; }
187 
188  bool isAlwaysUniform(const Value *V) { return false; }
189 
190  unsigned getFlatAddressSpace () {
191  return -1;
192  }
193 
194  bool isLoweredToCall(const Function *F) {
195  assert(F && "A concrete function must be provided to this routine.");
196 
197  // FIXME: These should almost certainly not be handled here, and instead
198  // handled with the help of TLI or the target itself. This was largely
199  // ported from existing analysis heuristics here so that such refactorings
200  // can take place in the future.
201 
202  if (F->isIntrinsic())
203  return false;
204 
205  if (F->hasLocalLinkage() || !F->hasName())
206  return true;
207 
208  StringRef Name = F->getName();
209 
210  // These will all likely lower to a single selection DAG node.
211  if (Name == "copysign" || Name == "copysignf" || Name == "copysignl" ||
212  Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" ||
213  Name == "fmin" || Name == "fminf" || Name == "fminl" ||
214  Name == "fmax" || Name == "fmaxf" || Name == "fmaxl" ||
215  Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" ||
216  Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl")
217  return false;
218 
219  // These are all likely to be optimized into something smaller.
220  if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" ||
221  Name == "exp2l" || Name == "exp2f" || Name == "floor" ||
222  Name == "floorf" || Name == "ceil" || Name == "round" ||
223  Name == "ffs" || Name == "ffsl" || Name == "abs" || Name == "labs" ||
224  Name == "llabs")
225  return false;
226 
227  return true;
228  }
229 
232 
233  bool isLegalAddImmediate(int64_t Imm) { return false; }
234 
235  bool isLegalICmpImmediate(int64_t Imm) { return false; }
236 
237  bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
238  bool HasBaseReg, int64_t Scale,
239  unsigned AddrSpace, Instruction *I = nullptr) {
240  // Guess that only reg and reg+reg addressing is allowed. This heuristic is
241  // taken from the implementation of LSR.
242  return !BaseGV && BaseOffset == 0 && (Scale == 0 || Scale == 1);
243  }
244 
246  return std::tie(C1.NumRegs, C1.AddRecCost, C1.NumIVMuls, C1.NumBaseAdds,
247  C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
248  std::tie(C2.NumRegs, C2.AddRecCost, C2.NumIVMuls, C2.NumBaseAdds,
249  C2.ScaleCost, C2.ImmCost, C2.SetupCost);
250  }
251 
252  bool canMacroFuseCmp() { return false; }
253 
254  bool shouldFavorPostInc() const { return false; }
255 
256  bool isLegalMaskedStore(Type *DataType) { return false; }
257 
258  bool isLegalMaskedLoad(Type *DataType) { return false; }
259 
260  bool isLegalMaskedScatter(Type *DataType) { return false; }
261 
262  bool isLegalMaskedGather(Type *DataType) { return false; }
263 
264  bool hasDivRemOp(Type *DataType, bool IsSigned) { return false; }
265 
266  bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) { return false; }
267 
268  bool prefersVectorizedAddressing() { return true; }
269 
270  int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
271  bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
272  // Guess that all legal addressing mode are free.
273  if (isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
274  Scale, AddrSpace))
275  return 0;
276  return -1;
277  }
278 
279  bool LSRWithInstrQueries() { return false; }
280 
281  bool isTruncateFree(Type *Ty1, Type *Ty2) { return false; }
282 
283  bool isProfitableToHoist(Instruction *I) { return true; }
284 
285  bool useAA() { return false; }
286 
287  bool isTypeLegal(Type *Ty) { return false; }
288 
289  unsigned getJumpBufAlignment() { return 0; }
290 
291  unsigned getJumpBufSize() { return 0; }
292 
293  bool shouldBuildLookupTables() { return true; }
295 
296  bool useColdCCForColdCall(Function &F) { return false; }
297 
298  unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
299  return 0;
300  }
301 
303  unsigned VF) { return 0; }
304 
306 
307  bool enableAggressiveInterleaving(bool LoopHasReductions) { return false; }
308 
310  bool IsZeroCmp) const {
311  return nullptr;
312  }
313 
314  bool enableInterleavedAccessVectorization() { return false; }
315 
317 
318  bool isFPVectorizationPotentiallyUnsafe() { return false; }
319 
321  unsigned BitWidth,
322  unsigned AddressSpace,
323  unsigned Alignment,
324  bool *Fast) { return false; }
325 
326  TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) {
327  return TTI::PSK_Software;
328  }
329 
330  bool haveFastSqrt(Type *Ty) { return false; }
331 
332  bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) { return true; }
333 
335 
336  int getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
337  Type *Ty) {
338  return 0;
339  }
340 
341  unsigned getIntImmCost(const APInt &Imm, Type *Ty) { return TTI::TCC_Basic; }
342 
343  unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
344  Type *Ty) {
345  return TTI::TCC_Free;
346  }
347 
348  unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
349  Type *Ty) {
350  return TTI::TCC_Free;
351  }
352 
353  unsigned getNumberOfRegisters(bool Vector) { return 8; }
354 
355  unsigned getRegisterBitWidth(bool Vector) const { return 32; }
356 
357  unsigned getMinVectorRegisterBitWidth() { return 128; }
358 
359  bool shouldMaximizeVectorBandwidth(bool OptSize) const { return false; }
360 
361  unsigned getMinimumVF(unsigned ElemWidth) const { return 0; }
362 
363  bool
365  bool &AllowPromotionWithoutCommonHeader) {
366  AllowPromotionWithoutCommonHeader = false;
367  return false;
368  }
369 
370  unsigned getCacheLineSize() { return 0; }
371 
373  switch (Level) {
377  return llvm::Optional<unsigned>();
378  }
379 
380  llvm_unreachable("Unknown TargetTransformInfo::CacheLevel");
381  }
382 
385  switch (Level) {
389  return llvm::Optional<unsigned>();
390  }
391 
392  llvm_unreachable("Unknown TargetTransformInfo::CacheLevel");
393  }
394 
395  unsigned getPrefetchDistance() { return 0; }
396 
397  unsigned getMinPrefetchStride() { return 1; }
398 
399  unsigned getMaxPrefetchIterationsAhead() { return UINT_MAX; }
400 
401  unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
402 
403  unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
404  TTI::OperandValueKind Opd1Info,
405  TTI::OperandValueKind Opd2Info,
406  TTI::OperandValueProperties Opd1PropInfo,
407  TTI::OperandValueProperties Opd2PropInfo,
409  return 1;
410  }
411 
413  Type *SubTp) {
414  return 1;
415  }
416 
417  unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
418  const Instruction *I) { return 1; }
419 
420  unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
421  VectorType *VecTy, unsigned Index) {
422  return 1;
423  }
424 
425  unsigned getCFInstrCost(unsigned Opcode) { return 1; }
426 
427  unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
428  const Instruction *I) {
429  return 1;
430  }
431 
432  unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
433  return 1;
434  }
435 
436  unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
437  unsigned AddressSpace, const Instruction *I) {
438  return 1;
439  }
440 
441  unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
442  unsigned AddressSpace) {
443  return 1;
444  }
445 
446  unsigned getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr,
447  bool VariableMask,
448  unsigned Alignment) {
449  return 1;
450  }
451 
452  unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
453  unsigned Factor,
454  ArrayRef<unsigned> Indices,
455  unsigned Alignment, unsigned AddressSpace,
456  bool IsMasked = false) {
457  return 1;
458  }
459 
462  unsigned ScalarizationCostPassed) {
463  return 1;
464  }
466  ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) {
467  return 1;
468  }
469 
470  unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
471  return 1;
472  }
473 
474  unsigned getNumberOfParts(Type *Tp) { return 0; }
475 
477  const SCEV *) {
478  return 0;
479  }
480 
481  unsigned getArithmeticReductionCost(unsigned, Type *, bool) { return 1; }
482 
483  unsigned getMinMaxReductionCost(Type *, Type *, bool, bool) { return 1; }
484 
485  unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { return 0; }
486 
488  return false;
489  }
490 
492  // Note for overrides: You must ensure for all element unordered-atomic
493  // memory intrinsics that all power-of-2 element sizes up to, and
494  // including, the return value of this method have a corresponding
495  // runtime lib call. These runtime lib call definitions can be found
496  // in RuntimeLibcalls.h
497  return 0;
498  }
499 
501  Type *ExpectedType) {
502  return nullptr;
503  }
504 
506  unsigned SrcAlign, unsigned DestAlign) const {
507  return Type::getInt8Ty(Context);
508  }
509 
512  unsigned RemainingBytes,
513  unsigned SrcAlign,
514  unsigned DestAlign) const {
515  for (unsigned i = 0; i != RemainingBytes; ++i)
516  OpsOut.push_back(Type::getInt8Ty(Context));
517  }
518 
519  bool areInlineCompatible(const Function *Caller,
520  const Function *Callee) const {
521  return (Caller->getFnAttribute("target-cpu") ==
522  Callee->getFnAttribute("target-cpu")) &&
523  (Caller->getFnAttribute("target-features") ==
524  Callee->getFnAttribute("target-features"));
525  }
526 
528  const DataLayout &DL) const {
529  return false;
530  }
531 
533  const DataLayout &DL) const {
534  return false;
535  }
536 
537  unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { return 128; }
538 
539  bool isLegalToVectorizeLoad(LoadInst *LI) const { return true; }
540 
541  bool isLegalToVectorizeStore(StoreInst *SI) const { return true; }
542 
543  bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
544  unsigned Alignment,
545  unsigned AddrSpace) const {
546  return true;
547  }
548 
549  bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
550  unsigned Alignment,
551  unsigned AddrSpace) const {
552  return true;
553  }
554 
555  unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
556  unsigned ChainSizeInBytes,
557  VectorType *VecTy) const {
558  return VF;
559  }
560 
561  unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
562  unsigned ChainSizeInBytes,
563  VectorType *VecTy) const {
564  return VF;
565  }
566 
567  bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
568  TTI::ReductionFlags Flags) const {
569  return false;
570  }
571 
572  bool shouldExpandReduction(const IntrinsicInst *II) const {
573  return true;
574  }
575 
576 protected:
577  // Obtain the minimum required size to hold the value (without the sign)
578  // In case of a vector it returns the min required size for one element.
579  unsigned minRequiredElementSize(const Value* Val, bool &isSigned) {
580  if (isa<ConstantDataVector>(Val) || isa<ConstantVector>(Val)) {
581  const auto* VectorValue = cast<Constant>(Val);
582 
583  // In case of a vector need to pick the max between the min
584  // required size for each element
585  auto *VT = cast<VectorType>(Val->getType());
586 
587  // Assume unsigned elements
588  isSigned = false;
589 
590  // The max required size is the total vector width divided by num
591  // of elements in the vector
592  unsigned MaxRequiredSize = VT->getBitWidth() / VT->getNumElements();
593 
594  unsigned MinRequiredSize = 0;
595  for(unsigned i = 0, e = VT->getNumElements(); i < e; ++i) {
596  if (auto* IntElement =
597  dyn_cast<ConstantInt>(VectorValue->getAggregateElement(i))) {
598  bool signedElement = IntElement->getValue().isNegative();
599  // Get the element min required size.
600  unsigned ElementMinRequiredSize =
601  IntElement->getValue().getMinSignedBits() - 1;
602  // In case one element is signed then all the vector is signed.
603  isSigned |= signedElement;
604  // Save the max required bit size between all the elements.
605  MinRequiredSize = std::max(MinRequiredSize, ElementMinRequiredSize);
606  }
607  else {
608  // not an int constant element
609  return MaxRequiredSize;
610  }
611  }
612  return MinRequiredSize;
613  }
614 
615  if (const auto* CI = dyn_cast<ConstantInt>(Val)) {
616  isSigned = CI->getValue().isNegative();
617  return CI->getValue().getMinSignedBits() - 1;
618  }
619 
620  if (const auto* Cast = dyn_cast<SExtInst>(Val)) {
621  isSigned = true;
622  return Cast->getSrcTy()->getScalarSizeInBits() - 1;
623  }
624 
625  if (const auto* Cast = dyn_cast<ZExtInst>(Val)) {
626  isSigned = false;
627  return Cast->getSrcTy()->getScalarSizeInBits();
628  }
629 
630  isSigned = false;
631  return Val->getType()->getScalarSizeInBits();
632  }
633 
634  bool isStridedAccess(const SCEV *Ptr) {
635  return Ptr && isa<SCEVAddRecExpr>(Ptr);
636  }
637 
639  const SCEV *Ptr) {
640  if (!isStridedAccess(Ptr))
641  return nullptr;
642  const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ptr);
643  return dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*SE));
644  }
645 
647  int64_t MergeDistance) {
648  const SCEVConstant *Step = getConstantStrideStep(SE, Ptr);
649  if (!Step)
650  return false;
651  APInt StrideVal = Step->getAPInt();
652  if (StrideVal.getBitWidth() > 64)
653  return false;
654  // FIXME: Need to take absolute value for negative stride case.
655  return StrideVal.getSExtValue() < MergeDistance;
656  }
657 };
658 
659 /// CRTP base class for use as a mix-in that aids implementing
660 /// a TargetTransformInfo-compatible class.
661 template <typename T>
663 private:
665 
666 protected:
667  explicit TargetTransformInfoImplCRTPBase(const DataLayout &DL) : BaseT(DL) {}
668 
669 public:
670  using BaseT::getCallCost;
671 
672  unsigned getCallCost(const Function *F, int NumArgs) {
673  assert(F && "A concrete function must be provided to this routine.");
674 
675  if (NumArgs < 0)
676  // Set the argument number to the number of explicit arguments in the
677  // function.
678  NumArgs = F->arg_size();
679 
680  if (Intrinsic::ID IID = F->getIntrinsicID()) {
681  FunctionType *FTy = F->getFunctionType();
682  SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end());
683  return static_cast<T *>(this)
684  ->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys);
685  }
686 
687  if (!static_cast<T *>(this)->isLoweredToCall(F))
688  return TTI::TCC_Basic; // Give a basic cost if it will be lowered
689  // directly.
690 
691  return static_cast<T *>(this)->getCallCost(F->getFunctionType(), NumArgs);
692  }
693 
695  // Simply delegate to generic handling of the call.
696  // FIXME: We should use instsimplify or something else to catch calls which
697  // will constant fold with these arguments.
698  return static_cast<T *>(this)->getCallCost(F, Arguments.size());
699  }
700 
701  using BaseT::getGEPCost;
702 
703  int getGEPCost(Type *PointeeType, const Value *Ptr,
704  ArrayRef<const Value *> Operands) {
705  const GlobalValue *BaseGV = nullptr;
706  if (Ptr != nullptr) {
707  // TODO: will remove this when pointers have an opaque type.
709  PointeeType &&
710  "explicit pointee type doesn't match operand's pointee type");
711  BaseGV = dyn_cast<GlobalValue>(Ptr->stripPointerCasts());
712  }
713  bool HasBaseReg = (BaseGV == nullptr);
714 
715  auto PtrSizeBits = DL.getPointerTypeSizeInBits(Ptr->getType());
716  APInt BaseOffset(PtrSizeBits, 0);
717  int64_t Scale = 0;
718 
719  auto GTI = gep_type_begin(PointeeType, Operands);
720  Type *TargetType = nullptr;
721 
722  // Handle the case where the GEP instruction has a single operand,
723  // the basis, therefore TargetType is a nullptr.
724  if (Operands.empty())
725  return !BaseGV ? TTI::TCC_Free : TTI::TCC_Basic;
726 
727  for (auto I = Operands.begin(); I != Operands.end(); ++I, ++GTI) {
728  TargetType = GTI.getIndexedType();
729  // We assume that the cost of Scalar GEP with constant index and the
730  // cost of Vector GEP with splat constant index are the same.
731  const ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
732  if (!ConstIdx)
733  if (auto Splat = getSplatValue(*I))
734  ConstIdx = dyn_cast<ConstantInt>(Splat);
735  if (StructType *STy = GTI.getStructTypeOrNull()) {
736  // For structures the index is always splat or scalar constant
737  assert(ConstIdx && "Unexpected GEP index");
738  uint64_t Field = ConstIdx->getZExtValue();
739  BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field);
740  } else {
741  int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType());
742  if (ConstIdx) {
743  BaseOffset +=
744  ConstIdx->getValue().sextOrTrunc(PtrSizeBits) * ElementSize;
745  } else {
746  // Needs scale register.
747  if (Scale != 0)
748  // No addressing mode takes two scale registers.
749  return TTI::TCC_Basic;
750  Scale = ElementSize;
751  }
752  }
753  }
754 
755  // Assumes the address space is 0 when Ptr is nullptr.
756  unsigned AS =
757  (Ptr == nullptr ? 0 : Ptr->getType()->getPointerAddressSpace());
758 
759  if (static_cast<T *>(this)->isLegalAddressingMode(
760  TargetType, const_cast<GlobalValue *>(BaseGV),
761  BaseOffset.sextOrTrunc(64).getSExtValue(), HasBaseReg, Scale, AS))
762  return TTI::TCC_Free;
763  return TTI::TCC_Basic;
764  }
765 
766  using BaseT::getIntrinsicCost;
767 
768  unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
770  // Delegate to the generic intrinsic handling code. This mostly provides an
771  // opportunity for targets to (for example) special case the cost of
772  // certain intrinsics based on constants used as arguments.
773  SmallVector<Type *, 8> ParamTys;
774  ParamTys.reserve(Arguments.size());
775  for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
776  ParamTys.push_back(Arguments[Idx]->getType());
777  return static_cast<T *>(this)->getIntrinsicCost(IID, RetTy, ParamTys);
778  }
779 
780  unsigned getUserCost(const User *U, ArrayRef<const Value *> Operands) {
781  if (isa<PHINode>(U))
782  return TTI::TCC_Free; // Model all PHI nodes as free.
783 
784  // Static alloca doesn't generate target instructions.
785  if (auto *A = dyn_cast<AllocaInst>(U))
786  if (A->isStaticAlloca())
787  return TTI::TCC_Free;
788 
789  if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
790  return static_cast<T *>(this)->getGEPCost(GEP->getSourceElementType(),
791  GEP->getPointerOperand(),
792  Operands.drop_front());
793  }
794 
795  if (auto CS = ImmutableCallSite(U)) {
796  const Function *F = CS.getCalledFunction();
797  if (!F) {
798  // Just use the called value type.
799  Type *FTy = CS.getCalledValue()->getType()->getPointerElementType();
800  return static_cast<T *>(this)
801  ->getCallCost(cast<FunctionType>(FTy), CS.arg_size());
802  }
803 
804  SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end());
805  return static_cast<T *>(this)->getCallCost(F, Arguments);
806  }
807 
808  if (const CastInst *CI = dyn_cast<CastInst>(U)) {
809  // Result of a cmp instruction is often extended (to be used by other
810  // cmp instructions, logical or return instructions). These are usually
811  // nop on most sane targets.
812  if (isa<CmpInst>(CI->getOperand(0)))
813  return TTI::TCC_Free;
814  if (isa<SExtInst>(CI) || isa<ZExtInst>(CI) || isa<FPExtInst>(CI))
815  return static_cast<T *>(this)->getExtCost(CI, Operands.back());
816  }
817 
818  return static_cast<T *>(this)->getOperationCost(
819  Operator::getOpcode(U), U->getType(),
820  U->getNumOperands() == 1 ? U->getOperand(0)->getType() : nullptr);
821  }
822 
825  I->value_op_end());
826  if (getUserCost(I, Operands) == TTI::TCC_Free)
827  return 0;
828 
829  if (isa<LoadInst>(I))
830  return 4;
831 
832  Type *DstTy = I->getType();
833 
834  // Usually an intrinsic is a simple instruction.
835  // A real function call is much slower.
836  if (auto *CI = dyn_cast<CallInst>(I)) {
837  const Function *F = CI->getCalledFunction();
838  if (!F || static_cast<T *>(this)->isLoweredToCall(F))
839  return 40;
840  // Some intrinsics return a value and a flag, we use the value type
841  // to decide its latency.
842  if (StructType* StructTy = dyn_cast<StructType>(DstTy))
843  DstTy = StructTy->getElementType(0);
844  // Fall through to simple instructions.
845  }
846 
847  if (VectorType *VectorTy = dyn_cast<VectorType>(DstTy))
848  DstTy = VectorTy->getElementType();
849  if (DstTy->isFloatingPointTy())
850  return 3;
851 
852  return 1;
853  }
854 };
855 }
856 
857 #endif
uint64_t CallInst * C
unsigned getNumCases() const
Return the number of &#39;cases&#39; in this switch instruction, excluding the default case.
bool isIntrinsic() const
isIntrinsic - Returns true if the function&#39;s name starts with "llvm.".
Definition: Function.h:199
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:111
bool isConstantStridedAccessLessThan(ScalarEvolution *SE, const SCEV *Ptr, int64_t MergeDistance)
bool hasLocalLinkage() const
Definition: GlobalValue.h:436
unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, ArrayRef< Type *> Tys, FastMathFlags FMF, unsigned ScalarizationCostPassed)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
LLVMContext & Context
const T & back() const
back - Get the last element.
Definition: ArrayRef.h:158
SI Whole Quad Mode
unsigned getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr, bool VariableMask, unsigned Alignment)
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
unsigned minRequiredElementSize(const Value *Val, bool &isSigned)
void getUnrollingPreferences(Loop *, ScalarEvolution &, TTI::UnrollingPreferences &)
unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index)
iterator begin() const
Definition: ArrayRef.h:137
#define LLVM_FALLTHROUGH
Definition: Compiler.h:86
unsigned getCostOfKeepingLiveOverCall(ArrayRef< Type *> Tys)
const Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
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:588
value_op_iterator value_op_begin()
Definition: User.h:256
The main scalar evolution driver.
MemIndexedMode
The type of load/store indexing.
unsigned getCallCost(const Function *F, int NumArgs)
unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::OperandValueKind Opd1Info, TTI::OperandValueKind Opd2Info, TTI::OperandValueProperties Opd1PropInfo, TTI::OperandValueProperties Opd2PropInfo, ArrayRef< const Value *> Args)
unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy)
value_op_iterator value_op_end()
Definition: User.h:259
Fast - This calling convention attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:43
F(f)
unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, const Instruction *I)
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
param_iterator param_end() const
Definition: DerivedTypes.h:129
An instruction for reading from memory.
Definition: Instructions.h:168
Hexagon Common GEP
unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment, unsigned AddressSpace, const Instruction *I)
void reserve(size_type N)
Definition: SmallVector.h:376
unsigned getIntImmCost(const APInt &Imm, Type *Ty)
int getExtCost(const Instruction *I, const Value *Src)
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1503
bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, unsigned Alignment, unsigned AddrSpace) const
bool isIndexedLoadLegal(TTI::MemIndexedMode Mode, Type *Ty, const DataLayout &DL) const
CRTP base class for use as a mix-in that aids implementing a TargetTransformInfo-compatible class...
bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info)
unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize, unsigned ChainSizeInBytes, VectorType *VecTy) const
amdgpu Simplify well known AMD library false Value Value const Twine & Name
Type * getPointerElementType() const
Definition: Type.h:376
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:364
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
Definition: DataLayout.cpp:638
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
Definition: Type.h:162
Class to represent struct types.
Definition: DerivedTypes.h:201
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
unsigned getArithmeticReductionCost(unsigned, Type *, bool)
const APInt & getAPInt() const
bool isLegalToVectorizeLoad(LoadInst *LI) const
Type * getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length, unsigned SrcAlign, unsigned DestAlign) const
bool isTruncateFree(Type *Ty1, Type *Ty2)
bool enableAggressiveInterleaving(bool LoopHasReductions)
Class to represent function types.
Definition: DerivedTypes.h:103
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1569
llvm::Optional< unsigned > getCacheSize(TargetTransformInfo::CacheLevel Level)
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
This node represents a polynomial recurrence on the trip count of the specified loop.
void getMemcpyLoopResidualLoweringType(SmallVectorImpl< Type *> &OpsOut, LLVMContext &Context, unsigned RemainingBytes, unsigned SrcAlign, unsigned DestAlign) const
PopcntSupportKind
Flags indicating the kind of support for population count.
APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition: APInt.cpp:884
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:138
An instruction for storing to memory.
Definition: Instructions.h:310
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy, unsigned Index)
Value * getOperand(unsigned i) const
Definition: User.h:170
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return &#39;this&#39;.
Definition: Type.h:304
bool isLegalToVectorizeStore(StoreInst *SI) const
unsigned getMinimumVF(unsigned ElemWidth) const
If not nullptr, enable inline expansion of memcmp.
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
unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index, Type *SubTp)
unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef< Type *> Tys)
bool hasName() const
Definition: Value.h:251
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
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, const Instruction *I)
unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy, ArrayRef< const Value *> Arguments)
TargetTransformInfoImplBase(const TargetTransformInfoImplBase &Arg)
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
This is an important base class in LLVM.
Definition: Constant.h:42
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:224
bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, unsigned Alignment, unsigned AddrSpace) const
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, unsigned Alignment, unsigned AddressSpace, bool IsMasked=false)
unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm, Type *Ty)
bool hasVolatileVariant(Instruction *I, unsigned AddrSpace)
Expected to fold away in lowering.
AMDGPU Lower Kernel Arguments
unsigned getUserCost(const User *U, ArrayRef< const Value *> Operands)
bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace, Instruction *I=nullptr)
param_iterator param_begin() const
Definition: DerivedTypes.h:128
const TTI::MemCmpExpansionOptions * enableMemCmpExpansion(bool IsZeroCmp) const
unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize)
size_t arg_size() const
Definition: Function.h:698
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:539
unsigned getCallCost(FunctionType *FTy, int NumArgs)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const SCEVConstant * getConstantStrideStep(ScalarEvolution *SE, const SCEV *Ptr)
OperandValueProperties
Additional properties of an operand&#39;s values.
int getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, const APInt &Imm, Type *Ty)
unsigned getNumOperands() const
Definition: User.h:192
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.
unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize, unsigned ChainSizeInBytes, VectorType *VecTy) const
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 &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
AddressSpace
Definition: NVPTXBaseInfo.h:22
iterator end() const
Definition: ArrayRef.h:138
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:243
Type * getReturnType() const
Definition: DerivedTypes.h:124
bool useReductionIntrinsic(unsigned Opcode, Type *Ty, TTI::ReductionFlags Flags) 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:194
bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader)
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:164
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
Class for arbitrary precision integers.
Definition: APInt.h:70
unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const
unsigned getMinMaxReductionCost(Type *, Type *, bool, bool)
amdgpu Simplify well known AMD library false Value Value * Arg
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:560
bool isLSRCostLess(TTI::LSRCost &C1, TTI::LSRCost &C2)
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:428
unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment, unsigned AddressSpace)
unsigned getCFInstrCost(unsigned Opcode)
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:543
This class represents an analyzed expression in the program.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:459
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition: ArrayRef.h:188
Parameters that control the generic loop unrolling transformation.
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
Establish a view to a call site for examination.
Definition: CallSite.h:714
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned getOperandsScalarizationOverhead(ArrayRef< const Value *> Args, unsigned VF)
int getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value *> Operands)
bool isIndexedStoreLegal(TTI::MemIndexedMode Mode, Type *Ty, const DataLayout &DL) const
bool areInlineCompatible(const Function *Caller, const Function *Callee) const
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
uint32_t Size
Definition: Profile.cpp:47
unsigned getAddressComputationCost(Type *Tp, ScalarEvolution *, const SCEV *)
const unsigned Kind
Multiway switch.
TargetTransformInfoImplBase(TargetTransformInfoImplBase &&Arg)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
The cost of a typical &#39;add&#39; instruction.
LLVM Value Representation.
Definition: Value.h:73
unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm, Type *Ty)
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition: Operator.h:41
bool shouldExpandReduction(const IntrinsicInst *II) const
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:331
bool shouldMaximizeVectorBandwidth(bool OptSize) const
const DataLayout & getDataLayout() 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.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
This pass exposes codegen information to IR-level passes.
llvm::Optional< unsigned > getCacheAssociativity(TargetTransformInfo::CacheLevel Level)
CacheLevel
The possible cache levels.
unsigned getRegisterBitWidth(bool Vector) const
Information about a load/store intrinsic defined by the target.
unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy, ArrayRef< Type *> ParamTys)
The cost of a &#39;div&#39; instruction on x86.
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:174
int getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value *> Operands)
unsigned getCallCost(const Function *F, ArrayRef< const Value *> Arguments)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
bool hasDivRemOp(Type *DataType, bool IsSigned)
TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit)
Value * getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst, Type *ExpectedType)
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
This class represents a constant integer value.
unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, ArrayRef< Value *> Args, FastMathFlags FMF, unsigned VF)
ShuffleKind
The various kinds of shuffle patterns for vector queries.
gep_type_iterator gep_type_begin(const User *GEP)