Begin fleshing out an interface in TTI for modelling the costs of
[oota-llvm.git] / include / llvm / Analysis / TargetTransformInfo.h
1 //===- llvm/Analysis/TargetTransformInfo.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 //
10 // This pass exposes codegen information to IR-level passes. Every
11 // transformation that uses codegen information is broken into three parts:
12 // 1. The IR-level analysis pass.
13 // 2. The IR-level transformation interface which provides the needed
14 //    information.
15 // 3. Codegen-level implementation which uses target-specific hooks.
16 //
17 // This file defines #2, which is the interface that IR-level transformations
18 // use for querying the codegen.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
23 #define LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
24
25 #include "llvm/CodeGen/ValueTypes.h"
26 #include "llvm/IR/GlobalValue.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/Type.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/DataTypes.h"
31
32 namespace llvm {
33
34 /// TargetTransformInfo - This pass provides access to the codegen
35 /// interfaces that are needed for IR-level transformations.
36 class TargetTransformInfo {
37 protected:
38   /// \brief The TTI instance one level down the stack.
39   ///
40   /// This is used to implement the default behavior all of the methods which
41   /// is to delegate up through the stack of TTIs until one can answer the
42   /// query.
43   TargetTransformInfo *PrevTTI;
44
45   /// \brief The top of the stack of TTI analyses available.
46   ///
47   /// This is a convenience routine maintained as TTI analyses become available
48   /// that complements the PrevTTI delegation chain. When one part of an
49   /// analysis pass wants to query another part of the analysis pass it can use
50   /// this to start back at the top of the stack.
51   TargetTransformInfo *TopTTI;
52
53   /// All pass subclasses must in their initializePass routine call
54   /// pushTTIStack with themselves to update the pointers tracking the previous
55   /// TTI instance in the analysis group's stack, and the top of the analysis
56   /// group's stack.
57   void pushTTIStack(Pass *P);
58
59   /// All pass subclasses must in their finalizePass routine call popTTIStack
60   /// to update the pointers tracking the previous TTI instance in the analysis
61   /// group's stack, and the top of the analysis group's stack.
62   void popTTIStack();
63
64   /// All pass subclasses must call TargetTransformInfo::getAnalysisUsage.
65   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
66
67 public:
68   /// This class is intended to be subclassed by real implementations.
69   virtual ~TargetTransformInfo() = 0;
70
71   /// \name Generic Target Information
72   /// @{
73
74   /// \brief Underlying constants for 'cost' values in this interface.
75   ///
76   /// Many APIs in this interface return a cost. This enum defines the
77   /// fundamental values that should be used to interpret (and produce) those
78   /// costs. The costs are returned as an unsigned rather than a member of this
79   /// enumeration because it is expected that the cost of one IR instruction
80   /// may have a multiplicative factor to it or otherwise won't fit dircetly
81   /// into the enum. Moreover, it is common to sum or average costs which works
82   /// better as simple integral values. Thus this enum only provides constants.
83   ///
84   /// Note that these costs should usually reflect the intersection of code-size
85   /// cost and execution cost. A free instruction is typically one that folds
86   /// into another instruction. For example, reg-to-reg moves can often be
87   /// skipped by renaming the registers in the CPU, but they still are encoded
88   /// and thus wouldn't be considered 'free' here.
89   enum TargetCostConstants {
90     TCC_Free = 0,       ///< Expected to fold away in lowering.
91     TCC_Basic = 1,      ///< The cost of a typical 'add' instruction.
92     TCC_Expensive = 4   ///< The cost of a 'div' instruction on x86.
93   };
94
95   /// \brief Estimate the cost of a specific operation when lowered.
96   ///
97   /// Note that this is designed to work on an arbitrary synthetic opcode, and
98   /// thus work for hypothetical queries before an instruction has even been
99   /// formed. However, this does *not* work for GEPs, and must not be called
100   /// for a GEP instruction. Instead, use the dedicated getGEPCost interface as
101   /// analyzing a GEP's cost required more information.
102   ///
103   /// Typically only the result type is required, and the operand type can be
104   /// omitted. However, if the opcode is one of the cast instructions, the
105   /// operand type is required.
106   ///
107   /// The returned cost is defined in terms of \c TargetCostConstants, see its
108   /// comments for a detailed explanation of the cost values.
109   virtual unsigned getOperationCost(unsigned Opcode, Type *Ty,
110                                     Type *OpTy = 0) const;
111
112   /// \brief Estimate the cost of a GEP operation when lowered.
113   ///
114   /// The contract for this function is the same as \c getOperationCost except
115   /// that it supports an interface that provides extra information specific to
116   /// the GEP operation.
117   virtual unsigned getGEPCost(const Value *Ptr,
118                               ArrayRef<const Value *> Operands) const;
119
120   /// \brief Estimate the cost of a function call when lowered.
121   ///
122   /// The contract for this is the same as \c getOperationCost except that it
123   /// supports an interface that provides extra information specific to call
124   /// instructions.
125   ///
126   /// This is the most basic query for estimating call cost: it only knows the
127   /// function type and (potentially) the number of arguments at the call site.
128   /// The latter is only interesting for varargs function types.
129   virtual unsigned getCallCost(FunctionType *FTy, int NumArgs = -1) const;
130
131   /// \brief Estimate the cost of calling a specific function when lowered.
132   ///
133   /// This overload adds the ability to reason about the particular function
134   /// being called in the event it is a library call with special lowering.
135   virtual unsigned getCallCost(const Function *F, int NumArgs = -1) const;
136
137   /// \brief Estimate the cost of calling a specific function when lowered.
138   ///
139   /// This overload allows specifying a set of candidate argument values.
140   virtual unsigned getCallCost(const Function *F,
141                                ArrayRef<const Value *> Arguments) const;
142
143   /// \brief Estimate the cost of an intrinsic when lowered.
144   ///
145   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
146   virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
147                                     ArrayRef<Type *> ParamTys) const;
148
149   /// \brief Estimate the cost of an intrinsic when lowered.
150   ///
151   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
152   virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
153                                     ArrayRef<const Value *> Arguments) const;
154
155   /// \brief Estimate the cost of a given IR user when lowered.
156   ///
157   /// This can estimate the cost of either a ConstantExpr or Instruction when
158   /// lowered. It has two primary advantages over the \c getOperationCost and
159   /// \c getGEPCost above, and one significant disadvantage: it can only be
160   /// used when the IR construct has already been formed.
161   ///
162   /// The advantages are that it can inspect the SSA use graph to reason more
163   /// accurately about the cost. For example, all-constant-GEPs can often be
164   /// folded into a load or other instruction, but if they are used in some
165   /// other context they may not be folded. This routine can distinguish such
166   /// cases.
167   ///
168   /// The returned cost is defined in terms of \c TargetCostConstants, see its
169   /// comments for a detailed explanation of the cost values.
170   virtual unsigned getUserCost(const User *U) const;
171
172   /// \brief Test whether calls to a function lower to actual program function
173   /// calls.
174   ///
175   /// The idea is to test whether the program is likely to require a 'call'
176   /// instruction or equivalent in order to call the given function.
177   ///
178   /// FIXME: It's not clear that this is a good or useful query API. Client's
179   /// should probably move to simpler cost metrics using the above.
180   /// Alternatively, we could split the cost interface into distinct code-size
181   /// and execution-speed costs. This would allow modelling the core of this
182   /// query more accurately as the a call is a single small instruction, but
183   /// incurs significant execution cost.
184   virtual bool isLoweredToCall(const Function *F) const;
185
186   /// @}
187
188   /// \name Scalar Target Information
189   /// @{
190
191   /// \brief Flags indicating the kind of support for population count.
192   ///
193   /// Compared to the SW implementation, HW support is supposed to
194   /// significantly boost the performance when the population is dense, and it
195   /// may or may not degrade performance if the population is sparse. A HW
196   /// support is considered as "Fast" if it can outperform, or is on a par
197   /// with, SW implementaion when the population is sparse; otherwise, it is
198   /// considered as "Slow".
199   enum PopcntSupportKind {
200     PSK_Software,
201     PSK_SlowHardware,
202     PSK_FastHardware
203   };
204
205   /// isLegalAddImmediate - Return true if the specified immediate is legal
206   /// add immediate, that is the target has add instructions which can add
207   /// a register with the immediate without having to materialize the
208   /// immediate into a register.
209   virtual bool isLegalAddImmediate(int64_t Imm) const;
210
211   /// isLegalICmpImmediate - Return true if the specified immediate is legal
212   /// icmp immediate, that is the target has icmp instructions which can compare
213   /// a register against the immediate without having to materialize the
214   /// immediate into a register.
215   virtual bool isLegalICmpImmediate(int64_t Imm) const;
216
217   /// isLegalAddressingMode - Return true if the addressing mode represented by
218   /// AM is legal for this target, for a load/store of the specified type.
219   /// The type may be VoidTy, in which case only return true if the addressing
220   /// mode is legal for a load/store of any legal type.
221   /// TODO: Handle pre/postinc as well.
222   virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
223                                      int64_t BaseOffset, bool HasBaseReg,
224                                      int64_t Scale) const;
225
226   /// isTruncateFree - Return true if it's free to truncate a value of
227   /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in
228   /// register EAX to i16 by referencing its sub-register AX.
229   virtual bool isTruncateFree(Type *Ty1, Type *Ty2) const;
230
231   /// Is this type legal.
232   virtual bool isTypeLegal(Type *Ty) const;
233
234   /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes
235   virtual unsigned getJumpBufAlignment() const;
236
237   /// getJumpBufSize - returns the target's jmp_buf size in bytes.
238   virtual unsigned getJumpBufSize() const;
239
240   /// shouldBuildLookupTables - Return true if switches should be turned into
241   /// lookup tables for the target.
242   virtual bool shouldBuildLookupTables() const;
243
244   /// getPopcntSupport - Return hardware support for population count.
245   virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
246
247   /// getIntImmCost - Return the expected cost of materializing the given
248   /// integer immediate of the specified type.
249   virtual unsigned getIntImmCost(const APInt &Imm, Type *Ty) const;
250
251   /// @}
252
253   /// \name Vector Target Information
254   /// @{
255
256   /// \brief The various kinds of shuffle patterns for vector queries.
257   enum ShuffleKind {
258     SK_Broadcast,       ///< Broadcast element 0 to all other elements.
259     SK_Reverse,         ///< Reverse the order of the vector.
260     SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
261     SK_ExtractSubvector ///< ExtractSubvector Index indicates start offset.
262   };
263
264   /// \return The number of scalar or vector registers that the target has.
265   /// If 'Vectors' is true, it returns the number of vector registers. If it is
266   /// set to false, it returns the number of scalar registers.
267   virtual unsigned getNumberOfRegisters(bool Vector) const;
268
269   /// \return The width of the largest scalar or vector register type.
270   virtual unsigned getRegisterBitWidth(bool Vector) const;
271
272   /// \return The maximum unroll factor that the vectorizer should try to
273   /// perform for this target. This number depends on the level of parallelism
274   /// and the number of execution units in the CPU.
275   virtual unsigned getMaximumUnrollFactor() const;
276
277   /// \return The expected cost of arithmetic ops, such as mul, xor, fsub, etc.
278   virtual unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty) const;
279
280   /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
281   /// The index and subtype parameters are used by the subvector insertion and
282   /// extraction shuffle kinds.
283   virtual unsigned getShuffleCost(ShuffleKind Kind, Type *Tp, int Index = 0,
284                                   Type *SubTp = 0) const;
285
286   /// \return The expected cost of cast instructions, such as bitcast, trunc,
287   /// zext, etc.
288   virtual unsigned getCastInstrCost(unsigned Opcode, Type *Dst,
289                                     Type *Src) const;
290
291   /// \return The expected cost of control-flow related instrutctions such as
292   /// Phi, Ret, Br.
293   virtual unsigned getCFInstrCost(unsigned Opcode) const;
294
295   /// \returns The expected cost of compare and select instructions.
296   virtual unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
297                                       Type *CondTy = 0) const;
298
299   /// \return The expected cost of vector Insert and Extract.
300   /// Use -1 to indicate that there is no information on the index value.
301   virtual unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
302                                       unsigned Index = -1) const;
303
304   /// \return The cost of Load and Store instructions.
305   virtual unsigned getMemoryOpCost(unsigned Opcode, Type *Src,
306                                    unsigned Alignment,
307                                    unsigned AddressSpace) const;
308
309   /// \returns The cost of Intrinsic instructions.
310   virtual unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
311                                          ArrayRef<Type *> Tys) const;
312
313   /// \returns The number of pieces into which the provided type must be
314   /// split during legalization. Zero is returned when the answer is unknown.
315   virtual unsigned getNumberOfParts(Type *Tp) const;
316
317   /// @}
318
319   /// Analysis group identification.
320   static char ID;
321 };
322
323 /// \brief Create the base case instance of a pass in the TTI analysis group.
324 ///
325 /// This class provides the base case for the stack of TTI analyses. It doesn't
326 /// delegate to anything and uses the STTI and VTTI objects passed in to
327 /// satisfy the queries.
328 ImmutablePass *createNoTargetTransformInfoPass();
329
330 } // End llvm namespace
331
332 #endif