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/Operator.h"
27 #include "llvm/IR/PassManager.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/AtomicOrdering.h"
30 #include "llvm/Support/DataTypes.h"
45 class ScalarEvolution;
52 /// \brief Information about a load/store intrinsic defined by the target.
53 struct MemIntrinsicInfo {
54 /// This is the pointer that the intrinsic is loading from or storing to.
55 /// If this is non-null, then analysis/optimization passes can assume that
56 /// this intrinsic is functionally equivalent to a load/store from this
58 Value *PtrVal = nullptr;
60 // Ordering for atomic operations.
61 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
63 // Same Id is set by the target for corresponding load/store intrinsics.
64 unsigned short MatchingId = 0;
67 bool WriteMem = false;
68 bool IsVolatile = false;
70 bool isUnordered() const {
71 return (Ordering == AtomicOrdering::NotAtomic ||
72 Ordering == AtomicOrdering::Unordered) && !IsVolatile;
76 /// \brief This pass provides access to the codegen interfaces that are needed
77 /// for IR-level transformations.
78 class TargetTransformInfo {
80 /// \brief Construct a TTI object using a type implementing the \c Concept
83 /// This is used by targets to construct a TTI wrapping their target-specific
84 /// implementaion that encodes appropriate costs for their target.
85 template <typename T> TargetTransformInfo(T Impl);
87 /// \brief Construct a baseline TTI object using a minimal implementation of
88 /// the \c Concept API below.
90 /// The TTI implementation will reflect the information in the DataLayout
91 /// provided if non-null.
92 explicit TargetTransformInfo(const DataLayout &DL);
94 // Provide move semantics.
95 TargetTransformInfo(TargetTransformInfo &&Arg);
96 TargetTransformInfo &operator=(TargetTransformInfo &&RHS);
98 // We need to define the destructor out-of-line to define our sub-classes
100 ~TargetTransformInfo();
102 /// \brief Handle the invalidation of this information.
104 /// When used as a result of \c TargetIRAnalysis this method will be called
105 /// when the function this was computed for changes. When it returns false,
106 /// the information is preserved across those changes.
107 bool invalidate(Function &, const PreservedAnalyses &,
108 FunctionAnalysisManager::Invalidator &) {
109 // FIXME: We should probably in some way ensure that the subtarget
110 // information for a function hasn't changed.
114 /// \name Generic Target Information
117 /// \brief The kind of cost model.
119 /// There are several different cost models that can be customized by the
120 /// target. The normalization of each cost model may be target specific.
121 enum TargetCostKind {
122 TCK_RecipThroughput, ///< Reciprocal throughput.
123 TCK_Latency, ///< The latency of instruction.
124 TCK_CodeSize ///< Instruction code size.
127 /// \brief Query the cost of a specified instruction.
129 /// Clients should use this interface to query the cost of an existing
130 /// instruction. The instruction must have a valid parent (basic block).
132 /// Note, this method does not cache the cost calculation and it
133 /// can be expensive in some cases.
134 int getInstructionCost(const Instruction *I, enum TargetCostKind kind) const {
136 case TCK_RecipThroughput:
137 return getInstructionThroughput(I);
140 return getInstructionLatency(I);
143 return getUserCost(I);
145 llvm_unreachable("Unknown instruction cost kind");
148 /// \brief Underlying constants for 'cost' values in this interface.
150 /// Many APIs in this interface return a cost. This enum defines the
151 /// fundamental values that should be used to interpret (and produce) those
152 /// costs. The costs are returned as an int rather than a member of this
153 /// enumeration because it is expected that the cost of one IR instruction
154 /// may have a multiplicative factor to it or otherwise won't fit directly
155 /// into the enum. Moreover, it is common to sum or average costs which works
156 /// better as simple integral values. Thus this enum only provides constants.
157 /// Also note that the returned costs are signed integers to make it natural
158 /// to add, subtract, and test with zero (a common boundary condition). It is
159 /// not expected that 2^32 is a realistic cost to be modeling at any point.
161 /// Note that these costs should usually reflect the intersection of code-size
162 /// cost and execution cost. A free instruction is typically one that folds
163 /// into another instruction. For example, reg-to-reg moves can often be
164 /// skipped by renaming the registers in the CPU, but they still are encoded
165 /// and thus wouldn't be considered 'free' here.
166 enum TargetCostConstants {
167 TCC_Free = 0, ///< Expected to fold away in lowering.
168 TCC_Basic = 1, ///< The cost of a typical 'add' instruction.
169 TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
172 /// \brief Estimate the cost of a specific operation when lowered.
174 /// Note that this is designed to work on an arbitrary synthetic opcode, and
175 /// thus work for hypothetical queries before an instruction has even been
176 /// formed. However, this does *not* work for GEPs, and must not be called
177 /// for a GEP instruction. Instead, use the dedicated getGEPCost interface as
178 /// analyzing a GEP's cost required more information.
180 /// Typically only the result type is required, and the operand type can be
181 /// omitted. However, if the opcode is one of the cast instructions, the
182 /// operand type is required.
184 /// The returned cost is defined in terms of \c TargetCostConstants, see its
185 /// comments for a detailed explanation of the cost values.
186 int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy = nullptr) const;
188 /// \brief Estimate the cost of a GEP operation when lowered.
190 /// The contract for this function is the same as \c getOperationCost except
191 /// that it supports an interface that provides extra information specific to
192 /// the GEP operation.
193 int getGEPCost(Type *PointeeType, const Value *Ptr,
194 ArrayRef<const Value *> Operands) const;
196 /// \brief Estimate the cost of a EXT operation when lowered.
198 /// The contract for this function is the same as \c getOperationCost except
199 /// that it supports an interface that provides extra information specific to
200 /// the EXT operation.
201 int getExtCost(const Instruction *I, const Value *Src) const;
203 /// \brief Estimate the cost of a function call when lowered.
205 /// The contract for this is the same as \c getOperationCost except that it
206 /// supports an interface that provides extra information specific to call
209 /// This is the most basic query for estimating call cost: it only knows the
210 /// function type and (potentially) the number of arguments at the call site.
211 /// The latter is only interesting for varargs function types.
212 int getCallCost(FunctionType *FTy, int NumArgs = -1) const;
214 /// \brief Estimate the cost of calling a specific function when lowered.
216 /// This overload adds the ability to reason about the particular function
217 /// being called in the event it is a library call with special lowering.
218 int getCallCost(const Function *F, int NumArgs = -1) const;
220 /// \brief Estimate the cost of calling a specific function when lowered.
222 /// This overload allows specifying a set of candidate argument values.
223 int getCallCost(const Function *F, ArrayRef<const Value *> Arguments) const;
225 /// \returns A value by which our inlining threshold should be multiplied.
226 /// This is primarily used to bump up the inlining threshold wholesale on
227 /// targets where calls are unusually expensive.
229 /// TODO: This is a rather blunt instrument. Perhaps altering the costs of
230 /// individual classes of instructions would be better.
231 unsigned getInliningThresholdMultiplier() const;
233 /// \brief Estimate the cost of an intrinsic when lowered.
235 /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
236 int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
237 ArrayRef<Type *> ParamTys) const;
239 /// \brief Estimate the cost of an intrinsic when lowered.
241 /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
242 int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
243 ArrayRef<const Value *> Arguments) const;
245 /// \return The estimated number of case clusters when lowering \p 'SI'.
246 /// \p JTSize Set a jump table size only when \p SI is suitable for a jump
248 unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
249 unsigned &JTSize) const;
251 /// \brief Estimate the cost of a given IR user when lowered.
253 /// This can estimate the cost of either a ConstantExpr or Instruction when
254 /// lowered. It has two primary advantages over the \c getOperationCost and
255 /// \c getGEPCost above, and one significant disadvantage: it can only be
256 /// used when the IR construct has already been formed.
258 /// The advantages are that it can inspect the SSA use graph to reason more
259 /// accurately about the cost. For example, all-constant-GEPs can often be
260 /// folded into a load or other instruction, but if they are used in some
261 /// other context they may not be folded. This routine can distinguish such
264 /// \p Operands is a list of operands which can be a result of transformations
265 /// of the current operands. The number of the operands on the list must equal
266 /// to the number of the current operands the IR user has. Their order on the
267 /// list must be the same as the order of the current operands the IR user
270 /// The returned cost is defined in terms of \c TargetCostConstants, see its
271 /// comments for a detailed explanation of the cost values.
272 int getUserCost(const User *U, ArrayRef<const Value *> Operands) const;
274 /// \brief This is a helper function which calls the two-argument getUserCost
275 /// with \p Operands which are the current operands U has.
276 int getUserCost(const User *U) const {
277 SmallVector<const Value *, 4> Operands(U->value_op_begin(),
279 return getUserCost(U, Operands);
282 /// \brief Return true if branch divergence exists.
284 /// Branch divergence has a significantly negative impact on GPU performance
285 /// when threads in the same wavefront take different paths due to conditional
287 bool hasBranchDivergence() const;
289 /// \brief Returns whether V is a source of divergence.
291 /// This function provides the target-dependent information for
292 /// the target-independent DivergenceAnalysis. DivergenceAnalysis first
293 /// builds the dependency graph, and then runs the reachability algorithm
294 /// starting with the sources of divergence.
295 bool isSourceOfDivergence(const Value *V) const;
297 // \brief Returns true for the target specific
298 // set of operations which produce uniform result
299 // even taking non-unform arguments
300 bool isAlwaysUniform(const Value *V) const;
302 /// Returns the address space ID for a target's 'flat' address space. Note
303 /// this is not necessarily the same as addrspace(0), which LLVM sometimes
304 /// refers to as the generic address space. The flat address space is a
305 /// generic address space that can be used access multiple segments of memory
306 /// with different address spaces. Access of a memory location through a
307 /// pointer with this address space is expected to be legal but slower
308 /// compared to the same memory location accessed through a pointer with a
309 /// different address space.
311 /// This is for for targets with different pointer representations which can
312 /// be converted with the addrspacecast instruction. If a pointer is converted
313 /// to this address space, optimizations should attempt to replace the access
314 /// with the source address space.
316 /// \returns ~0u if the target does not have such a flat address space to
318 unsigned getFlatAddressSpace() const;
320 /// \brief Test whether calls to a function lower to actual program function
323 /// The idea is to test whether the program is likely to require a 'call'
324 /// instruction or equivalent in order to call the given function.
326 /// FIXME: It's not clear that this is a good or useful query API. Client's
327 /// should probably move to simpler cost metrics using the above.
328 /// Alternatively, we could split the cost interface into distinct code-size
329 /// and execution-speed costs. This would allow modelling the core of this
330 /// query more accurately as a call is a single small instruction, but
331 /// incurs significant execution cost.
332 bool isLoweredToCall(const Function *F) const;
335 /// TODO: Some of these could be merged. Also, a lexical ordering
336 /// isn't always optimal.
341 unsigned NumBaseAdds;
347 /// Parameters that control the generic loop unrolling transformation.
348 struct UnrollingPreferences {
349 /// The cost threshold for the unrolled loop. Should be relative to the
350 /// getUserCost values returned by this API, and the expectation is that
351 /// the unrolled loop's instructions when run through that interface should
352 /// not exceed this cost. However, this is only an estimate. Also, specific
353 /// loops may be unrolled even with a cost above this threshold if deemed
354 /// profitable. Set this to UINT_MAX to disable the loop body cost
357 /// If complete unrolling will reduce the cost of the loop, we will boost
358 /// the Threshold by a certain percent to allow more aggressive complete
359 /// unrolling. This value provides the maximum boost percentage that we
360 /// can apply to Threshold (The value should be no less than 100).
361 /// BoostedThreshold = Threshold * min(RolledCost / UnrolledCost,
362 /// MaxPercentThresholdBoost / 100)
363 /// E.g. if complete unrolling reduces the loop execution time by 50%
364 /// then we boost the threshold by the factor of 2x. If unrolling is not
365 /// expected to reduce the running time, then we do not increase the
367 unsigned MaxPercentThresholdBoost;
368 /// The cost threshold for the unrolled loop when optimizing for size (set
369 /// to UINT_MAX to disable).
370 unsigned OptSizeThreshold;
371 /// The cost threshold for the unrolled loop, like Threshold, but used
372 /// for partial/runtime unrolling (set to UINT_MAX to disable).
373 unsigned PartialThreshold;
374 /// The cost threshold for the unrolled loop when optimizing for size, like
375 /// OptSizeThreshold, but used for partial/runtime unrolling (set to
376 /// UINT_MAX to disable).
377 unsigned PartialOptSizeThreshold;
378 /// A forced unrolling factor (the number of concatenated bodies of the
379 /// original loop in the unrolled loop body). When set to 0, the unrolling
380 /// transformation will select an unrolling factor based on the current cost
381 /// threshold and other factors.
383 /// A forced peeling factor (the number of bodied of the original loop
384 /// that should be peeled off before the loop body). When set to 0, the
385 /// unrolling transformation will select a peeling factor based on profile
386 /// information and other factors.
388 /// Default unroll count for loops with run-time trip count.
389 unsigned DefaultUnrollRuntimeCount;
390 // Set the maximum unrolling factor. The unrolling factor may be selected
391 // using the appropriate cost threshold, but may not exceed this number
392 // (set to UINT_MAX to disable). This does not apply in cases where the
393 // loop is being fully unrolled.
395 /// Set the maximum unrolling factor for full unrolling. Like MaxCount, but
396 /// applies even if full unrolling is selected. This allows a target to fall
397 /// back to Partial unrolling if full unrolling is above FullUnrollMaxCount.
398 unsigned FullUnrollMaxCount;
399 // Represents number of instructions optimized when "back edge"
400 // becomes "fall through" in unrolled loop.
401 // For now we count a conditional branch on a backedge and a comparison
404 /// Allow partial unrolling (unrolling of loops to expand the size of the
405 /// loop body, not only to eliminate small constant-trip-count loops).
407 /// Allow runtime unrolling (unrolling of loops to expand the size of the
408 /// loop body even when the number of loop iterations is not known at
411 /// Allow generation of a loop remainder (extra iterations after unroll).
413 /// Allow emitting expensive instructions (such as divisions) when computing
414 /// the trip count of a loop for runtime unrolling.
415 bool AllowExpensiveTripCount;
416 /// Apply loop unroll on any kind of loop
417 /// (mainly to loops that fail runtime unrolling).
419 /// Allow using trip count upper bound to unroll loops.
421 /// Allow peeling off loop iterations for loops with low dynamic tripcount.
423 /// Allow unrolling of all the iterations of the runtime loop remainder.
424 bool UnrollRemainder;
427 /// \brief Get target-customized preferences for the generic loop unrolling
428 /// transformation. The caller will initialize UP with the current
429 /// target-independent defaults.
430 void getUnrollingPreferences(Loop *L, ScalarEvolution &,
431 UnrollingPreferences &UP) const;
435 /// \name Scalar Target Information
438 /// \brief Flags indicating the kind of support for population count.
440 /// Compared to the SW implementation, HW support is supposed to
441 /// significantly boost the performance when the population is dense, and it
442 /// may or may not degrade performance if the population is sparse. A HW
443 /// support is considered as "Fast" if it can outperform, or is on a par
444 /// with, SW implementation when the population is sparse; otherwise, it is
445 /// considered as "Slow".
446 enum PopcntSupportKind { PSK_Software, PSK_SlowHardware, PSK_FastHardware };
448 /// \brief Return true if the specified immediate is legal add immediate, that
449 /// is the target has add instructions which can add a register with the
450 /// immediate without having to materialize the immediate into a register.
451 bool isLegalAddImmediate(int64_t Imm) const;
453 /// \brief Return true if the specified immediate is legal icmp immediate,
454 /// that is the target has icmp instructions which can compare a register
455 /// against the immediate without having to materialize the immediate into a
457 bool isLegalICmpImmediate(int64_t Imm) const;
459 /// \brief Return true if the addressing mode represented by AM is legal for
460 /// this target, for a load/store of the specified type.
461 /// The type may be VoidTy, in which case only return true if the addressing
462 /// mode is legal for a load/store of any legal type.
463 /// If target returns true in LSRWithInstrQueries(), I may be valid.
464 /// TODO: Handle pre/postinc as well.
465 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
466 bool HasBaseReg, int64_t Scale,
467 unsigned AddrSpace = 0,
468 Instruction *I = nullptr) const;
470 /// \brief Return true if LSR cost of C1 is lower than C1.
471 bool isLSRCostLess(TargetTransformInfo::LSRCost &C1,
472 TargetTransformInfo::LSRCost &C2) const;
474 /// \brief Return true if the target supports masked load/store
475 /// AVX2 and AVX-512 targets allow masks for consecutive load and store
476 bool isLegalMaskedStore(Type *DataType) const;
477 bool isLegalMaskedLoad(Type *DataType) const;
479 /// \brief Return true if the target supports masked gather/scatter
480 /// AVX-512 fully supports gather and scatter for vectors with 32 and 64
481 /// bits scalar type.
482 bool isLegalMaskedScatter(Type *DataType) const;
483 bool isLegalMaskedGather(Type *DataType) const;
485 /// Return true if the target has a unified operation to calculate division
486 /// and remainder. If so, the additional implicit multiplication and
487 /// subtraction required to calculate a remainder from division are free. This
488 /// can enable more aggressive transformations for division and remainder than
489 /// would typically be allowed using throughput or size cost models.
490 bool hasDivRemOp(Type *DataType, bool IsSigned) const;
492 /// Return true if the given instruction (assumed to be a memory access
493 /// instruction) has a volatile variant. If that's the case then we can avoid
494 /// addrspacecast to generic AS for volatile loads/stores. Default
495 /// implementation returns false, which prevents address space inference for
496 /// volatile loads/stores.
497 bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) const;
499 /// Return true if target doesn't mind addresses in vectors.
500 bool prefersVectorizedAddressing() const;
502 /// \brief Return the cost of the scaling factor used in the addressing
503 /// mode represented by AM for this target, for a load/store
504 /// of the specified type.
505 /// If the AM is supported, the return value must be >= 0.
506 /// If the AM is not supported, it returns a negative value.
507 /// TODO: Handle pre/postinc as well.
508 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
509 bool HasBaseReg, int64_t Scale,
510 unsigned AddrSpace = 0) const;
512 /// \brief Return true if the loop strength reduce pass should make
513 /// Instruction* based TTI queries to isLegalAddressingMode(). This is
514 /// needed on SystemZ, where e.g. a memcpy can only have a 12 bit unsigned
515 /// immediate offset and no index register.
516 bool LSRWithInstrQueries() const;
518 /// \brief Return true if it's free to truncate a value of type Ty1 to type
519 /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
520 /// by referencing its sub-register AX.
521 bool isTruncateFree(Type *Ty1, Type *Ty2) const;
523 /// \brief Return true if it is profitable to hoist instruction in the
524 /// then/else to before if.
525 bool isProfitableToHoist(Instruction *I) const;
527 /// \brief Return true if this type is legal.
528 bool isTypeLegal(Type *Ty) const;
530 /// \brief Returns the target's jmp_buf alignment in bytes.
531 unsigned getJumpBufAlignment() const;
533 /// \brief Returns the target's jmp_buf size in bytes.
534 unsigned getJumpBufSize() const;
536 /// \brief Return true if switches should be turned into lookup tables for the
538 bool shouldBuildLookupTables() const;
540 /// \brief Return true if switches should be turned into lookup tables
541 /// containing this constant value for the target.
542 bool shouldBuildLookupTablesForConstant(Constant *C) const;
544 unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const;
546 unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
549 /// If target has efficient vector element load/store instructions, it can
550 /// return true here so that insertion/extraction costs are not added to
551 /// the scalarization cost of a load/store.
552 bool supportsEfficientVectorElementLoadStore() const;
554 /// \brief Don't restrict interleaved unrolling to small loops.
555 bool enableAggressiveInterleaving(bool LoopHasReductions) const;
557 /// \brief If not nullptr, enable inline expansion of memcmp. IsZeroCmp is
558 /// true if this is the expansion of memcmp(p1, p2, s) == 0.
559 struct MemCmpExpansionOptions {
560 // The list of available load sizes (in bytes), sorted in decreasing order.
561 SmallVector<unsigned, 8> LoadSizes;
563 const MemCmpExpansionOptions *enableMemCmpExpansion(bool IsZeroCmp) const;
565 /// \brief Enable matching of interleaved access groups.
566 bool enableInterleavedAccessVectorization() const;
568 /// \brief Indicate that it is potentially unsafe to automatically vectorize
569 /// floating-point operations because the semantics of vector and scalar
570 /// floating-point semantics may differ. For example, ARM NEON v7 SIMD math
571 /// does not support IEEE-754 denormal numbers, while depending on the
572 /// platform, scalar floating-point math does.
573 /// This applies to floating-point math operations and calls, not memory
574 /// operations, shuffles, or casts.
575 bool isFPVectorizationPotentiallyUnsafe() const;
577 /// \brief Determine if the target supports unaligned memory accesses.
578 bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
579 unsigned BitWidth, unsigned AddressSpace = 0,
580 unsigned Alignment = 1,
581 bool *Fast = nullptr) const;
583 /// \brief Return hardware support for population count.
584 PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
586 /// \brief Return true if the hardware has a fast square-root instruction.
587 bool haveFastSqrt(Type *Ty) const;
589 /// Return true if it is faster to check if a floating-point value is NaN
590 /// (or not-NaN) versus a comparison against a constant FP zero value.
591 /// Targets should override this if materializing a 0.0 for comparison is
592 /// generally as cheap as checking for ordered/unordered.
593 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) const;
595 /// \brief Return the expected cost of supporting the floating point operation
596 /// of the specified type.
597 int getFPOpCost(Type *Ty) const;
599 /// \brief Return the expected cost of materializing for the given integer
600 /// immediate of the specified type.
601 int getIntImmCost(const APInt &Imm, Type *Ty) const;
603 /// \brief Return the expected cost of materialization for the given integer
604 /// immediate of the specified type for a given instruction. The cost can be
605 /// zero if the immediate can be folded into the specified instruction.
606 int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
608 int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
611 /// \brief Return the expected cost for the given integer when optimising
612 /// for size. This is different than the other integer immediate cost
613 /// functions in that it is subtarget agnostic. This is useful when you e.g.
614 /// target one ISA such as Aarch32 but smaller encodings could be possible
615 /// with another such as Thumb. This return value is used as a penalty when
616 /// the total costs for a constant is calculated (the bigger the cost, the
617 /// more beneficial constant hoisting is).
618 int getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm,
622 /// \name Vector Target Information
625 /// \brief The various kinds of shuffle patterns for vector queries.
627 SK_Broadcast, ///< Broadcast element 0 to all other elements.
628 SK_Reverse, ///< Reverse the order of the vector.
629 SK_Alternate, ///< Choose alternate elements from vector.
630 SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
631 SK_ExtractSubvector,///< ExtractSubvector Index indicates start offset.
632 SK_PermuteTwoSrc, ///< Merge elements from two source vectors into one
633 ///< with any shuffle mask.
634 SK_PermuteSingleSrc ///< Shuffle elements of single source vector with any
638 /// \brief Additional information about an operand's possible values.
639 enum OperandValueKind {
640 OK_AnyValue, // Operand can have any value.
641 OK_UniformValue, // Operand is uniform (splat of a value).
642 OK_UniformConstantValue, // Operand is uniform constant.
643 OK_NonUniformConstantValue // Operand is a non uniform constant value.
646 /// \brief Additional properties of an operand's values.
647 enum OperandValueProperties { OP_None = 0, OP_PowerOf2 = 1 };
649 /// \return True if target can execute instructions out of order.
650 bool isOutOfOrder() const;
652 /// \return The number of scalar or vector registers that the target has.
653 /// If 'Vectors' is true, it returns the number of vector registers. If it is
654 /// set to false, it returns the number of scalar registers.
655 unsigned getNumberOfRegisters(bool Vector) const;
657 /// \return The width of the largest scalar or vector register type.
658 unsigned getRegisterBitWidth(bool Vector) const;
660 /// \return The width of the smallest vector register type.
661 unsigned getMinVectorRegisterBitWidth() const;
663 /// \return True if it should be considered for address type promotion.
664 /// \p AllowPromotionWithoutCommonHeader Set true if promoting \p I is
665 /// profitable without finding other extensions fed by the same input.
666 bool shouldConsiderAddressTypePromotion(
667 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const;
669 /// \return The size of a cache line in bytes.
670 unsigned getCacheLineSize() const;
672 /// The possible cache levels
673 enum class CacheLevel {
674 L1D, // The L1 data cache
675 L2D, // The L2 data cache
677 // We currently do not model L3 caches, as their sizes differ widely between
678 // microarchitectures. Also, we currently do not have a use for L3 cache
679 // size modeling yet.
682 /// \return The size of the cache level in bytes, if available.
683 llvm::Optional<unsigned> getCacheSize(CacheLevel Level) const;
685 /// \return The associativity of the cache level, if available.
686 llvm::Optional<unsigned> getCacheAssociativity(CacheLevel Level) const;
688 /// \return How much before a load we should place the prefetch instruction.
689 /// This is currently measured in number of instructions.
690 unsigned getPrefetchDistance() const;
692 /// \return Some HW prefetchers can handle accesses up to a certain constant
693 /// stride. This is the minimum stride in bytes where it makes sense to start
694 /// adding SW prefetches. The default is 1, i.e. prefetch with any stride.
695 unsigned getMinPrefetchStride() const;
697 /// \return The maximum number of iterations to prefetch ahead. If the
698 /// required number of iterations is more than this number, no prefetching is
700 unsigned getMaxPrefetchIterationsAhead() const;
702 /// \return The maximum interleave factor that any transform should try to
703 /// perform for this target. This number depends on the level of parallelism
704 /// and the number of execution units in the CPU.
705 unsigned getMaxInterleaveFactor(unsigned VF) const;
707 /// \return The expected cost of arithmetic ops, such as mul, xor, fsub, etc.
708 /// \p Args is an optional argument which holds the instruction operands
709 /// values so the TTI can analyize those values searching for special
710 /// cases\optimizations based on those values.
711 int getArithmeticInstrCost(
712 unsigned Opcode, Type *Ty, OperandValueKind Opd1Info = OK_AnyValue,
713 OperandValueKind Opd2Info = OK_AnyValue,
714 OperandValueProperties Opd1PropInfo = OP_None,
715 OperandValueProperties Opd2PropInfo = OP_None,
716 ArrayRef<const Value *> Args = ArrayRef<const Value *>()) const;
718 /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
719 /// The index and subtype parameters are used by the subvector insertion and
720 /// extraction shuffle kinds.
721 int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index = 0,
722 Type *SubTp = nullptr) const;
724 /// \return The expected cost of cast instructions, such as bitcast, trunc,
725 /// zext, etc. If there is an existing instruction that holds Opcode, it
726 /// may be passed in the 'I' parameter.
727 int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
728 const Instruction *I = nullptr) const;
730 /// \return The expected cost of a sign- or zero-extended vector extract. Use
731 /// -1 to indicate that there is no information about the index value.
732 int getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy,
733 unsigned Index = -1) const;
735 /// \return The expected cost of control-flow related instructions such as
737 int getCFInstrCost(unsigned Opcode) const;
739 /// \returns The expected cost of compare and select instructions. If there
740 /// is an existing instruction that holds Opcode, it may be passed in the
742 int getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
743 Type *CondTy = nullptr, const Instruction *I = nullptr) const;
745 /// \return The expected cost of vector Insert and Extract.
746 /// Use -1 to indicate that there is no information on the index value.
747 int getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index = -1) const;
749 /// \return The cost of Load and Store instructions.
750 int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
751 unsigned AddressSpace, const Instruction *I = nullptr) const;
753 /// \return The cost of masked Load and Store instructions.
754 int getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
755 unsigned AddressSpace) const;
757 /// \return The cost of Gather or Scatter operation
758 /// \p Opcode - is a type of memory access Load or Store
759 /// \p DataTy - a vector type of the data to be loaded or stored
760 /// \p Ptr - pointer [or vector of pointers] - address[es] in memory
761 /// \p VariableMask - true when the memory access is predicated with a mask
762 /// that is not a compile-time constant
763 /// \p Alignment - alignment of single element
764 int getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr,
765 bool VariableMask, unsigned Alignment) const;
767 /// \return The cost of the interleaved memory operation.
768 /// \p Opcode is the memory operation code
769 /// \p VecTy is the vector type of the interleaved access.
770 /// \p Factor is the interleave factor
771 /// \p Indices is the indices for interleaved load members (as interleaved
772 /// load allows gaps)
773 /// \p Alignment is the alignment of the memory operation
774 /// \p AddressSpace is address space of the pointer.
775 int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor,
776 ArrayRef<unsigned> Indices, unsigned Alignment,
777 unsigned AddressSpace) const;
779 /// \brief Calculate the cost of performing a vector reduction.
781 /// This is the cost of reducing the vector value of type \p Ty to a scalar
782 /// value using the operation denoted by \p Opcode. The form of the reduction
783 /// can either be a pairwise reduction or a reduction that splits the vector
784 /// at every reduction level.
788 /// ((v0+v1), (v2+v3), undef, undef)
791 /// ((v0+v2), (v1+v3), undef, undef)
792 int getArithmeticReductionCost(unsigned Opcode, Type *Ty,
793 bool IsPairwiseForm) const;
794 int getMinMaxReductionCost(Type *Ty, Type *CondTy, bool IsPairwiseForm,
795 bool IsUnsigned) const;
797 /// \returns The cost of Intrinsic instructions. Analyses the real arguments.
798 /// Three cases are handled: 1. scalar instruction 2. vector instruction
799 /// 3. scalar instruction which is to be vectorized with VF.
800 int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
801 ArrayRef<Value *> Args, FastMathFlags FMF,
802 unsigned VF = 1) const;
804 /// \returns The cost of Intrinsic instructions. Types analysis only.
805 /// If ScalarizationCostPassed is UINT_MAX, the cost of scalarizing the
806 /// arguments and the return value will be computed based on types.
807 int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
808 ArrayRef<Type *> Tys, FastMathFlags FMF,
809 unsigned ScalarizationCostPassed = UINT_MAX) const;
811 /// \returns The cost of Call instructions.
812 int getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) const;
814 /// \returns The number of pieces into which the provided type must be
815 /// split during legalization. Zero is returned when the answer is unknown.
816 unsigned getNumberOfParts(Type *Tp) const;
818 /// \returns The cost of the address computation. For most targets this can be
819 /// merged into the instruction indexing mode. Some targets might want to
820 /// distinguish between address computation for memory operations on vector
821 /// types and scalar types. Such targets should override this function.
822 /// The 'SE' parameter holds pointer for the scalar evolution object which
823 /// is used in order to get the Ptr step value in case of constant stride.
824 /// The 'Ptr' parameter holds SCEV of the access pointer.
825 int getAddressComputationCost(Type *Ty, ScalarEvolution *SE = nullptr,
826 const SCEV *Ptr = nullptr) const;
828 /// \returns The cost, if any, of keeping values of the given types alive
831 /// Some types may require the use of register classes that do not have
832 /// any callee-saved registers, so would require a spill and fill.
833 unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const;
835 /// \returns True if the intrinsic is a supported memory intrinsic. Info
836 /// will contain additional information - whether the intrinsic may write
837 /// or read to memory, volatility and the pointer. Info is undefined
838 /// if false is returned.
839 bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const;
841 /// \returns The maximum element size, in bytes, for an element
842 /// unordered-atomic memory intrinsic.
843 unsigned getAtomicMemIntrinsicMaxElementSize() const;
845 /// \returns A value which is the result of the given memory intrinsic. New
846 /// instructions may be created to extract the result from the given intrinsic
847 /// memory operation. Returns nullptr if the target cannot create a result
848 /// from the given intrinsic.
849 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
850 Type *ExpectedType) const;
852 /// \returns The type to use in a loop expansion of a memcpy call.
853 Type *getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
854 unsigned SrcAlign, unsigned DestAlign) const;
856 /// \param[out] OpsOut The operand types to copy RemainingBytes of memory.
857 /// \param RemainingBytes The number of bytes to copy.
859 /// Calculates the operand types to use when copying \p RemainingBytes of
860 /// memory, where source and destination alignments are \p SrcAlign and
861 /// \p DestAlign respectively.
862 void getMemcpyLoopResidualLoweringType(SmallVectorImpl<Type *> &OpsOut,
863 LLVMContext &Context,
864 unsigned RemainingBytes,
866 unsigned DestAlign) const;
868 /// \returns True if the two functions have compatible attributes for inlining
870 bool areInlineCompatible(const Function *Caller,
871 const Function *Callee) const;
873 /// \returns The bitwidth of the largest vector type that should be used to
874 /// load/store in the given address space.
875 unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const;
877 /// \returns True if the load instruction is legal to vectorize.
878 bool isLegalToVectorizeLoad(LoadInst *LI) const;
880 /// \returns True if the store instruction is legal to vectorize.
881 bool isLegalToVectorizeStore(StoreInst *SI) const;
883 /// \returns True if it is legal to vectorize the given load chain.
884 bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
886 unsigned AddrSpace) const;
888 /// \returns True if it is legal to vectorize the given store chain.
889 bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
891 unsigned AddrSpace) const;
893 /// \returns The new vector factor value if the target doesn't support \p
894 /// SizeInBytes loads or has a better vector factor.
895 unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
896 unsigned ChainSizeInBytes,
897 VectorType *VecTy) const;
899 /// \returns The new vector factor value if the target doesn't support \p
900 /// SizeInBytes stores or has a better vector factor.
901 unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
902 unsigned ChainSizeInBytes,
903 VectorType *VecTy) const;
905 /// Flags describing the kind of vector reduction.
906 struct ReductionFlags {
907 ReductionFlags() : IsMaxOp(false), IsSigned(false), NoNaN(false) {}
908 bool IsMaxOp; ///< If the op a min/max kind, true if it's a max operation.
909 bool IsSigned; ///< Whether the operation is a signed int reduction.
910 bool NoNaN; ///< If op is an fp min/max, whether NaNs may be present.
913 /// \returns True if the target wants to handle the given reduction idiom in
914 /// the intrinsics form instead of the shuffle form.
915 bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
916 ReductionFlags Flags) const;
918 /// \returns True if the target wants to expand the given reduction intrinsic
919 /// into a shuffle sequence.
920 bool shouldExpandReduction(const IntrinsicInst *II) const;
924 /// \brief Estimate the latency of specified instruction.
925 /// Returns 1 as the default value.
926 int getInstructionLatency(const Instruction *I) const;
928 /// \brief Returns the expected throughput cost of the instruction.
929 /// Returns -1 if the cost is unknown.
930 int getInstructionThroughput(const Instruction *I) const;
932 /// \brief The abstract base class used to type erase specific TTI
936 /// \brief The template model for the base class which wraps a concrete
937 /// implementation in a type erased interface.
938 template <typename T> class Model;
940 std::unique_ptr<Concept> TTIImpl;
943 class TargetTransformInfo::Concept {
945 virtual ~Concept() = 0;
946 virtual const DataLayout &getDataLayout() const = 0;
947 virtual int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) = 0;
948 virtual int getGEPCost(Type *PointeeType, const Value *Ptr,
949 ArrayRef<const Value *> Operands) = 0;
950 virtual int getExtCost(const Instruction *I, const Value *Src) = 0;
951 virtual int getCallCost(FunctionType *FTy, int NumArgs) = 0;
952 virtual int getCallCost(const Function *F, int NumArgs) = 0;
953 virtual int getCallCost(const Function *F,
954 ArrayRef<const Value *> Arguments) = 0;
955 virtual unsigned getInliningThresholdMultiplier() = 0;
956 virtual int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
957 ArrayRef<Type *> ParamTys) = 0;
958 virtual int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
959 ArrayRef<const Value *> Arguments) = 0;
960 virtual unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
961 unsigned &JTSize) = 0;
963 getUserCost(const User *U, ArrayRef<const Value *> Operands) = 0;
964 virtual bool hasBranchDivergence() = 0;
965 virtual bool isSourceOfDivergence(const Value *V) = 0;
966 virtual bool isAlwaysUniform(const Value *V) = 0;
967 virtual unsigned getFlatAddressSpace() = 0;
968 virtual bool isLoweredToCall(const Function *F) = 0;
969 virtual void getUnrollingPreferences(Loop *L, ScalarEvolution &,
970 UnrollingPreferences &UP) = 0;
971 virtual bool isLegalAddImmediate(int64_t Imm) = 0;
972 virtual bool isLegalICmpImmediate(int64_t Imm) = 0;
973 virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
974 int64_t BaseOffset, bool HasBaseReg,
978 virtual bool isLSRCostLess(TargetTransformInfo::LSRCost &C1,
979 TargetTransformInfo::LSRCost &C2) = 0;
980 virtual bool isLegalMaskedStore(Type *DataType) = 0;
981 virtual bool isLegalMaskedLoad(Type *DataType) = 0;
982 virtual bool isLegalMaskedScatter(Type *DataType) = 0;
983 virtual bool isLegalMaskedGather(Type *DataType) = 0;
984 virtual bool hasDivRemOp(Type *DataType, bool IsSigned) = 0;
985 virtual bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) = 0;
986 virtual bool prefersVectorizedAddressing() = 0;
987 virtual int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
988 int64_t BaseOffset, bool HasBaseReg,
989 int64_t Scale, unsigned AddrSpace) = 0;
990 virtual bool LSRWithInstrQueries() = 0;
991 virtual bool isTruncateFree(Type *Ty1, Type *Ty2) = 0;
992 virtual bool isProfitableToHoist(Instruction *I) = 0;
993 virtual bool isTypeLegal(Type *Ty) = 0;
994 virtual unsigned getJumpBufAlignment() = 0;
995 virtual unsigned getJumpBufSize() = 0;
996 virtual bool shouldBuildLookupTables() = 0;
997 virtual bool shouldBuildLookupTablesForConstant(Constant *C) = 0;
999 getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) = 0;
1000 virtual unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
1002 virtual bool supportsEfficientVectorElementLoadStore() = 0;
1003 virtual bool enableAggressiveInterleaving(bool LoopHasReductions) = 0;
1004 virtual const MemCmpExpansionOptions *enableMemCmpExpansion(
1005 bool IsZeroCmp) const = 0;
1006 virtual bool enableInterleavedAccessVectorization() = 0;
1007 virtual bool isFPVectorizationPotentiallyUnsafe() = 0;
1008 virtual bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
1010 unsigned AddressSpace,
1013 virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) = 0;
1014 virtual bool haveFastSqrt(Type *Ty) = 0;
1015 virtual bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) = 0;
1016 virtual int getFPOpCost(Type *Ty) = 0;
1017 virtual int getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm,
1019 virtual int getIntImmCost(const APInt &Imm, Type *Ty) = 0;
1020 virtual int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
1022 virtual int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
1024 virtual bool isOutOfOrder() const = 0;
1025 virtual unsigned getNumberOfRegisters(bool Vector) = 0;
1026 virtual unsigned getRegisterBitWidth(bool Vector) const = 0;
1027 virtual unsigned getMinVectorRegisterBitWidth() = 0;
1028 virtual bool shouldConsiderAddressTypePromotion(
1029 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) = 0;
1030 virtual unsigned getCacheLineSize() = 0;
1031 virtual llvm::Optional<unsigned> getCacheSize(CacheLevel Level) = 0;
1032 virtual llvm::Optional<unsigned> getCacheAssociativity(CacheLevel Level) = 0;
1033 virtual unsigned getPrefetchDistance() = 0;
1034 virtual unsigned getMinPrefetchStride() = 0;
1035 virtual unsigned getMaxPrefetchIterationsAhead() = 0;
1036 virtual unsigned getMaxInterleaveFactor(unsigned VF) = 0;
1038 getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
1039 OperandValueKind Opd2Info,
1040 OperandValueProperties Opd1PropInfo,
1041 OperandValueProperties Opd2PropInfo,
1042 ArrayRef<const Value *> Args) = 0;
1043 virtual int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
1045 virtual int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
1046 const Instruction *I) = 0;
1047 virtual int getExtractWithExtendCost(unsigned Opcode, Type *Dst,
1048 VectorType *VecTy, unsigned Index) = 0;
1049 virtual int getCFInstrCost(unsigned Opcode) = 0;
1050 virtual int getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
1051 Type *CondTy, const Instruction *I) = 0;
1052 virtual int getVectorInstrCost(unsigned Opcode, Type *Val,
1053 unsigned Index) = 0;
1054 virtual int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
1055 unsigned AddressSpace, const Instruction *I) = 0;
1056 virtual int getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
1058 unsigned AddressSpace) = 0;
1059 virtual int getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
1060 Value *Ptr, bool VariableMask,
1061 unsigned Alignment) = 0;
1062 virtual int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
1064 ArrayRef<unsigned> Indices,
1066 unsigned AddressSpace) = 0;
1067 virtual int getArithmeticReductionCost(unsigned Opcode, Type *Ty,
1068 bool IsPairwiseForm) = 0;
1069 virtual int getMinMaxReductionCost(Type *Ty, Type *CondTy,
1070 bool IsPairwiseForm, bool IsUnsigned) = 0;
1071 virtual int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
1072 ArrayRef<Type *> Tys, FastMathFlags FMF,
1073 unsigned ScalarizationCostPassed) = 0;
1074 virtual int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
1075 ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) = 0;
1076 virtual int getCallInstrCost(Function *F, Type *RetTy,
1077 ArrayRef<Type *> Tys) = 0;
1078 virtual unsigned getNumberOfParts(Type *Tp) = 0;
1079 virtual int getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
1080 const SCEV *Ptr) = 0;
1081 virtual unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) = 0;
1082 virtual bool getTgtMemIntrinsic(IntrinsicInst *Inst,
1083 MemIntrinsicInfo &Info) = 0;
1084 virtual unsigned getAtomicMemIntrinsicMaxElementSize() const = 0;
1085 virtual Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
1086 Type *ExpectedType) = 0;
1087 virtual Type *getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
1089 unsigned DestAlign) const = 0;
1090 virtual void getMemcpyLoopResidualLoweringType(
1091 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
1092 unsigned RemainingBytes, unsigned SrcAlign, unsigned DestAlign) const = 0;
1093 virtual bool areInlineCompatible(const Function *Caller,
1094 const Function *Callee) const = 0;
1095 virtual unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const = 0;
1096 virtual bool isLegalToVectorizeLoad(LoadInst *LI) const = 0;
1097 virtual bool isLegalToVectorizeStore(StoreInst *SI) const = 0;
1098 virtual bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1100 unsigned AddrSpace) const = 0;
1101 virtual bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1103 unsigned AddrSpace) const = 0;
1104 virtual unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
1105 unsigned ChainSizeInBytes,
1106 VectorType *VecTy) const = 0;
1107 virtual unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
1108 unsigned ChainSizeInBytes,
1109 VectorType *VecTy) const = 0;
1110 virtual bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
1111 ReductionFlags) const = 0;
1112 virtual bool shouldExpandReduction(const IntrinsicInst *II) const = 0;
1113 virtual int getInstructionLatency(const Instruction *I) = 0;
1116 template <typename T>
1117 class TargetTransformInfo::Model final : public TargetTransformInfo::Concept {
1121 Model(T Impl) : Impl(std::move(Impl)) {}
1122 ~Model() override {}
1124 const DataLayout &getDataLayout() const override {
1125 return Impl.getDataLayout();
1128 int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) override {
1129 return Impl.getOperationCost(Opcode, Ty, OpTy);
1131 int getGEPCost(Type *PointeeType, const Value *Ptr,
1132 ArrayRef<const Value *> Operands) override {
1133 return Impl.getGEPCost(PointeeType, Ptr, Operands);
1135 int getExtCost(const Instruction *I, const Value *Src) override {
1136 return Impl.getExtCost(I, Src);
1138 int getCallCost(FunctionType *FTy, int NumArgs) override {
1139 return Impl.getCallCost(FTy, NumArgs);
1141 int getCallCost(const Function *F, int NumArgs) override {
1142 return Impl.getCallCost(F, NumArgs);
1144 int getCallCost(const Function *F,
1145 ArrayRef<const Value *> Arguments) override {
1146 return Impl.getCallCost(F, Arguments);
1148 unsigned getInliningThresholdMultiplier() override {
1149 return Impl.getInliningThresholdMultiplier();
1151 int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
1152 ArrayRef<Type *> ParamTys) override {
1153 return Impl.getIntrinsicCost(IID, RetTy, ParamTys);
1155 int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
1156 ArrayRef<const Value *> Arguments) override {
1157 return Impl.getIntrinsicCost(IID, RetTy, Arguments);
1159 int getUserCost(const User *U, ArrayRef<const Value *> Operands) override {
1160 return Impl.getUserCost(U, Operands);
1162 bool hasBranchDivergence() override { return Impl.hasBranchDivergence(); }
1163 bool isSourceOfDivergence(const Value *V) override {
1164 return Impl.isSourceOfDivergence(V);
1167 bool isAlwaysUniform(const Value *V) override {
1168 return Impl.isAlwaysUniform(V);
1171 unsigned getFlatAddressSpace() override {
1172 return Impl.getFlatAddressSpace();
1175 bool isLoweredToCall(const Function *F) override {
1176 return Impl.isLoweredToCall(F);
1178 void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1179 UnrollingPreferences &UP) override {
1180 return Impl.getUnrollingPreferences(L, SE, UP);
1182 bool isLegalAddImmediate(int64_t Imm) override {
1183 return Impl.isLegalAddImmediate(Imm);
1185 bool isLegalICmpImmediate(int64_t Imm) override {
1186 return Impl.isLegalICmpImmediate(Imm);
1188 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
1189 bool HasBaseReg, int64_t Scale,
1191 Instruction *I) override {
1192 return Impl.isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
1193 Scale, AddrSpace, I);
1195 bool isLSRCostLess(TargetTransformInfo::LSRCost &C1,
1196 TargetTransformInfo::LSRCost &C2) override {
1197 return Impl.isLSRCostLess(C1, C2);
1199 bool isLegalMaskedStore(Type *DataType) override {
1200 return Impl.isLegalMaskedStore(DataType);
1202 bool isLegalMaskedLoad(Type *DataType) override {
1203 return Impl.isLegalMaskedLoad(DataType);
1205 bool isLegalMaskedScatter(Type *DataType) override {
1206 return Impl.isLegalMaskedScatter(DataType);
1208 bool isLegalMaskedGather(Type *DataType) override {
1209 return Impl.isLegalMaskedGather(DataType);
1211 bool hasDivRemOp(Type *DataType, bool IsSigned) override {
1212 return Impl.hasDivRemOp(DataType, IsSigned);
1214 bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) override {
1215 return Impl.hasVolatileVariant(I, AddrSpace);
1217 bool prefersVectorizedAddressing() override {
1218 return Impl.prefersVectorizedAddressing();
1220 int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
1221 bool HasBaseReg, int64_t Scale,
1222 unsigned AddrSpace) override {
1223 return Impl.getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg,
1226 bool LSRWithInstrQueries() override {
1227 return Impl.LSRWithInstrQueries();
1229 bool isTruncateFree(Type *Ty1, Type *Ty2) override {
1230 return Impl.isTruncateFree(Ty1, Ty2);
1232 bool isProfitableToHoist(Instruction *I) override {
1233 return Impl.isProfitableToHoist(I);
1235 bool isTypeLegal(Type *Ty) override { return Impl.isTypeLegal(Ty); }
1236 unsigned getJumpBufAlignment() override { return Impl.getJumpBufAlignment(); }
1237 unsigned getJumpBufSize() override { return Impl.getJumpBufSize(); }
1238 bool shouldBuildLookupTables() override {
1239 return Impl.shouldBuildLookupTables();
1241 bool shouldBuildLookupTablesForConstant(Constant *C) override {
1242 return Impl.shouldBuildLookupTablesForConstant(C);
1244 unsigned getScalarizationOverhead(Type *Ty, bool Insert,
1245 bool Extract) override {
1246 return Impl.getScalarizationOverhead(Ty, Insert, Extract);
1248 unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
1249 unsigned VF) override {
1250 return Impl.getOperandsScalarizationOverhead(Args, VF);
1253 bool supportsEfficientVectorElementLoadStore() override {
1254 return Impl.supportsEfficientVectorElementLoadStore();
1257 bool enableAggressiveInterleaving(bool LoopHasReductions) override {
1258 return Impl.enableAggressiveInterleaving(LoopHasReductions);
1260 const MemCmpExpansionOptions *enableMemCmpExpansion(
1261 bool IsZeroCmp) const override {
1262 return Impl.enableMemCmpExpansion(IsZeroCmp);
1264 bool enableInterleavedAccessVectorization() override {
1265 return Impl.enableInterleavedAccessVectorization();
1267 bool isFPVectorizationPotentiallyUnsafe() override {
1268 return Impl.isFPVectorizationPotentiallyUnsafe();
1270 bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
1271 unsigned BitWidth, unsigned AddressSpace,
1272 unsigned Alignment, bool *Fast) override {
1273 return Impl.allowsMisalignedMemoryAccesses(Context, BitWidth, AddressSpace,
1276 PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) override {
1277 return Impl.getPopcntSupport(IntTyWidthInBit);
1279 bool haveFastSqrt(Type *Ty) override { return Impl.haveFastSqrt(Ty); }
1281 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) override {
1282 return Impl.isFCmpOrdCheaperThanFCmpZero(Ty);
1285 int getFPOpCost(Type *Ty) override { return Impl.getFPOpCost(Ty); }
1287 int getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm,
1288 Type *Ty) override {
1289 return Impl.getIntImmCodeSizeCost(Opc, Idx, Imm, Ty);
1291 int getIntImmCost(const APInt &Imm, Type *Ty) override {
1292 return Impl.getIntImmCost(Imm, Ty);
1294 int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
1295 Type *Ty) override {
1296 return Impl.getIntImmCost(Opc, Idx, Imm, Ty);
1298 int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
1299 Type *Ty) override {
1300 return Impl.getIntImmCost(IID, Idx, Imm, Ty);
1302 bool isOutOfOrder() const override {
1303 return Impl.isOutOfOrder();
1305 unsigned getNumberOfRegisters(bool Vector) override {
1306 return Impl.getNumberOfRegisters(Vector);
1308 unsigned getRegisterBitWidth(bool Vector) const override {
1309 return Impl.getRegisterBitWidth(Vector);
1311 unsigned getMinVectorRegisterBitWidth() override {
1312 return Impl.getMinVectorRegisterBitWidth();
1314 bool shouldConsiderAddressTypePromotion(
1315 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) override {
1316 return Impl.shouldConsiderAddressTypePromotion(
1317 I, AllowPromotionWithoutCommonHeader);
1319 unsigned getCacheLineSize() override {
1320 return Impl.getCacheLineSize();
1322 llvm::Optional<unsigned> getCacheSize(CacheLevel Level) override {
1323 return Impl.getCacheSize(Level);
1325 llvm::Optional<unsigned> getCacheAssociativity(CacheLevel Level) override {
1326 return Impl.getCacheAssociativity(Level);
1328 unsigned getPrefetchDistance() override { return Impl.getPrefetchDistance(); }
1329 unsigned getMinPrefetchStride() override {
1330 return Impl.getMinPrefetchStride();
1332 unsigned getMaxPrefetchIterationsAhead() override {
1333 return Impl.getMaxPrefetchIterationsAhead();
1335 unsigned getMaxInterleaveFactor(unsigned VF) override {
1336 return Impl.getMaxInterleaveFactor(VF);
1338 unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
1339 unsigned &JTSize) override {
1340 return Impl.getEstimatedNumberOfCaseClusters(SI, JTSize);
1343 getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
1344 OperandValueKind Opd2Info,
1345 OperandValueProperties Opd1PropInfo,
1346 OperandValueProperties Opd2PropInfo,
1347 ArrayRef<const Value *> Args) override {
1348 return Impl.getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
1349 Opd1PropInfo, Opd2PropInfo, Args);
1351 int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
1352 Type *SubTp) override {
1353 return Impl.getShuffleCost(Kind, Tp, Index, SubTp);
1355 int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
1356 const Instruction *I) override {
1357 return Impl.getCastInstrCost(Opcode, Dst, Src, I);
1359 int getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy,
1360 unsigned Index) override {
1361 return Impl.getExtractWithExtendCost(Opcode, Dst, VecTy, Index);
1363 int getCFInstrCost(unsigned Opcode) override {
1364 return Impl.getCFInstrCost(Opcode);
1366 int getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
1367 const Instruction *I) override {
1368 return Impl.getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
1370 int getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) override {
1371 return Impl.getVectorInstrCost(Opcode, Val, Index);
1373 int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
1374 unsigned AddressSpace, const Instruction *I) override {
1375 return Impl.getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, I);
1377 int getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
1378 unsigned AddressSpace) override {
1379 return Impl.getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
1381 int getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
1382 Value *Ptr, bool VariableMask,
1383 unsigned Alignment) override {
1384 return Impl.getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
1387 int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor,
1388 ArrayRef<unsigned> Indices, unsigned Alignment,
1389 unsigned AddressSpace) override {
1390 return Impl.getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1391 Alignment, AddressSpace);
1393 int getArithmeticReductionCost(unsigned Opcode, Type *Ty,
1394 bool IsPairwiseForm) override {
1395 return Impl.getArithmeticReductionCost(Opcode, Ty, IsPairwiseForm);
1397 int getMinMaxReductionCost(Type *Ty, Type *CondTy,
1398 bool IsPairwiseForm, bool IsUnsigned) override {
1399 return Impl.getMinMaxReductionCost(Ty, CondTy, IsPairwiseForm, IsUnsigned);
1401 int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, ArrayRef<Type *> Tys,
1402 FastMathFlags FMF, unsigned ScalarizationCostPassed) override {
1403 return Impl.getIntrinsicInstrCost(ID, RetTy, Tys, FMF,
1404 ScalarizationCostPassed);
1406 int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
1407 ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) override {
1408 return Impl.getIntrinsicInstrCost(ID, RetTy, Args, FMF, VF);
1410 int getCallInstrCost(Function *F, Type *RetTy,
1411 ArrayRef<Type *> Tys) override {
1412 return Impl.getCallInstrCost(F, RetTy, Tys);
1414 unsigned getNumberOfParts(Type *Tp) override {
1415 return Impl.getNumberOfParts(Tp);
1417 int getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
1418 const SCEV *Ptr) override {
1419 return Impl.getAddressComputationCost(Ty, SE, Ptr);
1421 unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) override {
1422 return Impl.getCostOfKeepingLiveOverCall(Tys);
1424 bool getTgtMemIntrinsic(IntrinsicInst *Inst,
1425 MemIntrinsicInfo &Info) override {
1426 return Impl.getTgtMemIntrinsic(Inst, Info);
1428 unsigned getAtomicMemIntrinsicMaxElementSize() const override {
1429 return Impl.getAtomicMemIntrinsicMaxElementSize();
1431 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
1432 Type *ExpectedType) override {
1433 return Impl.getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
1435 Type *getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
1437 unsigned DestAlign) const override {
1438 return Impl.getMemcpyLoopLoweringType(Context, Length, SrcAlign, DestAlign);
1440 void getMemcpyLoopResidualLoweringType(SmallVectorImpl<Type *> &OpsOut,
1441 LLVMContext &Context,
1442 unsigned RemainingBytes,
1444 unsigned DestAlign) const override {
1445 Impl.getMemcpyLoopResidualLoweringType(OpsOut, Context, RemainingBytes,
1446 SrcAlign, DestAlign);
1448 bool areInlineCompatible(const Function *Caller,
1449 const Function *Callee) const override {
1450 return Impl.areInlineCompatible(Caller, Callee);
1452 unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const override {
1453 return Impl.getLoadStoreVecRegBitWidth(AddrSpace);
1455 bool isLegalToVectorizeLoad(LoadInst *LI) const override {
1456 return Impl.isLegalToVectorizeLoad(LI);
1458 bool isLegalToVectorizeStore(StoreInst *SI) const override {
1459 return Impl.isLegalToVectorizeStore(SI);
1461 bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1463 unsigned AddrSpace) const override {
1464 return Impl.isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment,
1467 bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1469 unsigned AddrSpace) const override {
1470 return Impl.isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment,
1473 unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
1474 unsigned ChainSizeInBytes,
1475 VectorType *VecTy) const override {
1476 return Impl.getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy);
1478 unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
1479 unsigned ChainSizeInBytes,
1480 VectorType *VecTy) const override {
1481 return Impl.getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy);
1483 bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
1484 ReductionFlags Flags) const override {
1485 return Impl.useReductionIntrinsic(Opcode, Ty, Flags);
1487 bool shouldExpandReduction(const IntrinsicInst *II) const override {
1488 return Impl.shouldExpandReduction(II);
1490 int getInstructionLatency(const Instruction *I) override {
1491 return Impl.getInstructionLatency(I);
1495 template <typename T>
1496 TargetTransformInfo::TargetTransformInfo(T Impl)
1497 : TTIImpl(new Model<T>(Impl)) {}
1499 /// \brief Analysis pass providing the \c TargetTransformInfo.
1501 /// The core idea of the TargetIRAnalysis is to expose an interface through
1502 /// which LLVM targets can analyze and provide information about the middle
1503 /// end's target-independent IR. This supports use cases such as target-aware
1504 /// cost modeling of IR constructs.
1506 /// This is a function analysis because much of the cost modeling for targets
1507 /// is done in a subtarget specific way and LLVM supports compiling different
1508 /// functions targeting different subtargets in order to support runtime
1509 /// dispatch according to the observed subtarget.
1510 class TargetIRAnalysis : public AnalysisInfoMixin<TargetIRAnalysis> {
1512 typedef TargetTransformInfo Result;
1514 /// \brief Default construct a target IR analysis.
1516 /// This will use the module's datalayout to construct a baseline
1517 /// conservative TTI result.
1520 /// \brief Construct an IR analysis pass around a target-provide callback.
1522 /// The callback will be called with a particular function for which the TTI
1523 /// is needed and must return a TTI object for that function.
1524 TargetIRAnalysis(std::function<Result(const Function &)> TTICallback);
1526 // Value semantics. We spell out the constructors for MSVC.
1527 TargetIRAnalysis(const TargetIRAnalysis &Arg)
1528 : TTICallback(Arg.TTICallback) {}
1529 TargetIRAnalysis(TargetIRAnalysis &&Arg)
1530 : TTICallback(std::move(Arg.TTICallback)) {}
1531 TargetIRAnalysis &operator=(const TargetIRAnalysis &RHS) {
1532 TTICallback = RHS.TTICallback;
1535 TargetIRAnalysis &operator=(TargetIRAnalysis &&RHS) {
1536 TTICallback = std::move(RHS.TTICallback);
1540 Result run(const Function &F, FunctionAnalysisManager &);
1543 friend AnalysisInfoMixin<TargetIRAnalysis>;
1544 static AnalysisKey Key;
1546 /// \brief The callback used to produce a result.
1548 /// We use a completely opaque callback so that targets can provide whatever
1549 /// mechanism they desire for constructing the TTI for a given function.
1551 /// FIXME: Should we really use std::function? It's relatively inefficient.
1552 /// It might be possible to arrange for even stateful callbacks to outlive
1553 /// the analysis and thus use a function_ref which would be lighter weight.
1554 /// This may also be less error prone as the callback is likely to reference
1555 /// the external TargetMachine, and that reference needs to never dangle.
1556 std::function<Result(const Function &)> TTICallback;
1558 /// \brief Helper function used as the callback in the default constructor.
1559 static Result getDefaultTTI(const Function &F);
1562 /// \brief Wrapper pass for TargetTransformInfo.
1564 /// This pass can be constructed from a TTI object which it stores internally
1565 /// and is queried by passes.
1566 class TargetTransformInfoWrapperPass : public ImmutablePass {
1567 TargetIRAnalysis TIRA;
1568 Optional<TargetTransformInfo> TTI;
1570 virtual void anchor();
1575 /// \brief We must provide a default constructor for the pass but it should
1578 /// Use the constructor below or call one of the creation routines.
1579 TargetTransformInfoWrapperPass();
1581 explicit TargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
1583 TargetTransformInfo &getTTI(const Function &F);
1586 /// \brief Create an analysis pass wrapper around a TTI object.
1588 /// This analysis pass just holds the TTI instance and makes it available to
1590 ImmutablePass *createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
1592 } // End llvm namespace