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"
36 class PreservedAnalyses;
41 /// \brief Information about a load/store intrinsic defined by the target.
42 struct MemIntrinsicInfo {
44 : ReadMem(false), WriteMem(false), Vol(false), MatchingId(0),
45 NumMemRefs(0), PtrVal(nullptr) {}
49 // Same Id is set by the target for corresponding load/store intrinsics.
50 unsigned short MatchingId;
55 /// \brief This pass provides access to the codegen interfaces that are needed
56 /// for IR-level transformations.
57 class TargetTransformInfo {
59 /// \brief Construct a TTI object using a type implementing the \c Concept
62 /// This is used by targets to construct a TTI wrapping their target-specific
63 /// implementaion that encodes appropriate costs for their target.
64 template <typename T> TargetTransformInfo(T Impl);
66 /// \brief Construct a baseline TTI object using a minimal implementation of
67 /// the \c Concept API below.
69 /// The TTI implementation will reflect the information in the DataLayout
70 /// provided if non-null.
71 explicit TargetTransformInfo(const DataLayout *DL);
73 // Provide move semantics.
74 TargetTransformInfo(TargetTransformInfo &&Arg);
75 TargetTransformInfo &operator=(TargetTransformInfo &&RHS);
77 // We need to define the destructor out-of-line to define our sub-classes
79 ~TargetTransformInfo();
81 /// \brief Handle the invalidation of this information.
83 /// When used as a result of \c TargetIRAnalysis this method will be called
84 /// when the function this was computed for changes. When it returns false,
85 /// the information is preserved across those changes.
86 bool invalidate(Function &, const PreservedAnalyses &) {
87 // FIXME: We should probably in some way ensure that the subtarget
88 // information for a function hasn't changed.
92 /// \name Generic Target Information
95 /// \brief Underlying constants for 'cost' values in this interface.
97 /// Many APIs in this interface return a cost. This enum defines the
98 /// fundamental values that should be used to interpret (and produce) those
99 /// costs. The costs are returned as an unsigned rather than a member of this
100 /// enumeration because it is expected that the cost of one IR instruction
101 /// may have a multiplicative factor to it or otherwise won't fit directly
102 /// into the enum. Moreover, it is common to sum or average costs which works
103 /// better as simple integral values. Thus this enum only provides constants.
105 /// Note that these costs should usually reflect the intersection of code-size
106 /// cost and execution cost. A free instruction is typically one that folds
107 /// into another instruction. For example, reg-to-reg moves can often be
108 /// skipped by renaming the registers in the CPU, but they still are encoded
109 /// and thus wouldn't be considered 'free' here.
110 enum TargetCostConstants {
111 TCC_Free = 0, ///< Expected to fold away in lowering.
112 TCC_Basic = 1, ///< The cost of a typical 'add' instruction.
113 TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
116 /// \brief Estimate the cost of a specific operation when lowered.
118 /// Note that this is designed to work on an arbitrary synthetic opcode, and
119 /// thus work for hypothetical queries before an instruction has even been
120 /// formed. However, this does *not* work for GEPs, and must not be called
121 /// for a GEP instruction. Instead, use the dedicated getGEPCost interface as
122 /// analyzing a GEP's cost required more information.
124 /// Typically only the result type is required, and the operand type can be
125 /// omitted. However, if the opcode is one of the cast instructions, the
126 /// operand type is required.
128 /// The returned cost is defined in terms of \c TargetCostConstants, see its
129 /// comments for a detailed explanation of the cost values.
130 unsigned getOperationCost(unsigned Opcode, Type *Ty,
131 Type *OpTy = nullptr) const;
133 /// \brief Estimate the cost of a GEP operation when lowered.
135 /// The contract for this function is the same as \c getOperationCost except
136 /// that it supports an interface that provides extra information specific to
137 /// the GEP operation.
138 unsigned getGEPCost(const Value *Ptr, ArrayRef<const Value *> Operands) const;
140 /// \brief Estimate the cost of a function call when lowered.
142 /// The contract for this is the same as \c getOperationCost except that it
143 /// supports an interface that provides extra information specific to call
146 /// This is the most basic query for estimating call cost: it only knows the
147 /// function type and (potentially) the number of arguments at the call site.
148 /// The latter is only interesting for varargs function types.
149 unsigned getCallCost(FunctionType *FTy, int NumArgs = -1) const;
151 /// \brief Estimate the cost of calling a specific function when lowered.
153 /// This overload adds the ability to reason about the particular function
154 /// being called in the event it is a library call with special lowering.
155 unsigned getCallCost(const Function *F, int NumArgs = -1) const;
157 /// \brief Estimate the cost of calling a specific function when lowered.
159 /// This overload allows specifying a set of candidate argument values.
160 unsigned getCallCost(const Function *F,
161 ArrayRef<const Value *> Arguments) const;
163 /// \brief Estimate the cost of an intrinsic when lowered.
165 /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
166 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
167 ArrayRef<Type *> ParamTys) const;
169 /// \brief Estimate the cost of an intrinsic when lowered.
171 /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
172 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
173 ArrayRef<const Value *> Arguments) const;
175 /// \brief Estimate the cost of a given IR user when lowered.
177 /// This can estimate the cost of either a ConstantExpr or Instruction when
178 /// lowered. It has two primary advantages over the \c getOperationCost and
179 /// \c getGEPCost above, and one significant disadvantage: it can only be
180 /// used when the IR construct has already been formed.
182 /// The advantages are that it can inspect the SSA use graph to reason more
183 /// accurately about the cost. For example, all-constant-GEPs can often be
184 /// folded into a load or other instruction, but if they are used in some
185 /// other context they may not be folded. This routine can distinguish such
188 /// The returned cost is defined in terms of \c TargetCostConstants, see its
189 /// comments for a detailed explanation of the cost values.
190 unsigned getUserCost(const User *U) const;
192 /// \brief hasBranchDivergence - Return true if branch divergence exists.
193 /// Branch divergence has a significantly negative impact on GPU performance
194 /// when threads in the same wavefront take different paths due to conditional
196 bool hasBranchDivergence() const;
198 /// \brief Test whether calls to a function lower to actual program function
201 /// The idea is to test whether the program is likely to require a 'call'
202 /// instruction or equivalent in order to call the given function.
204 /// FIXME: It's not clear that this is a good or useful query API. Client's
205 /// should probably move to simpler cost metrics using the above.
206 /// Alternatively, we could split the cost interface into distinct code-size
207 /// and execution-speed costs. This would allow modelling the core of this
208 /// query more accurately as a call is a single small instruction, but
209 /// incurs significant execution cost.
210 bool isLoweredToCall(const Function *F) const;
212 /// Parameters that control the generic loop unrolling transformation.
213 struct UnrollingPreferences {
214 /// The cost threshold for the unrolled loop, compared to
215 /// CodeMetrics.NumInsts aggregated over all basic blocks in the loop body.
216 /// The unrolling factor is set such that the unrolled loop body does not
217 /// exceed this cost. Set this to UINT_MAX to disable the loop body cost
220 /// If complete unrolling could help other optimizations (e.g. InstSimplify)
221 /// to remove N% of instructions, then we can go beyond unroll threshold.
222 /// This value set the minimal percent for allowing that.
223 unsigned MinPercentOfOptimized;
224 /// The absolute cost threshold. We won't go beyond this even if complete
225 /// unrolling could result in optimizing out 90% of instructions.
226 unsigned AbsoluteThreshold;
227 /// The cost threshold for the unrolled loop when optimizing for size (set
228 /// to UINT_MAX to disable).
229 unsigned OptSizeThreshold;
230 /// The cost threshold for the unrolled loop, like Threshold, but used
231 /// for partial/runtime unrolling (set to UINT_MAX to disable).
232 unsigned PartialThreshold;
233 /// The cost threshold for the unrolled loop when optimizing for size, like
234 /// OptSizeThreshold, but used for partial/runtime unrolling (set to
235 /// UINT_MAX to disable).
236 unsigned PartialOptSizeThreshold;
237 /// A forced unrolling factor (the number of concatenated bodies of the
238 /// original loop in the unrolled loop body). When set to 0, the unrolling
239 /// transformation will select an unrolling factor based on the current cost
240 /// threshold and other factors.
242 // Set the maximum unrolling factor. The unrolling factor may be selected
243 // using the appropriate cost threshold, but may not exceed this number
244 // (set to UINT_MAX to disable). This does not apply in cases where the
245 // loop is being fully unrolled.
247 /// Allow partial unrolling (unrolling of loops to expand the size of the
248 /// loop body, not only to eliminate small constant-trip-count loops).
250 /// Allow runtime unrolling (unrolling of loops to expand the size of the
251 /// loop body even when the number of loop iterations is not known at
256 /// \brief Get target-customized preferences for the generic loop unrolling
257 /// transformation. The caller will initialize UP with the current
258 /// target-independent defaults.
259 void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) const;
263 /// \name Scalar Target Information
266 /// \brief Flags indicating the kind of support for population count.
268 /// Compared to the SW implementation, HW support is supposed to
269 /// significantly boost the performance when the population is dense, and it
270 /// may or may not degrade performance if the population is sparse. A HW
271 /// support is considered as "Fast" if it can outperform, or is on a par
272 /// with, SW implementation when the population is sparse; otherwise, it is
273 /// considered as "Slow".
274 enum PopcntSupportKind { PSK_Software, PSK_SlowHardware, PSK_FastHardware };
276 /// \brief Return true if the specified immediate is legal add immediate, that
277 /// is the target has add instructions which can add a register with the
278 /// immediate without having to materialize the immediate into a register.
279 bool isLegalAddImmediate(int64_t Imm) const;
281 /// \brief Return true if the specified immediate is legal icmp immediate,
282 /// that is the target has icmp instructions which can compare a register
283 /// against the immediate without having to materialize the immediate into a
285 bool isLegalICmpImmediate(int64_t Imm) const;
287 /// \brief Return true if the addressing mode represented by AM is legal for
288 /// this target, for a load/store of the specified type.
289 /// The type may be VoidTy, in which case only return true if the addressing
290 /// mode is legal for a load/store of any legal type.
291 /// TODO: Handle pre/postinc as well.
292 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
293 bool HasBaseReg, int64_t Scale) const;
295 /// \brief Return true if the target works with masked instruction
296 /// AVX2 allows masks for consecutive load and store for i32 and i64 elements.
297 /// AVX-512 architecture will also allow masks for non-consecutive memory
299 bool isLegalMaskedStore(Type *DataType, int Consecutive) const;
300 bool isLegalMaskedLoad(Type *DataType, int Consecutive) const;
302 /// \brief Return the cost of the scaling factor used in the addressing
303 /// mode represented by AM for this target, for a load/store
304 /// of the specified type.
305 /// If the AM is supported, the return value must be >= 0.
306 /// If the AM is not supported, it returns a negative value.
307 /// TODO: Handle pre/postinc as well.
308 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
309 bool HasBaseReg, int64_t Scale) const;
311 /// \brief Return true if it's free to truncate a value of type Ty1 to type
312 /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
313 /// by referencing its sub-register AX.
314 bool isTruncateFree(Type *Ty1, Type *Ty2) const;
316 /// \brief Return true if it is profitable to hoist instruction in the
317 /// then/else to before if.
318 bool isProfitableToHoist(Instruction *I) const;
320 /// \brief Return true if this type is legal.
321 bool isTypeLegal(Type *Ty) const;
323 /// \brief Returns the target's jmp_buf alignment in bytes.
324 unsigned getJumpBufAlignment() const;
326 /// \brief Returns the target's jmp_buf size in bytes.
327 unsigned getJumpBufSize() const;
329 /// \brief Return true if switches should be turned into lookup tables for the
331 bool shouldBuildLookupTables() const;
333 /// \brief Return hardware support for population count.
334 PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
336 /// \brief Return true if the hardware has a fast square-root instruction.
337 bool haveFastSqrt(Type *Ty) const;
339 /// \brief Return the expected cost of supporting the floating point operation
340 /// of the specified type.
341 unsigned getFPOpCost(Type *Ty) const;
343 /// \brief Return the expected cost of materializing for the given integer
344 /// immediate of the specified type.
345 unsigned getIntImmCost(const APInt &Imm, Type *Ty) const;
347 /// \brief Return the expected cost of materialization for the given integer
348 /// immediate of the specified type for a given instruction. The cost can be
349 /// zero if the immediate can be folded into the specified instruction.
350 unsigned getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
352 unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
356 /// \name Vector Target Information
359 /// \brief The various kinds of shuffle patterns for vector queries.
361 SK_Broadcast, ///< Broadcast element 0 to all other elements.
362 SK_Reverse, ///< Reverse the order of the vector.
363 SK_Alternate, ///< Choose alternate elements from vector.
364 SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
365 SK_ExtractSubvector ///< ExtractSubvector Index indicates start offset.
368 /// \brief Additional information about an operand's possible values.
369 enum OperandValueKind {
370 OK_AnyValue, // Operand can have any value.
371 OK_UniformValue, // Operand is uniform (splat of a value).
372 OK_UniformConstantValue, // Operand is uniform constant.
373 OK_NonUniformConstantValue // Operand is a non uniform constant value.
376 /// \brief Additional properties of an operand's values.
377 enum OperandValueProperties { OP_None = 0, OP_PowerOf2 = 1 };
379 /// \return The number of scalar or vector registers that the target has.
380 /// If 'Vectors' is true, it returns the number of vector registers. If it is
381 /// set to false, it returns the number of scalar registers.
382 unsigned getNumberOfRegisters(bool Vector) const;
384 /// \return The width of the largest scalar or vector register type.
385 unsigned getRegisterBitWidth(bool Vector) const;
387 /// \return The maximum interleave factor that any transform should try to
388 /// perform for this target. This number depends on the level of parallelism
389 /// and the number of execution units in the CPU.
390 unsigned getMaxInterleaveFactor() const;
392 /// \return The expected cost of arithmetic ops, such as mul, xor, fsub, etc.
394 getArithmeticInstrCost(unsigned Opcode, Type *Ty,
395 OperandValueKind Opd1Info = OK_AnyValue,
396 OperandValueKind Opd2Info = OK_AnyValue,
397 OperandValueProperties Opd1PropInfo = OP_None,
398 OperandValueProperties Opd2PropInfo = OP_None) const;
400 /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
401 /// The index and subtype parameters are used by the subvector insertion and
402 /// extraction shuffle kinds.
403 unsigned getShuffleCost(ShuffleKind Kind, Type *Tp, int Index = 0,
404 Type *SubTp = nullptr) const;
406 /// \return The expected cost of cast instructions, such as bitcast, trunc,
408 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) const;
410 /// \return The expected cost of control-flow related instructions such as
412 unsigned getCFInstrCost(unsigned Opcode) const;
414 /// \returns The expected cost of compare and select instructions.
415 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
416 Type *CondTy = nullptr) const;
418 /// \return The expected cost of vector Insert and Extract.
419 /// Use -1 to indicate that there is no information on the index value.
420 unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
421 unsigned Index = -1) const;
423 /// \return The cost of Load and Store instructions.
424 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
425 unsigned AddressSpace) const;
427 /// \return The cost of masked Load and Store instructions.
428 unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
429 unsigned AddressSpace) const;
431 /// \brief Calculate the cost of performing a vector reduction.
433 /// This is the cost of reducing the vector value of type \p Ty to a scalar
434 /// value using the operation denoted by \p Opcode. The form of the reduction
435 /// can either be a pairwise reduction or a reduction that splits the vector
436 /// at every reduction level.
440 /// ((v0+v1), (v2, v3), undef, undef)
443 /// ((v0+v2), (v1+v3), undef, undef)
444 unsigned getReductionCost(unsigned Opcode, Type *Ty,
445 bool IsPairwiseForm) const;
447 /// \returns The cost of Intrinsic instructions.
448 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
449 ArrayRef<Type *> Tys) const;
451 /// \returns The number of pieces into which the provided type must be
452 /// split during legalization. Zero is returned when the answer is unknown.
453 unsigned getNumberOfParts(Type *Tp) const;
455 /// \returns The cost of the address computation. For most targets this can be
456 /// merged into the instruction indexing mode. Some targets might want to
457 /// distinguish between address computation for memory operations on vector
458 /// types and scalar types. Such targets should override this function.
459 /// The 'IsComplex' parameter is a hint that the address computation is likely
460 /// to involve multiple instructions and as such unlikely to be merged into
461 /// the address indexing mode.
462 unsigned getAddressComputationCost(Type *Ty, bool IsComplex = false) const;
464 /// \returns The cost, if any, of keeping values of the given types alive
467 /// Some types may require the use of register classes that do not have
468 /// any callee-saved registers, so would require a spill and fill.
469 unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const;
471 /// \returns True if the intrinsic is a supported memory intrinsic. Info
472 /// will contain additional information - whether the intrinsic may write
473 /// or read to memory, volatility and the pointer. Info is undefined
474 /// if false is returned.
475 bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const;
477 /// \returns A value which is the result of the given memory intrinsic. New
478 /// instructions may be created to extract the result from the given intrinsic
479 /// memory operation. Returns nullptr if the target cannot create a result
480 /// from the given intrinsic.
481 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
482 Type *ExpectedType) const;
487 /// \brief The abstract base class used to type erase specific TTI
491 /// \brief The template model for the base class which wraps a concrete
492 /// implementation in a type erased interface.
493 template <typename T> class Model;
495 std::unique_ptr<Concept> TTIImpl;
498 class TargetTransformInfo::Concept {
500 virtual ~Concept() = 0;
502 virtual unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) = 0;
503 virtual unsigned getGEPCost(const Value *Ptr,
504 ArrayRef<const Value *> Operands) = 0;
505 virtual unsigned getCallCost(FunctionType *FTy, int NumArgs) = 0;
506 virtual unsigned getCallCost(const Function *F, int NumArgs) = 0;
507 virtual unsigned getCallCost(const Function *F,
508 ArrayRef<const Value *> Arguments) = 0;
509 virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
510 ArrayRef<Type *> ParamTys) = 0;
511 virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
512 ArrayRef<const Value *> Arguments) = 0;
513 virtual unsigned getUserCost(const User *U) = 0;
514 virtual bool hasBranchDivergence() = 0;
515 virtual bool isLoweredToCall(const Function *F) = 0;
516 virtual void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) = 0;
517 virtual bool isLegalAddImmediate(int64_t Imm) = 0;
518 virtual bool isLegalICmpImmediate(int64_t Imm) = 0;
519 virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
520 int64_t BaseOffset, bool HasBaseReg,
522 virtual bool isLegalMaskedStore(Type *DataType, int Consecutive) = 0;
523 virtual bool isLegalMaskedLoad(Type *DataType, int Consecutive) = 0;
524 virtual int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
525 int64_t BaseOffset, bool HasBaseReg,
527 virtual bool isTruncateFree(Type *Ty1, Type *Ty2) = 0;
528 virtual bool isProfitableToHoist(Instruction *I) = 0;
529 virtual bool isTypeLegal(Type *Ty) = 0;
530 virtual unsigned getJumpBufAlignment() = 0;
531 virtual unsigned getJumpBufSize() = 0;
532 virtual bool shouldBuildLookupTables() = 0;
533 virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) = 0;
534 virtual bool haveFastSqrt(Type *Ty) = 0;
535 virtual unsigned getFPOpCost(Type *Ty) = 0;
536 virtual unsigned getIntImmCost(const APInt &Imm, Type *Ty) = 0;
537 virtual unsigned getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
539 virtual unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx,
540 const APInt &Imm, Type *Ty) = 0;
541 virtual unsigned getNumberOfRegisters(bool Vector) = 0;
542 virtual unsigned getRegisterBitWidth(bool Vector) = 0;
543 virtual unsigned getMaxInterleaveFactor() = 0;
545 getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
546 OperandValueKind Opd2Info,
547 OperandValueProperties Opd1PropInfo,
548 OperandValueProperties Opd2PropInfo) = 0;
549 virtual unsigned getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
551 virtual unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) = 0;
552 virtual unsigned getCFInstrCost(unsigned Opcode) = 0;
553 virtual unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
555 virtual unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
557 virtual unsigned getMemoryOpCost(unsigned Opcode, Type *Src,
559 unsigned AddressSpace) = 0;
560 virtual unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
562 unsigned AddressSpace) = 0;
563 virtual unsigned getReductionCost(unsigned Opcode, Type *Ty,
564 bool IsPairwiseForm) = 0;
565 virtual unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
566 ArrayRef<Type *> Tys) = 0;
567 virtual unsigned getNumberOfParts(Type *Tp) = 0;
568 virtual unsigned getAddressComputationCost(Type *Ty, bool IsComplex) = 0;
569 virtual unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) = 0;
570 virtual bool getTgtMemIntrinsic(IntrinsicInst *Inst,
571 MemIntrinsicInfo &Info) = 0;
572 virtual Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
573 Type *ExpectedType) = 0;
576 template <typename T>
577 class TargetTransformInfo::Model final : public TargetTransformInfo::Concept {
581 Model(T Impl) : Impl(std::move(Impl)) {}
584 unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) override {
585 return Impl.getOperationCost(Opcode, Ty, OpTy);
587 unsigned getGEPCost(const Value *Ptr,
588 ArrayRef<const Value *> Operands) override {
589 return Impl.getGEPCost(Ptr, Operands);
591 unsigned getCallCost(FunctionType *FTy, int NumArgs) override {
592 return Impl.getCallCost(FTy, NumArgs);
594 unsigned getCallCost(const Function *F, int NumArgs) override {
595 return Impl.getCallCost(F, NumArgs);
597 unsigned getCallCost(const Function *F,
598 ArrayRef<const Value *> Arguments) override {
599 return Impl.getCallCost(F, Arguments);
601 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
602 ArrayRef<Type *> ParamTys) override {
603 return Impl.getIntrinsicCost(IID, RetTy, ParamTys);
605 unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
606 ArrayRef<const Value *> Arguments) override {
607 return Impl.getIntrinsicCost(IID, RetTy, Arguments);
609 unsigned getUserCost(const User *U) override { return Impl.getUserCost(U); }
610 bool hasBranchDivergence() override { return Impl.hasBranchDivergence(); }
611 bool isLoweredToCall(const Function *F) override {
612 return Impl.isLoweredToCall(F);
614 void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) override {
615 return Impl.getUnrollingPreferences(L, UP);
617 bool isLegalAddImmediate(int64_t Imm) override {
618 return Impl.isLegalAddImmediate(Imm);
620 bool isLegalICmpImmediate(int64_t Imm) override {
621 return Impl.isLegalICmpImmediate(Imm);
623 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
624 bool HasBaseReg, int64_t Scale) override {
625 return Impl.isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
628 bool isLegalMaskedStore(Type *DataType, int Consecutive) override {
629 return Impl.isLegalMaskedStore(DataType, Consecutive);
631 bool isLegalMaskedLoad(Type *DataType, int Consecutive) override {
632 return Impl.isLegalMaskedLoad(DataType, Consecutive);
634 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
635 bool HasBaseReg, int64_t Scale) override {
636 return Impl.getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg, Scale);
638 bool isTruncateFree(Type *Ty1, Type *Ty2) override {
639 return Impl.isTruncateFree(Ty1, Ty2);
641 bool isProfitableToHoist(Instruction *I) override {
642 return Impl.isProfitableToHoist(I);
644 bool isTypeLegal(Type *Ty) override { return Impl.isTypeLegal(Ty); }
645 unsigned getJumpBufAlignment() override { return Impl.getJumpBufAlignment(); }
646 unsigned getJumpBufSize() override { return Impl.getJumpBufSize(); }
647 bool shouldBuildLookupTables() override {
648 return Impl.shouldBuildLookupTables();
650 PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) override {
651 return Impl.getPopcntSupport(IntTyWidthInBit);
653 bool haveFastSqrt(Type *Ty) override { return Impl.haveFastSqrt(Ty); }
655 unsigned getFPOpCost(Type *Ty) override {
656 return Impl.getFPOpCost(Ty);
659 unsigned getIntImmCost(const APInt &Imm, Type *Ty) override {
660 return Impl.getIntImmCost(Imm, Ty);
662 unsigned getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
664 return Impl.getIntImmCost(Opc, Idx, Imm, Ty);
666 unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
668 return Impl.getIntImmCost(IID, Idx, Imm, Ty);
670 unsigned getNumberOfRegisters(bool Vector) override {
671 return Impl.getNumberOfRegisters(Vector);
673 unsigned getRegisterBitWidth(bool Vector) override {
674 return Impl.getRegisterBitWidth(Vector);
676 unsigned getMaxInterleaveFactor() override {
677 return Impl.getMaxInterleaveFactor();
680 getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
681 OperandValueKind Opd2Info,
682 OperandValueProperties Opd1PropInfo,
683 OperandValueProperties Opd2PropInfo) override {
684 return Impl.getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
685 Opd1PropInfo, Opd2PropInfo);
687 unsigned getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
688 Type *SubTp) override {
689 return Impl.getShuffleCost(Kind, Tp, Index, SubTp);
691 unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) override {
692 return Impl.getCastInstrCost(Opcode, Dst, Src);
694 unsigned getCFInstrCost(unsigned Opcode) override {
695 return Impl.getCFInstrCost(Opcode);
697 unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
698 Type *CondTy) override {
699 return Impl.getCmpSelInstrCost(Opcode, ValTy, CondTy);
701 unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
702 unsigned Index) override {
703 return Impl.getVectorInstrCost(Opcode, Val, Index);
705 unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
706 unsigned AddressSpace) override {
707 return Impl.getMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
709 unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
710 unsigned AddressSpace) override {
711 return Impl.getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
713 unsigned getReductionCost(unsigned Opcode, Type *Ty,
714 bool IsPairwiseForm) override {
715 return Impl.getReductionCost(Opcode, Ty, IsPairwiseForm);
717 unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
718 ArrayRef<Type *> Tys) override {
719 return Impl.getIntrinsicInstrCost(ID, RetTy, Tys);
721 unsigned getNumberOfParts(Type *Tp) override {
722 return Impl.getNumberOfParts(Tp);
724 unsigned getAddressComputationCost(Type *Ty, bool IsComplex) override {
725 return Impl.getAddressComputationCost(Ty, IsComplex);
727 unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) override {
728 return Impl.getCostOfKeepingLiveOverCall(Tys);
730 bool getTgtMemIntrinsic(IntrinsicInst *Inst,
731 MemIntrinsicInfo &Info) override {
732 return Impl.getTgtMemIntrinsic(Inst, Info);
734 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
735 Type *ExpectedType) override {
736 return Impl.getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
740 template <typename T>
741 TargetTransformInfo::TargetTransformInfo(T Impl)
742 : TTIImpl(new Model<T>(Impl)) {}
744 /// \brief Analysis pass providing the \c TargetTransformInfo.
746 /// The core idea of the TargetIRAnalysis is to expose an interface through
747 /// which LLVM targets can analyze and provide information about the middle
748 /// end's target-independent IR. This supports use cases such as target-aware
749 /// cost modeling of IR constructs.
751 /// This is a function analysis because much of the cost modeling for targets
752 /// is done in a subtarget specific way and LLVM supports compiling different
753 /// functions targeting different subtargets in order to support runtime
754 /// dispatch according to the observed subtarget.
755 class TargetIRAnalysis {
757 typedef TargetTransformInfo Result;
759 /// \brief Opaque, unique identifier for this analysis pass.
760 static void *ID() { return (void *)&PassID; }
762 /// \brief Provide access to a name for this pass for debugging purposes.
763 static StringRef name() { return "TargetIRAnalysis"; }
765 /// \brief Default construct a target IR analysis.
767 /// This will use the module's datalayout to construct a baseline
768 /// conservative TTI result.
771 /// \brief Construct an IR analysis pass around a target-provide callback.
773 /// The callback will be called with a particular function for which the TTI
774 /// is needed and must return a TTI object for that function.
775 TargetIRAnalysis(std::function<Result(Function &)> TTICallback);
777 // Value semantics. We spell out the constructors for MSVC.
778 TargetIRAnalysis(const TargetIRAnalysis &Arg)
779 : TTICallback(Arg.TTICallback) {}
780 TargetIRAnalysis(TargetIRAnalysis &&Arg)
781 : TTICallback(std::move(Arg.TTICallback)) {}
782 TargetIRAnalysis &operator=(const TargetIRAnalysis &RHS) {
783 TTICallback = RHS.TTICallback;
786 TargetIRAnalysis &operator=(TargetIRAnalysis &&RHS) {
787 TTICallback = std::move(RHS.TTICallback);
791 Result run(Function &F);
796 /// \brief The callback used to produce a result.
798 /// We use a completely opaque callback so that targets can provide whatever
799 /// mechanism they desire for constructing the TTI for a given function.
801 /// FIXME: Should we really use std::function? It's relatively inefficient.
802 /// It might be possible to arrange for even stateful callbacks to outlive
803 /// the analysis and thus use a function_ref which would be lighter weight.
804 /// This may also be less error prone as the callback is likely to reference
805 /// the external TargetMachine, and that reference needs to never dangle.
806 std::function<Result(Function &)> TTICallback;
808 /// \brief Helper function used as the callback in the default constructor.
809 static Result getDefaultTTI(Function &F);
812 /// \brief Wrapper pass for TargetTransformInfo.
814 /// This pass can be constructed from a TTI object which it stores internally
815 /// and is queried by passes.
816 class TargetTransformInfoWrapperPass : public ImmutablePass {
817 TargetIRAnalysis TIRA;
818 Optional<TargetTransformInfo> TTI;
820 virtual void anchor();
825 /// \brief We must provide a default constructor for the pass but it should
828 /// Use the constructor below or call one of the creation routines.
829 TargetTransformInfoWrapperPass();
831 explicit TargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
833 TargetTransformInfo &getTTI(Function &F);
836 /// \brief Create an analysis pass wrapper around a TTI object.
838 /// This analysis pass just holds the TTI instance and makes it available to
840 ImmutablePass *createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
842 } // End llvm namespace