1 //===- llvm/Analysis/TargetTransformInfo.h ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
15 // 3. Codegen-level implementation which uses target-specific hooks.
17 // This file defines #2, which is the interface that IR-level transformations
18 // use for querying the codegen.
20 //===----------------------------------------------------------------------===//
22 #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
23 #define LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/DataTypes.h"
37 /// TargetTransformInfo - This pass provides access to the codegen
38 /// interfaces that are needed for IR-level transformations.
39 class TargetTransformInfo {
41 /// \brief The TTI instance one level down the stack.
43 /// This is used to implement the default behavior all of the methods which
44 /// is to delegate up through the stack of TTIs until one can answer the
46 TargetTransformInfo *PrevTTI;
48 /// \brief The top of the stack of TTI analyses available.
50 /// This is a convenience routine maintained as TTI analyses become available
51 /// that complements the PrevTTI delegation chain. When one part of an
52 /// analysis pass wants to query another part of the analysis pass it can use
53 /// this to start back at the top of the stack.
54 TargetTransformInfo *TopTTI;
56 /// All pass subclasses must in their initializePass routine call
57 /// pushTTIStack with themselves to update the pointers tracking the previous
58 /// TTI instance in the analysis group's stack, and the top of the analysis
60 void pushTTIStack(Pass *P);
62 /// All pass subclasses must in their finalizePass routine call popTTIStack
63 /// to update the pointers tracking the previous TTI instance in the analysis
64 /// group's stack, and the top of the analysis group's stack.
67 /// All pass subclasses must call TargetTransformInfo::getAnalysisUsage.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
71 /// This class is intended to be subclassed by real implementations.
72 virtual ~TargetTransformInfo() = 0;
74 /// \name Generic Target Information
77 /// \brief Underlying constants for 'cost' values in this interface.
79 /// Many APIs in this interface return a cost. This enum defines the
80 /// fundamental values that should be used to interpret (and produce) those
81 /// costs. The costs are returned as an unsigned rather than a member of this
82 /// enumeration because it is expected that the cost of one IR instruction
83 /// may have a multiplicative factor to it or otherwise won't fit directly
84 /// into the enum. Moreover, it is common to sum or average costs which works
85 /// better as simple integral values. Thus this enum only provides constants.
87 /// Note that these costs should usually reflect the intersection of code-size
88 /// cost and execution cost. A free instruction is typically one that folds
89 /// into another instruction. For example, reg-to-reg moves can often be
90 /// skipped by renaming the registers in the CPU, but they still are encoded
91 /// and thus wouldn't be considered 'free' here.
92 enum TargetCostConstants {
93 TCC_Free = 0, ///< Expected to fold away in lowering.
94 TCC_Basic = 1, ///< The cost of a typical 'add' instruction.
95 TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
98 /// \brief Estimate the cost of a specific operation when lowered.
100 /// Note that this is designed to work on an arbitrary synthetic opcode, and
101 /// thus work for hypothetical queries before an instruction has even been
102 /// formed. However, this does *not* work for GEPs, and must not be called
103 /// for a GEP instruction. Instead, use the dedicated getGEPCost interface as
104 /// analyzing a GEP's cost required more information.
106 /// Typically only the result type is required, and the operand type can be
107 /// omitted. However, if the opcode is one of the cast instructions, the
108 /// operand type is required.
110 /// The returned cost is defined in terms of \c TargetCostConstants, see its
111 /// comments for a detailed explanation of the cost values.
112 virtual unsigned getOperationCost(unsigned Opcode, Type *Ty,
113 Type *OpTy = 0) const;
115 /// \brief Estimate the cost of a GEP operation when lowered.
117 /// The contract for this function is the same as \c getOperationCost except
118 /// that it supports an interface that provides extra information specific to
119 /// the GEP operation.
120 virtual unsigned getGEPCost(const Value *Ptr,
121 ArrayRef<const Value *> Operands) const;
123 /// \brief Estimate the cost of a function call when lowered.
125 /// The contract for this is the same as \c getOperationCost except that it
126 /// supports an interface that provides extra information specific to call
129 /// This is the most basic query for estimating call cost: it only knows the
130 /// function type and (potentially) the number of arguments at the call site.
131 /// The latter is only interesting for varargs function types.
132 virtual unsigned getCallCost(FunctionType *FTy, int NumArgs = -1) const;
134 /// \brief Estimate the cost of calling a specific function when lowered.
136 /// This overload adds the ability to reason about the particular function
137 /// being called in the event it is a library call with special lowering.
138 virtual unsigned getCallCost(const Function *F, int NumArgs = -1) const;
140 /// \brief Estimate the cost of calling a specific function when lowered.
142 /// This overload allows specifying a set of candidate argument values.
143 virtual unsigned getCallCost(const Function *F,
144 ArrayRef<const Value *> Arguments) const;
146 /// \brief Estimate the cost of an intrinsic when lowered.
148 /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
149 virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
150 ArrayRef<Type *> ParamTys) const;
152 /// \brief Estimate the cost of an intrinsic when lowered.
154 /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
155 virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
156 ArrayRef<const Value *> Arguments) const;
158 /// \brief Estimate the cost of a given IR user when lowered.
160 /// This can estimate the cost of either a ConstantExpr or Instruction when
161 /// lowered. It has two primary advantages over the \c getOperationCost and
162 /// \c getGEPCost above, and one significant disadvantage: it can only be
163 /// used when the IR construct has already been formed.
165 /// The advantages are that it can inspect the SSA use graph to reason more
166 /// accurately about the cost. For example, all-constant-GEPs can often be
167 /// folded into a load or other instruction, but if they are used in some
168 /// other context they may not be folded. This routine can distinguish such
171 /// The returned cost is defined in terms of \c TargetCostConstants, see its
172 /// comments for a detailed explanation of the cost values.
173 virtual unsigned getUserCost(const User *U) const;
175 /// \brief hasBranchDivergence - Return true if branch divergence exists.
176 /// Branch divergence has a significantly negative impact on GPU performance
177 /// when threads in the same wavefront take different paths due to conditional
179 virtual bool hasBranchDivergence() const;
181 /// \brief Test whether calls to a function lower to actual program function
184 /// The idea is to test whether the program is likely to require a 'call'
185 /// instruction or equivalent in order to call the given function.
187 /// FIXME: It's not clear that this is a good or useful query API. Client's
188 /// should probably move to simpler cost metrics using the above.
189 /// Alternatively, we could split the cost interface into distinct code-size
190 /// and execution-speed costs. This would allow modelling the core of this
191 /// query more accurately as the a call is a single small instruction, but
192 /// incurs significant execution cost.
193 virtual bool isLoweredToCall(const Function *F) const;
195 /// Parameters that control the generic loop unrolling transformation.
196 struct UnrollingPreferences {
197 /// The cost threshold for the unrolled loop, compared to
198 /// CodeMetrics.NumInsts aggregated over all basic blocks in the loop body.
199 /// The unrolling factor is set such that the unrolled loop body does not
200 /// exceed this cost. Set this to UINT_MAX to disable the loop body cost
203 /// The cost threshold for the unrolled loop when optimizing for size (set
204 /// to UINT_MAX to disable).
205 unsigned OptSizeThreshold;
206 /// A forced unrolling factor (the number of concatenated bodies of the
207 /// original loop in the unrolled loop body). When set to 0, the unrolling
208 /// transformation will select an unrolling factor based on the current cost
209 /// threshold and other factors.
211 /// Allow partial unrolling (unrolling of loops to expand the size of the
212 /// loop body, not only to eliminate small constant-trip-count loops).
214 /// Allow runtime unrolling (unrolling of loops to expand the size of the
215 /// loop body even when the number of loop iterations is not known at compile
220 /// \brief Get target-customized preferences for the generic loop unrolling
221 /// transformation. The caller will initialize UP with the current
222 /// target-independent defaults.
223 virtual void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) const;
227 /// \name Scalar Target Information
230 /// \brief Flags indicating the kind of support for population count.
232 /// Compared to the SW implementation, HW support is supposed to
233 /// significantly boost the performance when the population is dense, and it
234 /// may or may not degrade performance if the population is sparse. A HW
235 /// support is considered as "Fast" if it can outperform, or is on a par
236 /// with, SW implementation when the population is sparse; otherwise, it is
237 /// considered as "Slow".
238 enum PopcntSupportKind {
244 /// \brief Return true if the specified immediate is legal add immediate, that
245 /// is the target has add instructions which can add a register with the
246 /// immediate without having to materialize the immediate into a register.
247 virtual bool isLegalAddImmediate(int64_t Imm) const;
249 /// \brief Return true if the specified immediate is legal icmp immediate,
250 /// that is the target has icmp instructions which can compare a register
251 /// against the immediate without having to materialize the immediate into a
253 virtual bool isLegalICmpImmediate(int64_t Imm) const;
255 /// \brief Return true if the addressing mode represented by AM is legal for
256 /// this target, for a load/store of the specified type.
257 /// The type may be VoidTy, in which case only return true if the addressing
258 /// mode is legal for a load/store of any legal type.
259 /// TODO: Handle pre/postinc as well.
260 virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
261 int64_t BaseOffset, bool HasBaseReg,
262 int64_t Scale) const;
264 /// \brief Return the cost of the scaling factor used in the addressing
265 /// mode represented by AM for this target, for a load/store
266 /// of the specified type.
267 /// If the AM is supported, the return value must be >= 0.
268 /// If the AM is not supported, it returns a negative value.
269 /// TODO: Handle pre/postinc as well.
270 virtual int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
271 int64_t BaseOffset, bool HasBaseReg,
272 int64_t Scale) const;
274 /// \brief Return true if it's free to truncate a value of type Ty1 to type
275 /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
276 /// by referencing its sub-register AX.
277 virtual bool isTruncateFree(Type *Ty1, Type *Ty2) const;
279 /// \brief Return true if this type is legal.
280 virtual bool isTypeLegal(Type *Ty) const;
282 /// \brief Returns the target's jmp_buf alignment in bytes.
283 virtual unsigned getJumpBufAlignment() const;
285 /// \brief Returns the target's jmp_buf size in bytes.
286 virtual unsigned getJumpBufSize() const;
288 /// \brief Return true if switches should be turned into lookup tables for the
290 virtual bool shouldBuildLookupTables() const;
292 /// \brief Return hardware support for population count.
293 virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
295 /// \brief Return true if the hardware has a fast square-root instruction.
296 virtual bool haveFastSqrt(Type *Ty) const;
298 /// \brief Return the expected cost of materializing for the given integer
299 /// immediate of the specified type.
300 virtual unsigned getIntImmCost(const APInt &Imm, Type *Ty) const;
304 /// \name Vector Target Information
307 /// \brief The various kinds of shuffle patterns for vector queries.
309 SK_Broadcast, ///< Broadcast element 0 to all other elements.
310 SK_Reverse, ///< Reverse the order of the vector.
311 SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
312 SK_ExtractSubvector ///< ExtractSubvector Index indicates start offset.
315 /// \brief Additional information about an operand's possible values.
316 enum OperandValueKind {
317 OK_AnyValue, // Operand can have any value.
318 OK_UniformValue, // Operand is uniform (splat of a value).
319 OK_UniformConstantValue // Operand is uniform constant.
322 /// \return The number of scalar or vector registers that the target has.
323 /// If 'Vectors' is true, it returns the number of vector registers. If it is
324 /// set to false, it returns the number of scalar registers.
325 virtual unsigned getNumberOfRegisters(bool Vector) const;
327 /// \return The width of the largest scalar or vector register type.
328 virtual unsigned getRegisterBitWidth(bool Vector) const;
330 /// \return The maximum unroll factor that the vectorizer should try to
331 /// perform for this target. This number depends on the level of parallelism
332 /// and the number of execution units in the CPU.
333 virtual unsigned getMaximumUnrollFactor() const;
335 /// \return The expected cost of arithmetic ops, such as mul, xor, fsub, etc.
336 virtual unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
337 OperandValueKind Opd1Info = OK_AnyValue,
338 OperandValueKind Opd2Info = OK_AnyValue) const;
340 /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
341 /// The index and subtype parameters are used by the subvector insertion and
342 /// extraction shuffle kinds.
343 virtual unsigned getShuffleCost(ShuffleKind Kind, Type *Tp, int Index = 0,
344 Type *SubTp = 0) const;
346 /// \return The expected cost of cast instructions, such as bitcast, trunc,
348 virtual unsigned getCastInstrCost(unsigned Opcode, Type *Dst,
351 /// \return The expected cost of control-flow related instructions such as
353 virtual unsigned getCFInstrCost(unsigned Opcode) const;
355 /// \returns The expected cost of compare and select instructions.
356 virtual unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
357 Type *CondTy = 0) const;
359 /// \return The expected cost of vector Insert and Extract.
360 /// Use -1 to indicate that there is no information on the index value.
361 virtual unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
362 unsigned Index = -1) const;
364 /// \return The cost of Load and Store instructions.
365 virtual unsigned getMemoryOpCost(unsigned Opcode, Type *Src,
367 unsigned AddressSpace) const;
369 /// \brief Calculate the cost of performing a vector reduction.
371 /// This is the cost of reducing the vector value of type \p Ty to a scalar
372 /// value using the operation denoted by \p Opcode. The form of the reduction
373 /// can either be a pairwise reduction or a reduction that splits the vector
374 /// at every reduction level.
378 /// ((v0+v1), (v2, v3), undef, undef)
381 /// ((v0+v2), (v1+v3), undef, undef)
382 virtual unsigned getReductionCost(unsigned Opcode, Type *Ty,
383 bool IsPairwiseForm) const;
385 /// \returns The cost of Intrinsic instructions.
386 virtual unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
387 ArrayRef<Type *> Tys) const;
389 /// \returns The number of pieces into which the provided type must be
390 /// split during legalization. Zero is returned when the answer is unknown.
391 virtual unsigned getNumberOfParts(Type *Tp) const;
393 /// \returns The cost of the address computation. For most targets this can be
394 /// merged into the instruction indexing mode. Some targets might want to
395 /// distinguish between address computation for memory operations on vector
396 /// types and scalar types. Such targets should override this function.
397 /// The 'IsComplex' parameter is a hint that the address computation is likely
398 /// to involve multiple instructions and as such unlikely to be merged into
399 /// the address indexing mode.
400 virtual unsigned getAddressComputationCost(Type *Ty,
401 bool IsComplex = false) const;
405 /// Analysis group identification.
409 /// \brief Create the base case instance of a pass in the TTI analysis group.
411 /// This class provides the base case for the stack of TTI analyzes. It doesn't
412 /// delegate to anything and uses the STTI and VTTI objects passed in to
413 /// satisfy the queries.
414 ImmutablePass *createNoTargetTransformInfoPass();
416 } // End llvm namespace