[PM/AA] Run clang-format over this code to establish a clean baseline
[oota-llvm.git] / include / llvm / Analysis / TargetTransformInfoImpl.h
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
18 #include "llvm/Analysis/TargetTransformInfo.h"
19 #include "llvm/IR/CallSite.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/GetElementPtrTypeIterator.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/IR/Type.h"
25
26 namespace llvm {
27
28 /// \brief Base class for use as a mix-in that aids implementing
29 /// a TargetTransformInfo-compatible class.
30 class TargetTransformInfoImplBase {
31 protected:
32   typedef TargetTransformInfo TTI;
33
34   const DataLayout &DL;
35
36   explicit TargetTransformInfoImplBase(const DataLayout &DL) : DL(DL) {}
37
38 public:
39   // Provide value semantics. MSVC requires that we spell all of these out.
40   TargetTransformInfoImplBase(const TargetTransformInfoImplBase &Arg)
41       : DL(Arg.DL) {}
42   TargetTransformInfoImplBase(TargetTransformInfoImplBase &&Arg) : DL(Arg.DL) {}
43
44   const DataLayout &getDataLayout() const { return DL; }
45
46   unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
47     switch (Opcode) {
48     default:
49       // By default, just classify everything as 'basic'.
50       return TTI::TCC_Basic;
51
52     case Instruction::GetElementPtr:
53       llvm_unreachable("Use getGEPCost for GEP operations!");
54
55     case Instruction::BitCast:
56       assert(OpTy && "Cast instructions must provide the operand type");
57       if (Ty == OpTy || (Ty->isPointerTy() && OpTy->isPointerTy()))
58         // Identity and pointer-to-pointer casts are free.
59         return TTI::TCC_Free;
60
61       // Otherwise, the default basic cost is used.
62       return TTI::TCC_Basic;
63
64     case Instruction::IntToPtr: {
65       // An inttoptr cast is free so long as the input is a legal integer type
66       // which doesn't contain values outside the range of a pointer.
67       unsigned OpSize = OpTy->getScalarSizeInBits();
68       if (DL.isLegalInteger(OpSize) &&
69           OpSize <= DL.getPointerTypeSizeInBits(Ty))
70         return TTI::TCC_Free;
71
72       // Otherwise it's not a no-op.
73       return TTI::TCC_Basic;
74     }
75     case Instruction::PtrToInt: {
76       // A ptrtoint cast is free so long as the result is large enough to store
77       // the pointer, and a legal integer type.
78       unsigned DestSize = Ty->getScalarSizeInBits();
79       if (DL.isLegalInteger(DestSize) &&
80           DestSize >= DL.getPointerTypeSizeInBits(OpTy))
81         return TTI::TCC_Free;
82
83       // Otherwise it's not a no-op.
84       return TTI::TCC_Basic;
85     }
86     case Instruction::Trunc:
87       // trunc to a native type is free (assuming the target has compare and
88       // shift-right of the same width).
89       if (DL.isLegalInteger(DL.getTypeSizeInBits(Ty)))
90         return TTI::TCC_Free;
91
92       return TTI::TCC_Basic;
93     }
94   }
95
96   unsigned getGEPCost(Type *PointeeType, const Value *Ptr,
97                       ArrayRef<const Value *> Operands) {
98     // In the basic model, we just assume that all-constant GEPs will be folded
99     // into their uses via addressing modes.
100     for (unsigned Idx = 0, Size = Operands.size(); Idx != Size; ++Idx)
101       if (!isa<Constant>(Operands[Idx]))
102         return TTI::TCC_Basic;
103
104     return TTI::TCC_Free;
105   }
106
107   unsigned getCallCost(FunctionType *FTy, int NumArgs) {
108     assert(FTy && "FunctionType must be provided to this routine.");
109
110     // The target-independent implementation just measures the size of the
111     // function by approximating that each argument will take on average one
112     // instruction to prepare.
113
114     if (NumArgs < 0)
115       // Set the argument number to the number of explicit arguments in the
116       // function.
117       NumArgs = FTy->getNumParams();
118
119     return TTI::TCC_Basic * (NumArgs + 1);
120   }
121
122   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
123                             ArrayRef<Type *> ParamTys) {
124     switch (IID) {
125     default:
126       // Intrinsics rarely (if ever) have normal argument setup constraints.
127       // Model them as having a basic instruction cost.
128       // FIXME: This is wrong for libc intrinsics.
129       return TTI::TCC_Basic;
130
131     case Intrinsic::annotation:
132     case Intrinsic::assume:
133     case Intrinsic::dbg_declare:
134     case Intrinsic::dbg_value:
135     case Intrinsic::invariant_start:
136     case Intrinsic::invariant_end:
137     case Intrinsic::lifetime_start:
138     case Intrinsic::lifetime_end:
139     case Intrinsic::objectsize:
140     case Intrinsic::ptr_annotation:
141     case Intrinsic::var_annotation:
142     case Intrinsic::experimental_gc_result_int:
143     case Intrinsic::experimental_gc_result_float:
144     case Intrinsic::experimental_gc_result_ptr:
145     case Intrinsic::experimental_gc_result:
146     case Intrinsic::experimental_gc_relocate:
147       // These intrinsics don't actually represent code after lowering.
148       return TTI::TCC_Free;
149     }
150   }
151
152   bool hasBranchDivergence() { return false; }
153
154   bool isSourceOfDivergence(const Value *V) { return false; }
155
156   bool isLoweredToCall(const Function *F) {
157     // FIXME: These should almost certainly not be handled here, and instead
158     // handled with the help of TLI or the target itself. This was largely
159     // ported from existing analysis heuristics here so that such refactorings
160     // can take place in the future.
161
162     if (F->isIntrinsic())
163       return false;
164
165     if (F->hasLocalLinkage() || !F->hasName())
166       return true;
167
168     StringRef Name = F->getName();
169
170     // These will all likely lower to a single selection DAG node.
171     if (Name == "copysign" || Name == "copysignf" || Name == "copysignl" ||
172         Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" ||
173         Name == "fmin" || Name == "fminf" || Name == "fminl" ||
174         Name == "fmax" || Name == "fmaxf" || Name == "fmaxl" ||
175         Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" ||
176         Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl")
177       return false;
178
179     // These are all likely to be optimized into something smaller.
180     if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" ||
181         Name == "exp2l" || Name == "exp2f" || Name == "floor" ||
182         Name == "floorf" || Name == "ceil" || Name == "round" ||
183         Name == "ffs" || Name == "ffsl" || Name == "abs" || Name == "labs" ||
184         Name == "llabs")
185       return false;
186
187     return true;
188   }
189
190   void getUnrollingPreferences(Loop *, TTI::UnrollingPreferences &) {}
191
192   bool isLegalAddImmediate(int64_t Imm) { return false; }
193
194   bool isLegalICmpImmediate(int64_t Imm) { return false; }
195
196   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
197                              bool HasBaseReg, int64_t Scale,
198                              unsigned AddrSpace) {
199     // Guess that only reg and reg+reg addressing is allowed. This heuristic is
200     // taken from the implementation of LSR.
201     return !BaseGV && BaseOffset == 0 && (Scale == 0 || Scale == 1);
202   }
203
204   bool isLegalMaskedStore(Type *DataType, int Consecutive) { return false; }
205
206   bool isLegalMaskedLoad(Type *DataType, int Consecutive) { return false; }
207
208   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
209                            bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
210     // Guess that all legal addressing mode are free.
211     if (isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
212                               Scale, AddrSpace))
213       return 0;
214     return -1;
215   }
216
217   bool isTruncateFree(Type *Ty1, Type *Ty2) { return false; }
218
219   bool isZExtFree(Type *Ty1, Type *Ty2) { return false; }
220
221   bool isProfitableToHoist(Instruction *I) { return true; }
222
223   bool isTypeLegal(Type *Ty) { return false; }
224
225   unsigned getJumpBufAlignment() { return 0; }
226
227   unsigned getJumpBufSize() { return 0; }
228
229   bool shouldBuildLookupTables() { return true; }
230
231   bool enableAggressiveInterleaving(bool LoopHasReductions) { return false; }
232
233   bool enableInterleavedAccessVectorization() { return false; }
234
235   TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) {
236     return TTI::PSK_Software;
237   }
238
239   bool haveFastSqrt(Type *Ty) { return false; }
240
241   unsigned getFPOpCost(Type *Ty) { return TargetTransformInfo::TCC_Basic; }
242
243   unsigned getIntImmCost(const APInt &Imm, Type *Ty) { return TTI::TCC_Basic; }
244
245   unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
246                          Type *Ty) {
247     return TTI::TCC_Free;
248   }
249
250   unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
251                          Type *Ty) {
252     return TTI::TCC_Free;
253   }
254
255   unsigned getNumberOfRegisters(bool Vector) { return 8; }
256
257   unsigned getRegisterBitWidth(bool Vector) { return 32; }
258
259   unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
260
261   unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
262                                   TTI::OperandValueKind Opd1Info,
263                                   TTI::OperandValueKind Opd2Info,
264                                   TTI::OperandValueProperties Opd1PropInfo,
265                                   TTI::OperandValueProperties Opd2PropInfo) {
266     return 1;
267   }
268
269   unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index,
270                           Type *SubTp) {
271     return 1;
272   }
273
274   unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) { return 1; }
275
276   unsigned getCFInstrCost(unsigned Opcode) { return 1; }
277
278   unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) {
279     return 1;
280   }
281
282   unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
283     return 1;
284   }
285
286   unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
287                            unsigned AddressSpace) {
288     return 1;
289   }
290
291   unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
292                                  unsigned AddressSpace) {
293     return 1;
294   }
295
296   unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
297                                       unsigned Factor,
298                                       ArrayRef<unsigned> Indices,
299                                       unsigned Alignment,
300                                       unsigned AddressSpace) {
301     return 1;
302   }
303
304   unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
305                                  ArrayRef<Type *> Tys) {
306     return 1;
307   }
308
309   unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
310     return 1;
311   }
312
313   unsigned getNumberOfParts(Type *Tp) { return 0; }
314
315   unsigned getAddressComputationCost(Type *Tp, bool) { return 0; }
316
317   unsigned getReductionCost(unsigned, Type *, bool) { return 1; }
318
319   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { return 0; }
320
321   bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) {
322     return false;
323   }
324
325   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
326                                            Type *ExpectedType) {
327     return nullptr;
328   }
329
330   bool areInlineCompatible(const Function *Caller,
331                            const Function *Callee) const {
332     return (Caller->getFnAttribute("target-cpu") ==
333             Callee->getFnAttribute("target-cpu")) &&
334            (Caller->getFnAttribute("target-features") ==
335             Callee->getFnAttribute("target-features"));
336   }
337 };
338
339 /// \brief CRTP base class for use as a mix-in that aids implementing
340 /// a TargetTransformInfo-compatible class.
341 template <typename T>
342 class TargetTransformInfoImplCRTPBase : public TargetTransformInfoImplBase {
343 private:
344   typedef TargetTransformInfoImplBase BaseT;
345
346 protected:
347   explicit TargetTransformInfoImplCRTPBase(const DataLayout &DL) : BaseT(DL) {}
348
349 public:
350   // Provide value semantics. MSVC requires that we spell all of these out.
351   TargetTransformInfoImplCRTPBase(const TargetTransformInfoImplCRTPBase &Arg)
352       : BaseT(static_cast<const BaseT &>(Arg)) {}
353   TargetTransformInfoImplCRTPBase(TargetTransformInfoImplCRTPBase &&Arg)
354       : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
355
356   using BaseT::getCallCost;
357
358   unsigned getCallCost(const Function *F, int NumArgs) {
359     assert(F && "A concrete function must be provided to this routine.");
360
361     if (NumArgs < 0)
362       // Set the argument number to the number of explicit arguments in the
363       // function.
364       NumArgs = F->arg_size();
365
366     if (Intrinsic::ID IID = F->getIntrinsicID()) {
367       FunctionType *FTy = F->getFunctionType();
368       SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end());
369       return static_cast<T *>(this)
370           ->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys);
371     }
372
373     if (!static_cast<T *>(this)->isLoweredToCall(F))
374       return TTI::TCC_Basic; // Give a basic cost if it will be lowered
375                              // directly.
376
377     return static_cast<T *>(this)->getCallCost(F->getFunctionType(), NumArgs);
378   }
379
380   unsigned getCallCost(const Function *F, ArrayRef<const Value *> Arguments) {
381     // Simply delegate to generic handling of the call.
382     // FIXME: We should use instsimplify or something else to catch calls which
383     // will constant fold with these arguments.
384     return static_cast<T *>(this)->getCallCost(F, Arguments.size());
385   }
386
387   using BaseT::getGEPCost;
388
389   unsigned getGEPCost(Type *PointeeType, const Value *Ptr,
390                       ArrayRef<const Value *> Operands) {
391     const GlobalValue *BaseGV = nullptr;
392     if (Ptr != nullptr) {
393       // TODO: will remove this when pointers have an opaque type.
394       assert(Ptr->getType()->getScalarType()->getPointerElementType() ==
395                  PointeeType &&
396              "explicit pointee type doesn't match operand's pointee type");
397       BaseGV = dyn_cast<GlobalValue>(Ptr->stripPointerCasts());
398     }
399     bool HasBaseReg = (BaseGV == nullptr);
400     int64_t BaseOffset = 0;
401     int64_t Scale = 0;
402
403     // Assumes the address space is 0 when Ptr is nullptr.
404     unsigned AS =
405         (Ptr == nullptr ? 0 : Ptr->getType()->getPointerAddressSpace());
406     auto GTI = gep_type_begin(PointerType::get(PointeeType, AS), Operands);
407     for (auto I = Operands.begin(); I != Operands.end(); ++I, ++GTI) {
408       if (isa<SequentialType>(*GTI)) {
409         int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType());
410         if (const ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) {
411           BaseOffset += ConstIdx->getSExtValue() * ElementSize;
412         } else {
413           // Needs scale register.
414           if (Scale != 0) {
415             // No addressing mode takes two scale registers.
416             return TTI::TCC_Basic;
417           }
418           Scale = ElementSize;
419         }
420       } else {
421         StructType *STy = cast<StructType>(*GTI);
422         uint64_t Field = cast<ConstantInt>(*I)->getZExtValue();
423         BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field);
424       }
425     }
426
427     if (static_cast<T *>(this)->isLegalAddressingMode(
428             PointerType::get(*GTI, AS), const_cast<GlobalValue *>(BaseGV),
429             BaseOffset, HasBaseReg, Scale, AS)) {
430       return TTI::TCC_Free;
431     }
432     return TTI::TCC_Basic;
433   }
434
435   using BaseT::getIntrinsicCost;
436
437   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
438                             ArrayRef<const Value *> Arguments) {
439     // Delegate to the generic intrinsic handling code. This mostly provides an
440     // opportunity for targets to (for example) special case the cost of
441     // certain intrinsics based on constants used as arguments.
442     SmallVector<Type *, 8> ParamTys;
443     ParamTys.reserve(Arguments.size());
444     for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
445       ParamTys.push_back(Arguments[Idx]->getType());
446     return static_cast<T *>(this)->getIntrinsicCost(IID, RetTy, ParamTys);
447   }
448
449   unsigned getUserCost(const User *U) {
450     if (isa<PHINode>(U))
451       return TTI::TCC_Free; // Model all PHI nodes as free.
452
453     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
454       SmallVector<Value *, 4> Indices(GEP->idx_begin(), GEP->idx_end());
455       return static_cast<T *>(this)->getGEPCost(
456           GEP->getSourceElementType(), GEP->getPointerOperand(), Indices);
457     }
458
459     if (auto CS = ImmutableCallSite(U)) {
460       const Function *F = CS.getCalledFunction();
461       if (!F) {
462         // Just use the called value type.
463         Type *FTy = CS.getCalledValue()->getType()->getPointerElementType();
464         return static_cast<T *>(this)
465             ->getCallCost(cast<FunctionType>(FTy), CS.arg_size());
466       }
467
468       SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end());
469       return static_cast<T *>(this)->getCallCost(F, Arguments);
470     }
471
472     if (const CastInst *CI = dyn_cast<CastInst>(U)) {
473       // Result of a cmp instruction is often extended (to be used by other
474       // cmp instructions, logical or return instructions). These are usually
475       // nop on most sane targets.
476       if (isa<CmpInst>(CI->getOperand(0)))
477         return TTI::TCC_Free;
478     }
479
480     return static_cast<T *>(this)->getOperationCost(
481         Operator::getOpcode(U), U->getType(),
482         U->getNumOperands() == 1 ? U->getOperand(0)->getType() : nullptr);
483   }
484 };
485 }
486
487 #endif