1 //===- 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/ADT/Optional.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/DataTypes.h"
37 class PreservedAnalyses;
42 /// \brief Information about a load/store intrinsic defined by the target.
43 struct MemIntrinsicInfo {
45 : ReadMem(false), WriteMem(false), Vol(false), MatchingId(0),
46 NumMemRefs(0), PtrVal(nullptr) {}
50 // Same Id is set by the target for corresponding load/store intrinsics.
51 unsigned short MatchingId;
56 /// \brief This pass provides access to the codegen interfaces that are needed
57 /// for IR-level transformations.
58 class TargetTransformInfo {
60 /// \brief Construct a TTI object using a type implementing the \c Concept
63 /// This is used by targets to construct a TTI wrapping their target-specific
64 /// implementaion that encodes appropriate costs for their target.
65 template <typename T> TargetTransformInfo(T Impl);
67 /// \brief Construct a baseline TTI object using a minimal implementation of
68 /// the \c Concept API below.
70 /// The TTI implementation will reflect the information in the DataLayout
71 /// provided if non-null.
72 explicit TargetTransformInfo(const DataLayout *DL);
74 // Provide move semantics.
75 TargetTransformInfo(TargetTransformInfo &&Arg);
76 TargetTransformInfo &operator=(TargetTransformInfo &&RHS);
78 // We need to define the destructor out-of-line to define our sub-classes
80 ~TargetTransformInfo();
82 /// \brief Handle the invalidation of this information.
84 /// When used as a result of \c TargetIRAnalysis this method will be called
85 /// when the function this was computed for changes. When it returns false,
86 /// the information is preserved across those changes.
87 bool invalidate(Function &, const PreservedAnalyses &) {
88 // FIXME: We should probably in some way ensure that the subtarget
89 // information for a function hasn't changed.
93 /// \name Generic Target Information
96 /// \brief Underlying constants for 'cost' values in this interface.
98 /// Many APIs in this interface return a cost. This enum defines the
99 /// fundamental values that should be used to interpret (and produce) those
100 /// costs. The costs are returned as an unsigned rather than a member of this
101 /// enumeration because it is expected that the cost of one IR instruction
102 /// may have a multiplicative factor to it or otherwise won't fit directly
103 /// into the enum. Moreover, it is common to sum or average costs which works
104 /// better as simple integral values. Thus this enum only provides constants.
106 /// Note that these costs should usually reflect the intersection of code-size
107 /// cost and execution cost. A free instruction is typically one that folds
108 /// into another instruction. For example, reg-to-reg moves can often be
109 /// skipped by renaming the registers in the CPU, but they still are encoded
110 /// and thus wouldn't be considered 'free' here.
111 enum TargetCostConstants {
112 TCC_Free = 0, ///< Expected to fold away in lowering.
113 TCC_Basic = 1, ///< The cost of a typical 'add' instruction.
114 TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
117 /// \brief Estimate the cost of a specific operation when lowered.
119 /// Note that this is designed to work on an arbitrary synthetic opcode, and
120 /// thus work for hypothetical queries before an instruction has even been
121 /// formed. However, this does *not* work for GEPs, and must not be called
122 /// for a GEP instruction. Instead, use the dedicated getGEPCost interface as
123 /// analyzing a GEP's cost required more information.
125 /// Typically only the result type is required, and the operand type can be
126 /// omitted. However, if the opcode is one of the cast instructions, the
127 /// operand type is required.
129 /// The returned cost is defined in terms of \c TargetCostConstants, see its
130 /// comments for a detailed explanation of the cost values.
131 unsigned getOperationCost(unsigned Opcode, Type *Ty,
132 Type *OpTy = nullptr) const;
134 /// \brief Estimate the cost of a GEP operation when lowered.
136 /// The contract for this function is the same as \c getOperationCost except
137 /// that it supports an interface that provides extra information specific to
138 /// the GEP operation.
139 unsigned getGEPCost(const Value *Ptr, ArrayRef<const Value *> Operands) const;
141 /// \brief Estimate the cost of a function call when lowered.
143 /// The contract for this is the same as \c getOperationCost except that it
144 /// supports an interface that provides extra information specific to call
147 /// This is the most basic query for estimating call cost: it only knows the
148 /// function type and (potentially) the number of arguments at the call site.
149 /// The latter is only interesting for varargs function types.
150 unsigned getCallCost(FunctionType *FTy, int NumArgs = -1) const;
152 /// \brief Estimate the cost of calling a specific function when lowered.
154 /// This overload adds the ability to reason about the particular function
155 /// being called in the event it is a library call with special lowering.
156 unsigned getCallCost(const Function *F, int NumArgs = -1) const;
158 /// \brief Estimate the cost of calling a specific function when lowered.
160 /// This overload allows specifying a set of candidate argument values.
161 unsigned getCallCost(const Function *F,
162 ArrayRef<const Value *> Arguments) const;
164 /// \brief Estimate the cost of an intrinsic when lowered.
166 /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
167 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
168 ArrayRef<Type *> ParamTys) const;
170 /// \brief Estimate the cost of an intrinsic when lowered.
172 /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
173 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
174 ArrayRef<const Value *> Arguments) const;
176 /// \brief Estimate the cost of a given IR user when lowered.
178 /// This can estimate the cost of either a ConstantExpr or Instruction when
179 /// lowered. It has two primary advantages over the \c getOperationCost and
180 /// \c getGEPCost above, and one significant disadvantage: it can only be
181 /// used when the IR construct has already been formed.
183 /// The advantages are that it can inspect the SSA use graph to reason more
184 /// accurately about the cost. For example, all-constant-GEPs can often be
185 /// folded into a load or other instruction, but if they are used in some
186 /// other context they may not be folded. This routine can distinguish such
189 /// The returned cost is defined in terms of \c TargetCostConstants, see its
190 /// comments for a detailed explanation of the cost values.
191 unsigned getUserCost(const User *U) const;
193 /// \brief hasBranchDivergence - Return true if branch divergence exists.
194 /// Branch divergence has a significantly negative impact on GPU performance
195 /// when threads in the same wavefront take different paths due to conditional
197 bool hasBranchDivergence() const;
199 /// \brief Test whether calls to a function lower to actual program function
202 /// The idea is to test whether the program is likely to require a 'call'
203 /// instruction or equivalent in order to call the given function.
205 /// FIXME: It's not clear that this is a good or useful query API. Client's
206 /// should probably move to simpler cost metrics using the above.
207 /// Alternatively, we could split the cost interface into distinct code-size
208 /// and execution-speed costs. This would allow modelling the core of this
209 /// query more accurately as a call is a single small instruction, but
210 /// incurs significant execution cost.
211 bool isLoweredToCall(const Function *F) const;
213 /// Parameters that control the generic loop unrolling transformation.
214 struct UnrollingPreferences {
215 /// The cost threshold for the unrolled loop, compared to
216 /// CodeMetrics.NumInsts aggregated over all basic blocks in the loop body.
217 /// The unrolling factor is set such that the unrolled loop body does not
218 /// exceed this cost. Set this to UINT_MAX to disable the loop body cost
221 /// If complete unrolling could help other optimizations (e.g. InstSimplify)
222 /// to remove N% of instructions, then we can go beyond unroll threshold.
223 /// This value set the minimal percent for allowing that.
224 unsigned MinPercentOfOptimized;
225 /// The absolute cost threshold. We won't go beyond this even if complete
226 /// unrolling could result in optimizing out 90% of instructions.
227 unsigned AbsoluteThreshold;
228 /// The cost threshold for the unrolled loop when optimizing for size (set
229 /// to UINT_MAX to disable).
230 unsigned OptSizeThreshold;
231 /// The cost threshold for the unrolled loop, like Threshold, but used
232 /// for partial/runtime unrolling (set to UINT_MAX to disable).
233 unsigned PartialThreshold;
234 /// The cost threshold for the unrolled loop when optimizing for size, like
235 /// OptSizeThreshold, but used for partial/runtime unrolling (set to
236 /// UINT_MAX to disable).
237 unsigned PartialOptSizeThreshold;
238 /// A forced unrolling factor (the number of concatenated bodies of the
239 /// original loop in the unrolled loop body). When set to 0, the unrolling
240 /// transformation will select an unrolling factor based on the current cost
241 /// threshold and other factors.
243 // Set the maximum unrolling factor. The unrolling factor may be selected
244 // using the appropriate cost threshold, but may not exceed this number
245 // (set to UINT_MAX to disable). This does not apply in cases where the
246 // loop is being fully unrolled.
248 /// Allow partial unrolling (unrolling of loops to expand the size of the
249 /// loop body, not only to eliminate small constant-trip-count loops).
251 /// Allow runtime unrolling (unrolling of loops to expand the size of the
252 /// loop body even when the number of loop iterations is not known at
257 /// \brief Get target-customized preferences for the generic loop unrolling
258 /// transformation. The caller will initialize UP with the current
259 /// target-independent defaults.
260 void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) const;
264 /// \name Scalar Target Information
267 /// \brief Flags indicating the kind of support for population count.
269 /// Compared to the SW implementation, HW support is supposed to
270 /// significantly boost the performance when the population is dense, and it
271 /// may or may not degrade performance if the population is sparse. A HW
272 /// support is considered as "Fast" if it can outperform, or is on a par
273 /// with, SW implementation when the population is sparse; otherwise, it is
274 /// considered as "Slow".
275 enum PopcntSupportKind { PSK_Software, PSK_SlowHardware, PSK_FastHardware };
277 /// \brief Return true if the specified immediate is legal add immediate, that
278 /// is the target has add instructions which can add a register with the
279 /// immediate without having to materialize the immediate into a register.
280 bool isLegalAddImmediate(int64_t Imm) const;
282 /// \brief Return true if the specified immediate is legal icmp immediate,
283 /// that is the target has icmp instructions which can compare a register
284 /// against the immediate without having to materialize the immediate into a
286 bool isLegalICmpImmediate(int64_t Imm) const;
288 /// \brief Return true if the addressing mode represented by AM is legal for
289 /// this target, for a load/store of the specified type.
290 /// The type may be VoidTy, in which case only return true if the addressing
291 /// mode is legal for a load/store of any legal type.
292 /// TODO: Handle pre/postinc as well.
293 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
294 bool HasBaseReg, int64_t Scale) const;
296 /// \brief Return true if the target works with masked instruction
297 /// AVX2 allows masks for consecutive load and store for i32 and i64 elements.
298 /// AVX-512 architecture will also allow masks for non-consecutive memory
300 bool isLegalMaskedStore(Type *DataType, int Consecutive) const;
301 bool isLegalMaskedLoad(Type *DataType, int Consecutive) const;
303 /// \brief Return the cost of the scaling factor used in the addressing
304 /// mode represented by AM for this target, for a load/store
305 /// of the specified type.
306 /// If the AM is supported, the return value must be >= 0.
307 /// If the AM is not supported, it returns a negative value.
308 /// TODO: Handle pre/postinc as well.
309 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
310 bool HasBaseReg, int64_t Scale) const;
312 /// \brief Return true if it's free to truncate a value of type Ty1 to type
313 /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
314 /// by referencing its sub-register AX.
315 bool isTruncateFree(Type *Ty1, Type *Ty2) const;
317 /// \brief Return true if it is profitable to hoist instruction in the
318 /// then/else to before if.
319 bool isProfitableToHoist(Instruction *I) const;
321 /// \brief Return true if this type is legal.
322 bool isTypeLegal(Type *Ty) const;
324 /// \brief Returns the target's jmp_buf alignment in bytes.
325 unsigned getJumpBufAlignment() const;
327 /// \brief Returns the target's jmp_buf size in bytes.
328 unsigned getJumpBufSize() const;
330 /// \brief Return true if switches should be turned into lookup tables for the
332 bool shouldBuildLookupTables() const;
334 /// \brief Don't restrict interleaved unrolling to small loops.
335 bool enableAggressiveInterleaving(bool LoopHasReductions) const;
337 /// \brief Return hardware support for population count.
338 PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
340 /// \brief Return true if the hardware has a fast square-root instruction.
341 bool haveFastSqrt(Type *Ty) const;
343 /// \brief Return the expected cost of supporting the floating point operation
344 /// of the specified type.
345 unsigned getFPOpCost(Type *Ty) const;
347 /// \brief Return the expected cost of materializing for the given integer
348 /// immediate of the specified type.
349 unsigned getIntImmCost(const APInt &Imm, Type *Ty) const;
351 /// \brief Return the expected cost of materialization for the given integer
352 /// immediate of the specified type for a given instruction. The cost can be
353 /// zero if the immediate can be folded into the specified instruction.
354 unsigned getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
356 unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
360 /// \name Vector Target Information
363 /// \brief The various kinds of shuffle patterns for vector queries.
365 SK_Broadcast, ///< Broadcast element 0 to all other elements.
366 SK_Reverse, ///< Reverse the order of the vector.
367 SK_Alternate, ///< Choose alternate elements from vector.
368 SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
369 SK_ExtractSubvector ///< ExtractSubvector Index indicates start offset.
372 /// \brief Additional information about an operand's possible values.
373 enum OperandValueKind {
374 OK_AnyValue, // Operand can have any value.
375 OK_UniformValue, // Operand is uniform (splat of a value).
376 OK_UniformConstantValue, // Operand is uniform constant.
377 OK_NonUniformConstantValue // Operand is a non uniform constant value.
380 /// \brief Additional properties of an operand's values.
381 enum OperandValueProperties { OP_None = 0, OP_PowerOf2 = 1 };
383 /// \return The number of scalar or vector registers that the target has.
384 /// If 'Vectors' is true, it returns the number of vector registers. If it is
385 /// set to false, it returns the number of scalar registers.
386 unsigned getNumberOfRegisters(bool Vector) const;
388 /// \return The width of the largest scalar or vector register type.
389 unsigned getRegisterBitWidth(bool Vector) const;
391 /// \return The maximum interleave factor that any transform should try to
392 /// perform for this target. This number depends on the level of parallelism
393 /// and the number of execution units in the CPU.
394 unsigned getMaxInterleaveFactor() const;
396 /// \return The expected cost of arithmetic ops, such as mul, xor, fsub, etc.
398 getArithmeticInstrCost(unsigned Opcode, Type *Ty,
399 OperandValueKind Opd1Info = OK_AnyValue,
400 OperandValueKind Opd2Info = OK_AnyValue,
401 OperandValueProperties Opd1PropInfo = OP_None,
402 OperandValueProperties Opd2PropInfo = OP_None) const;
404 /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
405 /// The index and subtype parameters are used by the subvector insertion and
406 /// extraction shuffle kinds.
407 unsigned getShuffleCost(ShuffleKind Kind, Type *Tp, int Index = 0,
408 Type *SubTp = nullptr) const;
410 /// \return The expected cost of cast instructions, such as bitcast, trunc,
412 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) const;
414 /// \return The expected cost of control-flow related instructions such as
416 unsigned getCFInstrCost(unsigned Opcode) const;
418 /// \returns The expected cost of compare and select instructions.
419 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
420 Type *CondTy = nullptr) const;
422 /// \return The expected cost of vector Insert and Extract.
423 /// Use -1 to indicate that there is no information on the index value.
424 unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
425 unsigned Index = -1) const;
427 /// \return The cost of Load and Store instructions.
428 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
429 unsigned AddressSpace) const;
431 /// \return The cost of masked Load and Store instructions.
432 unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
433 unsigned AddressSpace) const;
435 /// \brief Calculate the cost of performing a vector reduction.
437 /// This is the cost of reducing the vector value of type \p Ty to a scalar
438 /// value using the operation denoted by \p Opcode. The form of the reduction
439 /// can either be a pairwise reduction or a reduction that splits the vector
440 /// at every reduction level.
444 /// ((v0+v1), (v2, v3), undef, undef)
447 /// ((v0+v2), (v1+v3), undef, undef)
448 unsigned getReductionCost(unsigned Opcode, Type *Ty,
449 bool IsPairwiseForm) const;
451 /// \returns The cost of Intrinsic instructions.
452 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
453 ArrayRef<Type *> Tys) const;
455 /// \returns The cost of Call instructions.
456 unsigned getCallInstrCost(Function *F, Type *RetTy,
457 ArrayRef<Type *> Tys) const;
459 /// \returns The number of pieces into which the provided type must be
460 /// split during legalization. Zero is returned when the answer is unknown.
461 unsigned getNumberOfParts(Type *Tp) const;
463 /// \returns The cost of the address computation. For most targets this can be
464 /// merged into the instruction indexing mode. Some targets might want to
465 /// distinguish between address computation for memory operations on vector
466 /// types and scalar types. Such targets should override this function.
467 /// The 'IsComplex' parameter is a hint that the address computation is likely
468 /// to involve multiple instructions and as such unlikely to be merged into
469 /// the address indexing mode.
470 unsigned getAddressComputationCost(Type *Ty, bool IsComplex = false) const;
472 /// \returns The cost, if any, of keeping values of the given types alive
475 /// Some types may require the use of register classes that do not have
476 /// any callee-saved registers, so would require a spill and fill.
477 unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const;
479 /// \returns True if the intrinsic is a supported memory intrinsic. Info
480 /// will contain additional information - whether the intrinsic may write
481 /// or read to memory, volatility and the pointer. Info is undefined
482 /// if false is returned.
483 bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const;
485 /// \returns A value which is the result of the given memory intrinsic. New
486 /// instructions may be created to extract the result from the given intrinsic
487 /// memory operation. Returns nullptr if the target cannot create a result
488 /// from the given intrinsic.
489 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
490 Type *ExpectedType) const;
495 /// \brief The abstract base class used to type erase specific TTI
499 /// \brief The template model for the base class which wraps a concrete
500 /// implementation in a type erased interface.
501 template <typename T> class Model;
503 std::unique_ptr<Concept> TTIImpl;
506 class TargetTransformInfo::Concept {
508 virtual ~Concept() = 0;
510 virtual unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) = 0;
511 virtual unsigned getGEPCost(const Value *Ptr,
512 ArrayRef<const Value *> Operands) = 0;
513 virtual unsigned getCallCost(FunctionType *FTy, int NumArgs) = 0;
514 virtual unsigned getCallCost(const Function *F, int NumArgs) = 0;
515 virtual unsigned getCallCost(const Function *F,
516 ArrayRef<const Value *> Arguments) = 0;
517 virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
518 ArrayRef<Type *> ParamTys) = 0;
519 virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
520 ArrayRef<const Value *> Arguments) = 0;
521 virtual unsigned getUserCost(const User *U) = 0;
522 virtual bool hasBranchDivergence() = 0;
523 virtual bool isLoweredToCall(const Function *F) = 0;
524 virtual void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) = 0;
525 virtual bool isLegalAddImmediate(int64_t Imm) = 0;
526 virtual bool isLegalICmpImmediate(int64_t Imm) = 0;
527 virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
528 int64_t BaseOffset, bool HasBaseReg,
530 virtual bool isLegalMaskedStore(Type *DataType, int Consecutive) = 0;
531 virtual bool isLegalMaskedLoad(Type *DataType, int Consecutive) = 0;
532 virtual int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
533 int64_t BaseOffset, bool HasBaseReg,
535 virtual bool isTruncateFree(Type *Ty1, Type *Ty2) = 0;
536 virtual bool isProfitableToHoist(Instruction *I) = 0;
537 virtual bool isTypeLegal(Type *Ty) = 0;
538 virtual unsigned getJumpBufAlignment() = 0;
539 virtual unsigned getJumpBufSize() = 0;
540 virtual bool shouldBuildLookupTables() = 0;
541 virtual bool enableAggressiveInterleaving(bool LoopHasReductions) = 0;
542 virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) = 0;
543 virtual bool haveFastSqrt(Type *Ty) = 0;
544 virtual unsigned getFPOpCost(Type *Ty) = 0;
545 virtual unsigned getIntImmCost(const APInt &Imm, Type *Ty) = 0;
546 virtual unsigned getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
548 virtual unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx,
549 const APInt &Imm, Type *Ty) = 0;
550 virtual unsigned getNumberOfRegisters(bool Vector) = 0;
551 virtual unsigned getRegisterBitWidth(bool Vector) = 0;
552 virtual unsigned getMaxInterleaveFactor() = 0;
554 getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
555 OperandValueKind Opd2Info,
556 OperandValueProperties Opd1PropInfo,
557 OperandValueProperties Opd2PropInfo) = 0;
558 virtual unsigned getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
560 virtual unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) = 0;
561 virtual unsigned getCFInstrCost(unsigned Opcode) = 0;
562 virtual unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
564 virtual unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
566 virtual unsigned getMemoryOpCost(unsigned Opcode, Type *Src,
568 unsigned AddressSpace) = 0;
569 virtual unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
571 unsigned AddressSpace) = 0;
572 virtual unsigned getReductionCost(unsigned Opcode, Type *Ty,
573 bool IsPairwiseForm) = 0;
574 virtual unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
575 ArrayRef<Type *> Tys) = 0;
576 virtual unsigned getCallInstrCost(Function *F, Type *RetTy,
577 ArrayRef<Type *> Tys) = 0;
578 virtual unsigned getNumberOfParts(Type *Tp) = 0;
579 virtual unsigned getAddressComputationCost(Type *Ty, bool IsComplex) = 0;
580 virtual unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) = 0;
581 virtual bool getTgtMemIntrinsic(IntrinsicInst *Inst,
582 MemIntrinsicInfo &Info) = 0;
583 virtual Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
584 Type *ExpectedType) = 0;
587 template <typename T>
588 class TargetTransformInfo::Model final : public TargetTransformInfo::Concept {
592 Model(T Impl) : Impl(std::move(Impl)) {}
595 unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) override {
596 return Impl.getOperationCost(Opcode, Ty, OpTy);
598 unsigned getGEPCost(const Value *Ptr,
599 ArrayRef<const Value *> Operands) override {
600 return Impl.getGEPCost(Ptr, Operands);
602 unsigned getCallCost(FunctionType *FTy, int NumArgs) override {
603 return Impl.getCallCost(FTy, NumArgs);
605 unsigned getCallCost(const Function *F, int NumArgs) override {
606 return Impl.getCallCost(F, NumArgs);
608 unsigned getCallCost(const Function *F,
609 ArrayRef<const Value *> Arguments) override {
610 return Impl.getCallCost(F, Arguments);
612 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
613 ArrayRef<Type *> ParamTys) override {
614 return Impl.getIntrinsicCost(IID, RetTy, ParamTys);
616 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
617 ArrayRef<const Value *> Arguments) override {
618 return Impl.getIntrinsicCost(IID, RetTy, Arguments);
620 unsigned getUserCost(const User *U) override { return Impl.getUserCost(U); }
621 bool hasBranchDivergence() override { return Impl.hasBranchDivergence(); }
622 bool isLoweredToCall(const Function *F) override {
623 return Impl.isLoweredToCall(F);
625 void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) override {
626 return Impl.getUnrollingPreferences(L, UP);
628 bool isLegalAddImmediate(int64_t Imm) override {
629 return Impl.isLegalAddImmediate(Imm);
631 bool isLegalICmpImmediate(int64_t Imm) override {
632 return Impl.isLegalICmpImmediate(Imm);
634 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
635 bool HasBaseReg, int64_t Scale) override {
636 return Impl.isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
639 bool isLegalMaskedStore(Type *DataType, int Consecutive) override {
640 return Impl.isLegalMaskedStore(DataType, Consecutive);
642 bool isLegalMaskedLoad(Type *DataType, int Consecutive) override {
643 return Impl.isLegalMaskedLoad(DataType, Consecutive);
645 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
646 bool HasBaseReg, int64_t Scale) override {
647 return Impl.getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg, Scale);
649 bool isTruncateFree(Type *Ty1, Type *Ty2) override {
650 return Impl.isTruncateFree(Ty1, Ty2);
652 bool isProfitableToHoist(Instruction *I) override {
653 return Impl.isProfitableToHoist(I);
655 bool isTypeLegal(Type *Ty) override { return Impl.isTypeLegal(Ty); }
656 unsigned getJumpBufAlignment() override { return Impl.getJumpBufAlignment(); }
657 unsigned getJumpBufSize() override { return Impl.getJumpBufSize(); }
658 bool shouldBuildLookupTables() override {
659 return Impl.shouldBuildLookupTables();
661 bool enableAggressiveInterleaving(bool LoopHasReductions) override {
662 return Impl.enableAggressiveInterleaving(LoopHasReductions);
664 PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) override {
665 return Impl.getPopcntSupport(IntTyWidthInBit);
667 bool haveFastSqrt(Type *Ty) override { return Impl.haveFastSqrt(Ty); }
669 unsigned getFPOpCost(Type *Ty) override {
670 return Impl.getFPOpCost(Ty);
673 unsigned getIntImmCost(const APInt &Imm, Type *Ty) override {
674 return Impl.getIntImmCost(Imm, Ty);
676 unsigned getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
678 return Impl.getIntImmCost(Opc, Idx, Imm, Ty);
680 unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
682 return Impl.getIntImmCost(IID, Idx, Imm, Ty);
684 unsigned getNumberOfRegisters(bool Vector) override {
685 return Impl.getNumberOfRegisters(Vector);
687 unsigned getRegisterBitWidth(bool Vector) override {
688 return Impl.getRegisterBitWidth(Vector);
690 unsigned getMaxInterleaveFactor() override {
691 return Impl.getMaxInterleaveFactor();
694 getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
695 OperandValueKind Opd2Info,
696 OperandValueProperties Opd1PropInfo,
697 OperandValueProperties Opd2PropInfo) override {
698 return Impl.getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
699 Opd1PropInfo, Opd2PropInfo);
701 unsigned getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
702 Type *SubTp) override {
703 return Impl.getShuffleCost(Kind, Tp, Index, SubTp);
705 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) override {
706 return Impl.getCastInstrCost(Opcode, Dst, Src);
708 unsigned getCFInstrCost(unsigned Opcode) override {
709 return Impl.getCFInstrCost(Opcode);
711 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
712 Type *CondTy) override {
713 return Impl.getCmpSelInstrCost(Opcode, ValTy, CondTy);
715 unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
716 unsigned Index) override {
717 return Impl.getVectorInstrCost(Opcode, Val, Index);
719 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
720 unsigned AddressSpace) override {
721 return Impl.getMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
723 unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
724 unsigned AddressSpace) override {
725 return Impl.getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
727 unsigned getReductionCost(unsigned Opcode, Type *Ty,
728 bool IsPairwiseForm) override {
729 return Impl.getReductionCost(Opcode, Ty, IsPairwiseForm);
731 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
732 ArrayRef<Type *> Tys) override {
733 return Impl.getIntrinsicInstrCost(ID, RetTy, Tys);
735 unsigned getCallInstrCost(Function *F, Type *RetTy,
736 ArrayRef<Type *> Tys) override {
737 return Impl.getCallInstrCost(F, RetTy, Tys);
739 unsigned getNumberOfParts(Type *Tp) override {
740 return Impl.getNumberOfParts(Tp);
742 unsigned getAddressComputationCost(Type *Ty, bool IsComplex) override {
743 return Impl.getAddressComputationCost(Ty, IsComplex);
745 unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) override {
746 return Impl.getCostOfKeepingLiveOverCall(Tys);
748 bool getTgtMemIntrinsic(IntrinsicInst *Inst,
749 MemIntrinsicInfo &Info) override {
750 return Impl.getTgtMemIntrinsic(Inst, Info);
752 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
753 Type *ExpectedType) override {
754 return Impl.getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
758 template <typename T>
759 TargetTransformInfo::TargetTransformInfo(T Impl)
760 : TTIImpl(new Model<T>(Impl)) {}
762 /// \brief Analysis pass providing the \c TargetTransformInfo.
764 /// The core idea of the TargetIRAnalysis is to expose an interface through
765 /// which LLVM targets can analyze and provide information about the middle
766 /// end's target-independent IR. This supports use cases such as target-aware
767 /// cost modeling of IR constructs.
769 /// This is a function analysis because much of the cost modeling for targets
770 /// is done in a subtarget specific way and LLVM supports compiling different
771 /// functions targeting different subtargets in order to support runtime
772 /// dispatch according to the observed subtarget.
773 class TargetIRAnalysis {
775 typedef TargetTransformInfo Result;
777 /// \brief Opaque, unique identifier for this analysis pass.
778 static void *ID() { return (void *)&PassID; }
780 /// \brief Provide access to a name for this pass for debugging purposes.
781 static StringRef name() { return "TargetIRAnalysis"; }
783 /// \brief Default construct a target IR analysis.
785 /// This will use the module's datalayout to construct a baseline
786 /// conservative TTI result.
789 /// \brief Construct an IR analysis pass around a target-provide callback.
791 /// The callback will be called with a particular function for which the TTI
792 /// is needed and must return a TTI object for that function.
793 TargetIRAnalysis(std::function<Result(Function &)> TTICallback);
795 // Value semantics. We spell out the constructors for MSVC.
796 TargetIRAnalysis(const TargetIRAnalysis &Arg)
797 : TTICallback(Arg.TTICallback) {}
798 TargetIRAnalysis(TargetIRAnalysis &&Arg)
799 : TTICallback(std::move(Arg.TTICallback)) {}
800 TargetIRAnalysis &operator=(const TargetIRAnalysis &RHS) {
801 TTICallback = RHS.TTICallback;
804 TargetIRAnalysis &operator=(TargetIRAnalysis &&RHS) {
805 TTICallback = std::move(RHS.TTICallback);
809 Result run(Function &F);
814 /// \brief The callback used to produce a result.
816 /// We use a completely opaque callback so that targets can provide whatever
817 /// mechanism they desire for constructing the TTI for a given function.
819 /// FIXME: Should we really use std::function? It's relatively inefficient.
820 /// It might be possible to arrange for even stateful callbacks to outlive
821 /// the analysis and thus use a function_ref which would be lighter weight.
822 /// This may also be less error prone as the callback is likely to reference
823 /// the external TargetMachine, and that reference needs to never dangle.
824 std::function<Result(Function &)> TTICallback;
826 /// \brief Helper function used as the callback in the default constructor.
827 static Result getDefaultTTI(Function &F);
830 /// \brief Wrapper pass for TargetTransformInfo.
832 /// This pass can be constructed from a TTI object which it stores internally
833 /// and is queried by passes.
834 class TargetTransformInfoWrapperPass : public ImmutablePass {
835 TargetIRAnalysis TIRA;
836 Optional<TargetTransformInfo> TTI;
838 virtual void anchor();
843 /// \brief We must provide a default constructor for the pass but it should
846 /// Use the constructor below or call one of the creation routines.
847 TargetTransformInfoWrapperPass();
849 explicit TargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
851 TargetTransformInfo &getTTI(Function &F);
854 /// \brief Create an analysis pass wrapper around a TTI object.
856 /// This analysis pass just holds the TTI instance and makes it available to
858 ImmutablePass *createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
860 } // End llvm namespace