LLVM 19.0.0git
TargetTransformInfo.h
Go to the documentation of this file.
1//===- TargetTransformInfo.h ------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This pass exposes codegen information to IR-level passes. Every
10/// transformation that uses codegen information is broken into three parts:
11/// 1. The IR-level analysis pass.
12/// 2. The IR-level transformation interface which provides the needed
13/// information.
14/// 3. Codegen-level implementation which uses target-specific hooks.
15///
16/// This file defines #2, which is the interface that IR-level transformations
17/// use for querying the codegen.
18///
19//===----------------------------------------------------------------------===//
20
21#ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
22#define LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
23
25#include "llvm/IR/FMF.h"
26#include "llvm/IR/InstrTypes.h"
27#include "llvm/IR/PassManager.h"
28#include "llvm/Pass.h"
32#include <functional>
33#include <optional>
34#include <utility>
35
36namespace llvm {
37
38namespace Intrinsic {
39typedef unsigned ID;
40}
41
42class AllocaInst;
43class AssumptionCache;
44class BlockFrequencyInfo;
45class DominatorTree;
46class BranchInst;
47class CallBase;
48class Function;
49class GlobalValue;
50class InstCombiner;
51class OptimizationRemarkEmitter;
52class InterleavedAccessInfo;
53class IntrinsicInst;
54class LoadInst;
55class Loop;
56class LoopInfo;
57class LoopVectorizationLegality;
58class ProfileSummaryInfo;
59class RecurrenceDescriptor;
60class SCEV;
61class ScalarEvolution;
62class StoreInst;
63class SwitchInst;
64class TargetLibraryInfo;
65class Type;
66class User;
67class Value;
68class VPIntrinsic;
69struct KnownBits;
70
71/// Information about a load/store intrinsic defined by the target.
73 /// This is the pointer that the intrinsic is loading from or storing to.
74 /// If this is non-null, then analysis/optimization passes can assume that
75 /// this intrinsic is functionally equivalent to a load/store from this
76 /// pointer.
77 Value *PtrVal = nullptr;
78
79 // Ordering for atomic operations.
81
82 // Same Id is set by the target for corresponding load/store intrinsics.
83 unsigned short MatchingId = 0;
84
85 bool ReadMem = false;
86 bool WriteMem = false;
87 bool IsVolatile = false;
88
89 bool isUnordered() const {
93 }
94};
95
96/// Attributes of a target dependent hardware loop.
98 HardwareLoopInfo() = delete;
100 Loop *L = nullptr;
103 const SCEV *ExitCount = nullptr;
105 Value *LoopDecrement = nullptr; // Decrement the loop counter by this
106 // value in every iteration.
107 bool IsNestingLegal = false; // Can a hardware loop be a parent to
108 // another hardware loop?
109 bool CounterInReg = false; // Should loop counter be updated in
110 // the loop via a phi?
111 bool PerformEntryTest = false; // Generate the intrinsic which also performs
112 // icmp ne zero on the loop counter value and
113 // produces an i1 to guard the loop entry.
115 DominatorTree &DT, bool ForceNestedLoop = false,
116 bool ForceHardwareLoopPHI = false);
117 bool canAnalyze(LoopInfo &LI);
118};
119
121 const IntrinsicInst *II = nullptr;
122 Type *RetTy = nullptr;
123 Intrinsic::ID IID;
124 SmallVector<Type *, 4> ParamTys;
126 FastMathFlags FMF;
127 // If ScalarizationCost is UINT_MAX, the cost of scalarizing the
128 // arguments and the return value will be computed based on types.
129 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
130
131public:
133 Intrinsic::ID Id, const CallBase &CI,
135 bool TypeBasedOnly = false);
136
138 Intrinsic::ID Id, Type *RTy, ArrayRef<Type *> Tys,
139 FastMathFlags Flags = FastMathFlags(), const IntrinsicInst *I = nullptr,
141
144
148 const IntrinsicInst *I = nullptr,
150
151 Intrinsic::ID getID() const { return IID; }
152 const IntrinsicInst *getInst() const { return II; }
153 Type *getReturnType() const { return RetTy; }
154 FastMathFlags getFlags() const { return FMF; }
155 InstructionCost getScalarizationCost() const { return ScalarizationCost; }
157 const SmallVectorImpl<Type *> &getArgTypes() const { return ParamTys; }
158
159 bool isTypeBasedOnly() const {
160 return Arguments.empty();
161 }
162
163 bool skipScalarizationCost() const { return ScalarizationCost.isValid(); }
164};
165
167 /// Don't use tail folding
168 None,
169 /// Use predicate only to mask operations on data in the loop.
170 /// When the VL is not known to be a power-of-2, this method requires a
171 /// runtime overflow check for the i + VL in the loop because it compares the
172 /// scalar induction variable against the tripcount rounded up by VL which may
173 /// overflow. When the VL is a power-of-2, both the increment and uprounded
174 /// tripcount will overflow to 0, which does not require a runtime check
175 /// since the loop is exited when the loop induction variable equals the
176 /// uprounded trip-count, which are both 0.
177 Data,
178 /// Same as Data, but avoids using the get.active.lane.mask intrinsic to
179 /// calculate the mask and instead implements this with a
180 /// splat/stepvector/cmp.
181 /// FIXME: Can this kind be removed now that SelectionDAGBuilder expands the
182 /// active.lane.mask intrinsic when it is not natively supported?
184 /// Use predicate to control both data and control flow.
185 /// This method always requires a runtime overflow check for the i + VL
186 /// increment inside the loop, because it uses the result direclty in the
187 /// active.lane.mask to calculate the mask for the next iteration. If the
188 /// increment overflows, the mask is no longer correct.
190 /// Use predicate to control both data and control flow, but modify
191 /// the trip count so that a runtime overflow check can be avoided
192 /// and such that the scalar epilogue loop can always be removed.
194 /// Use predicated EVL instructions for tail-folding.
195 /// Indicates that VP intrinsics should be used.
197};
198
205 : TLI(TLI), LVL(LVL), IAI(IAI) {}
206};
207
208class TargetTransformInfo;
210
211/// This pass provides access to the codegen interfaces that are needed
212/// for IR-level transformations.
214public:
215 /// Construct a TTI object using a type implementing the \c Concept
216 /// API below.
217 ///
218 /// This is used by targets to construct a TTI wrapping their target-specific
219 /// implementation that encodes appropriate costs for their target.
220 template <typename T> TargetTransformInfo(T Impl);
221
222 /// Construct a baseline TTI object using a minimal implementation of
223 /// the \c Concept API below.
224 ///
225 /// The TTI implementation will reflect the information in the DataLayout
226 /// provided if non-null.
227 explicit TargetTransformInfo(const DataLayout &DL);
228
229 // Provide move semantics.
232
233 // We need to define the destructor out-of-line to define our sub-classes
234 // out-of-line.
236
237 /// Handle the invalidation of this information.
238 ///
239 /// When used as a result of \c TargetIRAnalysis this method will be called
240 /// when the function this was computed for changes. When it returns false,
241 /// the information is preserved across those changes.
244 // FIXME: We should probably in some way ensure that the subtarget
245 // information for a function hasn't changed.
246 return false;
247 }
248
249 /// \name Generic Target Information
250 /// @{
251
252 /// The kind of cost model.
253 ///
254 /// There are several different cost models that can be customized by the
255 /// target. The normalization of each cost model may be target specific.
256 /// e.g. TCK_SizeAndLatency should be comparable to target thresholds such as
257 /// those derived from MCSchedModel::LoopMicroOpBufferSize etc.
259 TCK_RecipThroughput, ///< Reciprocal throughput.
260 TCK_Latency, ///< The latency of instruction.
261 TCK_CodeSize, ///< Instruction code size.
262 TCK_SizeAndLatency ///< The weighted sum of size and latency.
263 };
264
265 /// Underlying constants for 'cost' values in this interface.
266 ///
267 /// Many APIs in this interface return a cost. This enum defines the
268 /// fundamental values that should be used to interpret (and produce) those
269 /// costs. The costs are returned as an int rather than a member of this
270 /// enumeration because it is expected that the cost of one IR instruction
271 /// may have a multiplicative factor to it or otherwise won't fit directly
272 /// into the enum. Moreover, it is common to sum or average costs which works
273 /// better as simple integral values. Thus this enum only provides constants.
274 /// Also note that the returned costs are signed integers to make it natural
275 /// to add, subtract, and test with zero (a common boundary condition). It is
276 /// not expected that 2^32 is a realistic cost to be modeling at any point.
277 ///
278 /// Note that these costs should usually reflect the intersection of code-size
279 /// cost and execution cost. A free instruction is typically one that folds
280 /// into another instruction. For example, reg-to-reg moves can often be
281 /// skipped by renaming the registers in the CPU, but they still are encoded
282 /// and thus wouldn't be considered 'free' here.
284 TCC_Free = 0, ///< Expected to fold away in lowering.
285 TCC_Basic = 1, ///< The cost of a typical 'add' instruction.
286 TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
287 };
288
289 /// Estimate the cost of a GEP operation when lowered.
290 ///
291 /// \p PointeeType is the source element type of the GEP.
292 /// \p Ptr is the base pointer operand.
293 /// \p Operands is the list of indices following the base pointer.
294 ///
295 /// \p AccessType is a hint as to what type of memory might be accessed by
296 /// users of the GEP. getGEPCost will use it to determine if the GEP can be
297 /// folded into the addressing mode of a load/store. If AccessType is null,
298 /// then the resulting target type based off of PointeeType will be used as an
299 /// approximation.
301 getGEPCost(Type *PointeeType, const Value *Ptr,
302 ArrayRef<const Value *> Operands, Type *AccessType = nullptr,
304
305 /// Describe known properties for a set of pointers.
307 /// All the GEPs in a set have same base address.
308 unsigned IsSameBaseAddress : 1;
309 /// These properties only valid if SameBaseAddress is set.
310 /// True if all pointers are separated by a unit stride.
311 unsigned IsUnitStride : 1;
312 /// True if distance between any two neigbouring pointers is a known value.
313 unsigned IsKnownStride : 1;
314 unsigned Reserved : 29;
315
316 bool isSameBase() const { return IsSameBaseAddress; }
317 bool isUnitStride() const { return IsSameBaseAddress && IsUnitStride; }
319
321 return {/*IsSameBaseAddress=*/1, /*IsUnitStride=*/1,
322 /*IsKnownStride=*/1, 0};
323 }
325 return {/*IsSameBaseAddress=*/1, /*IsUnitStride=*/0,
326 /*IsKnownStride=*/1, 0};
327 }
329 return {/*IsSameBaseAddress=*/1, /*IsUnitStride=*/0,
330 /*IsKnownStride=*/0, 0};
331 }
332 };
333 static_assert(sizeof(PointersChainInfo) == 4, "Was size increase justified?");
334
335 /// Estimate the cost of a chain of pointers (typically pointer operands of a
336 /// chain of loads or stores within same block) operations set when lowered.
337 /// \p AccessTy is the type of the loads/stores that will ultimately use the
338 /// \p Ptrs.
341 const PointersChainInfo &Info, Type *AccessTy,
343
344 ) const;
345
346 /// \returns A value by which our inlining threshold should be multiplied.
347 /// This is primarily used to bump up the inlining threshold wholesale on
348 /// targets where calls are unusually expensive.
349 ///
350 /// TODO: This is a rather blunt instrument. Perhaps altering the costs of
351 /// individual classes of instructions would be better.
352 unsigned getInliningThresholdMultiplier() const;
353
356
357 /// \returns A value to be added to the inlining threshold.
358 unsigned adjustInliningThreshold(const CallBase *CB) const;
359
360 /// \returns The cost of having an Alloca in the caller if not inlined, to be
361 /// added to the threshold
362 unsigned getCallerAllocaCost(const CallBase *CB, const AllocaInst *AI) const;
363
364 /// \returns Vector bonus in percent.
365 ///
366 /// Vector bonuses: We want to more aggressively inline vector-dense kernels
367 /// and apply this bonus based on the percentage of vector instructions. A
368 /// bonus is applied if the vector instructions exceed 50% and half that
369 /// amount is applied if it exceeds 10%. Note that these bonuses are some what
370 /// arbitrary and evolved over time by accident as much as because they are
371 /// principled bonuses.
372 /// FIXME: It would be nice to base the bonus values on something more
373 /// scientific. A target may has no bonus on vector instructions.
375
376 /// \return the expected cost of a memcpy, which could e.g. depend on the
377 /// source/destination type and alignment and the number of bytes copied.
379
380 /// Returns the maximum memset / memcpy size in bytes that still makes it
381 /// profitable to inline the call.
383
384 /// \return The estimated number of case clusters when lowering \p 'SI'.
385 /// \p JTSize Set a jump table size only when \p SI is suitable for a jump
386 /// table.
388 unsigned &JTSize,
390 BlockFrequencyInfo *BFI) const;
391
392 /// Estimate the cost of a given IR user when lowered.
393 ///
394 /// This can estimate the cost of either a ConstantExpr or Instruction when
395 /// lowered.
396 ///
397 /// \p Operands is a list of operands which can be a result of transformations
398 /// of the current operands. The number of the operands on the list must equal
399 /// to the number of the current operands the IR user has. Their order on the
400 /// list must be the same as the order of the current operands the IR user
401 /// has.
402 ///
403 /// The returned cost is defined in terms of \c TargetCostConstants, see its
404 /// comments for a detailed explanation of the cost values.
408
409 /// This is a helper function which calls the three-argument
410 /// getInstructionCost with \p Operands which are the current operands U has.
412 TargetCostKind CostKind) const {
413 SmallVector<const Value *, 4> Operands(U->operand_values());
415 }
416
417 /// If a branch or a select condition is skewed in one direction by more than
418 /// this factor, it is very likely to be predicted correctly.
420
421 /// Return true if branch divergence exists.
422 ///
423 /// Branch divergence has a significantly negative impact on GPU performance
424 /// when threads in the same wavefront take different paths due to conditional
425 /// branches.
426 ///
427 /// If \p F is passed, provides a context function. If \p F is known to only
428 /// execute in a single threaded environment, the target may choose to skip
429 /// uniformity analysis and assume all values are uniform.
430 bool hasBranchDivergence(const Function *F = nullptr) const;
431
432 /// Returns whether V is a source of divergence.
433 ///
434 /// This function provides the target-dependent information for
435 /// the target-independent UniformityAnalysis.
436 bool isSourceOfDivergence(const Value *V) const;
437
438 // Returns true for the target specific
439 // set of operations which produce uniform result
440 // even taking non-uniform arguments
441 bool isAlwaysUniform(const Value *V) const;
442
443 /// Query the target whether the specified address space cast from FromAS to
444 /// ToAS is valid.
445 bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const;
446
447 /// Return false if a \p AS0 address cannot possibly alias a \p AS1 address.
448 bool addrspacesMayAlias(unsigned AS0, unsigned AS1) const;
449
450 /// Returns the address space ID for a target's 'flat' address space. Note
451 /// this is not necessarily the same as addrspace(0), which LLVM sometimes
452 /// refers to as the generic address space. The flat address space is a
453 /// generic address space that can be used access multiple segments of memory
454 /// with different address spaces. Access of a memory location through a
455 /// pointer with this address space is expected to be legal but slower
456 /// compared to the same memory location accessed through a pointer with a
457 /// different address space.
458 //
459 /// This is for targets with different pointer representations which can
460 /// be converted with the addrspacecast instruction. If a pointer is converted
461 /// to this address space, optimizations should attempt to replace the access
462 /// with the source address space.
463 ///
464 /// \returns ~0u if the target does not have such a flat address space to
465 /// optimize away.
466 unsigned getFlatAddressSpace() const;
467
468 /// Return any intrinsic address operand indexes which may be rewritten if
469 /// they use a flat address space pointer.
470 ///
471 /// \returns true if the intrinsic was handled.
473 Intrinsic::ID IID) const;
474
475 bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const;
476
477 /// Return true if globals in this address space can have initializers other
478 /// than `undef`.
480
481 unsigned getAssumedAddrSpace(const Value *V) const;
482
483 bool isSingleThreaded() const;
484
485 std::pair<const Value *, unsigned>
486 getPredicatedAddrSpace(const Value *V) const;
487
488 /// Rewrite intrinsic call \p II such that \p OldV will be replaced with \p
489 /// NewV, which has a different address space. This should happen for every
490 /// operand index that collectFlatAddressOperands returned for the intrinsic.
491 /// \returns nullptr if the intrinsic was not handled. Otherwise, returns the
492 /// new value (which may be the original \p II with modified operands).
494 Value *NewV) const;
495
496 /// Test whether calls to a function lower to actual program function
497 /// calls.
498 ///
499 /// The idea is to test whether the program is likely to require a 'call'
500 /// instruction or equivalent in order to call the given function.
501 ///
502 /// FIXME: It's not clear that this is a good or useful query API. Client's
503 /// should probably move to simpler cost metrics using the above.
504 /// Alternatively, we could split the cost interface into distinct code-size
505 /// and execution-speed costs. This would allow modelling the core of this
506 /// query more accurately as a call is a single small instruction, but
507 /// incurs significant execution cost.
508 bool isLoweredToCall(const Function *F) const;
509
510 struct LSRCost {
511 /// TODO: Some of these could be merged. Also, a lexical ordering
512 /// isn't always optimal.
513 unsigned Insns;
514 unsigned NumRegs;
515 unsigned AddRecCost;
516 unsigned NumIVMuls;
517 unsigned NumBaseAdds;
518 unsigned ImmCost;
519 unsigned SetupCost;
520 unsigned ScaleCost;
521 };
522
523 /// Parameters that control the generic loop unrolling transformation.
525 /// The cost threshold for the unrolled loop. Should be relative to the
526 /// getInstructionCost values returned by this API, and the expectation is
527 /// that the unrolled loop's instructions when run through that interface
528 /// should not exceed this cost. However, this is only an estimate. Also,
529 /// specific loops may be unrolled even with a cost above this threshold if
530 /// deemed profitable. Set this to UINT_MAX to disable the loop body cost
531 /// restriction.
532 unsigned Threshold;
533 /// If complete unrolling will reduce the cost of the loop, we will boost
534 /// the Threshold by a certain percent to allow more aggressive complete
535 /// unrolling. This value provides the maximum boost percentage that we
536 /// can apply to Threshold (The value should be no less than 100).
537 /// BoostedThreshold = Threshold * min(RolledCost / UnrolledCost,
538 /// MaxPercentThresholdBoost / 100)
539 /// E.g. if complete unrolling reduces the loop execution time by 50%
540 /// then we boost the threshold by the factor of 2x. If unrolling is not
541 /// expected to reduce the running time, then we do not increase the
542 /// threshold.
544 /// The cost threshold for the unrolled loop when optimizing for size (set
545 /// to UINT_MAX to disable).
547 /// The cost threshold for the unrolled loop, like Threshold, but used
548 /// for partial/runtime unrolling (set to UINT_MAX to disable).
550 /// The cost threshold for the unrolled loop when optimizing for size, like
551 /// OptSizeThreshold, but used for partial/runtime unrolling (set to
552 /// UINT_MAX to disable).
554 /// A forced unrolling factor (the number of concatenated bodies of the
555 /// original loop in the unrolled loop body). When set to 0, the unrolling
556 /// transformation will select an unrolling factor based on the current cost
557 /// threshold and other factors.
558 unsigned Count;
559 /// Default unroll count for loops with run-time trip count.
561 // Set the maximum unrolling factor. The unrolling factor may be selected
562 // using the appropriate cost threshold, but may not exceed this number
563 // (set to UINT_MAX to disable). This does not apply in cases where the
564 // loop is being fully unrolled.
565 unsigned MaxCount;
566 /// Set the maximum upper bound of trip count. Allowing the MaxUpperBound
567 /// to be overrided by a target gives more flexiblity on certain cases.
568 /// By default, MaxUpperBound uses UnrollMaxUpperBound which value is 8.
570 /// Set the maximum unrolling factor for full unrolling. Like MaxCount, but
571 /// applies even if full unrolling is selected. This allows a target to fall
572 /// back to Partial unrolling if full unrolling is above FullUnrollMaxCount.
574 // Represents number of instructions optimized when "back edge"
575 // becomes "fall through" in unrolled loop.
576 // For now we count a conditional branch on a backedge and a comparison
577 // feeding it.
578 unsigned BEInsns;
579 /// Allow partial unrolling (unrolling of loops to expand the size of the
580 /// loop body, not only to eliminate small constant-trip-count loops).
582 /// Allow runtime unrolling (unrolling of loops to expand the size of the
583 /// loop body even when the number of loop iterations is not known at
584 /// compile time).
586 /// Allow generation of a loop remainder (extra iterations after unroll).
588 /// Allow emitting expensive instructions (such as divisions) when computing
589 /// the trip count of a loop for runtime unrolling.
591 /// Apply loop unroll on any kind of loop
592 /// (mainly to loops that fail runtime unrolling).
593 bool Force;
594 /// Allow using trip count upper bound to unroll loops.
596 /// Allow unrolling of all the iterations of the runtime loop remainder.
598 /// Allow unroll and jam. Used to enable unroll and jam for the target.
600 /// Threshold for unroll and jam, for inner loop size. The 'Threshold'
601 /// value above is used during unroll and jam for the outer loop size.
602 /// This value is used in the same manner to limit the size of the inner
603 /// loop.
605 /// Don't allow loop unrolling to simulate more than this number of
606 /// iterations when checking full unroll profitability
608 /// Don't disable runtime unroll for the loops which were vectorized.
610 };
611
612 /// Get target-customized preferences for the generic loop unrolling
613 /// transformation. The caller will initialize UP with the current
614 /// target-independent defaults.
617 OptimizationRemarkEmitter *ORE) const;
618
619 /// Query the target whether it would be profitable to convert the given loop
620 /// into a hardware loop.
623 HardwareLoopInfo &HWLoopInfo) const;
624
625 /// Query the target whether it would be prefered to create a predicated
626 /// vector loop, which can avoid the need to emit a scalar epilogue loop.
628
629 /// Query the target what the preferred style of tail folding is.
630 /// \param IVUpdateMayOverflow Tells whether it is known if the IV update
631 /// may (or will never) overflow for the suggested VF/UF in the given loop.
632 /// Targets can use this information to select a more optimal tail folding
633 /// style. The value conservatively defaults to true, such that no assumptions
634 /// are made on overflow.
636 getPreferredTailFoldingStyle(bool IVUpdateMayOverflow = true) const;
637
638 // Parameters that control the loop peeling transformation
640 /// A forced peeling factor (the number of bodied of the original loop
641 /// that should be peeled off before the loop body). When set to 0, the
642 /// a peeling factor based on profile information and other factors.
643 unsigned PeelCount;
644 /// Allow peeling off loop iterations.
646 /// Allow peeling off loop iterations for loop nests.
648 /// Allow peeling basing on profile. Uses to enable peeling off all
649 /// iterations basing on provided profile.
650 /// If the value is true the peeling cost model can decide to peel only
651 /// some iterations and in this case it will set this to false.
653 };
654
655 /// Get target-customized preferences for the generic loop peeling
656 /// transformation. The caller will initialize \p PP with the current
657 /// target-independent defaults with information from \p L and \p SE.
659 PeelingPreferences &PP) const;
660
661 /// Targets can implement their own combinations for target-specific
662 /// intrinsics. This function will be called from the InstCombine pass every
663 /// time a target-specific intrinsic is encountered.
664 ///
665 /// \returns std::nullopt to not do anything target specific or a value that
666 /// will be returned from the InstCombiner. It is possible to return null and
667 /// stop further processing of the intrinsic by returning nullptr.
668 std::optional<Instruction *> instCombineIntrinsic(InstCombiner & IC,
669 IntrinsicInst & II) const;
670 /// Can be used to implement target-specific instruction combining.
671 /// \see instCombineIntrinsic
672 std::optional<Value *> simplifyDemandedUseBitsIntrinsic(
673 InstCombiner & IC, IntrinsicInst & II, APInt DemandedMask,
674 KnownBits & Known, bool &KnownBitsComputed) const;
675 /// Can be used to implement target-specific instruction combining.
676 /// \see instCombineIntrinsic
677 std::optional<Value *> simplifyDemandedVectorEltsIntrinsic(
678 InstCombiner & IC, IntrinsicInst & II, APInt DemandedElts,
679 APInt & UndefElts, APInt & UndefElts2, APInt & UndefElts3,
680 std::function<void(Instruction *, unsigned, APInt, APInt &)>
681 SimplifyAndSetOp) const;
682 /// @}
683
684 /// \name Scalar Target Information
685 /// @{
686
687 /// Flags indicating the kind of support for population count.
688 ///
689 /// Compared to the SW implementation, HW support is supposed to
690 /// significantly boost the performance when the population is dense, and it
691 /// may or may not degrade performance if the population is sparse. A HW
692 /// support is considered as "Fast" if it can outperform, or is on a par
693 /// with, SW implementation when the population is sparse; otherwise, it is
694 /// considered as "Slow".
696
697 /// Return true if the specified immediate is legal add immediate, that
698 /// is the target has add instructions which can add a register with the
699 /// immediate without having to materialize the immediate into a register.
700 bool isLegalAddImmediate(int64_t Imm) const;
701
702 /// Return true if adding the specified scalable immediate is legal, that is
703 /// the target has add instructions which can add a register with the
704 /// immediate (multiplied by vscale) without having to materialize the
705 /// immediate into a register.
706 bool isLegalAddScalableImmediate(int64_t Imm) const;
707
708 /// Return true if the specified immediate is legal icmp immediate,
709 /// that is the target has icmp instructions which can compare a register
710 /// against the immediate without having to materialize the immediate into a
711 /// register.
712 bool isLegalICmpImmediate(int64_t Imm) const;
713
714 /// Return true if the addressing mode represented by AM is legal for
715 /// this target, for a load/store of the specified type.
716 /// The type may be VoidTy, in which case only return true if the addressing
717 /// mode is legal for a load/store of any legal type.
718 /// If target returns true in LSRWithInstrQueries(), I may be valid.
719 /// \param ScalableOffset represents a quantity of bytes multiplied by vscale,
720 /// an invariant value known only at runtime. Most targets should not accept
721 /// a scalable offset.
722 ///
723 /// TODO: Handle pre/postinc as well.
724 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
725 bool HasBaseReg, int64_t Scale,
726 unsigned AddrSpace = 0, Instruction *I = nullptr,
727 int64_t ScalableOffset = 0) const;
728
729 /// Return true if LSR cost of C1 is lower than C2.
731 const TargetTransformInfo::LSRCost &C2) const;
732
733 /// Return true if LSR major cost is number of registers. Targets which
734 /// implement their own isLSRCostLess and unset number of registers as major
735 /// cost should return false, otherwise return true.
736 bool isNumRegsMajorCostOfLSR() const;
737
738 /// Return true if LSR should attempts to replace a use of an otherwise dead
739 /// primary IV in the latch condition with another IV available in the loop.
740 /// When successful, makes the primary IV dead.
742
743 /// \returns true if LSR should not optimize a chain that includes \p I.
745
746 /// Return true if the target can fuse a compare and branch.
747 /// Loop-strength-reduction (LSR) uses that knowledge to adjust its cost
748 /// calculation for the instructions in a loop.
749 bool canMacroFuseCmp() const;
750
751 /// Return true if the target can save a compare for loop count, for example
752 /// hardware loop saves a compare.
753 bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE, LoopInfo *LI,
755 TargetLibraryInfo *LibInfo) const;
756
761 };
762
763 /// Return the preferred addressing mode LSR should make efforts to generate.
765 ScalarEvolution *SE) const;
766
767 /// Return true if the target supports masked store.
768 bool isLegalMaskedStore(Type *DataType, Align Alignment) const;
769 /// Return true if the target supports masked load.
770 bool isLegalMaskedLoad(Type *DataType, Align Alignment) const;
771
772 /// Return true if the target supports nontemporal store.
773 bool isLegalNTStore(Type *DataType, Align Alignment) const;
774 /// Return true if the target supports nontemporal load.
775 bool isLegalNTLoad(Type *DataType, Align Alignment) const;
776
777 /// \Returns true if the target supports broadcasting a load to a vector of
778 /// type <NumElements x ElementTy>.
779 bool isLegalBroadcastLoad(Type *ElementTy, ElementCount NumElements) const;
780
781 /// Return true if the target supports masked scatter.
782 bool isLegalMaskedScatter(Type *DataType, Align Alignment) const;
783 /// Return true if the target supports masked gather.
784 bool isLegalMaskedGather(Type *DataType, Align Alignment) const;
785 /// Return true if the target forces scalarizing of llvm.masked.gather
786 /// intrinsics.
787 bool forceScalarizeMaskedGather(VectorType *Type, Align Alignment) const;
788 /// Return true if the target forces scalarizing of llvm.masked.scatter
789 /// intrinsics.
790 bool forceScalarizeMaskedScatter(VectorType *Type, Align Alignment) const;
791
792 /// Return true if the target supports masked compress store.
793 bool isLegalMaskedCompressStore(Type *DataType, Align Alignment) const;
794 /// Return true if the target supports masked expand load.
795 bool isLegalMaskedExpandLoad(Type *DataType, Align Alignment) const;
796
797 /// Return true if the target supports strided load.
798 bool isLegalStridedLoadStore(Type *DataType, Align Alignment) const;
799
800 // Return true if the target supports masked vector histograms.
801 bool isLegalMaskedVectorHistogram(Type *AddrType, Type *DataType) const;
802
803 /// Return true if this is an alternating opcode pattern that can be lowered
804 /// to a single instruction on the target. In X86 this is for the addsub
805 /// instruction which corrsponds to a Shuffle + Fadd + FSub pattern in IR.
806 /// This function expectes two opcodes: \p Opcode1 and \p Opcode2 being
807 /// selected by \p OpcodeMask. The mask contains one bit per lane and is a `0`
808 /// when \p Opcode0 is selected and `1` when Opcode1 is selected.
809 /// \p VecTy is the vector type of the instruction to be generated.
810 bool isLegalAltInstr(VectorType *VecTy, unsigned Opcode0, unsigned Opcode1,
811 const SmallBitVector &OpcodeMask) const;
812
813 /// Return true if we should be enabling ordered reductions for the target.
814 bool enableOrderedReductions() const;
815
816 /// Return true if the target has a unified operation to calculate division
817 /// and remainder. If so, the additional implicit multiplication and
818 /// subtraction required to calculate a remainder from division are free. This
819 /// can enable more aggressive transformations for division and remainder than
820 /// would typically be allowed using throughput or size cost models.
821 bool hasDivRemOp(Type *DataType, bool IsSigned) const;
822
823 /// Return true if the given instruction (assumed to be a memory access
824 /// instruction) has a volatile variant. If that's the case then we can avoid
825 /// addrspacecast to generic AS for volatile loads/stores. Default
826 /// implementation returns false, which prevents address space inference for
827 /// volatile loads/stores.
828 bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) const;
829
830 /// Return true if target doesn't mind addresses in vectors.
831 bool prefersVectorizedAddressing() const;
832
833 /// Return the cost of the scaling factor used in the addressing
834 /// mode represented by AM for this target, for a load/store
835 /// of the specified type.
836 /// If the AM is supported, the return value must be >= 0.
837 /// If the AM is not supported, it returns a negative value.
838 /// TODO: Handle pre/postinc as well.
840 StackOffset BaseOffset, bool HasBaseReg,
841 int64_t Scale,
842 unsigned AddrSpace = 0) const;
843
844 /// Return true if the loop strength reduce pass should make
845 /// Instruction* based TTI queries to isLegalAddressingMode(). This is
846 /// needed on SystemZ, where e.g. a memcpy can only have a 12 bit unsigned
847 /// immediate offset and no index register.
848 bool LSRWithInstrQueries() const;
849
850 /// Return true if it's free to truncate a value of type Ty1 to type
851 /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
852 /// by referencing its sub-register AX.
853 bool isTruncateFree(Type *Ty1, Type *Ty2) const;
854
855 /// Return true if it is profitable to hoist instruction in the
856 /// then/else to before if.
857 bool isProfitableToHoist(Instruction *I) const;
858
859 bool useAA() const;
860
861 /// Return true if this type is legal.
862 bool isTypeLegal(Type *Ty) const;
863
864 /// Returns the estimated number of registers required to represent \p Ty.
865 unsigned getRegUsageForType(Type *Ty) const;
866
867 /// Return true if switches should be turned into lookup tables for the
868 /// target.
869 bool shouldBuildLookupTables() const;
870
871 /// Return true if switches should be turned into lookup tables
872 /// containing this constant value for the target.
874
875 /// Return true if lookup tables should be turned into relative lookup tables.
876 bool shouldBuildRelLookupTables() const;
877
878 /// Return true if the input function which is cold at all call sites,
879 /// should use coldcc calling convention.
880 bool useColdCCForColdCall(Function &F) const;
881
882 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
883 /// are set if the demanded result elements need to be inserted and/or
884 /// extracted from vectors.
886 const APInt &DemandedElts,
887 bool Insert, bool Extract,
889
890 /// Estimate the overhead of scalarizing an instructions unique
891 /// non-constant operands. The (potentially vector) types to use for each of
892 /// argument are passes via Tys.
897
898 /// If target has efficient vector element load/store instructions, it can
899 /// return true here so that insertion/extraction costs are not added to
900 /// the scalarization cost of a load/store.
902
903 /// If the target supports tail calls.
904 bool supportsTailCalls() const;
905
906 /// If target supports tail call on \p CB
907 bool supportsTailCallFor(const CallBase *CB) const;
908
909 /// Don't restrict interleaved unrolling to small loops.
910 bool enableAggressiveInterleaving(bool LoopHasReductions) const;
911
912 /// Returns options for expansion of memcmp. IsZeroCmp is
913 // true if this is the expansion of memcmp(p1, p2, s) == 0.
915 // Return true if memcmp expansion is enabled.
916 operator bool() const { return MaxNumLoads > 0; }
917
918 // Maximum number of load operations.
919 unsigned MaxNumLoads = 0;
920
921 // The list of available load sizes (in bytes), sorted in decreasing order.
923
924 // For memcmp expansion when the memcmp result is only compared equal or
925 // not-equal to 0, allow up to this number of load pairs per block. As an
926 // example, this may allow 'memcmp(a, b, 3) == 0' in a single block:
927 // a0 = load2bytes &a[0]
928 // b0 = load2bytes &b[0]
929 // a2 = load1byte &a[2]
930 // b2 = load1byte &b[2]
931 // r = cmp eq (a0 ^ b0 | a2 ^ b2), 0
932 unsigned NumLoadsPerBlock = 1;
933
934 // Set to true to allow overlapping loads. For example, 7-byte compares can
935 // be done with two 4-byte compares instead of 4+2+1-byte compares. This
936 // requires all loads in LoadSizes to be doable in an unaligned way.
938
939 // Sometimes, the amount of data that needs to be compared is smaller than
940 // the standard register size, but it cannot be loaded with just one load
941 // instruction. For example, if the size of the memory comparison is 6
942 // bytes, we can handle it more efficiently by loading all 6 bytes in a
943 // single block and generating an 8-byte number, instead of generating two
944 // separate blocks with conditional jumps for 4 and 2 byte loads. This
945 // approach simplifies the process and produces the comparison result as
946 // normal. This array lists the allowed sizes of memcmp tails that can be
947 // merged into one block
949 };
951 bool IsZeroCmp) const;
952
953 /// Should the Select Optimization pass be enabled and ran.
954 bool enableSelectOptimize() const;
955
956 /// Should the Select Optimization pass treat the given instruction like a
957 /// select, potentially converting it to a conditional branch. This can
958 /// include select-like instructions like or(zext(c), x) that can be converted
959 /// to selects.
961
962 /// Enable matching of interleaved access groups.
964
965 /// Enable matching of interleaved access groups that contain predicated
966 /// accesses or gaps and therefore vectorized using masked
967 /// vector loads/stores.
969
970 /// Indicate that it is potentially unsafe to automatically vectorize
971 /// floating-point operations because the semantics of vector and scalar
972 /// floating-point semantics may differ. For example, ARM NEON v7 SIMD math
973 /// does not support IEEE-754 denormal numbers, while depending on the
974 /// platform, scalar floating-point math does.
975 /// This applies to floating-point math operations and calls, not memory
976 /// operations, shuffles, or casts.
978
979 /// Determine if the target supports unaligned memory accesses.
981 unsigned AddressSpace = 0,
982 Align Alignment = Align(1),
983 unsigned *Fast = nullptr) const;
984
985 /// Return hardware support for population count.
986 PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
987
988 /// Return true if the hardware has a fast square-root instruction.
989 bool haveFastSqrt(Type *Ty) const;
990
991 /// Return true if the cost of the instruction is too high to speculatively
992 /// execute and should be kept behind a branch.
993 /// This normally just wraps around a getInstructionCost() call, but some
994 /// targets might report a low TCK_SizeAndLatency value that is incompatible
995 /// with the fixed TCC_Expensive value.
996 /// NOTE: This assumes the instruction passes isSafeToSpeculativelyExecute().
998
999 /// Return true if it is faster to check if a floating-point value is NaN
1000 /// (or not-NaN) versus a comparison against a constant FP zero value.
1001 /// Targets should override this if materializing a 0.0 for comparison is
1002 /// generally as cheap as checking for ordered/unordered.
1003 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) const;
1004
1005 /// Return the expected cost of supporting the floating point operation
1006 /// of the specified type.
1007 InstructionCost getFPOpCost(Type *Ty) const;
1008
1009 /// Return the expected cost of materializing for the given integer
1010 /// immediate of the specified type.
1011 InstructionCost getIntImmCost(const APInt &Imm, Type *Ty,
1012 TargetCostKind CostKind) const;
1013
1014 /// Return the expected cost of materialization for the given integer
1015 /// immediate of the specified type for a given instruction. The cost can be
1016 /// zero if the immediate can be folded into the specified instruction.
1017 InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx,
1018 const APInt &Imm, Type *Ty,
1020 Instruction *Inst = nullptr) const;
1022 const APInt &Imm, Type *Ty,
1023 TargetCostKind CostKind) const;
1024
1025 /// Return the expected cost for the given integer when optimising
1026 /// for size. This is different than the other integer immediate cost
1027 /// functions in that it is subtarget agnostic. This is useful when you e.g.
1028 /// target one ISA such as Aarch32 but smaller encodings could be possible
1029 /// with another such as Thumb. This return value is used as a penalty when
1030 /// the total costs for a constant is calculated (the bigger the cost, the
1031 /// more beneficial constant hoisting is).
1032 InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx,
1033 const APInt &Imm, Type *Ty) const;
1034
1035 /// It can be advantageous to detach complex constants from their uses to make
1036 /// their generation cheaper. This hook allows targets to report when such
1037 /// transformations might negatively effect the code generation of the
1038 /// underlying operation. The motivating example is divides whereby hoisting
1039 /// constants prevents the code generator's ability to transform them into
1040 /// combinations of simpler operations.
1042 const Function &Fn) const;
1043
1044 /// @}
1045
1046 /// \name Vector Target Information
1047 /// @{
1048
1049 /// The various kinds of shuffle patterns for vector queries.
1051 SK_Broadcast, ///< Broadcast element 0 to all other elements.
1052 SK_Reverse, ///< Reverse the order of the vector.
1053 SK_Select, ///< Selects elements from the corresponding lane of
1054 ///< either source operand. This is equivalent to a
1055 ///< vector select with a constant condition operand.
1056 SK_Transpose, ///< Transpose two vectors.
1057 SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
1058 SK_ExtractSubvector, ///< ExtractSubvector Index indicates start offset.
1059 SK_PermuteTwoSrc, ///< Merge elements from two source vectors into one
1060 ///< with any shuffle mask.
1061 SK_PermuteSingleSrc, ///< Shuffle elements of single source vector with any
1062 ///< shuffle mask.
1063 SK_Splice ///< Concatenates elements from the first input vector
1064 ///< with elements of the second input vector. Returning
1065 ///< a vector of the same type as the input vectors.
1066 ///< Index indicates start offset in first input vector.
1068
1069 /// Additional information about an operand's possible values.
1071 OK_AnyValue, // Operand can have any value.
1072 OK_UniformValue, // Operand is uniform (splat of a value).
1073 OK_UniformConstantValue, // Operand is uniform constant.
1074 OK_NonUniformConstantValue // Operand is a non uniform constant value.
1076
1077 /// Additional properties of an operand's values.
1082 };
1083
1084 // Describe the values an operand can take. We're in the process
1085 // of migrating uses of OperandValueKind and OperandValueProperties
1086 // to use this class, and then will change the internal representation.
1090
1091 bool isConstant() const {
1093 }
1094 bool isUniform() const {
1096 }
1097 bool isPowerOf2() const {
1098 return Properties == OP_PowerOf2;
1099 }
1100 bool isNegatedPowerOf2() const {
1102 }
1103
1105 return {Kind, OP_None};
1106 }
1107 };
1108
1109 /// \return the number of registers in the target-provided register class.
1110 unsigned getNumberOfRegisters(unsigned ClassID) const;
1111
1112 /// \return the target-provided register class ID for the provided type,
1113 /// accounting for type promotion and other type-legalization techniques that
1114 /// the target might apply. However, it specifically does not account for the
1115 /// scalarization or splitting of vector types. Should a vector type require
1116 /// scalarization or splitting into multiple underlying vector registers, that
1117 /// type should be mapped to a register class containing no registers.
1118 /// Specifically, this is designed to provide a simple, high-level view of the
1119 /// register allocation later performed by the backend. These register classes
1120 /// don't necessarily map onto the register classes used by the backend.
1121 /// FIXME: It's not currently possible to determine how many registers
1122 /// are used by the provided type.
1123 unsigned getRegisterClassForType(bool Vector, Type *Ty = nullptr) const;
1124
1125 /// \return the target-provided register class name
1126 const char *getRegisterClassName(unsigned ClassID) const;
1127
1129
1130 /// \return The width of the largest scalar or vector register type.
1132
1133 /// \return The width of the smallest vector register type.
1134 unsigned getMinVectorRegisterBitWidth() const;
1135
1136 /// \return The maximum value of vscale if the target specifies an
1137 /// architectural maximum vector length, and std::nullopt otherwise.
1138 std::optional<unsigned> getMaxVScale() const;
1139
1140 /// \return the value of vscale to tune the cost model for.
1141 std::optional<unsigned> getVScaleForTuning() const;
1142
1143 /// \return true if vscale is known to be a power of 2
1144 bool isVScaleKnownToBeAPowerOfTwo() const;
1145
1146 /// \return True if the vectorization factor should be chosen to
1147 /// make the vector of the smallest element type match the size of a
1148 /// vector register. For wider element types, this could result in
1149 /// creating vectors that span multiple vector registers.
1150 /// If false, the vectorization factor will be chosen based on the
1151 /// size of the widest element type.
1152 /// \p K Register Kind for vectorization.
1154
1155 /// \return The minimum vectorization factor for types of given element
1156 /// bit width, or 0 if there is no minimum VF. The returned value only
1157 /// applies when shouldMaximizeVectorBandwidth returns true.
1158 /// If IsScalable is true, the returned ElementCount must be a scalable VF.
1159 ElementCount getMinimumVF(unsigned ElemWidth, bool IsScalable) const;
1160
1161 /// \return The maximum vectorization factor for types of given element
1162 /// bit width and opcode, or 0 if there is no maximum VF.
1163 /// Currently only used by the SLP vectorizer.
1164 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const;
1165
1166 /// \return The minimum vectorization factor for the store instruction. Given
1167 /// the initial estimation of the minimum vector factor and store value type,
1168 /// it tries to find possible lowest VF, which still might be profitable for
1169 /// the vectorization.
1170 /// \param VF Initial estimation of the minimum vector factor.
1171 /// \param ScalarMemTy Scalar memory type of the store operation.
1172 /// \param ScalarValTy Scalar type of the stored value.
1173 /// Currently only used by the SLP vectorizer.
1174 unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy,
1175 Type *ScalarValTy) const;
1176
1177 /// \return True if it should be considered for address type promotion.
1178 /// \p AllowPromotionWithoutCommonHeader Set true if promoting \p I is
1179 /// profitable without finding other extensions fed by the same input.
1181 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const;
1182
1183 /// \return The size of a cache line in bytes.
1184 unsigned getCacheLineSize() const;
1185
1186 /// The possible cache levels
1187 enum class CacheLevel {
1188 L1D, // The L1 data cache
1189 L2D, // The L2 data cache
1190
1191 // We currently do not model L3 caches, as their sizes differ widely between
1192 // microarchitectures. Also, we currently do not have a use for L3 cache
1193 // size modeling yet.
1194 };
1195
1196 /// \return The size of the cache level in bytes, if available.
1197 std::optional<unsigned> getCacheSize(CacheLevel Level) const;
1198
1199 /// \return The associativity of the cache level, if available.
1200 std::optional<unsigned> getCacheAssociativity(CacheLevel Level) const;
1201
1202 /// \return The minimum architectural page size for the target.
1203 std::optional<unsigned> getMinPageSize() const;
1204
1205 /// \return How much before a load we should place the prefetch
1206 /// instruction. This is currently measured in number of
1207 /// instructions.
1208 unsigned getPrefetchDistance() const;
1209
1210 /// Some HW prefetchers can handle accesses up to a certain constant stride.
1211 /// Sometimes prefetching is beneficial even below the HW prefetcher limit,
1212 /// and the arguments provided are meant to serve as a basis for deciding this
1213 /// for a particular loop.
1214 ///
1215 /// \param NumMemAccesses Number of memory accesses in the loop.
1216 /// \param NumStridedMemAccesses Number of the memory accesses that
1217 /// ScalarEvolution could find a known stride
1218 /// for.
1219 /// \param NumPrefetches Number of software prefetches that will be
1220 /// emitted as determined by the addresses
1221 /// involved and the cache line size.
1222 /// \param HasCall True if the loop contains a call.
1223 ///
1224 /// \return This is the minimum stride in bytes where it makes sense to start
1225 /// adding SW prefetches. The default is 1, i.e. prefetch with any
1226 /// stride.
1227 unsigned getMinPrefetchStride(unsigned NumMemAccesses,
1228 unsigned NumStridedMemAccesses,
1229 unsigned NumPrefetches, bool HasCall) const;
1230
1231 /// \return The maximum number of iterations to prefetch ahead. If
1232 /// the required number of iterations is more than this number, no
1233 /// prefetching is performed.
1234 unsigned getMaxPrefetchIterationsAhead() const;
1235
1236 /// \return True if prefetching should also be done for writes.
1237 bool enableWritePrefetching() const;
1238
1239 /// \return if target want to issue a prefetch in address space \p AS.
1240 bool shouldPrefetchAddressSpace(unsigned AS) const;
1241
1242 /// \return The maximum interleave factor that any transform should try to
1243 /// perform for this target. This number depends on the level of parallelism
1244 /// and the number of execution units in the CPU.
1245 unsigned getMaxInterleaveFactor(ElementCount VF) const;
1246
1247 /// Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
1248 static OperandValueInfo getOperandInfo(const Value *V);
1249
1250 /// This is an approximation of reciprocal throughput of a math/logic op.
1251 /// A higher cost indicates less expected throughput.
1252 /// From Agner Fog's guides, reciprocal throughput is "the average number of
1253 /// clock cycles per instruction when the instructions are not part of a
1254 /// limiting dependency chain."
1255 /// Therefore, costs should be scaled to account for multiple execution units
1256 /// on the target that can process this type of instruction. For example, if
1257 /// there are 5 scalar integer units and 2 vector integer units that can
1258 /// calculate an 'add' in a single cycle, this model should indicate that the
1259 /// cost of the vector add instruction is 2.5 times the cost of the scalar
1260 /// add instruction.
1261 /// \p Args is an optional argument which holds the instruction operands
1262 /// values so the TTI can analyze those values searching for special
1263 /// cases or optimizations based on those values.
1264 /// \p CxtI is the optional original context instruction, if one exists, to
1265 /// provide even more information.
1266 /// \p TLibInfo is used to search for platform specific vector library
1267 /// functions for instructions that might be converted to calls (e.g. frem).
1269 unsigned Opcode, Type *Ty,
1272 TTI::OperandValueInfo Opd2Info = {TTI::OK_AnyValue, TTI::OP_None},
1273 ArrayRef<const Value *> Args = std::nullopt,
1274 const Instruction *CxtI = nullptr,
1275 const TargetLibraryInfo *TLibInfo = nullptr) const;
1276
1277 /// Returns the cost estimation for alternating opcode pattern that can be
1278 /// lowered to a single instruction on the target. In X86 this is for the
1279 /// addsub instruction which corrsponds to a Shuffle + Fadd + FSub pattern in
1280 /// IR. This function expects two opcodes: \p Opcode1 and \p Opcode2 being
1281 /// selected by \p OpcodeMask. The mask contains one bit per lane and is a `0`
1282 /// when \p Opcode0 is selected and `1` when Opcode1 is selected.
1283 /// \p VecTy is the vector type of the instruction to be generated.
1284 InstructionCost getAltInstrCost(
1285 VectorType *VecTy, unsigned Opcode0, unsigned Opcode1,
1286 const SmallBitVector &OpcodeMask,
1288
1289 /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
1290 /// The exact mask may be passed as Mask, or else the array will be empty.
1291 /// The index and subtype parameters are used by the subvector insertion and
1292 /// extraction shuffle kinds to show the insert/extract point and the type of
1293 /// the subvector being inserted/extracted. The operands of the shuffle can be
1294 /// passed through \p Args, which helps improve the cost estimation in some
1295 /// cases, like in broadcast loads.
1296 /// NOTE: For subvector extractions Tp represents the source type.
1297 InstructionCost getShuffleCost(
1298 ShuffleKind Kind, VectorType *Tp, ArrayRef<int> Mask = std::nullopt,
1300 VectorType *SubTp = nullptr, ArrayRef<const Value *> Args = std::nullopt,
1301 const Instruction *CxtI = nullptr) const;
1302
1303 /// Represents a hint about the context in which a cast is used.
1304 ///
1305 /// For zext/sext, the context of the cast is the operand, which must be a
1306 /// load of some kind. For trunc, the context is of the cast is the single
1307 /// user of the instruction, which must be a store of some kind.
1308 ///
1309 /// This enum allows the vectorizer to give getCastInstrCost an idea of the
1310 /// type of cast it's dealing with, as not every cast is equal. For instance,
1311 /// the zext of a load may be free, but the zext of an interleaving load can
1312 //// be (very) expensive!
1313 ///
1314 /// See \c getCastContextHint to compute a CastContextHint from a cast
1315 /// Instruction*. Callers can use it if they don't need to override the
1316 /// context and just want it to be calculated from the instruction.
1317 ///
1318 /// FIXME: This handles the types of load/store that the vectorizer can
1319 /// produce, which are the cases where the context instruction is most
1320 /// likely to be incorrect. There are other situations where that can happen
1321 /// too, which might be handled here but in the long run a more general
1322 /// solution of costing multiple instructions at the same times may be better.
1323 enum class CastContextHint : uint8_t {
1324 None, ///< The cast is not used with a load/store of any kind.
1325 Normal, ///< The cast is used with a normal load/store.
1326 Masked, ///< The cast is used with a masked load/store.
1327 GatherScatter, ///< The cast is used with a gather/scatter.
1328 Interleave, ///< The cast is used with an interleaved load/store.
1329 Reversed, ///< The cast is used with a reversed load/store.
1330 };
1331
1332 /// Calculates a CastContextHint from \p I.
1333 /// This should be used by callers of getCastInstrCost if they wish to
1334 /// determine the context from some instruction.
1335 /// \returns the CastContextHint for ZExt/SExt/Trunc, None if \p I is nullptr,
1336 /// or if it's another type of cast.
1338
1339 /// \return The expected cost of cast instructions, such as bitcast, trunc,
1340 /// zext, etc. If there is an existing instruction that holds Opcode, it
1341 /// may be passed in the 'I' parameter.
1343 getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
1346 const Instruction *I = nullptr) const;
1347
1348 /// \return The expected cost of a sign- or zero-extended vector extract. Use
1349 /// Index = -1 to indicate that there is no information about the index value.
1350 InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst,
1351 VectorType *VecTy,
1352 unsigned Index) const;
1353
1354 /// \return The expected cost of control-flow related instructions such as
1355 /// Phi, Ret, Br, Switch.
1357 getCFInstrCost(unsigned Opcode,
1359 const Instruction *I = nullptr) const;
1360
1361 /// \returns The expected cost of compare and select instructions. If there
1362 /// is an existing instruction that holds Opcode, it may be passed in the
1363 /// 'I' parameter. The \p VecPred parameter can be used to indicate the select
1364 /// is using a compare with the specified predicate as condition. When vector
1365 /// types are passed, \p VecPred must be used for all lanes.
1367 getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
1368 CmpInst::Predicate VecPred,
1370 const Instruction *I = nullptr) const;
1371
1372 /// \return The expected cost of vector Insert and Extract.
1373 /// Use -1 to indicate that there is no information on the index value.
1374 /// This is used when the instruction is not available; a typical use
1375 /// case is to provision the cost of vectorization/scalarization in
1376 /// vectorizer passes.
1377 InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val,
1379 unsigned Index = -1, Value *Op0 = nullptr,
1380 Value *Op1 = nullptr) const;
1381
1382 /// \return The expected cost of vector Insert and Extract.
1383 /// This is used when instruction is available, and implementation
1384 /// asserts 'I' is not nullptr.
1385 ///
1386 /// A typical suitable use case is cost estimation when vector instruction
1387 /// exists (e.g., from basic blocks during transformation).
1390 unsigned Index = -1) const;
1391
1392 /// \return The cost of replication shuffle of \p VF elements typed \p EltTy
1393 /// \p ReplicationFactor times.
1394 ///
1395 /// For example, the mask for \p ReplicationFactor=3 and \p VF=4 is:
1396 /// <0,0,0,1,1,1,2,2,2,3,3,3>
1397 InstructionCost getReplicationShuffleCost(Type *EltTy, int ReplicationFactor,
1398 int VF,
1399 const APInt &DemandedDstElts,
1401
1402 /// \return The cost of Load and Store instructions.
1404 getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
1405 unsigned AddressSpace,
1407 OperandValueInfo OpdInfo = {OK_AnyValue, OP_None},
1408 const Instruction *I = nullptr) const;
1409
1410 /// \return The cost of VP Load and Store instructions.
1411 InstructionCost
1412 getVPMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
1413 unsigned AddressSpace,
1415 const Instruction *I = nullptr) const;
1416
1417 /// \return The cost of masked Load and Store instructions.
1419 unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace,
1421
1422 /// \return The cost of Gather or Scatter operation
1423 /// \p Opcode - is a type of memory access Load or Store
1424 /// \p DataTy - a vector type of the data to be loaded or stored
1425 /// \p Ptr - pointer [or vector of pointers] - address[es] in memory
1426 /// \p VariableMask - true when the memory access is predicated with a mask
1427 /// that is not a compile-time constant
1428 /// \p Alignment - alignment of single element
1429 /// \p I - the optional original context instruction, if one exists, e.g. the
1430 /// load/store to transform or the call to the gather/scatter intrinsic
1432 unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
1434 const Instruction *I = nullptr) const;
1435
1436 /// \return The cost of strided memory operations.
1437 /// \p Opcode - is a type of memory access Load or Store
1438 /// \p DataTy - a vector type of the data to be loaded or stored
1439 /// \p Ptr - pointer [or vector of pointers] - address[es] in memory
1440 /// \p VariableMask - true when the memory access is predicated with a mask
1441 /// that is not a compile-time constant
1442 /// \p Alignment - alignment of single element
1443 /// \p I - the optional original context instruction, if one exists, e.g. the
1444 /// load/store to transform or the call to the gather/scatter intrinsic
1446 unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
1448 const Instruction *I = nullptr) const;
1449
1450 /// \return The cost of the interleaved memory operation.
1451 /// \p Opcode is the memory operation code
1452 /// \p VecTy is the vector type of the interleaved access.
1453 /// \p Factor is the interleave factor
1454 /// \p Indices is the indices for interleaved load members (as interleaved
1455 /// load allows gaps)
1456 /// \p Alignment is the alignment of the memory operation
1457 /// \p AddressSpace is address space of the pointer.
1458 /// \p UseMaskForCond indicates if the memory access is predicated.
1459 /// \p UseMaskForGaps indicates if gaps should be masked.
1461 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1462 Align Alignment, unsigned AddressSpace,
1464 bool UseMaskForCond = false, bool UseMaskForGaps = false) const;
1465
1466 /// A helper function to determine the type of reduction algorithm used
1467 /// for a given \p Opcode and set of FastMathFlags \p FMF.
1468 static bool requiresOrderedReduction(std::optional<FastMathFlags> FMF) {
1469 return FMF && !(*FMF).allowReassoc();
1470 }
1471
1472 /// Calculate the cost of vector reduction intrinsics.
1473 ///
1474 /// This is the cost of reducing the vector value of type \p Ty to a scalar
1475 /// value using the operation denoted by \p Opcode. The FastMathFlags
1476 /// parameter \p FMF indicates what type of reduction we are performing:
1477 /// 1. Tree-wise. This is the typical 'fast' reduction performed that
1478 /// involves successively splitting a vector into half and doing the
1479 /// operation on the pair of halves until you have a scalar value. For
1480 /// example:
1481 /// (v0, v1, v2, v3)
1482 /// ((v0+v2), (v1+v3), undef, undef)
1483 /// ((v0+v2+v1+v3), undef, undef, undef)
1484 /// This is the default behaviour for integer operations, whereas for
1485 /// floating point we only do this if \p FMF indicates that
1486 /// reassociation is allowed.
1487 /// 2. Ordered. For a vector with N elements this involves performing N
1488 /// operations in lane order, starting with an initial scalar value, i.e.
1489 /// result = InitVal + v0
1490 /// result = result + v1
1491 /// result = result + v2
1492 /// result = result + v3
1493 /// This is only the case for FP operations and when reassociation is not
1494 /// allowed.
1495 ///
1497 unsigned Opcode, VectorType *Ty, std::optional<FastMathFlags> FMF,
1499
1503
1504 /// Calculate the cost of an extended reduction pattern, similar to
1505 /// getArithmeticReductionCost of an Add reduction with multiply and optional
1506 /// extensions. This is the cost of as:
1507 /// ResTy vecreduce.add(mul (A, B)).
1508 /// ResTy vecreduce.add(mul(ext(Ty A), ext(Ty B)).
1510 bool IsUnsigned, Type *ResTy, VectorType *Ty,
1512
1513 /// Calculate the cost of an extended reduction pattern, similar to
1514 /// getArithmeticReductionCost of a reduction with an extension.
1515 /// This is the cost of as:
1516 /// ResTy vecreduce.opcode(ext(Ty A)).
1518 unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty,
1519 FastMathFlags FMF,
1521
1522 /// \returns The cost of Intrinsic instructions. Analyses the real arguments.
1523 /// Three cases are handled: 1. scalar instruction 2. vector instruction
1524 /// 3. scalar instruction which is to be vectorized.
1527
1528 /// \returns The cost of Call instructions.
1532
1533 /// \returns The number of pieces into which the provided type must be
1534 /// split during legalization. Zero is returned when the answer is unknown.
1535 unsigned getNumberOfParts(Type *Tp) const;
1536
1537 /// \returns The cost of the address computation. For most targets this can be
1538 /// merged into the instruction indexing mode. Some targets might want to
1539 /// distinguish between address computation for memory operations on vector
1540 /// types and scalar types. Such targets should override this function.
1541 /// The 'SE' parameter holds pointer for the scalar evolution object which
1542 /// is used in order to get the Ptr step value in case of constant stride.
1543 /// The 'Ptr' parameter holds SCEV of the access pointer.
1545 ScalarEvolution *SE = nullptr,
1546 const SCEV *Ptr = nullptr) const;
1547
1548 /// \returns The cost, if any, of keeping values of the given types alive
1549 /// over a callsite.
1550 ///
1551 /// Some types may require the use of register classes that do not have
1552 /// any callee-saved registers, so would require a spill and fill.
1554
1555 /// \returns True if the intrinsic is a supported memory intrinsic. Info
1556 /// will contain additional information - whether the intrinsic may write
1557 /// or read to memory, volatility and the pointer. Info is undefined
1558 /// if false is returned.
1560
1561 /// \returns The maximum element size, in bytes, for an element
1562 /// unordered-atomic memory intrinsic.
1563 unsigned getAtomicMemIntrinsicMaxElementSize() const;
1564
1565 /// \returns A value which is the result of the given memory intrinsic. New
1566 /// instructions may be created to extract the result from the given intrinsic
1567 /// memory operation. Returns nullptr if the target cannot create a result
1568 /// from the given intrinsic.
1570 Type *ExpectedType) const;
1571
1572 /// \returns The type to use in a loop expansion of a memcpy call.
1574 LLVMContext &Context, Value *Length, unsigned SrcAddrSpace,
1575 unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign,
1576 std::optional<uint32_t> AtomicElementSize = std::nullopt) const;
1577
1578 /// \param[out] OpsOut The operand types to copy RemainingBytes of memory.
1579 /// \param RemainingBytes The number of bytes to copy.
1580 ///
1581 /// Calculates the operand types to use when copying \p RemainingBytes of
1582 /// memory, where source and destination alignments are \p SrcAlign and
1583 /// \p DestAlign respectively.
1585 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
1586 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
1587 unsigned SrcAlign, unsigned DestAlign,
1588 std::optional<uint32_t> AtomicCpySize = std::nullopt) const;
1589
1590 /// \returns True if the two functions have compatible attributes for inlining
1591 /// purposes.
1592 bool areInlineCompatible(const Function *Caller,
1593 const Function *Callee) const;
1594
1595 /// Returns a penalty for invoking call \p Call in \p F.
1596 /// For example, if a function F calls a function G, which in turn calls
1597 /// function H, then getInlineCallPenalty(F, H()) would return the
1598 /// penalty of calling H from F, e.g. after inlining G into F.
1599 /// \p DefaultCallPenalty is passed to give a default penalty that
1600 /// the target can amend or override.
1601 unsigned getInlineCallPenalty(const Function *F, const CallBase &Call,
1602 unsigned DefaultCallPenalty) const;
1603
1604 /// \returns True if the caller and callee agree on how \p Types will be
1605 /// passed to or returned from the callee.
1606 /// to the callee.
1607 /// \param Types List of types to check.
1608 bool areTypesABICompatible(const Function *Caller, const Function *Callee,
1609 const ArrayRef<Type *> &Types) const;
1610
1611 /// The type of load/store indexing.
1613 MIM_Unindexed, ///< No indexing.
1614 MIM_PreInc, ///< Pre-incrementing.
1615 MIM_PreDec, ///< Pre-decrementing.
1616 MIM_PostInc, ///< Post-incrementing.
1617 MIM_PostDec ///< Post-decrementing.
1619
1620 /// \returns True if the specified indexed load for the given type is legal.
1621 bool isIndexedLoadLegal(enum MemIndexedMode Mode, Type *Ty) const;
1622
1623 /// \returns True if the specified indexed store for the given type is legal.
1624 bool isIndexedStoreLegal(enum MemIndexedMode Mode, Type *Ty) const;
1625
1626 /// \returns The bitwidth of the largest vector type that should be used to
1627 /// load/store in the given address space.
1628 unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const;
1629
1630 /// \returns True if the load instruction is legal to vectorize.
1631 bool isLegalToVectorizeLoad(LoadInst *LI) const;
1632
1633 /// \returns True if the store instruction is legal to vectorize.
1634 bool isLegalToVectorizeStore(StoreInst *SI) const;
1635
1636 /// \returns True if it is legal to vectorize the given load chain.
1637 bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, Align Alignment,
1638 unsigned AddrSpace) const;
1639
1640 /// \returns True if it is legal to vectorize the given store chain.
1641 bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, Align Alignment,
1642 unsigned AddrSpace) const;
1643
1644 /// \returns True if it is legal to vectorize the given reduction kind.
1646 ElementCount VF) const;
1647
1648 /// \returns True if the given type is supported for scalable vectors
1650
1651 /// \returns The new vector factor value if the target doesn't support \p
1652 /// SizeInBytes loads or has a better vector factor.
1653 unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
1654 unsigned ChainSizeInBytes,
1655 VectorType *VecTy) const;
1656
1657 /// \returns The new vector factor value if the target doesn't support \p
1658 /// SizeInBytes stores or has a better vector factor.
1659 unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
1660 unsigned ChainSizeInBytes,
1661 VectorType *VecTy) const;
1662
1663 /// Flags describing the kind of vector reduction.
1665 ReductionFlags() = default;
1666 bool IsMaxOp =
1667 false; ///< If the op a min/max kind, true if it's a max operation.
1668 bool IsSigned = false; ///< Whether the operation is a signed int reduction.
1669 bool NoNaN =
1670 false; ///< If op is an fp min/max, whether NaNs may be present.
1671 };
1672
1673 /// \returns True if the target prefers reductions in loop.
1674 bool preferInLoopReduction(unsigned Opcode, Type *Ty,
1675 ReductionFlags Flags) const;
1676
1677 /// \returns True if the target prefers reductions select kept in the loop
1678 /// when tail folding. i.e.
1679 /// loop:
1680 /// p = phi (0, s)
1681 /// a = add (p, x)
1682 /// s = select (mask, a, p)
1683 /// vecreduce.add(s)
1684 ///
1685 /// As opposed to the normal scheme of p = phi (0, a) which allows the select
1686 /// to be pulled out of the loop. If the select(.., add, ..) can be predicated
1687 /// by the target, this can lead to cleaner code generation.
1688 bool preferPredicatedReductionSelect(unsigned Opcode, Type *Ty,
1689 ReductionFlags Flags) const;
1690
1691 /// Return true if the loop vectorizer should consider vectorizing an
1692 /// otherwise scalar epilogue loop.
1693 bool preferEpilogueVectorization() const;
1694
1695 /// \returns True if the target wants to expand the given reduction intrinsic
1696 /// into a shuffle sequence.
1697 bool shouldExpandReduction(const IntrinsicInst *II) const;
1698
1699 /// \returns the size cost of rematerializing a GlobalValue address relative
1700 /// to a stack reload.
1701 unsigned getGISelRematGlobalCost() const;
1702
1703 /// \returns the lower bound of a trip count to decide on vectorization
1704 /// while tail-folding.
1705 unsigned getMinTripCountTailFoldingThreshold() const;
1706
1707 /// \returns True if the target supports scalable vectors.
1708 bool supportsScalableVectors() const;
1709
1710 /// \return true when scalable vectorization is preferred.
1711 bool enableScalableVectorization() const;
1712
1713 /// \name Vector Predication Information
1714 /// @{
1715 /// Whether the target supports the %evl parameter of VP intrinsic efficiently
1716 /// in hardware, for the given opcode and type/alignment. (see LLVM Language
1717 /// Reference - "Vector Predication Intrinsics").
1718 /// Use of %evl is discouraged when that is not the case.
1719 bool hasActiveVectorLength(unsigned Opcode, Type *DataType,
1720 Align Alignment) const;
1721
1724 // keep the predicating parameter
1726 // where legal, discard the predicate parameter
1728 // transform into something else that is also predicating
1729 Convert = 2
1731
1732 // How to transform the EVL parameter.
1733 // Legal: keep the EVL parameter as it is.
1734 // Discard: Ignore the EVL parameter where it is safe to do so.
1735 // Convert: Fold the EVL into the mask parameter.
1737
1738 // How to transform the operator.
1739 // Legal: The target supports this operator.
1740 // Convert: Convert this to a non-VP operation.
1741 // The 'Discard' strategy is invalid.
1743
1744 bool shouldDoNothing() const {
1745 return (EVLParamStrategy == Legal) && (OpStrategy == Legal);
1746 }
1749 };
1750
1751 /// \returns How the target needs this vector-predicated operation to be
1752 /// transformed.
1754 /// @}
1755
1756 /// \returns Whether a 32-bit branch instruction is available in Arm or Thumb
1757 /// state.
1758 ///
1759 /// Used by the LowerTypeTests pass, which constructs an IR inline assembler
1760 /// node containing a jump table in a format suitable for the target, so it
1761 /// needs to know what format of jump table it can legally use.
1762 ///
1763 /// For non-Arm targets, this function isn't used. It defaults to returning
1764 /// false, but it shouldn't matter what it returns anyway.
1765 bool hasArmWideBranch(bool Thumb) const;
1766
1767 /// \return The maximum number of function arguments the target supports.
1768 unsigned getMaxNumArgs() const;
1769
1770 /// @}
1771
1772private:
1773 /// The abstract base class used to type erase specific TTI
1774 /// implementations.
1775 class Concept;
1776
1777 /// The template model for the base class which wraps a concrete
1778 /// implementation in a type erased interface.
1779 template <typename T> class Model;
1780
1781 std::unique_ptr<Concept> TTIImpl;
1782};
1783
1785public:
1786 virtual ~Concept() = 0;
1787 virtual const DataLayout &getDataLayout() const = 0;
1788 virtual InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr,
1790 Type *AccessType,
1792 virtual InstructionCost
1794 const TTI::PointersChainInfo &Info, Type *AccessTy,
1796 virtual unsigned getInliningThresholdMultiplier() const = 0;
1798 virtual unsigned
1800 virtual unsigned adjustInliningThreshold(const CallBase *CB) = 0;
1801 virtual int getInlinerVectorBonusPercent() const = 0;
1802 virtual unsigned getCallerAllocaCost(const CallBase *CB,
1803 const AllocaInst *AI) const = 0;
1806 virtual unsigned
1808 ProfileSummaryInfo *PSI,
1809 BlockFrequencyInfo *BFI) = 0;
1814 virtual bool hasBranchDivergence(const Function *F = nullptr) = 0;
1815 virtual bool isSourceOfDivergence(const Value *V) = 0;
1816 virtual bool isAlwaysUniform(const Value *V) = 0;
1817 virtual bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const = 0;
1818 virtual bool addrspacesMayAlias(unsigned AS0, unsigned AS1) const = 0;
1819 virtual unsigned getFlatAddressSpace() = 0;
1821 Intrinsic::ID IID) const = 0;
1822 virtual bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const = 0;
1823 virtual bool
1825 virtual unsigned getAssumedAddrSpace(const Value *V) const = 0;
1826 virtual bool isSingleThreaded() const = 0;
1827 virtual std::pair<const Value *, unsigned>
1828 getPredicatedAddrSpace(const Value *V) const = 0;
1830 Value *OldV,
1831 Value *NewV) const = 0;
1832 virtual bool isLoweredToCall(const Function *F) = 0;
1835 OptimizationRemarkEmitter *ORE) = 0;
1837 PeelingPreferences &PP) = 0;
1839 AssumptionCache &AC,
1840 TargetLibraryInfo *LibInfo,
1841 HardwareLoopInfo &HWLoopInfo) = 0;
1843 virtual TailFoldingStyle
1844 getPreferredTailFoldingStyle(bool IVUpdateMayOverflow = true) = 0;
1845 virtual std::optional<Instruction *> instCombineIntrinsic(
1846 InstCombiner &IC, IntrinsicInst &II) = 0;
1847 virtual std::optional<Value *> simplifyDemandedUseBitsIntrinsic(
1848 InstCombiner &IC, IntrinsicInst &II, APInt DemandedMask,
1849 KnownBits & Known, bool &KnownBitsComputed) = 0;
1850 virtual std::optional<Value *> simplifyDemandedVectorEltsIntrinsic(
1851 InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts,
1852 APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3,
1853 std::function<void(Instruction *, unsigned, APInt, APInt &)>
1854 SimplifyAndSetOp) = 0;
1855 virtual bool isLegalAddImmediate(int64_t Imm) = 0;
1856 virtual bool isLegalAddScalableImmediate(int64_t Imm) = 0;
1857 virtual bool isLegalICmpImmediate(int64_t Imm) = 0;
1858 virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
1859 int64_t BaseOffset, bool HasBaseReg,
1860 int64_t Scale, unsigned AddrSpace,
1861 Instruction *I,
1862 int64_t ScalableOffset) = 0;
1864 const TargetTransformInfo::LSRCost &C2) = 0;
1865 virtual bool isNumRegsMajorCostOfLSR() = 0;
1868 virtual bool canMacroFuseCmp() = 0;
1869 virtual bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE,
1871 TargetLibraryInfo *LibInfo) = 0;
1872 virtual AddressingModeKind
1874 virtual bool isLegalMaskedStore(Type *DataType, Align Alignment) = 0;
1875 virtual bool isLegalMaskedLoad(Type *DataType, Align Alignment) = 0;
1876 virtual bool isLegalNTStore(Type *DataType, Align Alignment) = 0;
1877 virtual bool isLegalNTLoad(Type *DataType, Align Alignment) = 0;
1878 virtual bool isLegalBroadcastLoad(Type *ElementTy,
1879 ElementCount NumElements) const = 0;
1880 virtual bool isLegalMaskedScatter(Type *DataType, Align Alignment) = 0;
1881 virtual bool isLegalMaskedGather(Type *DataType, Align Alignment) = 0;
1883 Align Alignment) = 0;
1885 Align Alignment) = 0;
1886 virtual bool isLegalMaskedCompressStore(Type *DataType, Align Alignment) = 0;
1887 virtual bool isLegalMaskedExpandLoad(Type *DataType, Align Alignment) = 0;
1888 virtual bool isLegalStridedLoadStore(Type *DataType, Align Alignment) = 0;
1889 virtual bool isLegalMaskedVectorHistogram(Type *AddrType, Type *DataType) = 0;
1890 virtual bool isLegalAltInstr(VectorType *VecTy, unsigned Opcode0,
1891 unsigned Opcode1,
1892 const SmallBitVector &OpcodeMask) const = 0;
1893 virtual bool enableOrderedReductions() = 0;
1894 virtual bool hasDivRemOp(Type *DataType, bool IsSigned) = 0;
1895 virtual bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) = 0;
1898 StackOffset BaseOffset,
1899 bool HasBaseReg, int64_t Scale,
1900 unsigned AddrSpace) = 0;
1901 virtual bool LSRWithInstrQueries() = 0;
1902 virtual bool isTruncateFree(Type *Ty1, Type *Ty2) = 0;
1904 virtual bool useAA() = 0;
1905 virtual bool isTypeLegal(Type *Ty) = 0;
1906 virtual unsigned getRegUsageForType(Type *Ty) = 0;
1907 virtual bool shouldBuildLookupTables() = 0;
1909 virtual bool shouldBuildRelLookupTables() = 0;
1910 virtual bool useColdCCForColdCall(Function &F) = 0;
1912 const APInt &DemandedElts,
1913 bool Insert, bool Extract,
1915 virtual InstructionCost
1917 ArrayRef<Type *> Tys,
1920 virtual bool supportsTailCalls() = 0;
1921 virtual bool supportsTailCallFor(const CallBase *CB) = 0;
1922 virtual bool enableAggressiveInterleaving(bool LoopHasReductions) = 0;
1924 enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const = 0;
1925 virtual bool enableSelectOptimize() = 0;
1931 unsigned BitWidth,
1932 unsigned AddressSpace,
1933 Align Alignment,
1934 unsigned *Fast) = 0;
1935 virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) = 0;
1936 virtual bool haveFastSqrt(Type *Ty) = 0;
1938 virtual bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) = 0;
1940 virtual InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx,
1941 const APInt &Imm, Type *Ty) = 0;
1942 virtual InstructionCost getIntImmCost(const APInt &Imm, Type *Ty,
1944 virtual InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx,
1945 const APInt &Imm, Type *Ty,
1947 Instruction *Inst = nullptr) = 0;
1949 const APInt &Imm, Type *Ty,
1952 const Function &Fn) const = 0;
1953 virtual unsigned getNumberOfRegisters(unsigned ClassID) const = 0;
1954 virtual unsigned getRegisterClassForType(bool Vector,
1955 Type *Ty = nullptr) const = 0;
1956 virtual const char *getRegisterClassName(unsigned ClassID) const = 0;
1958 virtual unsigned getMinVectorRegisterBitWidth() const = 0;
1959 virtual std::optional<unsigned> getMaxVScale() const = 0;
1960 virtual std::optional<unsigned> getVScaleForTuning() const = 0;
1961 virtual bool isVScaleKnownToBeAPowerOfTwo() const = 0;
1962 virtual bool
1964 virtual ElementCount getMinimumVF(unsigned ElemWidth,
1965 bool IsScalable) const = 0;
1966 virtual unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const = 0;
1967 virtual unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy,
1968 Type *ScalarValTy) const = 0;
1970 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) = 0;
1971 virtual unsigned getCacheLineSize() const = 0;
1972 virtual std::optional<unsigned> getCacheSize(CacheLevel Level) const = 0;
1973 virtual std::optional<unsigned> getCacheAssociativity(CacheLevel Level)
1974 const = 0;
1975 virtual std::optional<unsigned> getMinPageSize() const = 0;
1976
1977 /// \return How much before a load we should place the prefetch
1978 /// instruction. This is currently measured in number of
1979 /// instructions.
1980 virtual unsigned getPrefetchDistance() const = 0;
1981
1982 /// \return Some HW prefetchers can handle accesses up to a certain
1983 /// constant stride. This is the minimum stride in bytes where it
1984 /// makes sense to start adding SW prefetches. The default is 1,
1985 /// i.e. prefetch with any stride. Sometimes prefetching is beneficial
1986 /// even below the HW prefetcher limit, and the arguments provided are
1987 /// meant to serve as a basis for deciding this for a particular loop.
1988 virtual unsigned getMinPrefetchStride(unsigned NumMemAccesses,
1989 unsigned NumStridedMemAccesses,
1990 unsigned NumPrefetches,
1991 bool HasCall) const = 0;
1992
1993 /// \return The maximum number of iterations to prefetch ahead. If
1994 /// the required number of iterations is more than this number, no
1995 /// prefetching is performed.
1996 virtual unsigned getMaxPrefetchIterationsAhead() const = 0;
1997
1998 /// \return True if prefetching should also be done for writes.
1999 virtual bool enableWritePrefetching() const = 0;
2000
2001 /// \return if target want to issue a prefetch in address space \p AS.
2002 virtual bool shouldPrefetchAddressSpace(unsigned AS) const = 0;
2003
2004 virtual unsigned getMaxInterleaveFactor(ElementCount VF) = 0;
2006 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
2007 OperandValueInfo Opd1Info, OperandValueInfo Opd2Info,
2008 ArrayRef<const Value *> Args, const Instruction *CxtI = nullptr) = 0;
2010 VectorType *VecTy, unsigned Opcode0, unsigned Opcode1,
2011 const SmallBitVector &OpcodeMask,
2013
2014 virtual InstructionCost
2017 ArrayRef<const Value *> Args, const Instruction *CxtI) = 0;
2018 virtual InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst,
2019 Type *Src, CastContextHint CCH,
2021 const Instruction *I) = 0;
2022 virtual InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst,
2023 VectorType *VecTy,
2024 unsigned Index) = 0;
2025 virtual InstructionCost getCFInstrCost(unsigned Opcode,
2027 const Instruction *I = nullptr) = 0;
2028 virtual InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
2029 Type *CondTy,
2030 CmpInst::Predicate VecPred,
2032 const Instruction *I) = 0;
2033 virtual InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val,
2035 unsigned Index, Value *Op0,
2036 Value *Op1) = 0;
2039 unsigned Index) = 0;
2040
2041 virtual InstructionCost
2042 getReplicationShuffleCost(Type *EltTy, int ReplicationFactor, int VF,
2043 const APInt &DemandedDstElts,
2045
2046 virtual InstructionCost
2047 getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
2049 OperandValueInfo OpInfo, const Instruction *I) = 0;
2050 virtual InstructionCost getVPMemoryOpCost(unsigned Opcode, Type *Src,
2051 Align Alignment,
2052 unsigned AddressSpace,
2054 const Instruction *I) = 0;
2055 virtual InstructionCost
2056 getMaskedMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
2057 unsigned AddressSpace,
2059 virtual InstructionCost
2060 getGatherScatterOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr,
2061 bool VariableMask, Align Alignment,
2063 const Instruction *I = nullptr) = 0;
2064 virtual InstructionCost
2065 getStridedMemoryOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr,
2066 bool VariableMask, Align Alignment,
2068 const Instruction *I = nullptr) = 0;
2069
2071 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
2072 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
2073 bool UseMaskForCond = false, bool UseMaskForGaps = false) = 0;
2074 virtual InstructionCost
2076 std::optional<FastMathFlags> FMF,
2078 virtual InstructionCost
2082 unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty,
2083 FastMathFlags FMF,
2086 bool IsUnsigned, Type *ResTy, VectorType *Ty,
2088 virtual InstructionCost
2092 ArrayRef<Type *> Tys,
2094 virtual unsigned getNumberOfParts(Type *Tp) = 0;
2095 virtual InstructionCost
2097 virtual InstructionCost
2100 MemIntrinsicInfo &Info) = 0;
2101 virtual unsigned getAtomicMemIntrinsicMaxElementSize() const = 0;
2103 Type *ExpectedType) = 0;
2105 LLVMContext &Context, Value *Length, unsigned SrcAddrSpace,
2106 unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign,
2107 std::optional<uint32_t> AtomicElementSize) const = 0;
2108
2110 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
2111 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
2112 unsigned SrcAlign, unsigned DestAlign,
2113 std::optional<uint32_t> AtomicCpySize) const = 0;
2114 virtual bool areInlineCompatible(const Function *Caller,
2115 const Function *Callee) const = 0;
2116 virtual unsigned getInlineCallPenalty(const Function *F, const CallBase &Call,
2117 unsigned DefaultCallPenalty) const = 0;
2118 virtual bool areTypesABICompatible(const Function *Caller,
2119 const Function *Callee,
2120 const ArrayRef<Type *> &Types) const = 0;
2121 virtual bool isIndexedLoadLegal(MemIndexedMode Mode, Type *Ty) const = 0;
2122 virtual bool isIndexedStoreLegal(MemIndexedMode Mode, Type *Ty) const = 0;
2123 virtual unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const = 0;
2124 virtual bool isLegalToVectorizeLoad(LoadInst *LI) const = 0;
2125 virtual bool isLegalToVectorizeStore(StoreInst *SI) const = 0;
2126 virtual bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
2127 Align Alignment,
2128 unsigned AddrSpace) const = 0;
2129 virtual bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
2130 Align Alignment,
2131 unsigned AddrSpace) const = 0;
2133 ElementCount VF) const = 0;
2134 virtual bool isElementTypeLegalForScalableVector(Type *Ty) const = 0;
2135 virtual unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
2136 unsigned ChainSizeInBytes,
2137 VectorType *VecTy) const = 0;
2138 virtual unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
2139 unsigned ChainSizeInBytes,
2140 VectorType *VecTy) const = 0;
2141 virtual bool preferInLoopReduction(unsigned Opcode, Type *Ty,
2142 ReductionFlags) const = 0;
2143 virtual bool preferPredicatedReductionSelect(unsigned Opcode, Type *Ty,
2144 ReductionFlags) const = 0;
2145 virtual bool preferEpilogueVectorization() const = 0;
2146
2147 virtual bool shouldExpandReduction(const IntrinsicInst *II) const = 0;
2148 virtual unsigned getGISelRematGlobalCost() const = 0;
2149 virtual unsigned getMinTripCountTailFoldingThreshold() const = 0;
2150 virtual bool enableScalableVectorization() const = 0;
2151 virtual bool supportsScalableVectors() const = 0;
2152 virtual bool hasActiveVectorLength(unsigned Opcode, Type *DataType,
2153 Align Alignment) const = 0;
2154 virtual VPLegalization
2156 virtual bool hasArmWideBranch(bool Thumb) const = 0;
2157 virtual unsigned getMaxNumArgs() const = 0;
2158};
2159
2160template <typename T>
2161class TargetTransformInfo::Model final : public TargetTransformInfo::Concept {
2162 T Impl;
2163
2164public:
2165 Model(T Impl) : Impl(std::move(Impl)) {}
2166 ~Model() override = default;
2167
2168 const DataLayout &getDataLayout() const override {
2169 return Impl.getDataLayout();
2170 }
2171
2172 InstructionCost
2173 getGEPCost(Type *PointeeType, const Value *Ptr,
2174 ArrayRef<const Value *> Operands, Type *AccessType,
2176 return Impl.getGEPCost(PointeeType, Ptr, Operands, AccessType, CostKind);
2177 }
2178 InstructionCost getPointersChainCost(ArrayRef<const Value *> Ptrs,
2179 const Value *Base,
2180 const PointersChainInfo &Info,
2181 Type *AccessTy,
2182 TargetCostKind CostKind) override {
2183 return Impl.getPointersChainCost(Ptrs, Base, Info, AccessTy, CostKind);
2184 }
2185 unsigned getInliningThresholdMultiplier() const override {
2186 return Impl.getInliningThresholdMultiplier();
2187 }
2188 unsigned adjustInliningThreshold(const CallBase *CB) override {
2189 return Impl.adjustInliningThreshold(CB);
2190 }
2191 unsigned getInliningCostBenefitAnalysisSavingsMultiplier() const override {
2192 return Impl.getInliningCostBenefitAnalysisSavingsMultiplier();
2193 }
2194 unsigned getInliningCostBenefitAnalysisProfitableMultiplier() const override {
2195 return Impl.getInliningCostBenefitAnalysisProfitableMultiplier();
2196 }
2197 int getInlinerVectorBonusPercent() const override {
2198 return Impl.getInlinerVectorBonusPercent();
2199 }
2200 unsigned getCallerAllocaCost(const CallBase *CB,
2201 const AllocaInst *AI) const override {
2202 return Impl.getCallerAllocaCost(CB, AI);
2203 }
2204 InstructionCost getMemcpyCost(const Instruction *I) override {
2205 return Impl.getMemcpyCost(I);
2206 }
2207
2208 uint64_t getMaxMemIntrinsicInlineSizeThreshold() const override {
2209 return Impl.getMaxMemIntrinsicInlineSizeThreshold();
2210 }
2211
2212 InstructionCost getInstructionCost(const User *U,
2213 ArrayRef<const Value *> Operands,
2214 TargetCostKind CostKind) override {
2215 return Impl.getInstructionCost(U, Operands, CostKind);
2216 }
2217 BranchProbability getPredictableBranchThreshold() override {
2218 return Impl.getPredictableBranchThreshold();
2219 }
2220 bool hasBranchDivergence(const Function *F = nullptr) override {
2221 return Impl.hasBranchDivergence(F);
2222 }
2223 bool isSourceOfDivergence(const Value *V) override {
2224 return Impl.isSourceOfDivergence(V);
2225 }
2226
2227 bool isAlwaysUniform(const Value *V) override {
2228 return Impl.isAlwaysUniform(V);
2229 }
2230
2231 bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const override {
2232 return Impl.isValidAddrSpaceCast(FromAS, ToAS);
2233 }
2234
2235 bool addrspacesMayAlias(unsigned AS0, unsigned AS1) const override {
2236 return Impl.addrspacesMayAlias(AS0, AS1);
2237 }
2238
2239 unsigned getFlatAddressSpace() override { return Impl.getFlatAddressSpace(); }
2240
2241 bool collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
2242 Intrinsic::ID IID) const override {
2243 return Impl.collectFlatAddressOperands(OpIndexes, IID);
2244 }
2245
2246 bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const override {
2247 return Impl.isNoopAddrSpaceCast(FromAS, ToAS);
2248 }
2249
2250 bool
2251 canHaveNonUndefGlobalInitializerInAddressSpace(unsigned AS) const override {
2252 return Impl.canHaveNonUndefGlobalInitializerInAddressSpace(AS);
2253 }
2254
2255 unsigned getAssumedAddrSpace(const Value *V) const override {
2256 return Impl.getAssumedAddrSpace(V);
2257 }
2258
2259 bool isSingleThreaded() const override { return Impl.isSingleThreaded(); }
2260
2261 std::pair<const Value *, unsigned>
2262 getPredicatedAddrSpace(const Value *V) const override {
2263 return Impl.getPredicatedAddrSpace(V);
2264 }
2265
2266 Value *rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, Value *OldV,
2267 Value *NewV) const override {
2268 return Impl.rewriteIntrinsicWithAddressSpace(II, OldV, NewV);
2269 }
2270
2271 bool isLoweredToCall(const Function *F) override {
2272 return Impl.isLoweredToCall(F);
2273 }
2274 void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
2275 UnrollingPreferences &UP,
2276 OptimizationRemarkEmitter *ORE) override {
2277 return Impl.getUnrollingPreferences(L, SE, UP, ORE);
2278 }
2279 void getPeelingPreferences(Loop *L, ScalarEvolution &SE,
2280 PeelingPreferences &PP) override {
2281 return Impl.getPeelingPreferences(L, SE, PP);
2282 }
2283 bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
2284 AssumptionCache &AC, TargetLibraryInfo *LibInfo,
2285 HardwareLoopInfo &HWLoopInfo) override {
2286 return Impl.isHardwareLoopProfitable(L, SE, AC, LibInfo, HWLoopInfo);
2287 }
2288 bool preferPredicateOverEpilogue(TailFoldingInfo *TFI) override {
2289 return Impl.preferPredicateOverEpilogue(TFI);
2290 }
2292 getPreferredTailFoldingStyle(bool IVUpdateMayOverflow = true) override {
2293 return Impl.getPreferredTailFoldingStyle(IVUpdateMayOverflow);
2294 }
2295 std::optional<Instruction *>
2296 instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) override {
2297 return Impl.instCombineIntrinsic(IC, II);
2298 }
2299 std::optional<Value *>
2300 simplifyDemandedUseBitsIntrinsic(InstCombiner &IC, IntrinsicInst &II,
2301 APInt DemandedMask, KnownBits &Known,
2302 bool &KnownBitsComputed) override {
2303 return Impl.simplifyDemandedUseBitsIntrinsic(IC, II, DemandedMask, Known,
2304 KnownBitsComputed);
2305 }
2306 std::optional<Value *> simplifyDemandedVectorEltsIntrinsic(
2307 InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
2308 APInt &UndefElts2, APInt &UndefElts3,
2309 std::function<void(Instruction *, unsigned, APInt, APInt &)>
2310 SimplifyAndSetOp) override {
2311 return Impl.simplifyDemandedVectorEltsIntrinsic(
2312 IC, II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
2313 SimplifyAndSetOp);
2314 }
2315 bool isLegalAddImmediate(int64_t Imm) override {
2316 return Impl.isLegalAddImmediate(Imm);
2317 }
2318 bool isLegalAddScalableImmediate(int64_t Imm) override {
2319 return Impl.isLegalAddScalableImmediate(Imm);
2320 }
2321 bool isLegalICmpImmediate(int64_t Imm) override {
2322 return Impl.isLegalICmpImmediate(Imm);
2323 }
2324 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
2325 bool HasBaseReg, int64_t Scale, unsigned AddrSpace,
2326 Instruction *I, int64_t ScalableOffset) override {
2327 return Impl.isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg, Scale,
2328 AddrSpace, I, ScalableOffset);
2329 }
2330 bool isLSRCostLess(const TargetTransformInfo::LSRCost &C1,
2331 const TargetTransformInfo::LSRCost &C2) override {
2332 return Impl.isLSRCostLess(C1, C2);
2333 }
2334 bool isNumRegsMajorCostOfLSR() override {
2335 return Impl.isNumRegsMajorCostOfLSR();
2336 }
2337 bool shouldFoldTerminatingConditionAfterLSR() const override {
2338 return Impl.shouldFoldTerminatingConditionAfterLSR();
2339 }
2340 bool isProfitableLSRChainElement(Instruction *I) override {
2341 return Impl.isProfitableLSRChainElement(I);
2342 }
2343 bool canMacroFuseCmp() override { return Impl.canMacroFuseCmp(); }
2344 bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE, LoopInfo *LI,
2345 DominatorTree *DT, AssumptionCache *AC,
2346 TargetLibraryInfo *LibInfo) override {
2347 return Impl.canSaveCmp(L, BI, SE, LI, DT, AC, LibInfo);
2348 }
2350 getPreferredAddressingMode(const Loop *L,
2351 ScalarEvolution *SE) const override {
2352 return Impl.getPreferredAddressingMode(L, SE);
2353 }
2354 bool isLegalMaskedStore(Type *DataType, Align Alignment) override {
2355 return Impl.isLegalMaskedStore(DataType, Alignment);
2356 }
2357 bool isLegalMaskedLoad(Type *DataType, Align Alignment) override {
2358 return Impl.isLegalMaskedLoad(DataType, Alignment);
2359 }
2360 bool isLegalNTStore(Type *DataType, Align Alignment) override {
2361 return Impl.isLegalNTStore(DataType, Alignment);
2362 }
2363 bool isLegalNTLoad(Type *DataType, Align Alignment) override {
2364 return Impl.isLegalNTLoad(DataType, Alignment);
2365 }
2366 bool isLegalBroadcastLoad(Type *ElementTy,
2367 ElementCount NumElements) const override {
2368 return Impl.isLegalBroadcastLoad(ElementTy, NumElements);
2369 }
2370 bool isLegalMaskedScatter(Type *DataType, Align Alignment) override {
2371 return Impl.isLegalMaskedScatter(DataType, Alignment);
2372 }
2373 bool isLegalMaskedGather(Type *DataType, Align Alignment) override {
2374 return Impl.isLegalMaskedGather(DataType, Alignment);
2375 }
2376 bool forceScalarizeMaskedGather(VectorType *DataType,
2377 Align Alignment) override {
2378 return Impl.forceScalarizeMaskedGather(DataType, Alignment);
2379 }
2380 bool forceScalarizeMaskedScatter(VectorType *DataType,
2381 Align Alignment) override {
2382 return Impl.forceScalarizeMaskedScatter(DataType, Alignment);
2383 }
2384 bool isLegalMaskedCompressStore(Type *DataType, Align Alignment) override {
2385 return Impl.isLegalMaskedCompressStore(DataType, Alignment);
2386 }
2387 bool isLegalMaskedExpandLoad(Type *DataType, Align Alignment) override {
2388 return Impl.isLegalMaskedExpandLoad(DataType, Alignment);
2389 }
2390 bool isLegalStridedLoadStore(Type *DataType, Align Alignment) override {
2391 return Impl.isLegalStridedLoadStore(DataType, Alignment);
2392 }
2393 bool isLegalMaskedVectorHistogram(Type *AddrType, Type *DataType) override {
2394 return Impl.isLegalMaskedVectorHistogram(AddrType, DataType);
2395 }
2396 bool isLegalAltInstr(VectorType *VecTy, unsigned Opcode0, unsigned Opcode1,
2397 const SmallBitVector &OpcodeMask) const override {
2398 return Impl.isLegalAltInstr(VecTy, Opcode0, Opcode1, OpcodeMask);
2399 }
2400 bool enableOrderedReductions() override {
2401 return Impl.enableOrderedReductions();
2402 }
2403 bool hasDivRemOp(Type *DataType, bool IsSigned) override {
2404 return Impl.hasDivRemOp(DataType, IsSigned);
2405 }
2406 bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) override {
2407 return Impl.hasVolatileVariant(I, AddrSpace);
2408 }
2409 bool prefersVectorizedAddressing() override {
2410 return Impl.prefersVectorizedAddressing();
2411 }
2412 InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
2413 StackOffset BaseOffset, bool HasBaseReg,
2414 int64_t Scale,
2415 unsigned AddrSpace) override {
2416 return Impl.getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg, Scale,
2417 AddrSpace);
2418 }
2419 bool LSRWithInstrQueries() override { return Impl.LSRWithInstrQueries(); }
2420 bool isTruncateFree(Type *Ty1, Type *Ty2) override {
2421 return Impl.isTruncateFree(Ty1, Ty2);
2422 }
2423 bool isProfitableToHoist(Instruction *I) override {
2424 return Impl.isProfitableToHoist(I);
2425 }
2426 bool useAA() override { return Impl.useAA(); }
2427 bool isTypeLegal(Type *Ty) override { return Impl.isTypeLegal(Ty); }
2428 unsigned getRegUsageForType(Type *Ty) override {
2429 return Impl.getRegUsageForType(Ty);
2430 }
2431 bool shouldBuildLookupTables() override {
2432 return Impl.shouldBuildLookupTables();
2433 }
2434 bool shouldBuildLookupTablesForConstant(Constant *C) override {
2435 return Impl.shouldBuildLookupTablesForConstant(C);
2436 }
2437 bool shouldBuildRelLookupTables() override {
2438 return Impl.shouldBuildRelLookupTables();
2439 }
2440 bool useColdCCForColdCall(Function &F) override {
2441 return Impl.useColdCCForColdCall(F);
2442 }
2443
2444 InstructionCost getScalarizationOverhead(VectorType *Ty,
2445 const APInt &DemandedElts,
2446 bool Insert, bool Extract,
2447 TargetCostKind CostKind) override {
2448 return Impl.getScalarizationOverhead(Ty, DemandedElts, Insert, Extract,
2449 CostKind);
2450 }
2451 InstructionCost
2452 getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
2453 ArrayRef<Type *> Tys,
2454 TargetCostKind CostKind) override {
2455 return Impl.getOperandsScalarizationOverhead(Args, Tys, CostKind);
2456 }
2457
2458 bool supportsEfficientVectorElementLoadStore() override {
2459 return Impl.supportsEfficientVectorElementLoadStore();
2460 }
2461
2462 bool supportsTailCalls() override { return Impl.supportsTailCalls(); }
2463 bool supportsTailCallFor(const CallBase *CB) override {
2464 return Impl.supportsTailCallFor(CB);
2465 }
2466
2467 bool enableAggressiveInterleaving(bool LoopHasReductions) override {
2468 return Impl.enableAggressiveInterleaving(LoopHasReductions);
2469 }
2470 MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize,
2471 bool IsZeroCmp) const override {
2472 return Impl.enableMemCmpExpansion(OptSize, IsZeroCmp);
2473 }
2474 bool enableSelectOptimize() override {
2475 return Impl.enableSelectOptimize();
2476 }
2477 bool shouldTreatInstructionLikeSelect(const Instruction *I) override {
2478 return Impl.shouldTreatInstructionLikeSelect(I);
2479 }
2480 bool enableInterleavedAccessVectorization() override {
2481 return Impl.enableInterleavedAccessVectorization();
2482 }
2483 bool enableMaskedInterleavedAccessVectorization() override {
2484 return Impl.enableMaskedInterleavedAccessVectorization();
2485 }
2486 bool isFPVectorizationPotentiallyUnsafe() override {
2487 return Impl.isFPVectorizationPotentiallyUnsafe();
2488 }
2489 bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth,
2490 unsigned AddressSpace, Align Alignment,
2491 unsigned *Fast) override {
2492 return Impl.allowsMisalignedMemoryAccesses(Context, BitWidth, AddressSpace,
2493 Alignment, Fast);
2494 }
2495 PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) override {
2496 return Impl.getPopcntSupport(IntTyWidthInBit);
2497 }
2498 bool haveFastSqrt(Type *Ty) override { return Impl.haveFastSqrt(Ty); }
2499
2500 bool isExpensiveToSpeculativelyExecute(const Instruction* I) override {
2501 return Impl.isExpensiveToSpeculativelyExecute(I);
2502 }
2503
2504 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) override {
2505 return Impl.isFCmpOrdCheaperThanFCmpZero(Ty);
2506 }
2507
2508 InstructionCost getFPOpCost(Type *Ty) override {
2509 return Impl.getFPOpCost(Ty);
2510 }
2511
2512 InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx,
2513 const APInt &Imm, Type *Ty) override {
2514 return Impl.getIntImmCodeSizeCost(Opc, Idx, Imm, Ty);
2515 }
2516 InstructionCost getIntImmCost(const APInt &Imm, Type *Ty,
2517 TargetCostKind CostKind) override {
2518 return Impl.getIntImmCost(Imm, Ty, CostKind);
2519 }
2520 InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx,
2521 const APInt &Imm, Type *Ty,
2523 Instruction *Inst = nullptr) override {
2524 return Impl.getIntImmCostInst(Opc, Idx, Imm, Ty, CostKind, Inst);
2525 }
2526 InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
2527 const APInt &Imm, Type *Ty,
2528 TargetCostKind CostKind) override {
2529 return Impl.getIntImmCostIntrin(IID, Idx, Imm, Ty, CostKind);
2530 }
2531 bool preferToKeepConstantsAttached(const Instruction &Inst,
2532 const Function &Fn) const override {
2533 return Impl.preferToKeepConstantsAttached(Inst, Fn);
2534 }
2535 unsigned getNumberOfRegisters(unsigned ClassID) const override {
2536 return Impl.getNumberOfRegisters(ClassID);
2537 }
2538 unsigned getRegisterClassForType(bool Vector,
2539 Type *Ty = nullptr) const override {
2540 return Impl.getRegisterClassForType(Vector, Ty);
2541 }
2542 const char *getRegisterClassName(unsigned ClassID) const override {
2543 return Impl.getRegisterClassName(ClassID);
2544 }
2545 TypeSize getRegisterBitWidth(RegisterKind K) const override {
2546 return Impl.getRegisterBitWidth(K);
2547 }
2548 unsigned getMinVectorRegisterBitWidth() const override {
2549 return Impl.getMinVectorRegisterBitWidth();
2550 }
2551 std::optional<unsigned> getMaxVScale() const override {
2552 return Impl.getMaxVScale();
2553 }
2554 std::optional<unsigned> getVScaleForTuning() const override {
2555 return Impl.getVScaleForTuning();
2556 }
2557 bool isVScaleKnownToBeAPowerOfTwo() const override {
2558 return Impl.isVScaleKnownToBeAPowerOfTwo();
2559 }
2560 bool shouldMaximizeVectorBandwidth(
2561 TargetTransformInfo::RegisterKind K) const override {
2562 return Impl.shouldMaximizeVectorBandwidth(K);
2563 }
2564 ElementCount getMinimumVF(unsigned ElemWidth,
2565 bool IsScalable) const override {
2566 return Impl.getMinimumVF(ElemWidth, IsScalable);
2567 }
2568 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const override {
2569 return Impl.getMaximumVF(ElemWidth, Opcode);
2570 }
2571 unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy,
2572 Type *ScalarValTy) const override {
2573 return Impl.getStoreMinimumVF(VF, ScalarMemTy, ScalarValTy);
2574 }
2575 bool shouldConsiderAddressTypePromotion(
2576 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) override {
2577 return Impl.shouldConsiderAddressTypePromotion(
2578 I, AllowPromotionWithoutCommonHeader);
2579 }
2580 unsigned getCacheLineSize() const override { return Impl.getCacheLineSize(); }
2581 std::optional<unsigned> getCacheSize(CacheLevel Level) const override {
2582 return Impl.getCacheSize(Level);
2583 }
2584 std::optional<unsigned>
2585 getCacheAssociativity(CacheLevel Level) const override {
2586 return Impl.getCacheAssociativity(Level);
2587 }
2588
2589 std::optional<unsigned> getMinPageSize() const override {
2590 return Impl.getMinPageSize();
2591 }
2592
2593 /// Return the preferred prefetch distance in terms of instructions.
2594 ///
2595 unsigned getPrefetchDistance() const override {
2596 return Impl.getPrefetchDistance();
2597 }
2598
2599 /// Return the minimum stride necessary to trigger software
2600 /// prefetching.
2601 ///
2602 unsigned getMinPrefetchStride(unsigned NumMemAccesses,
2603 unsigned NumStridedMemAccesses,
2604 unsigned NumPrefetches,
2605 bool HasCall) const override {
2606 return Impl.getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses,
2607 NumPrefetches, HasCall);
2608 }
2609
2610 /// Return the maximum prefetch distance in terms of loop
2611 /// iterations.
2612 ///
2613 unsigned getMaxPrefetchIterationsAhead() const override {
2614 return Impl.getMaxPrefetchIterationsAhead();
2615 }
2616
2617 /// \return True if prefetching should also be done for writes.
2618 bool enableWritePrefetching() const override {
2619 return Impl.enableWritePrefetching();
2620 }
2621
2622 /// \return if target want to issue a prefetch in address space \p AS.
2623 bool shouldPrefetchAddressSpace(unsigned AS) const override {
2624 return Impl.shouldPrefetchAddressSpace(AS);
2625 }
2626
2627 unsigned getMaxInterleaveFactor(ElementCount VF) override {
2628 return Impl.getMaxInterleaveFactor(VF);
2629 }
2630 unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
2631 unsigned &JTSize,
2632 ProfileSummaryInfo *PSI,
2633 BlockFrequencyInfo *BFI) override {
2634 return Impl.getEstimatedNumberOfCaseClusters(SI, JTSize, PSI, BFI);
2635 }
2636 InstructionCost getArithmeticInstrCost(
2637 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
2638 OperandValueInfo Opd1Info, OperandValueInfo Opd2Info,
2639 ArrayRef<const Value *> Args,
2640 const Instruction *CxtI = nullptr) override {
2641 return Impl.getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, Opd2Info,
2642 Args, CxtI);
2643 }
2644 InstructionCost getAltInstrCost(VectorType *VecTy, unsigned Opcode0,
2645 unsigned Opcode1,
2646 const SmallBitVector &OpcodeMask,
2647 TTI::TargetCostKind CostKind) const override {
2648 return Impl.getAltInstrCost(VecTy, Opcode0, Opcode1, OpcodeMask, CostKind);
2649 }
2650
2651 InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *Tp,
2652 ArrayRef<int> Mask,
2654 VectorType *SubTp,
2655 ArrayRef<const Value *> Args,
2656 const Instruction *CxtI) override {
2657 return Impl.getShuffleCost(Kind, Tp, Mask, CostKind, Index, SubTp, Args,
2658 CxtI);
2659 }
2660 InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
2661 CastContextHint CCH,
2663 const Instruction *I) override {
2664 return Impl.getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
2665 }
2666 InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst,
2667 VectorType *VecTy,
2668 unsigned Index) override {
2669 return Impl.getExtractWithExtendCost(Opcode, Dst, VecTy, Index);
2670 }
2671 InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind,
2672 const Instruction *I = nullptr) override {
2673 return Impl.getCFInstrCost(Opcode, CostKind, I);
2674 }
2675 InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
2676 CmpInst::Predicate VecPred,
2678 const Instruction *I) override {
2679 return Impl.getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
2680 }
2681 InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val,
2683 unsigned Index, Value *Op0,
2684 Value *Op1) override {
2685 return Impl.getVectorInstrCost(Opcode, Val, CostKind, Index, Op0, Op1);
2686 }
2687 InstructionCost getVectorInstrCost(const Instruction &I, Type *Val,
2689 unsigned Index) override {
2690 return Impl.getVectorInstrCost(I, Val, CostKind, Index);
2691 }
2692 InstructionCost
2693 getReplicationShuffleCost(Type *EltTy, int ReplicationFactor, int VF,
2694 const APInt &DemandedDstElts,
2695 TTI::TargetCostKind CostKind) override {
2696 return Impl.getReplicationShuffleCost(EltTy, ReplicationFactor, VF,
2697 DemandedDstElts, CostKind);
2698 }
2699 InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
2700 unsigned AddressSpace,
2702 OperandValueInfo OpInfo,
2703 const Instruction *I) override {
2704 return Impl.getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, CostKind,
2705 OpInfo, I);
2706 }
2707 InstructionCost getVPMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
2708 unsigned AddressSpace,
2710 const Instruction *I) override {
2711 return Impl.getVPMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
2712 CostKind, I);
2713 }
2714 InstructionCost getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
2715 Align Alignment, unsigned AddressSpace,
2716 TTI::TargetCostKind CostKind) override {
2717 return Impl.getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
2718 CostKind);
2719 }
2720 InstructionCost
2721 getGatherScatterOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr,
2722 bool VariableMask, Align Alignment,
2724 const Instruction *I = nullptr) override {
2725 return Impl.getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
2726 Alignment, CostKind, I);
2727 }
2728 InstructionCost
2729 getStridedMemoryOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr,
2730 bool VariableMask, Align Alignment,
2732 const Instruction *I = nullptr) override {
2733 return Impl.getStridedMemoryOpCost(Opcode, DataTy, Ptr, VariableMask,
2734 Alignment, CostKind, I);
2735 }
2736 InstructionCost getInterleavedMemoryOpCost(
2737 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
2738 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
2739 bool UseMaskForCond, bool UseMaskForGaps) override {
2740 return Impl.getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
2741 Alignment, AddressSpace, CostKind,
2742 UseMaskForCond, UseMaskForGaps);
2743 }
2744 InstructionCost
2745 getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
2746 std::optional<FastMathFlags> FMF,
2747 TTI::TargetCostKind CostKind) override {
2748 return Impl.getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
2749 }
2750 InstructionCost
2751 getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF,
2752 TTI::TargetCostKind CostKind) override {
2753 return Impl.getMinMaxReductionCost(IID, Ty, FMF, CostKind);
2754 }
2755 InstructionCost
2756 getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy,
2757 VectorType *Ty, FastMathFlags FMF,
2758 TTI::TargetCostKind CostKind) override {
2759 return Impl.getExtendedReductionCost(Opcode, IsUnsigned, ResTy, Ty, FMF,
2760 CostKind);
2761 }
2762 InstructionCost
2763 getMulAccReductionCost(bool IsUnsigned, Type *ResTy, VectorType *Ty,
2764 TTI::TargetCostKind CostKind) override {
2765 return Impl.getMulAccReductionCost(IsUnsigned, ResTy, Ty, CostKind);
2766 }
2767 InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
2768 TTI::TargetCostKind CostKind) override {
2769 return Impl.getIntrinsicInstrCost(ICA, CostKind);
2770 }
2771 InstructionCost getCallInstrCost(Function *F, Type *RetTy,
2772 ArrayRef<Type *> Tys,
2773 TTI::TargetCostKind CostKind) override {
2774 return Impl.getCallInstrCost(F, RetTy, Tys, CostKind);
2775 }
2776 unsigned getNumberOfParts(Type *Tp) override {
2777 return Impl.getNumberOfParts(Tp);
2778 }
2779 InstructionCost getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
2780 const SCEV *Ptr) override {
2781 return Impl.getAddressComputationCost(Ty, SE, Ptr);
2782 }
2783 InstructionCost getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) override {
2784 return Impl.getCostOfKeepingLiveOverCall(Tys);
2785 }
2786 bool getTgtMemIntrinsic(IntrinsicInst *Inst,
2787 MemIntrinsicInfo &Info) override {
2788 return Impl.getTgtMemIntrinsic(Inst, Info);
2789 }
2790 unsigned getAtomicMemIntrinsicMaxElementSize() const override {
2791 return Impl.getAtomicMemIntrinsicMaxElementSize();
2792 }
2793 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
2794 Type *ExpectedType) override {
2795 return Impl.getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
2796 }
2797 Type *getMemcpyLoopLoweringType(
2798 LLVMContext &Context, Value *Length, unsigned SrcAddrSpace,
2799 unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign,
2800 std::optional<uint32_t> AtomicElementSize) const override {
2801 return Impl.getMemcpyLoopLoweringType(Context, Length, SrcAddrSpace,
2802 DestAddrSpace, SrcAlign, DestAlign,
2803 AtomicElementSize);
2804 }
2805 void getMemcpyLoopResidualLoweringType(
2806 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
2807 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
2808 unsigned SrcAlign, unsigned DestAlign,
2809 std::optional<uint32_t> AtomicCpySize) const override {
2810 Impl.getMemcpyLoopResidualLoweringType(OpsOut, Context, RemainingBytes,
2811 SrcAddrSpace, DestAddrSpace,
2812 SrcAlign, DestAlign, AtomicCpySize);
2813 }
2814 bool areInlineCompatible(const Function *Caller,
2815 const Function *Callee) const override {
2816 return Impl.areInlineCompatible(Caller, Callee);
2817 }
2818 unsigned getInlineCallPenalty(const Function *F, const CallBase &Call,
2819 unsigned DefaultCallPenalty) const override {
2820 return Impl.getInlineCallPenalty(F, Call, DefaultCallPenalty);
2821 }
2822 bool areTypesABICompatible(const Function *Caller, const Function *Callee,
2823 const ArrayRef<Type *> &Types) const override {
2824 return Impl.areTypesABICompatible(Caller, Callee, Types);
2825 }
2826 bool isIndexedLoadLegal(MemIndexedMode Mode, Type *Ty) const override {
2827 return Impl.isIndexedLoadLegal(Mode, Ty, getDataLayout());
2828 }
2829 bool isIndexedStoreLegal(MemIndexedMode Mode, Type *Ty) const override {
2830 return Impl.isIndexedStoreLegal(Mode, Ty, getDataLayout());
2831 }
2832 unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const override {
2833 return Impl.getLoadStoreVecRegBitWidth(AddrSpace);
2834 }
2835 bool isLegalToVectorizeLoad(LoadInst *LI) const override {
2836 return Impl.isLegalToVectorizeLoad(LI);
2837 }
2838 bool isLegalToVectorizeStore(StoreInst *SI) const override {
2839 return Impl.isLegalToVectorizeStore(SI);
2840 }
2841 bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, Align Alignment,
2842 unsigned AddrSpace) const override {
2843 return Impl.isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment,
2844 AddrSpace);
2845 }
2846 bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, Align Alignment,
2847 unsigned AddrSpace) const override {
2848 return Impl.isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment,
2849 AddrSpace);
2850 }
2851 bool isLegalToVectorizeReduction(const RecurrenceDescriptor &RdxDesc,
2852 ElementCount VF) const override {
2853 return Impl.isLegalToVectorizeReduction(RdxDesc, VF);
2854 }
2855 bool isElementTypeLegalForScalableVector(Type *Ty) const override {
2856 return Impl.isElementTypeLegalForScalableVector(Ty);
2857 }
2858 unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
2859 unsigned ChainSizeInBytes,
2860 VectorType *VecTy) const override {
2861 return Impl.getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy);
2862 }
2863 unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
2864 unsigned ChainSizeInBytes,
2865 VectorType *VecTy) const override {
2866 return Impl.getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy);
2867 }
2868 bool preferInLoopReduction(unsigned Opcode, Type *Ty,
2869 ReductionFlags Flags) const override {
2870 return Impl.preferInLoopReduction(Opcode, Ty, Flags);
2871 }
2872 bool preferPredicatedReductionSelect(unsigned Opcode, Type *Ty,
2873 ReductionFlags Flags) const override {
2874 return Impl.preferPredicatedReductionSelect(Opcode, Ty, Flags);
2875 }
2876 bool preferEpilogueVectorization() const override {
2877 return Impl.preferEpilogueVectorization();
2878 }
2879
2880 bool shouldExpandReduction(const IntrinsicInst *II) const override {
2881 return Impl.shouldExpandReduction(II);
2882 }
2883
2884 unsigned getGISelRematGlobalCost() const override {
2885 return Impl.getGISelRematGlobalCost();
2886 }
2887
2888 unsigned getMinTripCountTailFoldingThreshold() const override {
2889 return Impl.getMinTripCountTailFoldingThreshold();
2890 }
2891
2892 bool supportsScalableVectors() const override {
2893 return Impl.supportsScalableVectors();
2894 }
2895
2896 bool enableScalableVectorization() const override {
2897 return Impl.enableScalableVectorization();
2898 }
2899
2900 bool hasActiveVectorLength(unsigned Opcode, Type *DataType,
2901 Align Alignment) const override {
2902 return Impl.hasActiveVectorLength(Opcode, DataType, Alignment);
2903 }
2904
2906 getVPLegalizationStrategy(const VPIntrinsic &PI) const override {
2907 return Impl.getVPLegalizationStrategy(PI);
2908 }
2909
2910 bool hasArmWideBranch(bool Thumb) const override {
2911 return Impl.hasArmWideBranch(Thumb);
2912 }
2913
2914 unsigned getMaxNumArgs() const override {
2915 return Impl.getMaxNumArgs();
2916 }
2917};
2918
2919template <typename T>
2921 : TTIImpl(new Model<T>(Impl)) {}
2922
2923/// Analysis pass providing the \c TargetTransformInfo.
2924///
2925/// The core idea of the TargetIRAnalysis is to expose an interface through
2926/// which LLVM targets can analyze and provide information about the middle
2927/// end's target-independent IR. This supports use cases such as target-aware
2928/// cost modeling of IR constructs.
2929///
2930/// This is a function analysis because much of the cost modeling for targets
2931/// is done in a subtarget specific way and LLVM supports compiling different
2932/// functions targeting different subtargets in order to support runtime
2933/// dispatch according to the observed subtarget.
2934class TargetIRAnalysis : public AnalysisInfoMixin<TargetIRAnalysis> {
2935public:
2937
2938 /// Default construct a target IR analysis.
2939 ///
2940 /// This will use the module's datalayout to construct a baseline
2941 /// conservative TTI result.
2943
2944 /// Construct an IR analysis pass around a target-provide callback.
2945 ///
2946 /// The callback will be called with a particular function for which the TTI
2947 /// is needed and must return a TTI object for that function.
2948 TargetIRAnalysis(std::function<Result(const Function &)> TTICallback);
2949
2950 // Value semantics. We spell out the constructors for MSVC.
2952 : TTICallback(Arg.TTICallback) {}
2954 : TTICallback(std::move(Arg.TTICallback)) {}
2956 TTICallback = RHS.TTICallback;
2957 return *this;
2958 }
2960 TTICallback = std::move(RHS.TTICallback);
2961 return *this;
2962 }
2963
2965
2966private:
2968 static AnalysisKey Key;
2969
2970 /// The callback used to produce a result.
2971 ///
2972 /// We use a completely opaque callback so that targets can provide whatever
2973 /// mechanism they desire for constructing the TTI for a given function.
2974 ///
2975 /// FIXME: Should we really use std::function? It's relatively inefficient.
2976 /// It might be possible to arrange for even stateful callbacks to outlive
2977 /// the analysis and thus use a function_ref which would be lighter weight.
2978 /// This may also be less error prone as the callback is likely to reference
2979 /// the external TargetMachine, and that reference needs to never dangle.
2980 std::function<Result(const Function &)> TTICallback;
2981
2982 /// Helper function used as the callback in the default constructor.
2983 static Result getDefaultTTI(const Function &F);
2984};
2985
2986/// Wrapper pass for TargetTransformInfo.
2987///
2988/// This pass can be constructed from a TTI object which it stores internally
2989/// and is queried by passes.
2991 TargetIRAnalysis TIRA;
2992 std::optional<TargetTransformInfo> TTI;
2993
2994 virtual void anchor();
2995
2996public:
2997 static char ID;
2998
2999 /// We must provide a default constructor for the pass but it should
3000 /// never be used.
3001 ///
3002 /// Use the constructor below or call one of the creation routines.
3004
3006
3008};
3009
3010/// Create an analysis pass wrapper around a TTI object.
3011///
3012/// This analysis pass just holds the TTI instance and makes it available to
3013/// clients.
3015
3016} // namespace llvm
3017
3018#endif
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
AMDGPU Lower Kernel Arguments
Atomic ordering constants.
RelocType Type
Definition: COFFYAML.cpp:391
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
static cl::opt< TargetTransformInfo::TargetCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(TargetTransformInfo::TCK_RecipThroughput), cl::values(clEnumValN(TargetTransformInfo::TCK_RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(TargetTransformInfo::TCK_Latency, "latency", "Instruction latency"), clEnumValN(TargetTransformInfo::TCK_CodeSize, "code-size", "Code size"), clEnumValN(TargetTransformInfo::TCK_SizeAndLatency, "size-latency", "Code size and latency")))
return RetTy
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
static cl::opt< bool > ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false), cl::desc("Force allowance of nested hardware loops"))
static cl::opt< bool > ForceHardwareLoopPHI("force-hardware-loop-phi", cl::Hidden, cl::init(false), cl::desc("Force hardware loop counter to be updated through a phi"))
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
std::optional< unsigned > getMaxVScale(const Function &F, const TargetTransformInfo &TTI)
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
Machine InstCombiner
This header defines various interfaces for pass management in LLVM.
static cl::opt< RegAllocEvictionAdvisorAnalysis::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Development, "development", "for training")))
This file implements the SmallBitVector class.
Value * RHS
Class for arbitrary precision integers.
Definition: APInt.h:76
an instruction to allocate memory on the stack
Definition: Instructions.h:59
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:360
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Conditional or Unconditional Branch instruction.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1494
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:993
This is an important base class in LLVM.
Definition: Constant.h:41
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:20
ImmutablePass class - This class is used to provide information that does not need to be run.
Definition: Pass.h:282
The core instruction combiner logic.
Definition: InstCombiner.h:47
static InstructionCost getInvalid(CostType Val=0)
Class to represent integer types.
Definition: DerivedTypes.h:40
Drive the analysis of interleaved memory accesses in the loop.
Definition: VectorUtils.h:586
const SmallVectorImpl< Type * > & getArgTypes() const
const SmallVectorImpl< const Value * > & getArgs() const
InstructionCost getScalarizationCost() const
const IntrinsicInst * getInst() const
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:47
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:184
LoopVectorizationLegality checks if it is legal to vectorize a loop, and to what vectorization factor...
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:44
The optimization diagnostic interface.
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
Analysis providing profile information.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Definition: IVDescriptors.h:71
This class represents an analyzed expression in the program.
The main scalar evolution driver.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StackOffset holds a fixed and a scalable offset in bytes.
Definition: TypeSize.h:33
An instruction for storing to memory.
Definition: Instructions.h:317
Multiway switch.
Analysis pass providing the TargetTransformInfo.
TargetIRAnalysis(const TargetIRAnalysis &Arg)
TargetIRAnalysis & operator=(const TargetIRAnalysis &RHS)
Result run(const Function &F, FunctionAnalysisManager &)
TargetTransformInfo Result
TargetIRAnalysis()
Default construct a target IR analysis.
TargetIRAnalysis & operator=(TargetIRAnalysis &&RHS)
TargetIRAnalysis(TargetIRAnalysis &&Arg)
Provides information about what library functions are available for the current target.
Wrapper pass for TargetTransformInfo.
TargetTransformInfoWrapperPass()
We must provide a default constructor for the pass but it should never be used.
TargetTransformInfo & getTTI(const Function &F)
virtual std::optional< Value * > simplifyDemandedUseBitsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed)=0
virtual InstructionCost getAddressComputationCost(Type *Ty, ScalarEvolution *SE, const SCEV *Ptr)=0
virtual TypeSize getRegisterBitWidth(RegisterKind K) const =0
virtual const DataLayout & getDataLayout() const =0
virtual bool isProfitableLSRChainElement(Instruction *I)=0
virtual InstructionCost getGatherScatterOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask, Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I=nullptr)=0
virtual InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx, const APInt &Imm, Type *Ty, TargetCostKind CostKind, Instruction *Inst=nullptr)=0
virtual InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind)=0
virtual void getUnrollingPreferences(Loop *L, ScalarEvolution &, UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE)=0
virtual bool isLegalNTStore(Type *DataType, Align Alignment)=0
virtual unsigned adjustInliningThreshold(const CallBase *CB)=0
virtual bool isExpensiveToSpeculativelyExecute(const Instruction *I)=0
virtual bool shouldMaximizeVectorBandwidth(TargetTransformInfo::RegisterKind K) const =0
virtual std::optional< Instruction * > instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II)=0
virtual bool preferPredicatedReductionSelect(unsigned Opcode, Type *Ty, ReductionFlags) const =0
virtual VPLegalization getVPLegalizationStrategy(const VPIntrinsic &PI) const =0
virtual bool isLegalNTLoad(Type *DataType, Align Alignment)=0
virtual bool enableOrderedReductions()=0
virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit)=0
virtual unsigned getNumberOfRegisters(unsigned ClassID) const =0
virtual std::pair< const Value *, unsigned > getPredicatedAddrSpace(const Value *V) const =0
virtual bool isLegalMaskedGather(Type *DataType, Align Alignment)=0
virtual bool areTypesABICompatible(const Function *Caller, const Function *Callee, const ArrayRef< Type * > &Types) const =0
virtual InstructionCost getIntImmCost(const APInt &Imm, Type *Ty, TargetCostKind CostKind)=0
virtual bool shouldPrefetchAddressSpace(unsigned AS) const =0
virtual bool isFCmpOrdCheaperThanFCmpZero(Type *Ty)=0
virtual unsigned getMinVectorRegisterBitWidth() const =0
virtual InstructionCost getAltInstrCost(VectorType *VecTy, unsigned Opcode0, unsigned Opcode1, const SmallBitVector &OpcodeMask, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const =0
virtual std::optional< unsigned > getVScaleForTuning() const =0
virtual InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, const APInt &Imm, Type *Ty, TargetCostKind CostKind)=0
virtual InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind)=0
virtual bool supportsEfficientVectorElementLoadStore()=0
virtual unsigned getRegUsageForType(Type *Ty)=0
virtual bool hasArmWideBranch(bool Thumb) const =0
virtual MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const =0
virtual InstructionCost getMulAccReductionCost(bool IsUnsigned, Type *ResTy, VectorType *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput)=0
virtual InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, OperandValueInfo Opd1Info, OperandValueInfo Opd2Info, ArrayRef< const Value * > Args, const Instruction *CxtI=nullptr)=0
virtual unsigned getAssumedAddrSpace(const Value *V) const =0
virtual bool isTruncateFree(Type *Ty1, Type *Ty2)=0
virtual bool collectFlatAddressOperands(SmallVectorImpl< int > &OpIndexes, Intrinsic::ID IID) const =0
virtual InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands, Type *AccessType, TTI::TargetCostKind CostKind)=0
virtual InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TargetCostKind CostKind)=0
virtual bool shouldBuildLookupTables()=0
virtual bool isLegalBroadcastLoad(Type *ElementTy, ElementCount NumElements) const =0
virtual bool isLegalToVectorizeStore(StoreInst *SI) const =0
virtual bool isLegalMaskedVectorHistogram(Type *AddrType, Type *DataType)=0
virtual unsigned getGISelRematGlobalCost() const =0
virtual unsigned getCallerAllocaCost(const CallBase *CB, const AllocaInst *AI) const =0
virtual InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, StackOffset BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace)=0
virtual void getMemcpyLoopResidualLoweringType(SmallVectorImpl< Type * > &OpsOut, LLVMContext &Context, unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign, std::optional< uint32_t > AtomicCpySize) const =0
virtual bool forceScalarizeMaskedScatter(VectorType *DataType, Align Alignment)=0
virtual bool supportsTailCallFor(const CallBase *CB)=0
virtual std::optional< unsigned > getMaxVScale() const =0
virtual InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind)=0
virtual bool isLegalToVectorizeReduction(const RecurrenceDescriptor &RdxDesc, ElementCount VF) const =0
virtual unsigned getMaxNumArgs() const =0
virtual bool shouldExpandReduction(const IntrinsicInst *II) const =0
virtual bool enableWritePrefetching() const =0
virtual bool useColdCCForColdCall(Function &F)=0
virtual unsigned getInlineCallPenalty(const Function *F, const CallBase &Call, unsigned DefaultCallPenalty) const =0
virtual bool preferInLoopReduction(unsigned Opcode, Type *Ty, ReductionFlags) const =0
virtual int getInlinerVectorBonusPercent() const =0
virtual unsigned getMaxPrefetchIterationsAhead() const =0
virtual bool isLegalMaskedScatter(Type *DataType, Align Alignment)=0
virtual bool isIndexedLoadLegal(MemIndexedMode Mode, Type *Ty) const =0
virtual unsigned getCacheLineSize() const =0
virtual bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const =0
virtual unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize, unsigned ChainSizeInBytes, VectorType *VecTy) const =0
virtual AddressingModeKind getPreferredAddressingMode(const Loop *L, ScalarEvolution *SE) const =0
virtual bool shouldBuildLookupTablesForConstant(Constant *C)=0
virtual bool preferPredicateOverEpilogue(TailFoldingInfo *TFI)=0
virtual bool isProfitableToHoist(Instruction *I)=0
virtual bool isLegalMaskedExpandLoad(Type *DataType, Align Alignment)=0
virtual InstructionCost getFPOpCost(Type *Ty)=0
virtual unsigned getMinTripCountTailFoldingThreshold() const =0
virtual bool enableMaskedInterleavedAccessVectorization()=0
virtual unsigned getRegisterClassForType(bool Vector, Type *Ty=nullptr) const =0
virtual bool isTypeLegal(Type *Ty)=0
virtual BranchProbability getPredictableBranchThreshold()=0
virtual bool enableScalableVectorization() const =0
virtual bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info)=0
virtual bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const =0
virtual const char * getRegisterClassName(unsigned ClassID) const =0
virtual unsigned getMaxInterleaveFactor(ElementCount VF)=0
virtual bool enableAggressiveInterleaving(bool LoopHasReductions)=0
virtual bool isLegalAltInstr(VectorType *VecTy, unsigned Opcode0, unsigned Opcode1, const SmallBitVector &OpcodeMask) const =0
virtual bool haveFastSqrt(Type *Ty)=0
virtual bool isLegalMaskedCompressStore(Type *DataType, Align Alignment)=0
virtual std::optional< unsigned > getCacheSize(CacheLevel Level) const =0
virtual InstructionCost getCallInstrCost(Function *F, Type *RetTy, ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind)=0
virtual InstructionCost getPointersChainCost(ArrayRef< const Value * > Ptrs, const Value *Base, const TTI::PointersChainInfo &Info, Type *AccessTy, TTI::TargetCostKind CostKind)=0
virtual void getPeelingPreferences(Loop *L, ScalarEvolution &SE, PeelingPreferences &PP)=0
virtual std::optional< unsigned > getCacheAssociativity(CacheLevel Level) const =0
virtual bool supportsScalableVectors() const =0
virtual bool forceScalarizeMaskedGather(VectorType *DataType, Align Alignment)=0
virtual unsigned getNumberOfParts(Type *Tp)=0
virtual bool isLegalICmpImmediate(int64_t Imm)=0
virtual unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)=0
virtual InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind, const Instruction *I=nullptr)=0
virtual bool isElementTypeLegalForScalableVector(Type *Ty) const =0
virtual TailFoldingStyle getPreferredTailFoldingStyle(bool IVUpdateMayOverflow=true)=0
virtual bool hasDivRemOp(Type *DataType, bool IsSigned)=0
virtual unsigned getMinPrefetchStride(unsigned NumMemAccesses, unsigned NumStridedMemAccesses, unsigned NumPrefetches, bool HasCall) const =0
virtual bool shouldBuildRelLookupTables()=0
virtual InstructionCost getOperandsScalarizationOverhead(ArrayRef< const Value * > Args, ArrayRef< Type * > Tys, TargetCostKind CostKind)=0
virtual bool isLoweredToCall(const Function *F)=0
virtual bool isSourceOfDivergence(const Value *V)=0
virtual bool isLegalAddScalableImmediate(int64_t Imm)=0
virtual bool canHaveNonUndefGlobalInitializerInAddressSpace(unsigned AS) const =0
virtual unsigned getInliningCostBenefitAnalysisSavingsMultiplier() const =0
virtual bool isLegalMaskedLoad(Type *DataType, Align Alignment)=0
virtual InstructionCost getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput)=0
virtual bool isFPVectorizationPotentiallyUnsafe()=0
virtual Value * getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst, Type *ExpectedType)=0
virtual unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize, unsigned ChainSizeInBytes, VectorType *VecTy) const =0
virtual InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm, Type *Ty)=0
virtual InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I)=0
virtual bool hasBranchDivergence(const Function *F=nullptr)=0
virtual InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind)=0
virtual InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind, const Instruction *I)=0
virtual unsigned getInliningThresholdMultiplier() const =0
virtual InstructionCost getReplicationShuffleCost(Type *EltTy, int ReplicationFactor, int VF, const APInt &DemandedDstElts, TTI::TargetCostKind CostKind)=0
virtual bool isLegalMaskedStore(Type *DataType, Align Alignment)=0
virtual InstructionCost getVectorInstrCost(const Instruction &I, Type *Val, TTI::TargetCostKind CostKind, unsigned Index)=0
virtual bool isLegalToVectorizeLoad(LoadInst *LI) const =0
virtual bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const =0
virtual unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const =0
virtual bool isLSRCostLess(const TargetTransformInfo::LSRCost &C1, const TargetTransformInfo::LSRCost &C2)=0
virtual bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const =0
virtual InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, bool UseMaskForCond=false, bool UseMaskForGaps=false)=0
virtual bool prefersVectorizedAddressing()=0
virtual uint64_t getMaxMemIntrinsicInlineSizeThreshold() const =0
virtual InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *Tp, ArrayRef< int > Mask, TTI::TargetCostKind CostKind, int Index, VectorType *SubTp, ArrayRef< const Value * > Args, const Instruction *CxtI)=0
virtual InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, OperandValueInfo OpInfo, const Instruction *I)=0
virtual bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE, LoopInfo *LI, DominatorTree *DT, AssumptionCache *AC, TargetLibraryInfo *LibInfo)=0
virtual Type * getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length, unsigned SrcAddrSpace, unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign, std::optional< uint32_t > AtomicElementSize) const =0
virtual InstructionCost getMaskedMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind)=0
virtual bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE, AssumptionCache &AC, TargetLibraryInfo *LibInfo, HardwareLoopInfo &HWLoopInfo)=0
virtual bool isAlwaysUniform(const Value *V)=0
virtual std::optional< unsigned > getMinPageSize() const =0
virtual InstructionCost getMemcpyCost(const Instruction *I)=0
virtual ElementCount getMinimumVF(unsigned ElemWidth, bool IsScalable) const =0
virtual bool areInlineCompatible(const Function *Caller, const Function *Callee) const =0
virtual bool addrspacesMayAlias(unsigned AS0, unsigned AS1) const =0
virtual InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy, unsigned Index)=0
virtual std::optional< Value * > simplifyDemandedVectorEltsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp)=0
virtual InstructionCost getStridedMemoryOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask, Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I=nullptr)=0
virtual unsigned getFlatAddressSpace()=0
virtual InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index, Value *Op0, Value *Op1)=0
virtual unsigned getPrefetchDistance() const =0
virtual bool shouldFoldTerminatingConditionAfterLSR() const =0
virtual bool shouldTreatInstructionLikeSelect(const Instruction *I)=0
virtual bool hasVolatileVariant(Instruction *I, unsigned AddrSpace)=0
virtual bool preferToKeepConstantsAttached(const Instruction &Inst, const Function &Fn) const =0
virtual bool isNumRegsMajorCostOfLSR()=0
virtual bool isLegalStridedLoadStore(Type *DataType, Align Alignment)=0
virtual bool isSingleThreaded() const =0
virtual bool isLegalAddImmediate(int64_t Imm)=0
virtual Value * rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, Value *OldV, Value *NewV) const =0
virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace, Instruction *I, int64_t ScalableOffset)=0
virtual bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader)=0
virtual unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy, Type *ScalarValTy) const =0
virtual bool isVScaleKnownToBeAPowerOfTwo() const =0
virtual InstructionCost getCostOfKeepingLiveOverCall(ArrayRef< Type * > Tys)=0
virtual bool hasActiveVectorLength(unsigned Opcode, Type *DataType, Align Alignment) const =0
virtual bool enableInterleavedAccessVectorization()=0
virtual unsigned getAtomicMemIntrinsicMaxElementSize() const =0
virtual bool preferEpilogueVectorization() const =0
virtual InstructionCost getVPMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, const Instruction *I)=0
virtual unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const =0
virtual bool isIndexedStoreLegal(MemIndexedMode Mode, Type *Ty) const =0
virtual bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth, unsigned AddressSpace, Align Alignment, unsigned *Fast)=0
virtual unsigned getInliningCostBenefitAnalysisProfitableMultiplier() const =0
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const
bool isLegalToVectorizeLoad(LoadInst *LI) const
std::optional< unsigned > getVScaleForTuning() const
static CastContextHint getCastContextHint(const Instruction *I)
Calculates a CastContextHint from I.
bool addrspacesMayAlias(unsigned AS0, unsigned AS1) const
Return false if a AS0 address cannot possibly alias a AS1 address.
bool isLegalMaskedScatter(Type *DataType, Align Alignment) const
Return true if the target supports masked scatter.
InstructionCost getStridedMemoryOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask, Align Alignment, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
InstructionCost getReplicationShuffleCost(Type *EltTy, int ReplicationFactor, int VF, const APInt &DemandedDstElts, TTI::TargetCostKind CostKind)
bool shouldBuildLookupTables() const
Return true if switches should be turned into lookup tables for the target.
bool isLegalToVectorizeStore(StoreInst *SI) const
bool enableAggressiveInterleaving(bool LoopHasReductions) const
Don't restrict interleaved unrolling to small loops.
void getMemcpyLoopResidualLoweringType(SmallVectorImpl< Type * > &OpsOut, LLVMContext &Context, unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign, std::optional< uint32_t > AtomicCpySize=std::nullopt) const
bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) const
Return true if it is faster to check if a floating-point value is NaN (or not-NaN) versus a compariso...
bool preferInLoopReduction(unsigned Opcode, Type *Ty, ReductionFlags Flags) const
bool supportsEfficientVectorElementLoadStore() const
If target has efficient vector element load/store instructions, it can return true here so that inser...
bool isAlwaysUniform(const Value *V) const
unsigned getAssumedAddrSpace(const Value *V) const
bool isLSRCostLess(const TargetTransformInfo::LSRCost &C1, const TargetTransformInfo::LSRCost &C2) const
Return true if LSR cost of C1 is lower than C2.
bool isLegalMaskedExpandLoad(Type *DataType, Align Alignment) const
Return true if the target supports masked expand load.
bool prefersVectorizedAddressing() const
Return true if target doesn't mind addresses in vectors.
bool hasBranchDivergence(const Function *F=nullptr) const
Return true if branch divergence exists.
MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const
InstructionCost getAddressComputationCost(Type *Ty, ScalarEvolution *SE=nullptr, const SCEV *Ptr=nullptr) const
bool invalidate(Function &, const PreservedAnalyses &, FunctionAnalysisManager::Invalidator &)
Handle the invalidation of this information.
void getUnrollingPreferences(Loop *L, ScalarEvolution &, UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE) const
Get target-customized preferences for the generic loop unrolling transformation.
bool shouldBuildLookupTablesForConstant(Constant *C) const
Return true if switches should be turned into lookup tables containing this constant value for the ta...
bool shouldFoldTerminatingConditionAfterLSR() const
Return true if LSR should attempts to replace a use of an otherwise dead primary IV in the latch cond...
InstructionCost getOperandsScalarizationOverhead(ArrayRef< const Value * > Args, ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind) const
Estimate the overhead of scalarizing an instructions unique non-constant operands.
bool supportsTailCallFor(const CallBase *CB) const
If target supports tail call on CB.
std::optional< Instruction * > instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const
Targets can implement their own combinations for target-specific intrinsics.
bool isProfitableLSRChainElement(Instruction *I) const
TypeSize getRegisterBitWidth(RegisterKind K) const
unsigned getInlineCallPenalty(const Function *F, const CallBase &Call, unsigned DefaultCallPenalty) const
Returns a penalty for invoking call Call in F.
bool isExpensiveToSpeculativelyExecute(const Instruction *I) const
Return true if the cost of the instruction is too high to speculatively execute and should be kept be...
bool isLegalMaskedGather(Type *DataType, Align Alignment) const
Return true if the target supports masked gather.
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, OperandValueInfo OpdInfo={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
std::optional< unsigned > getMaxVScale() const
InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, bool UseMaskForCond=false, bool UseMaskForGaps=false) const
std::optional< Value * > simplifyDemandedVectorEltsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp) const
Can be used to implement target-specific instruction combining.
bool enableOrderedReductions() const
Return true if we should be enabling ordered reductions for the target.
InstructionCost getInstructionCost(const User *U, TargetCostKind CostKind) const
This is a helper function which calls the three-argument getInstructionCost with Operands which are t...
unsigned getInliningCostBenefitAnalysisProfitableMultiplier() const
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of vector reduction intrinsics.
unsigned getAtomicMemIntrinsicMaxElementSize() const
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
bool LSRWithInstrQueries() const
Return true if the loop strength reduce pass should make Instruction* based TTI queries to isLegalAdd...
unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize, unsigned ChainSizeInBytes, VectorType *VecTy) const
VPLegalization getVPLegalizationStrategy(const VPIntrinsic &PI) const
bool shouldTreatInstructionLikeSelect(const Instruction *I) const
Should the Select Optimization pass treat the given instruction like a select, potentially converting...
bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const
InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args=std::nullopt, const Instruction *CxtI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
bool shouldMaximizeVectorBandwidth(TargetTransformInfo::RegisterKind K) const
TailFoldingStyle getPreferredTailFoldingStyle(bool IVUpdateMayOverflow=true) const
Query the target what the preferred style of tail folding is.
InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands, Type *AccessType=nullptr, TargetCostKind CostKind=TCK_SizeAndLatency) const
Estimate the cost of a GEP operation when lowered.
bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const
unsigned getRegUsageForType(Type *Ty) const
Returns the estimated number of registers required to represent Ty.
bool isLegalBroadcastLoad(Type *ElementTy, ElementCount NumElements) const
\Returns true if the target supports broadcasting a load to a vector of type <NumElements x ElementTy...
bool isIndexedStoreLegal(enum MemIndexedMode Mode, Type *Ty) const
std::pair< const Value *, unsigned > getPredicatedAddrSpace(const Value *V) const
unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const
InstructionCost getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of an extended reduction pattern, similar to getArithmeticReductionCost of a reduc...
static OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
InstructionCost getMulAccReductionCost(bool IsUnsigned, Type *ResTy, VectorType *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of an extended reduction pattern, similar to getArithmeticReductionCost of an Add ...
unsigned getRegisterClassForType(bool Vector, Type *Ty=nullptr) const
bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace=0, Instruction *I=nullptr, int64_t ScalableOffset=0) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const
Return hardware support for population count.
unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) const
bool isElementTypeLegalForScalableVector(Type *Ty) const
bool forceScalarizeMaskedGather(VectorType *Type, Align Alignment) const
Return true if the target forces scalarizing of llvm.masked.gather intrinsics.
unsigned getMaxPrefetchIterationsAhead() const
bool canHaveNonUndefGlobalInitializerInAddressSpace(unsigned AS) const
Return true if globals in this address space can have initializers other than undef.
ElementCount getMinimumVF(unsigned ElemWidth, bool IsScalable) const
InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, const APInt &Imm, Type *Ty, TargetCostKind CostKind) const
bool enableMaskedInterleavedAccessVectorization() const
Enable matching of interleaved access groups that contain predicated accesses or gaps and therefore v...
InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx, const APInt &Imm, Type *Ty, TargetCostKind CostKind, Instruction *Inst=nullptr) const
Return the expected cost of materialization for the given integer immediate of the specified type for...
bool isLegalStridedLoadStore(Type *DataType, Align Alignment) const
Return true if the target supports strided load.
TargetTransformInfo & operator=(TargetTransformInfo &&RHS)
InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF=FastMathFlags(), TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCK_Latency
The latency of instruction.
bool areTypesABICompatible(const Function *Caller, const Function *Callee, const ArrayRef< Type * > &Types) const
bool enableSelectOptimize() const
Should the Select Optimization pass be enabled and ran.
bool collectFlatAddressOperands(SmallVectorImpl< int > &OpIndexes, Intrinsic::ID IID) const
Return any intrinsic address operand indexes which may be rewritten if they use a flat address space ...
OperandValueProperties
Additional properties of an operand's values.
InstructionCost getPointersChainCost(ArrayRef< const Value * > Ptrs, const Value *Base, const PointersChainInfo &Info, Type *AccessTy, TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Estimate the cost of a chain of pointers (typically pointer operands of a chain of loads or stores wi...
bool isIndexedLoadLegal(enum MemIndexedMode Mode, Type *Ty) const
unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const
bool isSourceOfDivergence(const Value *V) const
Returns whether V is a source of divergence.
bool isLegalICmpImmediate(int64_t Imm) const
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
bool isTypeLegal(Type *Ty) const
Return true if this type is legal.
static bool requiresOrderedReduction(std::optional< FastMathFlags > FMF)
A helper function to determine the type of reduction algorithm used for a given Opcode and set of Fas...
bool isLegalToVectorizeReduction(const RecurrenceDescriptor &RdxDesc, ElementCount VF) const
std::optional< unsigned > getCacheAssociativity(CacheLevel Level) const
bool isLegalNTLoad(Type *DataType, Align Alignment) const
Return true if the target supports nontemporal load.
InstructionCost getMemcpyCost(const Instruction *I) const
unsigned adjustInliningThreshold(const CallBase *CB) const
bool isLegalAddImmediate(int64_t Imm) const
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
InstructionCost getVPMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize, unsigned ChainSizeInBytes, VectorType *VecTy) const
InstructionCost getMaskedMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE, LoopInfo *LI, DominatorTree *DT, AssumptionCache *AC, TargetLibraryInfo *LibInfo) const
Return true if the target can save a compare for loop count, for example hardware loop saves a compar...
Value * rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, Value *OldV, Value *NewV) const
Rewrite intrinsic call II such that OldV will be replaced with NewV, which has a different address sp...
InstructionCost getCostOfKeepingLiveOverCall(ArrayRef< Type * > Tys) const
unsigned getMinPrefetchStride(unsigned NumMemAccesses, unsigned NumStridedMemAccesses, unsigned NumPrefetches, bool HasCall) const
Some HW prefetchers can handle accesses up to a certain constant stride.
bool preferPredicatedReductionSelect(unsigned Opcode, Type *Ty, ReductionFlags Flags) const
bool shouldPrefetchAddressSpace(unsigned AS) const
InstructionCost getIntImmCost(const APInt &Imm, Type *Ty, TargetCostKind CostKind) const
Return the expected cost of materializing for the given integer immediate of the specified type.
unsigned getMinVectorRegisterBitWidth() const
bool isLegalNTStore(Type *DataType, Align Alignment) const
Return true if the target supports nontemporal store.
unsigned getFlatAddressSpace() const
Returns the address space ID for a target's 'flat' address space.
bool preferToKeepConstantsAttached(const Instruction &Inst, const Function &Fn) const
It can be advantageous to detach complex constants from their uses to make their generation cheaper.
bool hasArmWideBranch(bool Thumb) const
const char * getRegisterClassName(unsigned ClassID) const
bool preferEpilogueVectorization() const
Return true if the loop vectorizer should consider vectorizing an otherwise scalar epilogue loop.
bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const
BranchProbability getPredictableBranchThreshold() const
If a branch or a select condition is skewed in one direction by more than this factor,...
unsigned getCallerAllocaCost(const CallBase *CB, const AllocaInst *AI) const
bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth, unsigned AddressSpace=0, Align Alignment=Align(1), unsigned *Fast=nullptr) const
Determine if the target supports unaligned memory accesses.
InstructionCost getGatherScatterOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask, Align Alignment, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
bool hasActiveVectorLength(unsigned Opcode, Type *DataType, Align Alignment) const
PopcntSupportKind
Flags indicating the kind of support for population count.
InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm, Type *Ty) const
Return the expected cost for the given integer when optimising for size.
AddressingModeKind getPreferredAddressingMode(const Loop *L, ScalarEvolution *SE) const
Return the preferred addressing mode LSR should make efforts to generate.
bool isLoweredToCall(const Function *F) const
Test whether calls to a function lower to actual program function calls.
bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const
bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE, AssumptionCache &AC, TargetLibraryInfo *LibInfo, HardwareLoopInfo &HWLoopInfo) const
Query the target whether it would be profitable to convert the given loop into a hardware loop.
unsigned getInliningThresholdMultiplier() const
unsigned getNumberOfRegisters(unsigned ClassID) const
bool isLegalAltInstr(VectorType *VecTy, unsigned Opcode0, unsigned Opcode1, const SmallBitVector &OpcodeMask) const
Return true if this is an alternating opcode pattern that can be lowered to a single instruction on t...
bool isProfitableToHoist(Instruction *I) const
Return true if it is profitable to hoist instruction in the then/else to before if.
bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) const
Return true if the given instruction (assumed to be a memory access instruction) has a volatile varia...
bool isLegalMaskedCompressStore(Type *DataType, Align Alignment) const
Return true if the target supports masked compress store.
std::optional< unsigned > getMinPageSize() const
bool isFPVectorizationPotentiallyUnsafe() const
Indicate that it is potentially unsafe to automatically vectorize floating-point operations because t...
bool isLegalMaskedStore(Type *DataType, Align Alignment) const
Return true if the target supports masked store.
bool shouldBuildRelLookupTables() const
Return true if lookup tables should be turned into relative lookup tables.
unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy, Type *ScalarValTy) const
std::optional< unsigned > getCacheSize(CacheLevel Level) const
std::optional< Value * > simplifyDemandedUseBitsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed) const
Can be used to implement target-specific instruction combining.
bool isLegalAddScalableImmediate(int64_t Imm) const
Return true if adding the specified scalable immediate is legal, that is the target has add instructi...
bool hasDivRemOp(Type *DataType, bool IsSigned) const
Return true if the target has a unified operation to calculate division and remainder.
InstructionCost getAltInstrCost(VectorType *VecTy, unsigned Opcode0, unsigned Opcode1, const SmallBitVector &OpcodeMask, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Returns the cost estimation for alternating opcode pattern that can be lowered to a single instructio...
TargetCostConstants
Underlying constants for 'cost' values in this interface.
@ TCC_Expensive
The cost of a 'div' instruction on x86.
@ TCC_Free
Expected to fold away in lowering.
@ TCC_Basic
The cost of a typical 'add' instruction.
bool enableInterleavedAccessVectorization() const
Enable matching of interleaved access groups.
unsigned getMinTripCountTailFoldingThreshold() const
InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
unsigned getMaxInterleaveFactor(ElementCount VF) const
bool isNumRegsMajorCostOfLSR() const
Return true if LSR major cost is number of registers.
unsigned getInliningCostBenefitAnalysisSavingsMultiplier() const
bool isLegalMaskedVectorHistogram(Type *AddrType, Type *DataType) const
InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy, unsigned Index) const
unsigned getGISelRematGlobalCost() const
MemIndexedMode
The type of load/store indexing.
@ MIM_PostInc
Post-incrementing.
@ MIM_PostDec
Post-decrementing.
bool areInlineCompatible(const Function *Caller, const Function *Callee) const
bool useColdCCForColdCall(Function &F) const
Return true if the input function which is cold at all call sites, should use coldcc calling conventi...
InstructionCost getFPOpCost(Type *Ty) const
Return the expected cost of supporting the floating point operation of the specified type.
bool supportsTailCalls() const
If the target supports tail calls.
bool canMacroFuseCmp() const
Return true if the target can fuse a compare and branch.
Value * getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst, Type *ExpectedType) const
bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const
Query the target whether the specified address space cast from FromAS to ToAS is valid.
unsigned getNumberOfParts(Type *Tp) const
Type * getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length, unsigned SrcAddrSpace, unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign, std::optional< uint32_t > AtomicElementSize=std::nullopt) const
InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, StackOffset BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace=0) const
Return the cost of the scaling factor used in the addressing mode represented by AM for this target,...
bool isTruncateFree(Type *Ty1, Type *Ty2) const
Return true if it's free to truncate a value of type Ty1 to type Ty2.
InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *Tp, ArrayRef< int > Mask=std::nullopt, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args=std::nullopt, const Instruction *CxtI=nullptr) const
InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind) const
Estimate the overhead of scalarizing an instruction.
bool preferPredicateOverEpilogue(TailFoldingInfo *TFI) const
Query the target whether it would be prefered to create a predicated vector loop, which can avoid the...
bool forceScalarizeMaskedScatter(VectorType *Type, Align Alignment) const
Return true if the target forces scalarizing of llvm.masked.scatter intrinsics.
bool haveFastSqrt(Type *Ty) const
Return true if the hardware has a fast square-root instruction.
bool shouldExpandReduction(const IntrinsicInst *II) const
TargetTransformInfo(T Impl)
Construct a TTI object using a type implementing the Concept API below.
uint64_t getMaxMemIntrinsicInlineSizeThreshold() const
Returns the maximum memset / memcpy size in bytes that still makes it profitable to inline the call.
InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, Value *Op0=nullptr, Value *Op1=nullptr) const
ShuffleKind
The various kinds of shuffle patterns for vector queries.
@ SK_InsertSubvector
InsertSubvector. Index indicates start offset.
@ SK_Select
Selects elements from the corresponding lane of either source operand.
@ SK_PermuteSingleSrc
Shuffle elements of single source vector with any shuffle mask.
@ SK_Transpose
Transpose two vectors.
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
@ SK_Broadcast
Broadcast element 0 to all other elements.
@ SK_PermuteTwoSrc
Merge elements from two source vectors into one with any shuffle mask.
@ SK_Reverse
Reverse the order of the vector.
@ SK_ExtractSubvector
ExtractSubvector Index indicates start offset.
void getPeelingPreferences(Loop *L, ScalarEvolution &SE, PeelingPreferences &PP) const
Get target-customized preferences for the generic loop peeling transformation.
InstructionCost getCallInstrCost(Function *F, Type *RetTy, ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency) const
InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
CastContextHint
Represents a hint about the context in which a cast is used.
@ Reversed
The cast is used with a reversed load/store.
@ Masked
The cast is used with a masked load/store.
@ None
The cast is not used with a load/store of any kind.
@ Normal
The cast is used with a normal load/store.
@ Interleave
The cast is used with an interleaved load/store.
@ GatherScatter
The cast is used with a gather/scatter.
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
OperandValueKind
Additional information about an operand's possible values.
CacheLevel
The possible cache levels.
bool isLegalMaskedLoad(Type *DataType, Align Alignment) const
Return true if the target supports masked load.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
This is the common base class for vector predication intrinsics.
LLVM Value Representation.
Definition: Value.h:74
Base class of all SIMD vector types.
Definition: DerivedTypes.h:403
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
bool areInlineCompatible(const Function &Caller, const Function &Callee)
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Type
MessagePack types as defined in the standard, with the exception of Integer being divided into a sign...
Definition: MsgPackReader.h:53
@ User
could "use" a pointer
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Length
Definition: DWP.cpp:456
AddressSpace
Definition: NVPTXBaseInfo.h:21
AtomicOrdering
Atomic ordering for LLVM's memory model.
TargetTransformInfo TTI
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
@ None
Not a recurrence.
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1849
@ DataAndControlFlowWithoutRuntimeCheck
Use predicate to control both data and control flow, but modify the trip count so that a runtime over...
@ DataWithEVL
Use predicated EVL instructions for tail-folding.
@ DataAndControlFlow
Use predicate to control both data and control flow.
@ DataWithoutLaneMask
Same as Data, but avoids using the get.active.lane.mask intrinsic to calculate the mask and instead i...
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition: PassManager.h:97
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: Analysis.h:26
Attributes of a target dependent hardware loop.
bool canAnalyze(LoopInfo &LI)
bool isHardwareLoopCandidate(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, bool ForceNestedLoop=false, bool ForceHardwareLoopPHI=false)
Information about a load/store intrinsic defined by the target.
Value * PtrVal
This is the pointer that the intrinsic is loading from or storing to.
InterleavedAccessInfo * IAI
TailFoldingInfo(TargetLibraryInfo *TLI, LoopVectorizationLegality *LVL, InterleavedAccessInfo *IAI)
TargetLibraryInfo * TLI
LoopVectorizationLegality * LVL
unsigned Insns
TODO: Some of these could be merged.
Returns options for expansion of memcmp. IsZeroCmp is.
bool AllowPeeling
Allow peeling off loop iterations.
bool AllowLoopNestsPeeling
Allow peeling off loop iterations for loop nests.
bool PeelProfiledIterations
Allow peeling basing on profile.
unsigned PeelCount
A forced peeling factor (the number of bodied of the original loop that should be peeled off before t...
Describe known properties for a set of pointers.
unsigned IsKnownStride
True if distance between any two neigbouring pointers is a known value.
unsigned IsUnitStride
These properties only valid if SameBaseAddress is set.
unsigned IsSameBaseAddress
All the GEPs in a set have same base address.
Flags describing the kind of vector reduction.
bool IsSigned
Whether the operation is a signed int reduction.
bool IsMaxOp
If the op a min/max kind, true if it's a max operation.
bool NoNaN
If op is an fp min/max, whether NaNs may be present.
Parameters that control the generic loop unrolling transformation.
unsigned Count
A forced unrolling factor (the number of concatenated bodies of the original loop in the unrolled loo...
bool UpperBound
Allow using trip count upper bound to unroll loops.
unsigned Threshold
The cost threshold for the unrolled loop.
bool Force
Apply loop unroll on any kind of loop (mainly to loops that fail runtime unrolling).
unsigned PartialOptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size, like OptSizeThreshold,...
bool UnrollVectorizedLoop
Don't disable runtime unroll for the loops which were vectorized.
unsigned DefaultUnrollRuntimeCount
Default unroll count for loops with run-time trip count.
unsigned MaxPercentThresholdBoost
If complete unrolling will reduce the cost of the loop, we will boost the Threshold by a certain perc...
unsigned UnrollAndJamInnerLoopThreshold
Threshold for unroll and jam, for inner loop size.
unsigned MaxIterationsCountToAnalyze
Don't allow loop unrolling to simulate more than this number of iterations when checking full unroll ...
bool AllowRemainder
Allow generation of a loop remainder (extra iterations after unroll).
bool UnrollAndJam
Allow unroll and jam. Used to enable unroll and jam for the target.
bool UnrollRemainder
Allow unrolling of all the iterations of the runtime loop remainder.
unsigned FullUnrollMaxCount
Set the maximum unrolling factor for full unrolling.
unsigned PartialThreshold
The cost threshold for the unrolled loop, like Threshold, but used for partial/runtime unrolling (set...
bool Runtime
Allow runtime unrolling (unrolling of loops to expand the size of the loop body even when the number ...
bool Partial
Allow partial unrolling (unrolling of loops to expand the size of the loop body, not only to eliminat...
unsigned OptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size (set to UINT_MAX to disable).
bool AllowExpensiveTripCount
Allow emitting expensive instructions (such as divisions) when computing the trip count of a loop for...
unsigned MaxUpperBound
Set the maximum upper bound of trip count.
VPLegalization(VPTransform EVLParamStrategy, VPTransform OpStrategy)