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