LLVM 22.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"
25#include "llvm/ADT/ArrayRef.h"
29#include "llvm/IR/FMF.h"
30#include "llvm/IR/InstrTypes.h"
31#include "llvm/IR/PassManager.h"
32#include "llvm/Pass.h"
37#include <functional>
38#include <optional>
39#include <utility>
40
41namespace llvm {
42
43namespace Intrinsic {
44typedef unsigned ID;
45}
46
47class AllocaInst;
48class AssumptionCache;
50class DominatorTree;
51class BranchInst;
52class Function;
53class GlobalValue;
54class InstCombiner;
57class IntrinsicInst;
58class LoadInst;
59class Loop;
60class LoopInfo;
64class SCEV;
65class ScalarEvolution;
66class SmallBitVector;
67class StoreInst;
68class SwitchInst;
70class Type;
71class VPIntrinsic;
72struct KnownBits;
73
74/// Information about a load/store intrinsic defined by the target.
76 /// This is the pointer that the intrinsic is loading from or storing to.
77 /// If this is non-null, then analysis/optimization passes can assume that
78 /// this intrinsic is functionally equivalent to a load/store from this
79 /// pointer.
80 Value *PtrVal = nullptr;
81
82 // Ordering for atomic operations.
84
85 // Same Id is set by the target for corresponding load/store intrinsics.
86 unsigned short MatchingId = 0;
87
88 bool ReadMem = false;
89 bool WriteMem = false;
90 bool IsVolatile = false;
91
93
99};
100
101/// Attributes of a target dependent hardware loop.
105 Loop *L = nullptr;
108 const SCEV *ExitCount = nullptr;
110 Value *LoopDecrement = nullptr; // Decrement the loop counter by this
111 // value in every iteration.
112 bool IsNestingLegal = false; // Can a hardware loop be a parent to
113 // another hardware loop?
114 bool CounterInReg = false; // Should loop counter be updated in
115 // the loop via a phi?
116 bool PerformEntryTest = false; // Generate the intrinsic which also performs
117 // icmp ne zero on the loop counter value and
118 // produces an i1 to guard the loop entry.
120 DominatorTree &DT,
121 bool ForceNestedLoop = false,
122 bool ForceHardwareLoopPHI = false);
123 LLVM_ABI bool canAnalyze(LoopInfo &LI);
124};
125
126/// Information for memory intrinsic cost model.
128 /// Vector type of the data to be loaded or stored.
129 Type *DataTy = nullptr;
130
131 /// ID of the memory intrinsic.
132 Intrinsic::ID IID;
133
134 /// Address space of the pointer.
135 unsigned AddressSpace = 0;
136
137 /// Alignment of single element.
138 Align Alignment;
139
140public:
142 Align Alignment, unsigned AddressSpace)
143 : DataTy(DataTy), IID(Id), AddressSpace(AddressSpace),
144 Alignment(Alignment) {}
145
146 Intrinsic::ID getID() const { return IID; }
147 Type *getDataType() const { return DataTy; }
148 unsigned getAddressSpace() const { return AddressSpace; }
149 Align getAlignment() const { return Alignment; }
150};
151
153 const IntrinsicInst *II = nullptr;
154 Type *RetTy = nullptr;
155 Intrinsic::ID IID;
156 SmallVector<Type *, 4> ParamTys;
158 FastMathFlags FMF;
159 // If ScalarizationCost is UINT_MAX, the cost of scalarizing the
160 // arguments and the return value will be computed based on types.
161 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
162 TargetLibraryInfo const *LibInfo = nullptr;
163
164public:
166 Intrinsic::ID Id, const CallBase &CI,
168 bool TypeBasedOnly = false, TargetLibraryInfo const *LibInfo = nullptr);
169
171 Intrinsic::ID Id, Type *RTy, ArrayRef<Type *> Tys,
172 FastMathFlags Flags = FastMathFlags(), const IntrinsicInst *I = nullptr,
174
177
181 const IntrinsicInst *I = nullptr,
183 TargetLibraryInfo const *LibInfo = nullptr);
184
185 Intrinsic::ID getID() const { return IID; }
186 const IntrinsicInst *getInst() const { return II; }
187 Type *getReturnType() const { return RetTy; }
188 FastMathFlags getFlags() const { return FMF; }
189 InstructionCost getScalarizationCost() const { return ScalarizationCost; }
190 const SmallVectorImpl<const Value *> &getArgs() const { return Arguments; }
191 const SmallVectorImpl<Type *> &getArgTypes() const { return ParamTys; }
192 const TargetLibraryInfo *getLibInfo() const { return LibInfo; }
193
194 bool isTypeBasedOnly() const {
195 return Arguments.empty();
196 }
197
198 bool skipScalarizationCost() const { return ScalarizationCost.isValid(); }
199};
200
202 /// Don't use tail folding
204 /// Use predicate only to mask operations on data in the loop.
205 /// When the VL is not known to be a power-of-2, this method requires a
206 /// runtime overflow check for the i + VL in the loop because it compares the
207 /// scalar induction variable against the tripcount rounded up by VL which may
208 /// overflow. When the VL is a power-of-2, both the increment and uprounded
209 /// tripcount will overflow to 0, which does not require a runtime check
210 /// since the loop is exited when the loop induction variable equals the
211 /// uprounded trip-count, which are both 0.
213 /// Same as Data, but avoids using the get.active.lane.mask intrinsic to
214 /// calculate the mask and instead implements this with a
215 /// splat/stepvector/cmp.
216 /// FIXME: Can this kind be removed now that SelectionDAGBuilder expands the
217 /// active.lane.mask intrinsic when it is not natively supported?
219 /// Use predicate to control both data and control flow.
220 /// This method always requires a runtime overflow check for the i + VL
221 /// increment inside the loop, because it uses the result direclty in the
222 /// active.lane.mask to calculate the mask for the next iteration. If the
223 /// increment overflows, the mask is no longer correct.
225 /// Use predicate to control both data and control flow, but modify
226 /// the trip count so that a runtime overflow check can be avoided
227 /// and such that the scalar epilogue loop can always be removed.
229 /// Use predicated EVL instructions for tail-folding.
230 /// Indicates that VP intrinsics should be used.
232};
233
242
243class TargetTransformInfo;
246
247/// This pass provides access to the codegen interfaces that are needed
248/// for IR-level transformations.
250public:
252
253 /// Get the kind of extension that an instruction represents.
256 /// Get the kind of extension that a cast opcode represents.
259
260 /// Construct a TTI object using a type implementing the \c Concept
261 /// API below.
262 ///
263 /// This is used by targets to construct a TTI wrapping their target-specific
264 /// implementation that encodes appropriate costs for their target.
266 std::unique_ptr<const TargetTransformInfoImplBase> Impl);
267
268 /// Construct a baseline TTI object using a minimal implementation of
269 /// the \c Concept API below.
270 ///
271 /// The TTI implementation will reflect the information in the DataLayout
272 /// provided if non-null.
273 LLVM_ABI explicit TargetTransformInfo(const DataLayout &DL);
274
275 // Provide move semantics.
278
279 // We need to define the destructor out-of-line to define our sub-classes
280 // out-of-line.
282
283 /// Handle the invalidation of this information.
284 ///
285 /// When used as a result of \c TargetIRAnalysis this method will be called
286 /// when the function this was computed for changes. When it returns false,
287 /// the information is preserved across those changes.
289 FunctionAnalysisManager::Invalidator &) {
290 // FIXME: We should probably in some way ensure that the subtarget
291 // information for a function hasn't changed.
292 return false;
293 }
294
295 /// \name Generic Target Information
296 /// @{
297
298 /// The kind of cost model.
299 ///
300 /// There are several different cost models that can be customized by the
301 /// target. The normalization of each cost model may be target specific.
302 /// e.g. TCK_SizeAndLatency should be comparable to target thresholds such as
303 /// those derived from MCSchedModel::LoopMicroOpBufferSize etc.
305 TCK_RecipThroughput, ///< Reciprocal throughput.
306 TCK_Latency, ///< The latency of instruction.
307 TCK_CodeSize, ///< Instruction code size.
308 TCK_SizeAndLatency ///< The weighted sum of size and latency.
309 };
310
311 /// Underlying constants for 'cost' values in this interface.
312 ///
313 /// Many APIs in this interface return a cost. This enum defines the
314 /// fundamental values that should be used to interpret (and produce) those
315 /// costs. The costs are returned as an int rather than a member of this
316 /// enumeration because it is expected that the cost of one IR instruction
317 /// may have a multiplicative factor to it or otherwise won't fit directly
318 /// into the enum. Moreover, it is common to sum or average costs which works
319 /// better as simple integral values. Thus this enum only provides constants.
320 /// Also note that the returned costs are signed integers to make it natural
321 /// to add, subtract, and test with zero (a common boundary condition). It is
322 /// not expected that 2^32 is a realistic cost to be modeling at any point.
323 ///
324 /// Note that these costs should usually reflect the intersection of code-size
325 /// cost and execution cost. A free instruction is typically one that folds
326 /// into another instruction. For example, reg-to-reg moves can often be
327 /// skipped by renaming the registers in the CPU, but they still are encoded
328 /// and thus wouldn't be considered 'free' here.
330 TCC_Free = 0, ///< Expected to fold away in lowering.
331 TCC_Basic = 1, ///< The cost of a typical 'add' instruction.
332 TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
333 };
334
335 /// Estimate the cost of a GEP operation when lowered.
336 ///
337 /// \p PointeeType is the source element type of the GEP.
338 /// \p Ptr is the base pointer operand.
339 /// \p Operands is the list of indices following the base pointer.
340 ///
341 /// \p AccessType is a hint as to what type of memory might be accessed by
342 /// users of the GEP. getGEPCost will use it to determine if the GEP can be
343 /// folded into the addressing mode of a load/store. If AccessType is null,
344 /// then the resulting target type based off of PointeeType will be used as an
345 /// approximation.
347 getGEPCost(Type *PointeeType, const Value *Ptr,
348 ArrayRef<const Value *> Operands, Type *AccessType = nullptr,
349 TargetCostKind CostKind = TCK_SizeAndLatency) const;
350
351 /// Describe known properties for a set of pointers.
353 /// All the GEPs in a set have same base address.
354 unsigned IsSameBaseAddress : 1;
355 /// These properties only valid if SameBaseAddress is set.
356 /// True if all pointers are separated by a unit stride.
357 unsigned IsUnitStride : 1;
358 /// True if distance between any two neigbouring pointers is a known value.
359 unsigned IsKnownStride : 1;
360 unsigned Reserved : 29;
361
362 bool isSameBase() const { return IsSameBaseAddress; }
363 bool isUnitStride() const { return IsSameBaseAddress && IsUnitStride; }
365
367 return {/*IsSameBaseAddress=*/1, /*IsUnitStride=*/1,
368 /*IsKnownStride=*/1, 0};
369 }
371 return {/*IsSameBaseAddress=*/1, /*IsUnitStride=*/0,
372 /*IsKnownStride=*/1, 0};
373 }
375 return {/*IsSameBaseAddress=*/1, /*IsUnitStride=*/0,
376 /*IsKnownStride=*/0, 0};
377 }
378 };
379 static_assert(sizeof(PointersChainInfo) == 4, "Was size increase justified?");
380
381 /// Estimate the cost of a chain of pointers (typically pointer operands of a
382 /// chain of loads or stores within same block) operations set when lowered.
383 /// \p AccessTy is the type of the loads/stores that will ultimately use the
384 /// \p Ptrs.
387 const PointersChainInfo &Info, Type *AccessTy,
388 TargetCostKind CostKind = TTI::TCK_RecipThroughput) const;
389
390 /// \returns A value by which our inlining threshold should be multiplied.
391 /// This is primarily used to bump up the inlining threshold wholesale on
392 /// targets where calls are unusually expensive.
393 ///
394 /// TODO: This is a rather blunt instrument. Perhaps altering the costs of
395 /// individual classes of instructions would be better.
397
400
401 /// \returns The bonus of inlining the last call to a static function.
403
404 /// \returns A value to be added to the inlining threshold.
405 LLVM_ABI unsigned adjustInliningThreshold(const CallBase *CB) const;
406
407 /// \returns The cost of having an Alloca in the caller if not inlined, to be
408 /// added to the threshold
409 LLVM_ABI unsigned getCallerAllocaCost(const CallBase *CB,
410 const AllocaInst *AI) const;
411
412 /// \returns Vector bonus in percent.
413 ///
414 /// Vector bonuses: We want to more aggressively inline vector-dense kernels
415 /// and apply this bonus based on the percentage of vector instructions. A
416 /// bonus is applied if the vector instructions exceed 50% and half that
417 /// amount is applied if it exceeds 10%. Note that these bonuses are some what
418 /// arbitrary and evolved over time by accident as much as because they are
419 /// principled bonuses.
420 /// FIXME: It would be nice to base the bonus values on something more
421 /// scientific. A target may has no bonus on vector instructions.
423
424 /// \return the expected cost of a memcpy, which could e.g. depend on the
425 /// source/destination type and alignment and the number of bytes copied.
427
428 /// Returns the maximum memset / memcpy size in bytes that still makes it
429 /// profitable to inline the call.
431
432 /// \return The estimated number of case clusters when lowering \p 'SI'.
433 /// \p JTSize Set a jump table size only when \p SI is suitable for a jump
434 /// table.
435 LLVM_ABI unsigned
436 getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize,
438 BlockFrequencyInfo *BFI) const;
439
440 /// Estimate the cost of a given IR user when lowered.
441 ///
442 /// This can estimate the cost of either a ConstantExpr or Instruction when
443 /// lowered.
444 ///
445 /// \p Operands is a list of operands which can be a result of transformations
446 /// of the current operands. The number of the operands on the list must equal
447 /// to the number of the current operands the IR user has. Their order on the
448 /// list must be the same as the order of the current operands the IR user
449 /// has.
450 ///
451 /// The returned cost is defined in terms of \c TargetCostConstants, see its
452 /// comments for a detailed explanation of the cost values.
455 TargetCostKind CostKind) const;
456
457 /// This is a helper function which calls the three-argument
458 /// getInstructionCost with \p Operands which are the current operands U has.
460 TargetCostKind CostKind) const {
461 SmallVector<const Value *, 4> Operands(U->operand_values());
462 return getInstructionCost(U, Operands, CostKind);
463 }
464
465 /// If a branch or a select condition is skewed in one direction by more than
466 /// this factor, it is very likely to be predicted correctly.
468
469 /// Returns estimated penalty of a branch misprediction in latency. Indicates
470 /// how aggressive the target wants for eliminating unpredictable branches. A
471 /// zero return value means extra optimization applied to them should be
472 /// minimal.
474
475 /// Return true if branch divergence exists.
476 ///
477 /// Branch divergence has a significantly negative impact on GPU performance
478 /// when threads in the same wavefront take different paths due to conditional
479 /// branches.
480 ///
481 /// If \p F is passed, provides a context function. If \p F is known to only
482 /// execute in a single threaded environment, the target may choose to skip
483 /// uniformity analysis and assume all values are uniform.
484 LLVM_ABI bool hasBranchDivergence(const Function *F = nullptr) const;
485
486 /// Returns whether V is a source of divergence.
487 ///
488 /// This function provides the target-dependent information for
489 /// the target-independent UniformityAnalysis.
490 LLVM_ABI bool isSourceOfDivergence(const Value *V) const;
491
492 // Returns true for the target specific
493 // set of operations which produce uniform result
494 // even taking non-uniform arguments
495 LLVM_ABI bool isAlwaysUniform(const Value *V) const;
496
497 /// Query the target whether the specified address space cast from FromAS to
498 /// ToAS is valid.
499 LLVM_ABI bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const;
500
501 /// Return false if a \p AS0 address cannot possibly alias a \p AS1 address.
502 LLVM_ABI bool addrspacesMayAlias(unsigned AS0, unsigned AS1) const;
503
504 /// Returns the address space ID for a target's 'flat' address space. Note
505 /// this is not necessarily the same as addrspace(0), which LLVM sometimes
506 /// refers to as the generic address space. The flat address space is a
507 /// generic address space that can be used access multiple segments of memory
508 /// with different address spaces. Access of a memory location through a
509 /// pointer with this address space is expected to be legal but slower
510 /// compared to the same memory location accessed through a pointer with a
511 /// different address space.
512 //
513 /// This is for targets with different pointer representations which can
514 /// be converted with the addrspacecast instruction. If a pointer is converted
515 /// to this address space, optimizations should attempt to replace the access
516 /// with the source address space.
517 ///
518 /// \returns ~0u if the target does not have such a flat address space to
519 /// optimize away.
520 LLVM_ABI unsigned getFlatAddressSpace() const;
521
522 /// Return any intrinsic address operand indexes which may be rewritten if
523 /// they use a flat address space pointer.
524 ///
525 /// \returns true if the intrinsic was handled.
527 Intrinsic::ID IID) const;
528
529 LLVM_ABI bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const;
530
531 /// Return true if globals in this address space can have initializers other
532 /// than `undef`.
533 LLVM_ABI bool
535
536 LLVM_ABI unsigned getAssumedAddrSpace(const Value *V) const;
537
538 LLVM_ABI bool isSingleThreaded() const;
539
540 LLVM_ABI std::pair<const Value *, unsigned>
541 getPredicatedAddrSpace(const Value *V) const;
542
543 /// Rewrite intrinsic call \p II such that \p OldV will be replaced with \p
544 /// NewV, which has a different address space. This should happen for every
545 /// operand index that collectFlatAddressOperands returned for the intrinsic.
546 /// \returns nullptr if the intrinsic was not handled. Otherwise, returns the
547 /// new value (which may be the original \p II with modified operands).
549 Value *OldV,
550 Value *NewV) const;
551
552 /// Test whether calls to a function lower to actual program function
553 /// calls.
554 ///
555 /// The idea is to test whether the program is likely to require a 'call'
556 /// instruction or equivalent in order to call the given function.
557 ///
558 /// FIXME: It's not clear that this is a good or useful query API. Client's
559 /// should probably move to simpler cost metrics using the above.
560 /// Alternatively, we could split the cost interface into distinct code-size
561 /// and execution-speed costs. This would allow modelling the core of this
562 /// query more accurately as a call is a single small instruction, but
563 /// incurs significant execution cost.
564 LLVM_ABI bool isLoweredToCall(const Function *F) const;
565
566 struct LSRCost {
567 /// TODO: Some of these could be merged. Also, a lexical ordering
568 /// isn't always optimal.
569 unsigned Insns;
570 unsigned NumRegs;
571 unsigned AddRecCost;
572 unsigned NumIVMuls;
573 unsigned NumBaseAdds;
574 unsigned ImmCost;
575 unsigned SetupCost;
576 unsigned ScaleCost;
577 };
578
579 /// Parameters that control the generic loop unrolling transformation.
581 /// The cost threshold for the unrolled loop. Should be relative to the
582 /// getInstructionCost values returned by this API, and the expectation is
583 /// that the unrolled loop's instructions when run through that interface
584 /// should not exceed this cost. However, this is only an estimate. Also,
585 /// specific loops may be unrolled even with a cost above this threshold if
586 /// deemed profitable. Set this to UINT_MAX to disable the loop body cost
587 /// restriction.
588 unsigned Threshold;
589 /// If complete unrolling will reduce the cost of the loop, we will boost
590 /// the Threshold by a certain percent to allow more aggressive complete
591 /// unrolling. This value provides the maximum boost percentage that we
592 /// can apply to Threshold (The value should be no less than 100).
593 /// BoostedThreshold = Threshold * min(RolledCost / UnrolledCost,
594 /// MaxPercentThresholdBoost / 100)
595 /// E.g. if complete unrolling reduces the loop execution time by 50%
596 /// then we boost the threshold by the factor of 2x. If unrolling is not
597 /// expected to reduce the running time, then we do not increase the
598 /// threshold.
600 /// The cost threshold for the unrolled loop when optimizing for size (set
601 /// to UINT_MAX to disable).
603 /// The cost threshold for the unrolled loop, like Threshold, but used
604 /// for partial/runtime unrolling (set to UINT_MAX to disable).
606 /// The cost threshold for the unrolled loop when optimizing for size, like
607 /// OptSizeThreshold, but used for partial/runtime unrolling (set to
608 /// UINT_MAX to disable).
610 /// A forced unrolling factor (the number of concatenated bodies of the
611 /// original loop in the unrolled loop body). When set to 0, the unrolling
612 /// transformation will select an unrolling factor based on the current cost
613 /// threshold and other factors.
614 unsigned Count;
615 /// Default unroll count for loops with run-time trip count.
617 // Set the maximum unrolling factor. The unrolling factor may be selected
618 // using the appropriate cost threshold, but may not exceed this number
619 // (set to UINT_MAX to disable). This does not apply in cases where the
620 // loop is being fully unrolled.
621 unsigned MaxCount;
622 /// Set the maximum upper bound of trip count. Allowing the MaxUpperBound
623 /// to be overrided by a target gives more flexiblity on certain cases.
624 /// By default, MaxUpperBound uses UnrollMaxUpperBound which value is 8.
626 /// Set the maximum unrolling factor for full unrolling. Like MaxCount, but
627 /// applies even if full unrolling is selected. This allows a target to fall
628 /// back to Partial unrolling if full unrolling is above FullUnrollMaxCount.
630 // Represents number of instructions optimized when "back edge"
631 // becomes "fall through" in unrolled loop.
632 // For now we count a conditional branch on a backedge and a comparison
633 // feeding it.
634 unsigned BEInsns;
635 /// Allow partial unrolling (unrolling of loops to expand the size of the
636 /// loop body, not only to eliminate small constant-trip-count loops).
638 /// Allow runtime unrolling (unrolling of loops to expand the size of the
639 /// loop body even when the number of loop iterations is not known at
640 /// compile time).
642 /// Allow generation of a loop remainder (extra iterations after unroll).
644 /// Allow emitting expensive instructions (such as divisions) when computing
645 /// the trip count of a loop for runtime unrolling.
647 /// Apply loop unroll on any kind of loop
648 /// (mainly to loops that fail runtime unrolling).
649 bool Force;
650 /// Allow using trip count upper bound to unroll loops.
652 /// Allow unrolling of all the iterations of the runtime loop remainder.
654 /// Allow unroll and jam. Used to enable unroll and jam for the target.
656 /// Threshold for unroll and jam, for inner loop size. The 'Threshold'
657 /// value above is used during unroll and jam for the outer loop size.
658 /// This value is used in the same manner to limit the size of the inner
659 /// loop.
661 /// Don't allow loop unrolling to simulate more than this number of
662 /// iterations when checking full unroll profitability
664 /// Don't disable runtime unroll for the loops which were vectorized.
666 /// Don't allow runtime unrolling if expanding the trip count takes more
667 /// than SCEVExpansionBudget.
669 /// Allow runtime unrolling multi-exit loops. Should only be set if the
670 /// target determined that multi-exit unrolling is profitable for the loop.
671 /// Fall back to the generic logic to determine whether multi-exit unrolling
672 /// is profitable if set to false.
674 /// Allow unrolling to add parallel reduction phis.
676 };
677
678 /// Get target-customized preferences for the generic loop unrolling
679 /// transformation. The caller will initialize UP with the current
680 /// target-independent defaults.
683 OptimizationRemarkEmitter *ORE) const;
684
685 /// Query the target whether it would be profitable to convert the given loop
686 /// into a hardware loop.
688 AssumptionCache &AC,
689 TargetLibraryInfo *LibInfo,
690 HardwareLoopInfo &HWLoopInfo) const;
691
692 // Query the target for which minimum vectorization factor epilogue
693 // vectorization should be considered.
695
696 /// Query the target whether it would be prefered to create a predicated
697 /// vector loop, which can avoid the need to emit a scalar epilogue loop.
699
700 /// Query the target what the preferred style of tail folding is.
701 /// \param IVUpdateMayOverflow Tells whether it is known if the IV update
702 /// may (or will never) overflow for the suggested VF/UF in the given loop.
703 /// Targets can use this information to select a more optimal tail folding
704 /// style. The value conservatively defaults to true, such that no assumptions
705 /// are made on overflow.
707 getPreferredTailFoldingStyle(bool IVUpdateMayOverflow = true) const;
708
709 // Parameters that control the loop peeling transformation
711 /// A forced peeling factor (the number of bodied of the original loop
712 /// that should be peeled off before the loop body). When set to 0, the
713 /// a peeling factor based on profile information and other factors.
714 unsigned PeelCount;
715 /// Allow peeling off loop iterations.
717 /// Allow peeling off loop iterations for loop nests.
719 /// Allow peeling basing on profile. Uses to enable peeling off all
720 /// iterations basing on provided profile.
721 /// If the value is true the peeling cost model can decide to peel only
722 /// some iterations and in this case it will set this to false.
724
725 /// Peel off the last PeelCount loop iterations.
727 };
728
729 /// Get target-customized preferences for the generic loop peeling
730 /// transformation. The caller will initialize \p PP with the current
731 /// target-independent defaults with information from \p L and \p SE.
733 PeelingPreferences &PP) const;
734
735 /// Targets can implement their own combinations for target-specific
736 /// intrinsics. This function will be called from the InstCombine pass every
737 /// time a target-specific intrinsic is encountered.
738 ///
739 /// \returns std::nullopt to not do anything target specific or a value that
740 /// will be returned from the InstCombiner. It is possible to return null and
741 /// stop further processing of the intrinsic by returning nullptr.
742 LLVM_ABI std::optional<Instruction *>
744 /// Can be used to implement target-specific instruction combining.
745 /// \see instCombineIntrinsic
746 LLVM_ABI std::optional<Value *>
748 APInt DemandedMask, KnownBits &Known,
749 bool &KnownBitsComputed) const;
750 /// Can be used to implement target-specific instruction combining.
751 /// \see instCombineIntrinsic
752 LLVM_ABI std::optional<Value *> simplifyDemandedVectorEltsIntrinsic(
753 InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
754 APInt &UndefElts2, APInt &UndefElts3,
755 std::function<void(Instruction *, unsigned, APInt, APInt &)>
756 SimplifyAndSetOp) const;
757 /// @}
758
759 /// \name Scalar Target Information
760 /// @{
761
762 /// Flags indicating the kind of support for population count.
763 ///
764 /// Compared to the SW implementation, HW support is supposed to
765 /// significantly boost the performance when the population is dense, and it
766 /// may or may not degrade performance if the population is sparse. A HW
767 /// support is considered as "Fast" if it can outperform, or is on a par
768 /// with, SW implementation when the population is sparse; otherwise, it is
769 /// considered as "Slow".
771
772 /// Return true if the specified immediate is legal add immediate, that
773 /// is the target has add instructions which can add a register with the
774 /// immediate without having to materialize the immediate into a register.
775 LLVM_ABI bool isLegalAddImmediate(int64_t Imm) const;
776
777 /// Return true if adding the specified scalable immediate is legal, that is
778 /// the target has add instructions which can add a register with the
779 /// immediate (multiplied by vscale) without having to materialize the
780 /// immediate into a register.
781 LLVM_ABI bool isLegalAddScalableImmediate(int64_t Imm) const;
782
783 /// Return true if the specified immediate is legal icmp immediate,
784 /// that is the target has icmp instructions which can compare a register
785 /// against the immediate without having to materialize the immediate into a
786 /// register.
787 LLVM_ABI bool isLegalICmpImmediate(int64_t Imm) const;
788
789 /// Return true if the addressing mode represented by AM is legal for
790 /// this target, for a load/store of the specified type.
791 /// The type may be VoidTy, in which case only return true if the addressing
792 /// mode is legal for a load/store of any legal type.
793 /// If target returns true in LSRWithInstrQueries(), I may be valid.
794 /// \param ScalableOffset represents a quantity of bytes multiplied by vscale,
795 /// an invariant value known only at runtime. Most targets should not accept
796 /// a scalable offset.
797 ///
798 /// TODO: Handle pre/postinc as well.
800 int64_t BaseOffset, bool HasBaseReg,
801 int64_t Scale, unsigned AddrSpace = 0,
802 Instruction *I = nullptr,
803 int64_t ScalableOffset = 0) const;
804
805 /// Return true if LSR cost of C1 is lower than C2.
807 const TargetTransformInfo::LSRCost &C2) const;
808
809 /// Return true if LSR major cost is number of registers. Targets which
810 /// implement their own isLSRCostLess and unset number of registers as major
811 /// cost should return false, otherwise return true.
813
814 /// Return true if LSR should drop a found solution if it's calculated to be
815 /// less profitable than the baseline.
817
818 /// \returns true if LSR should not optimize a chain that includes \p I.
820
821 /// Return true if the target can fuse a compare and branch.
822 /// Loop-strength-reduction (LSR) uses that knowledge to adjust its cost
823 /// calculation for the instructions in a loop.
824 LLVM_ABI bool canMacroFuseCmp() const;
825
826 /// Return true if the target can save a compare for loop count, for example
827 /// hardware loop saves a compare.
830 TargetLibraryInfo *LibInfo) const;
831
832 /// Which addressing mode Loop Strength Reduction will try to generate.
834 AMK_None = 0x0, ///< Don't prefer any addressing mode
835 AMK_PreIndexed = 0x1, ///< Prefer pre-indexed addressing mode
836 AMK_PostIndexed = 0x2, ///< Prefer post-indexed addressing mode
837 AMK_All = 0x3, ///< Consider all addressing modes
838 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/AMK_All)
839 };
840
841 /// Return the preferred addressing mode LSR should make efforts to generate.
844
845 /// Return true if the target supports masked store.
846 LLVM_ABI bool isLegalMaskedStore(Type *DataType, Align Alignment,
847 unsigned AddressSpace) const;
848 /// Return true if the target supports masked load.
849 LLVM_ABI bool isLegalMaskedLoad(Type *DataType, Align Alignment,
850 unsigned AddressSpace) const;
851
852 /// Return true if the target supports nontemporal store.
853 LLVM_ABI bool isLegalNTStore(Type *DataType, Align Alignment) const;
854 /// Return true if the target supports nontemporal load.
855 LLVM_ABI bool isLegalNTLoad(Type *DataType, Align Alignment) const;
856
857 /// \Returns true if the target supports broadcasting a load to a vector of
858 /// type <NumElements x ElementTy>.
859 LLVM_ABI bool isLegalBroadcastLoad(Type *ElementTy,
860 ElementCount NumElements) const;
861
862 /// Return true if the target supports masked scatter.
863 LLVM_ABI bool isLegalMaskedScatter(Type *DataType, Align Alignment) const;
864 /// Return true if the target supports masked gather.
865 LLVM_ABI bool isLegalMaskedGather(Type *DataType, Align Alignment) const;
866 /// Return true if the target forces scalarizing of llvm.masked.gather
867 /// intrinsics.
869 Align Alignment) const;
870 /// Return true if the target forces scalarizing of llvm.masked.scatter
871 /// intrinsics.
873 Align Alignment) const;
874
875 /// Return true if the target supports masked compress store.
877 Align Alignment) const;
878 /// Return true if the target supports masked expand load.
879 LLVM_ABI bool isLegalMaskedExpandLoad(Type *DataType, Align Alignment) const;
880
881 /// Return true if the target supports strided load.
882 LLVM_ABI bool isLegalStridedLoadStore(Type *DataType, Align Alignment) const;
883
884 /// Return true is the target supports interleaved access for the given vector
885 /// type \p VTy, interleave factor \p Factor, alignment \p Alignment and
886 /// address space \p AddrSpace.
887 LLVM_ABI bool isLegalInterleavedAccessType(VectorType *VTy, unsigned Factor,
888 Align Alignment,
889 unsigned AddrSpace) const;
890
891 // Return true if the target supports masked vector histograms.
893 Type *DataType) const;
894
895 /// Return true if this is an alternating opcode pattern that can be lowered
896 /// to a single instruction on the target. In X86 this is for the addsub
897 /// instruction which corrsponds to a Shuffle + Fadd + FSub pattern in IR.
898 /// This function expectes two opcodes: \p Opcode1 and \p Opcode2 being
899 /// selected by \p OpcodeMask. The mask contains one bit per lane and is a `0`
900 /// when \p Opcode0 is selected and `1` when Opcode1 is selected.
901 /// \p VecTy is the vector type of the instruction to be generated.
902 LLVM_ABI bool isLegalAltInstr(VectorType *VecTy, unsigned Opcode0,
903 unsigned Opcode1,
904 const SmallBitVector &OpcodeMask) const;
905
906 /// Return true if we should be enabling ordered reductions for the target.
908
909 /// Return true if the target has a unified operation to calculate division
910 /// and remainder. If so, the additional implicit multiplication and
911 /// subtraction required to calculate a remainder from division are free. This
912 /// can enable more aggressive transformations for division and remainder than
913 /// would typically be allowed using throughput or size cost models.
914 LLVM_ABI bool hasDivRemOp(Type *DataType, bool IsSigned) const;
915
916 /// Return true if the given instruction (assumed to be a memory access
917 /// instruction) has a volatile variant. If that's the case then we can avoid
918 /// addrspacecast to generic AS for volatile loads/stores. Default
919 /// implementation returns false, which prevents address space inference for
920 /// volatile loads/stores.
921 LLVM_ABI bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) const;
922
923 /// Return true if target doesn't mind addresses in vectors.
925
926 /// Return the cost of the scaling factor used in the addressing
927 /// mode represented by AM for this target, for a load/store
928 /// of the specified type.
929 /// If the AM is supported, the return value must be >= 0.
930 /// If the AM is not supported, it returns a negative value.
931 /// TODO: Handle pre/postinc as well.
933 StackOffset BaseOffset,
934 bool HasBaseReg, int64_t Scale,
935 unsigned AddrSpace = 0) const;
936
937 /// Return true if the loop strength reduce pass should make
938 /// Instruction* based TTI queries to isLegalAddressingMode(). This is
939 /// needed on SystemZ, where e.g. a memcpy can only have a 12 bit unsigned
940 /// immediate offset and no index register.
941 LLVM_ABI bool LSRWithInstrQueries() const;
942
943 /// Return true if it's free to truncate a value of type Ty1 to type
944 /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
945 /// by referencing its sub-register AX.
946 LLVM_ABI bool isTruncateFree(Type *Ty1, Type *Ty2) const;
947
948 /// Return true if it is profitable to hoist instruction in the
949 /// then/else to before if.
951
952 LLVM_ABI bool useAA() const;
953
954 /// Return true if this type is legal.
955 LLVM_ABI bool isTypeLegal(Type *Ty) const;
956
957 /// Returns the estimated number of registers required to represent \p Ty.
958 LLVM_ABI unsigned getRegUsageForType(Type *Ty) const;
959
960 /// Return true if switches should be turned into lookup tables for the
961 /// target.
963
964 /// Return true if switches should be turned into lookup tables
965 /// containing this constant value for the target.
967
968 /// Return true if lookup tables should be turned into relative lookup tables.
970
971 /// Return true if the input function which is cold at all call sites,
972 /// should use coldcc calling convention.
974
976
977 /// Identifies if the vector form of the intrinsic has a scalar operand.
979 unsigned ScalarOpdIdx) const;
980
981 /// Identifies if the vector form of the intrinsic is overloaded on the type
982 /// of the operand at index \p OpdIdx, or on the return type if \p OpdIdx is
983 /// -1.
985 int OpdIdx) const;
986
987 /// Identifies if the vector form of the intrinsic that returns a struct is
988 /// overloaded at the struct element index \p RetIdx.
989 LLVM_ABI bool
991 int RetIdx) const;
992
993 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
994 /// are set if the demanded result elements need to be inserted and/or
995 /// extracted from vectors. The involved values may be passed in VL if
996 /// Insert is true.
998 VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract,
999 TTI::TargetCostKind CostKind, bool ForPoisonSrc = true,
1000 ArrayRef<Value *> VL = {}) const;
1001
1002 /// Estimate the overhead of scalarizing operands with the given types. The
1003 /// (potentially vector) types to use for each of argument are passes via Tys.
1006
1007 /// If target has efficient vector element load/store instructions, it can
1008 /// return true here so that insertion/extraction costs are not added to
1009 /// the scalarization cost of a load/store.
1011
1012 /// If the target supports tail calls.
1013 LLVM_ABI bool supportsTailCalls() const;
1014
1015 /// If target supports tail call on \p CB
1016 LLVM_ABI bool supportsTailCallFor(const CallBase *CB) const;
1017
1018 /// Don't restrict interleaved unrolling to small loops.
1019 LLVM_ABI bool enableAggressiveInterleaving(bool LoopHasReductions) const;
1020
1021 /// Returns options for expansion of memcmp. IsZeroCmp is
1022 // true if this is the expansion of memcmp(p1, p2, s) == 0.
1024 // Return true if memcmp expansion is enabled.
1025 operator bool() const { return MaxNumLoads > 0; }
1026
1027 // Maximum number of load operations.
1028 unsigned MaxNumLoads = 0;
1029
1030 // The list of available load sizes (in bytes), sorted in decreasing order.
1032
1033 // For memcmp expansion when the memcmp result is only compared equal or
1034 // not-equal to 0, allow up to this number of load pairs per block. As an
1035 // example, this may allow 'memcmp(a, b, 3) == 0' in a single block:
1036 // a0 = load2bytes &a[0]
1037 // b0 = load2bytes &b[0]
1038 // a2 = load1byte &a[2]
1039 // b2 = load1byte &b[2]
1040 // r = cmp eq (a0 ^ b0 | a2 ^ b2), 0
1041 unsigned NumLoadsPerBlock = 1;
1042
1043 // Set to true to allow overlapping loads. For example, 7-byte compares can
1044 // be done with two 4-byte compares instead of 4+2+1-byte compares. This
1045 // requires all loads in LoadSizes to be doable in an unaligned way.
1047
1048 // Sometimes, the amount of data that needs to be compared is smaller than
1049 // the standard register size, but it cannot be loaded with just one load
1050 // instruction. For example, if the size of the memory comparison is 6
1051 // bytes, we can handle it more efficiently by loading all 6 bytes in a
1052 // single block and generating an 8-byte number, instead of generating two
1053 // separate blocks with conditional jumps for 4 and 2 byte loads. This
1054 // approach simplifies the process and produces the comparison result as
1055 // normal. This array lists the allowed sizes of memcmp tails that can be
1056 // merged into one block
1058 };
1060 bool IsZeroCmp) const;
1061
1062 /// Should the Select Optimization pass be enabled and ran.
1063 LLVM_ABI bool enableSelectOptimize() const;
1064
1065 /// Should the Select Optimization pass treat the given instruction like a
1066 /// select, potentially converting it to a conditional branch. This can
1067 /// include select-like instructions like or(zext(c), x) that can be converted
1068 /// to selects.
1070
1071 /// Enable matching of interleaved access groups.
1073
1074 /// Enable matching of interleaved access groups that contain predicated
1075 /// accesses or gaps and therefore vectorized using masked
1076 /// vector loads/stores.
1078
1079 /// Indicate that it is potentially unsafe to automatically vectorize
1080 /// floating-point operations because the semantics of vector and scalar
1081 /// floating-point semantics may differ. For example, ARM NEON v7 SIMD math
1082 /// does not support IEEE-754 denormal numbers, while depending on the
1083 /// platform, scalar floating-point math does.
1084 /// This applies to floating-point math operations and calls, not memory
1085 /// operations, shuffles, or casts.
1087
1088 /// Determine if the target supports unaligned memory accesses.
1090 unsigned BitWidth,
1091 unsigned AddressSpace = 0,
1092 Align Alignment = Align(1),
1093 unsigned *Fast = nullptr) const;
1094
1095 /// Return hardware support for population count.
1096 LLVM_ABI PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
1097
1098 /// Return true if the hardware has a fast square-root instruction.
1099 LLVM_ABI bool haveFastSqrt(Type *Ty) const;
1100
1101 /// Return true if the cost of the instruction is too high to speculatively
1102 /// execute and should be kept behind a branch.
1103 /// This normally just wraps around a getInstructionCost() call, but some
1104 /// targets might report a low TCK_SizeAndLatency value that is incompatible
1105 /// with the fixed TCC_Expensive value.
1106 /// NOTE: This assumes the instruction passes isSafeToSpeculativelyExecute().
1108
1109 /// Return true if it is faster to check if a floating-point value is NaN
1110 /// (or not-NaN) versus a comparison against a constant FP zero value.
1111 /// Targets should override this if materializing a 0.0 for comparison is
1112 /// generally as cheap as checking for ordered/unordered.
1114
1115 /// Return the expected cost of supporting the floating point operation
1116 /// of the specified type.
1118
1119 /// Return the expected cost of materializing for the given integer
1120 /// immediate of the specified type.
1122 TargetCostKind CostKind) const;
1123
1124 /// Return the expected cost of materialization for the given integer
1125 /// immediate of the specified type for a given instruction. The cost can be
1126 /// zero if the immediate can be folded into the specified instruction.
1127 LLVM_ABI InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx,
1128 const APInt &Imm, Type *Ty,
1130 Instruction *Inst = nullptr) const;
1132 const APInt &Imm, Type *Ty,
1133 TargetCostKind CostKind) const;
1134
1135 /// Return the expected cost for the given integer when optimising
1136 /// for size. This is different than the other integer immediate cost
1137 /// functions in that it is subtarget agnostic. This is useful when you e.g.
1138 /// target one ISA such as Aarch32 but smaller encodings could be possible
1139 /// with another such as Thumb. This return value is used as a penalty when
1140 /// the total costs for a constant is calculated (the bigger the cost, the
1141 /// more beneficial constant hoisting is).
1142 LLVM_ABI InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx,
1143 const APInt &Imm,
1144 Type *Ty) const;
1145
1146 /// It can be advantageous to detach complex constants from their uses to make
1147 /// their generation cheaper. This hook allows targets to report when such
1148 /// transformations might negatively effect the code generation of the
1149 /// underlying operation. The motivating example is divides whereby hoisting
1150 /// constants prevents the code generator's ability to transform them into
1151 /// combinations of simpler operations.
1153 const Function &Fn) const;
1154
1155 /// @}
1156
1157 /// \name Vector Target Information
1158 /// @{
1159
1160 /// The various kinds of shuffle patterns for vector queries.
1162 SK_Broadcast, ///< Broadcast element 0 to all other elements.
1163 SK_Reverse, ///< Reverse the order of the vector.
1164 SK_Select, ///< Selects elements from the corresponding lane of
1165 ///< either source operand. This is equivalent to a
1166 ///< vector select with a constant condition operand.
1167 SK_Transpose, ///< Transpose two vectors.
1168 SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
1169 SK_ExtractSubvector, ///< ExtractSubvector Index indicates start offset.
1170 SK_PermuteTwoSrc, ///< Merge elements from two source vectors into one
1171 ///< with any shuffle mask.
1172 SK_PermuteSingleSrc, ///< Shuffle elements of single source vector with any
1173 ///< shuffle mask.
1174 SK_Splice ///< Concatenates elements from the first input vector
1175 ///< with elements of the second input vector. Returning
1176 ///< a vector of the same type as the input vectors.
1177 ///< Index indicates start offset in first input vector.
1178 };
1179
1180 /// Additional information about an operand's possible values.
1182 OK_AnyValue, // Operand can have any value.
1183 OK_UniformValue, // Operand is uniform (splat of a value).
1184 OK_UniformConstantValue, // Operand is uniform constant.
1185 OK_NonUniformConstantValue // Operand is a non uniform constant value.
1186 };
1187
1188 /// Additional properties of an operand's values.
1194
1195 // Describe the values an operand can take. We're in the process
1196 // of migrating uses of OperandValueKind and OperandValueProperties
1197 // to use this class, and then will change the internal representation.
1201
1202 bool isConstant() const {
1204 }
1205 bool isUniform() const {
1207 }
1208 bool isPowerOf2() const {
1209 return Properties == OP_PowerOf2;
1210 }
1211 bool isNegatedPowerOf2() const {
1213 }
1214
1216 return {Kind, OP_None};
1217 }
1218 };
1219
1220 /// \return the number of registers in the target-provided register class.
1221 LLVM_ABI unsigned getNumberOfRegisters(unsigned ClassID) const;
1222
1223 /// \return true if the target supports load/store that enables fault
1224 /// suppression of memory operands when the source condition is false.
1225 LLVM_ABI bool hasConditionalLoadStoreForType(Type *Ty, bool IsStore) const;
1226
1227 /// \return the target-provided register class ID for the provided type,
1228 /// accounting for type promotion and other type-legalization techniques that
1229 /// the target might apply. However, it specifically does not account for the
1230 /// scalarization or splitting of vector types. Should a vector type require
1231 /// scalarization or splitting into multiple underlying vector registers, that
1232 /// type should be mapped to a register class containing no registers.
1233 /// Specifically, this is designed to provide a simple, high-level view of the
1234 /// register allocation later performed by the backend. These register classes
1235 /// don't necessarily map onto the register classes used by the backend.
1236 /// FIXME: It's not currently possible to determine how many registers
1237 /// are used by the provided type.
1239 Type *Ty = nullptr) const;
1240
1241 /// \return the target-provided register class name
1242 LLVM_ABI const char *getRegisterClassName(unsigned ClassID) const;
1243
1245
1246 /// \return The width of the largest scalar or vector register type.
1247 LLVM_ABI TypeSize getRegisterBitWidth(RegisterKind K) const;
1248
1249 /// \return The width of the smallest vector register type.
1250 LLVM_ABI unsigned getMinVectorRegisterBitWidth() const;
1251
1252 /// \return The maximum value of vscale if the target specifies an
1253 /// architectural maximum vector length, and std::nullopt otherwise.
1254 LLVM_ABI std::optional<unsigned> getMaxVScale() const;
1255
1256 /// \return the value of vscale to tune the cost model for.
1257 LLVM_ABI std::optional<unsigned> getVScaleForTuning() const;
1258
1259 /// \return true if vscale is known to be a power of 2
1261
1262 /// \return True if the vectorization factor should be chosen to
1263 /// make the vector of the smallest element type match the size of a
1264 /// vector register. For wider element types, this could result in
1265 /// creating vectors that span multiple vector registers.
1266 /// If false, the vectorization factor will be chosen based on the
1267 /// size of the widest element type.
1268 /// \p K Register Kind for vectorization.
1269 LLVM_ABI bool
1271
1272 /// \return The minimum vectorization factor for types of given element
1273 /// bit width, or 0 if there is no minimum VF. The returned value only
1274 /// applies when shouldMaximizeVectorBandwidth returns true.
1275 /// If IsScalable is true, the returned ElementCount must be a scalable VF.
1276 LLVM_ABI ElementCount getMinimumVF(unsigned ElemWidth, bool IsScalable) const;
1277
1278 /// \return The maximum vectorization factor for types of given element
1279 /// bit width and opcode, or 0 if there is no maximum VF.
1280 /// Currently only used by the SLP vectorizer.
1281 LLVM_ABI unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const;
1282
1283 /// \return The minimum vectorization factor for the store instruction. Given
1284 /// the initial estimation of the minimum vector factor and store value type,
1285 /// it tries to find possible lowest VF, which still might be profitable for
1286 /// the vectorization.
1287 /// \param VF Initial estimation of the minimum vector factor.
1288 /// \param ScalarMemTy Scalar memory type of the store operation.
1289 /// \param ScalarValTy Scalar type of the stored value.
1290 /// Currently only used by the SLP vectorizer.
1291 LLVM_ABI unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy,
1292 Type *ScalarValTy) const;
1293
1294 /// \return True if it should be considered for address type promotion.
1295 /// \p AllowPromotionWithoutCommonHeader Set true if promoting \p I is
1296 /// profitable without finding other extensions fed by the same input.
1298 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const;
1299
1300 /// \return The size of a cache line in bytes.
1301 LLVM_ABI unsigned getCacheLineSize() const;
1302
1303 /// The possible cache levels
1304 enum class CacheLevel {
1305 L1D, // The L1 data cache
1306 L2D, // The L2 data cache
1307
1308 // We currently do not model L3 caches, as their sizes differ widely between
1309 // microarchitectures. Also, we currently do not have a use for L3 cache
1310 // size modeling yet.
1311 };
1312
1313 /// \return The size of the cache level in bytes, if available.
1314 LLVM_ABI std::optional<unsigned> getCacheSize(CacheLevel Level) const;
1315
1316 /// \return The associativity of the cache level, if available.
1317 LLVM_ABI std::optional<unsigned>
1318 getCacheAssociativity(CacheLevel Level) const;
1319
1320 /// \return The minimum architectural page size for the target.
1321 LLVM_ABI std::optional<unsigned> getMinPageSize() const;
1322
1323 /// \return How much before a load we should place the prefetch
1324 /// instruction. This is currently measured in number of
1325 /// instructions.
1326 LLVM_ABI unsigned getPrefetchDistance() const;
1327
1328 /// Some HW prefetchers can handle accesses up to a certain constant stride.
1329 /// Sometimes prefetching is beneficial even below the HW prefetcher limit,
1330 /// and the arguments provided are meant to serve as a basis for deciding this
1331 /// for a particular loop.
1332 ///
1333 /// \param NumMemAccesses Number of memory accesses in the loop.
1334 /// \param NumStridedMemAccesses Number of the memory accesses that
1335 /// ScalarEvolution could find a known stride
1336 /// for.
1337 /// \param NumPrefetches Number of software prefetches that will be
1338 /// emitted as determined by the addresses
1339 /// involved and the cache line size.
1340 /// \param HasCall True if the loop contains a call.
1341 ///
1342 /// \return This is the minimum stride in bytes where it makes sense to start
1343 /// adding SW prefetches. The default is 1, i.e. prefetch with any
1344 /// stride.
1345 LLVM_ABI unsigned getMinPrefetchStride(unsigned NumMemAccesses,
1346 unsigned NumStridedMemAccesses,
1347 unsigned NumPrefetches,
1348 bool HasCall) const;
1349
1350 /// \return The maximum number of iterations to prefetch ahead. If
1351 /// the required number of iterations is more than this number, no
1352 /// prefetching is performed.
1353 LLVM_ABI unsigned getMaxPrefetchIterationsAhead() const;
1354
1355 /// \return True if prefetching should also be done for writes.
1356 LLVM_ABI bool enableWritePrefetching() const;
1357
1358 /// \return if target want to issue a prefetch in address space \p AS.
1359 LLVM_ABI bool shouldPrefetchAddressSpace(unsigned AS) const;
1360
1361 /// \return The cost of a partial reduction, which is a reduction from a
1362 /// vector to another vector with fewer elements of larger size. They are
1363 /// represented by the llvm.vector.partial.reduce.add intrinsic, which
1364 /// takes an accumulator of type \p AccumType and a second vector operand to
1365 /// be accumulated, whose element count is specified by \p VF. The type of
1366 /// reduction is specified by \p Opcode. The second operand passed to the
1367 /// intrinsic could be the result of an extend, such as sext or zext. In
1368 /// this case \p BinOp is nullopt, \p InputTypeA represents the type being
1369 /// extended and \p OpAExtend the operation, i.e. sign- or zero-extend.
1370 /// Also, \p InputTypeB should be nullptr and OpBExtend should be None.
1371 /// Alternatively, the second operand could be the result of a binary
1372 /// operation performed on two extends, i.e.
1373 /// mul(zext i8 %a -> i32, zext i8 %b -> i32).
1374 /// In this case \p BinOp may specify the opcode of the binary operation,
1375 /// \p InputTypeA and \p InputTypeB the types being extended, and
1376 /// \p OpAExtend, \p OpBExtend the form of extensions. An example of an
1377 /// operation that uses a partial reduction is a dot product, which reduces
1378 /// two vectors in binary mul operation to another of 4 times fewer and 4
1379 /// times larger elements.
1381 unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType,
1383 PartialReductionExtendKind OpBExtend, std::optional<unsigned> BinOp,
1385
1386 /// \return The maximum interleave factor that any transform should try to
1387 /// perform for this target. This number depends on the level of parallelism
1388 /// and the number of execution units in the CPU.
1389 LLVM_ABI unsigned getMaxInterleaveFactor(ElementCount VF) const;
1390
1391 /// Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
1392 LLVM_ABI static OperandValueInfo getOperandInfo(const Value *V);
1393
1394 /// This is an approximation of reciprocal throughput of a math/logic op.
1395 /// A higher cost indicates less expected throughput.
1396 /// From Agner Fog's guides, reciprocal throughput is "the average number of
1397 /// clock cycles per instruction when the instructions are not part of a
1398 /// limiting dependency chain."
1399 /// Therefore, costs should be scaled to account for multiple execution units
1400 /// on the target that can process this type of instruction. For example, if
1401 /// there are 5 scalar integer units and 2 vector integer units that can
1402 /// calculate an 'add' in a single cycle, this model should indicate that the
1403 /// cost of the vector add instruction is 2.5 times the cost of the scalar
1404 /// add instruction.
1405 /// \p Args is an optional argument which holds the instruction operands
1406 /// values so the TTI can analyze those values searching for special
1407 /// cases or optimizations based on those values.
1408 /// \p CxtI is the optional original context instruction, if one exists, to
1409 /// provide even more information.
1410 /// \p TLibInfo is used to search for platform specific vector library
1411 /// functions for instructions that might be converted to calls (e.g. frem).
1413 unsigned Opcode, Type *Ty,
1417 ArrayRef<const Value *> Args = {}, const Instruction *CxtI = nullptr,
1418 const TargetLibraryInfo *TLibInfo = nullptr) const;
1419
1420 /// Returns the cost estimation for alternating opcode pattern that can be
1421 /// lowered to a single instruction on the target. In X86 this is for the
1422 /// addsub instruction which corrsponds to a Shuffle + Fadd + FSub pattern in
1423 /// IR. This function expects two opcodes: \p Opcode1 and \p Opcode2 being
1424 /// selected by \p OpcodeMask. The mask contains one bit per lane and is a `0`
1425 /// when \p Opcode0 is selected and `1` when Opcode1 is selected.
1426 /// \p VecTy is the vector type of the instruction to be generated.
1428 VectorType *VecTy, unsigned Opcode0, unsigned Opcode1,
1429 const SmallBitVector &OpcodeMask,
1431
1432 /// \return The cost of a shuffle instruction of kind Kind with inputs of type
1433 /// SrcTy, producing a vector of type DstTy. The exact mask may be passed as
1434 /// Mask, or else the array will be empty. The Index and SubTp parameters
1435 /// are used by the subvector insertions shuffle kinds to show the insert
1436 /// point and the type of the subvector being inserted. The operands of the
1437 /// shuffle can be passed through \p Args, which helps improve the cost
1438 /// estimation in some cases, like in broadcast loads.
1440 ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy,
1441 ArrayRef<int> Mask = {},
1443 VectorType *SubTp = nullptr, ArrayRef<const Value *> Args = {},
1444 const Instruction *CxtI = nullptr) const;
1445
1446 /// Represents a hint about the context in which a cast is used.
1447 ///
1448 /// For zext/sext, the context of the cast is the operand, which must be a
1449 /// load of some kind. For trunc, the context is of the cast is the single
1450 /// user of the instruction, which must be a store of some kind.
1451 ///
1452 /// This enum allows the vectorizer to give getCastInstrCost an idea of the
1453 /// type of cast it's dealing with, as not every cast is equal. For instance,
1454 /// the zext of a load may be free, but the zext of an interleaving load can
1455 //// be (very) expensive!
1456 ///
1457 /// See \c getCastContextHint to compute a CastContextHint from a cast
1458 /// Instruction*. Callers can use it if they don't need to override the
1459 /// context and just want it to be calculated from the instruction.
1460 ///
1461 /// FIXME: This handles the types of load/store that the vectorizer can
1462 /// produce, which are the cases where the context instruction is most
1463 /// likely to be incorrect. There are other situations where that can happen
1464 /// too, which might be handled here but in the long run a more general
1465 /// solution of costing multiple instructions at the same times may be better.
1467 None, ///< The cast is not used with a load/store of any kind.
1468 Normal, ///< The cast is used with a normal load/store.
1469 Masked, ///< The cast is used with a masked load/store.
1470 GatherScatter, ///< The cast is used with a gather/scatter.
1471 Interleave, ///< The cast is used with an interleaved load/store.
1472 Reversed, ///< The cast is used with a reversed load/store.
1473 };
1474
1475 /// Calculates a CastContextHint from \p I.
1476 /// This should be used by callers of getCastInstrCost if they wish to
1477 /// determine the context from some instruction.
1478 /// \returns the CastContextHint for ZExt/SExt/Trunc, None if \p I is nullptr,
1479 /// or if it's another type of cast.
1481
1482 /// \return The expected cost of cast instructions, such as bitcast, trunc,
1483 /// zext, etc. If there is an existing instruction that holds Opcode, it
1484 /// may be passed in the 'I' parameter.
1486 unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH,
1488 const Instruction *I = nullptr) const;
1489
1490 /// \return The expected cost of a sign- or zero-extended vector extract. Use
1491 /// Index = -1 to indicate that there is no information about the index value.
1493 getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy,
1494 unsigned Index, TTI::TargetCostKind CostKind) const;
1495
1496 /// \return The expected cost of control-flow related instructions such as
1497 /// Phi, Ret, Br, Switch.
1500 const Instruction *I = nullptr) const;
1501
1502 /// \returns The expected cost of compare and select instructions. If there
1503 /// is an existing instruction that holds Opcode, it may be passed in the
1504 /// 'I' parameter. The \p VecPred parameter can be used to indicate the select
1505 /// is using a compare with the specified predicate as condition. When vector
1506 /// types are passed, \p VecPred must be used for all lanes. For a
1507 /// comparison, the two operands are the natural values. For a select, the
1508 /// two operands are the *value* operands, not the condition operand.
1510 unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred,
1512 OperandValueInfo Op1Info = {OK_AnyValue, OP_None},
1513 OperandValueInfo Op2Info = {OK_AnyValue, OP_None},
1514 const Instruction *I = nullptr) const;
1515
1516 /// \return The expected cost of vector Insert and Extract.
1517 /// Use -1 to indicate that there is no information on the index value.
1518 /// This is used when the instruction is not available; a typical use
1519 /// case is to provision the cost of vectorization/scalarization in
1520 /// vectorizer passes.
1521 LLVM_ABI InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val,
1523 unsigned Index = -1,
1524 const Value *Op0 = nullptr,
1525 const Value *Op1 = nullptr) const;
1526
1527 /// \return The expected cost of vector Insert and Extract.
1528 /// Use -1 to indicate that there is no information on the index value.
1529 /// This is used when the instruction is not available; a typical use
1530 /// case is to provision the cost of vectorization/scalarization in
1531 /// vectorizer passes.
1532 /// \param ScalarUserAndIdx encodes the information about extracts from a
1533 /// vector with 'Scalar' being the value being extracted,'User' being the user
1534 /// of the extract(nullptr if user is not known before vectorization) and
1535 /// 'Idx' being the extract lane.
1537 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index,
1538 Value *Scalar,
1539 ArrayRef<std::tuple<Value *, User *, int>> ScalarUserAndIdx) const;
1540
1541 /// \return The expected cost of vector Insert and Extract.
1542 /// This is used when instruction is available, and implementation
1543 /// asserts 'I' is not nullptr.
1544 ///
1545 /// A typical suitable use case is cost estimation when vector instruction
1546 /// exists (e.g., from basic blocks during transformation).
1547 LLVM_ABI InstructionCost getVectorInstrCost(const Instruction &I, Type *Val,
1549 unsigned Index = -1) const;
1550
1551 /// \return The expected cost of inserting or extracting a lane that is \p
1552 /// Index elements from the end of a vector, i.e. the mathematical expression
1553 /// for the lane is (VF - 1 - Index). This is required for scalable vectors
1554 /// where the exact lane index is unknown at compile time.
1556 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind,
1557 unsigned Index) const;
1558
1559 /// \return The expected cost of aggregate inserts and extracts. This is
1560 /// used when the instruction is not available; a typical use case is to
1561 /// provision the cost of vectorization/scalarization in vectorizer passes.
1563 unsigned Opcode, TTI::TargetCostKind CostKind) const;
1564
1565 /// \return The cost of replication shuffle of \p VF elements typed \p EltTy
1566 /// \p ReplicationFactor times.
1567 ///
1568 /// For example, the mask for \p ReplicationFactor=3 and \p VF=4 is:
1569 /// <0,0,0,1,1,1,2,2,2,3,3,3>
1571 Type *EltTy, int ReplicationFactor, int VF, const APInt &DemandedDstElts,
1573
1574 /// \return The cost of Load and Store instructions. The operand info
1575 /// \p OpdInfo should refer to the stored value for stores and the address
1576 /// for loads.
1578 unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace,
1581 const Instruction *I = nullptr) const;
1582
1583 /// \return The cost of masked Load and Store instructions.
1585 const MemIntrinsicCostAttributes &MICA,
1587
1588 /// \return The cost of Gather or Scatter operation
1589 /// \p Opcode - is a type of memory access Load or Store
1590 /// \p DataTy - a vector type of the data to be loaded or stored
1591 /// \p Ptr - pointer [or vector of pointers] - address[es] in memory
1592 /// \p VariableMask - true when the memory access is predicated with a mask
1593 /// that is not a compile-time constant
1594 /// \p Alignment - alignment of single element
1595 /// \p I - the optional original context instruction, if one exists, e.g. the
1596 /// load/store to transform or the call to the gather/scatter intrinsic
1598 unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
1600 const Instruction *I = nullptr) const;
1601
1602 /// \return The cost of Expand Load or Compress Store operation
1603 /// \p Opcode - is a type of memory access Load or Store
1604 /// \p Src - a vector type of the data to be loaded or stored
1605 /// \p VariableMask - true when the memory access is predicated with a mask
1606 /// that is not a compile-time constant
1607 /// \p Alignment - alignment of single element
1608 /// \p I - the optional original context instruction, if one exists, e.g. the
1609 /// load/store to transform or the call to the gather/scatter intrinsic
1611 unsigned Opcode, Type *DataTy, bool VariableMask, Align Alignment,
1613 const Instruction *I = nullptr) const;
1614
1615 /// \return The cost of strided memory operations.
1616 /// \p Opcode - is a type of memory access Load or Store
1617 /// \p DataTy - a vector type of the data to be loaded or stored
1618 /// \p Ptr - pointer [or vector of pointers] - address[es] in memory
1619 /// \p VariableMask - true when the memory access is predicated with a mask
1620 /// that is not a compile-time constant
1621 /// \p Alignment - alignment of single element
1622 /// \p I - the optional original context instruction, if one exists, e.g. the
1623 /// load/store to transform or the call to the gather/scatter intrinsic
1625 unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
1627 const Instruction *I = nullptr) const;
1628
1629 /// \return The cost of the interleaved memory operation.
1630 /// \p Opcode is the memory operation code
1631 /// \p VecTy is the vector type of the interleaved access.
1632 /// \p Factor is the interleave factor
1633 /// \p Indices is the indices for interleaved load members (as interleaved
1634 /// load allows gaps)
1635 /// \p Alignment is the alignment of the memory operation
1636 /// \p AddressSpace is address space of the pointer.
1637 /// \p UseMaskForCond indicates if the memory access is predicated.
1638 /// \p UseMaskForGaps indicates if gaps should be masked.
1640 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1641 Align Alignment, unsigned AddressSpace,
1643 bool UseMaskForCond = false, bool UseMaskForGaps = false) const;
1644
1645 /// A helper function to determine the type of reduction algorithm used
1646 /// for a given \p Opcode and set of FastMathFlags \p FMF.
1647 static bool requiresOrderedReduction(std::optional<FastMathFlags> FMF) {
1648 return FMF && !(*FMF).allowReassoc();
1649 }
1650
1651 /// Calculate the cost of vector reduction intrinsics.
1652 ///
1653 /// This is the cost of reducing the vector value of type \p Ty to a scalar
1654 /// value using the operation denoted by \p Opcode. The FastMathFlags
1655 /// parameter \p FMF indicates what type of reduction we are performing:
1656 /// 1. Tree-wise. This is the typical 'fast' reduction performed that
1657 /// involves successively splitting a vector into half and doing the
1658 /// operation on the pair of halves until you have a scalar value. For
1659 /// example:
1660 /// (v0, v1, v2, v3)
1661 /// ((v0+v2), (v1+v3), undef, undef)
1662 /// ((v0+v2+v1+v3), undef, undef, undef)
1663 /// This is the default behaviour for integer operations, whereas for
1664 /// floating point we only do this if \p FMF indicates that
1665 /// reassociation is allowed.
1666 /// 2. Ordered. For a vector with N elements this involves performing N
1667 /// operations in lane order, starting with an initial scalar value, i.e.
1668 /// result = InitVal + v0
1669 /// result = result + v1
1670 /// result = result + v2
1671 /// result = result + v3
1672 /// This is only the case for FP operations and when reassociation is not
1673 /// allowed.
1674 ///
1676 unsigned Opcode, VectorType *Ty, std::optional<FastMathFlags> FMF,
1678
1682
1683 /// Calculate the cost of an extended reduction pattern, similar to
1684 /// getArithmeticReductionCost of an Add/Sub reduction with multiply and
1685 /// optional extensions. This is the cost of as:
1686 /// * ResTy vecreduce.add/sub(mul (A, B)) or,
1687 /// * ResTy vecreduce.add/sub(mul(ext(Ty A), ext(Ty B)).
1689 bool IsUnsigned, unsigned RedOpcode, Type *ResTy, VectorType *Ty,
1691
1692 /// Calculate the cost of an extended reduction pattern, similar to
1693 /// getArithmeticReductionCost of a reduction with an extension.
1694 /// This is the cost of as:
1695 /// ResTy vecreduce.opcode(ext(Ty A)).
1697 unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty,
1698 std::optional<FastMathFlags> FMF,
1700
1701 /// \returns The cost of Intrinsic instructions. Analyses the real arguments.
1702 /// Three cases are handled: 1. scalar instruction 2. vector instruction
1703 /// 3. scalar instruction which is to be vectorized.
1706
1707 /// \returns The cost of Call instructions.
1709 Function *F, Type *RetTy, ArrayRef<Type *> Tys,
1711
1712 /// \returns The number of pieces into which the provided type must be
1713 /// split during legalization. Zero is returned when the answer is unknown.
1714 LLVM_ABI unsigned getNumberOfParts(Type *Tp) const;
1715
1716 /// \returns The cost of the address computation. For most targets this can be
1717 /// merged into the instruction indexing mode. Some targets might want to
1718 /// distinguish between address computation for memory operations with vector
1719 /// pointer types and scalar pointer types. Such targets should override this
1720 /// function. \p SE holds the pointer for the scalar evolution object which
1721 /// was used in order to get the Ptr step value. \p Ptr holds the SCEV of the
1722 /// access pointer.
1724 getAddressComputationCost(Type *PtrTy, ScalarEvolution *SE, const SCEV *Ptr,
1726
1727 /// \returns The cost, if any, of keeping values of the given types alive
1728 /// over a callsite.
1729 ///
1730 /// Some types may require the use of register classes that do not have
1731 /// any callee-saved registers, so would require a spill and fill.
1734
1735 /// \returns True if the intrinsic is a supported memory intrinsic. Info
1736 /// will contain additional information - whether the intrinsic may write
1737 /// or read to memory, volatility and the pointer. Info is undefined
1738 /// if false is returned.
1740 MemIntrinsicInfo &Info) const;
1741
1742 /// \returns The maximum element size, in bytes, for an element
1743 /// unordered-atomic memory intrinsic.
1745
1746 /// \returns A value which is the result of the given memory intrinsic. If \p
1747 /// CanCreate is true, new instructions may be created to extract the result
1748 /// from the given intrinsic memory operation. Returns nullptr if the target
1749 /// cannot create a result from the given intrinsic.
1750 LLVM_ABI Value *
1752 bool CanCreate = true) const;
1753
1754 /// \returns The type to use in a loop expansion of a memcpy call.
1756 LLVMContext &Context, Value *Length, unsigned SrcAddrSpace,
1757 unsigned DestAddrSpace, Align SrcAlign, Align DestAlign,
1758 std::optional<uint32_t> AtomicElementSize = std::nullopt) const;
1759
1760 /// \param[out] OpsOut The operand types to copy RemainingBytes of memory.
1761 /// \param RemainingBytes The number of bytes to copy.
1762 ///
1763 /// Calculates the operand types to use when copying \p RemainingBytes of
1764 /// memory, where source and destination alignments are \p SrcAlign and
1765 /// \p DestAlign respectively.
1767 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
1768 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
1769 Align SrcAlign, Align DestAlign,
1770 std::optional<uint32_t> AtomicCpySize = std::nullopt) const;
1771
1772 /// \returns True if the two functions have compatible attributes for inlining
1773 /// purposes.
1774 LLVM_ABI bool areInlineCompatible(const Function *Caller,
1775 const Function *Callee) const;
1776
1777 /// Returns a penalty for invoking call \p Call in \p F.
1778 /// For example, if a function F calls a function G, which in turn calls
1779 /// function H, then getInlineCallPenalty(F, H()) would return the
1780 /// penalty of calling H from F, e.g. after inlining G into F.
1781 /// \p DefaultCallPenalty is passed to give a default penalty that
1782 /// the target can amend or override.
1783 LLVM_ABI unsigned getInlineCallPenalty(const Function *F,
1784 const CallBase &Call,
1785 unsigned DefaultCallPenalty) const;
1786
1787 /// \returns True if the caller and callee agree on how \p Types will be
1788 /// passed to or returned from the callee.
1789 /// to the callee.
1790 /// \param Types List of types to check.
1791 LLVM_ABI bool areTypesABICompatible(const Function *Caller,
1792 const Function *Callee,
1793 ArrayRef<Type *> Types) const;
1794
1795 /// The type of load/store indexing.
1797 MIM_Unindexed, ///< No indexing.
1798 MIM_PreInc, ///< Pre-incrementing.
1799 MIM_PreDec, ///< Pre-decrementing.
1800 MIM_PostInc, ///< Post-incrementing.
1801 MIM_PostDec ///< Post-decrementing.
1802 };
1803
1804 /// \returns True if the specified indexed load for the given type is legal.
1805 LLVM_ABI bool isIndexedLoadLegal(enum MemIndexedMode Mode, Type *Ty) const;
1806
1807 /// \returns True if the specified indexed store for the given type is legal.
1808 LLVM_ABI bool isIndexedStoreLegal(enum MemIndexedMode Mode, Type *Ty) const;
1809
1810 /// \returns The bitwidth of the largest vector type that should be used to
1811 /// load/store in the given address space.
1812 LLVM_ABI unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const;
1813
1814 /// \returns True if the load instruction is legal to vectorize.
1816
1817 /// \returns True if the store instruction is legal to vectorize.
1819
1820 /// \returns True if it is legal to vectorize the given load chain.
1821 LLVM_ABI bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1822 Align Alignment,
1823 unsigned AddrSpace) const;
1824
1825 /// \returns True if it is legal to vectorize the given store chain.
1826 LLVM_ABI bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1827 Align Alignment,
1828 unsigned AddrSpace) const;
1829
1830 /// \returns True if it is legal to vectorize the given reduction kind.
1832 ElementCount VF) const;
1833
1834 /// \returns True if the given type is supported for scalable vectors
1836
1837 /// \returns The new vector factor value if the target doesn't support \p
1838 /// SizeInBytes loads or has a better vector factor.
1839 LLVM_ABI unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
1840 unsigned ChainSizeInBytes,
1841 VectorType *VecTy) const;
1842
1843 /// \returns The new vector factor value if the target doesn't support \p
1844 /// SizeInBytes stores or has a better vector factor.
1845 LLVM_ABI unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
1846 unsigned ChainSizeInBytes,
1847 VectorType *VecTy) const;
1848
1849 /// \returns True if the target prefers fixed width vectorization if the
1850 /// loop vectorizer's cost-model assigns an equal cost to the fixed and
1851 /// scalable version of the vectorized loop.
1852 /// \p IsEpilogue is true if the decision is for the epilogue loop.
1853 LLVM_ABI bool preferFixedOverScalableIfEqualCost(bool IsEpilogue) const;
1854
1855 /// \returns True if target prefers SLP vectorizer with altermate opcode
1856 /// vectorization, false - otherwise.
1858
1859 /// \returns True if the target prefers reductions of \p Kind to be performed
1860 /// in the loop.
1861 LLVM_ABI bool preferInLoopReduction(RecurKind Kind, Type *Ty) const;
1862
1863 /// \returns True if the target prefers reductions select kept in the loop
1864 /// when tail folding. i.e.
1865 /// loop:
1866 /// p = phi (0, s)
1867 /// a = add (p, x)
1868 /// s = select (mask, a, p)
1869 /// vecreduce.add(s)
1870 ///
1871 /// As opposed to the normal scheme of p = phi (0, a) which allows the select
1872 /// to be pulled out of the loop. If the select(.., add, ..) can be predicated
1873 /// by the target, this can lead to cleaner code generation.
1875
1876 /// Return true if the loop vectorizer should consider vectorizing an
1877 /// otherwise scalar epilogue loop.
1879
1880 /// \returns True if the loop vectorizer should discard any VFs where the
1881 /// maximum register pressure exceeds getNumberOfRegisters.
1883
1884 /// \returns True if the target wants to expand the given reduction intrinsic
1885 /// into a shuffle sequence.
1887
1889
1890 /// \returns The shuffle sequence pattern used to expand the given reduction
1891 /// intrinsic.
1894
1895 /// \returns the size cost of rematerializing a GlobalValue address relative
1896 /// to a stack reload.
1897 LLVM_ABI unsigned getGISelRematGlobalCost() const;
1898
1899 /// \returns the lower bound of a trip count to decide on vectorization
1900 /// while tail-folding.
1902
1903 /// \returns True if the target supports scalable vectors.
1904 LLVM_ABI bool supportsScalableVectors() const;
1905
1906 /// \return true when scalable vectorization is preferred.
1908
1909 /// \name Vector Predication Information
1910 /// @{
1911 /// Whether the target supports the %evl parameter of VP intrinsic efficiently
1912 /// in hardware. (see LLVM Language Reference - "Vector Predication
1913 /// Intrinsics"). Use of %evl is discouraged when that is not the case.
1914 LLVM_ABI bool hasActiveVectorLength() const;
1915
1916 /// Return true if sinking I's operands to the same basic block as I is
1917 /// profitable, e.g. because the operands can be folded into a target
1918 /// instruction during instruction selection. After calling the function
1919 /// \p Ops contains the Uses to sink ordered by dominance (dominating users
1920 /// come first).
1923
1924 /// Return true if it's significantly cheaper to shift a vector by a uniform
1925 /// scalar than by an amount which will vary across each lane. On x86 before
1926 /// AVX2 for example, there is a "psllw" instruction for the former case, but
1927 /// no simple instruction for a general "a << b" operation on vectors.
1928 /// This should also apply to lowering for vector funnel shifts (rotates).
1930
1933 // keep the predicating parameter
1935 // where legal, discard the predicate parameter
1937 // transform into something else that is also predicating
1939 };
1940
1941 // How to transform the EVL parameter.
1942 // Legal: keep the EVL parameter as it is.
1943 // Discard: Ignore the EVL parameter where it is safe to do so.
1944 // Convert: Fold the EVL into the mask parameter.
1946
1947 // How to transform the operator.
1948 // Legal: The target supports this operator.
1949 // Convert: Convert this to a non-VP operation.
1950 // The 'Discard' strategy is invalid.
1952
1953 bool shouldDoNothing() const {
1954 return (EVLParamStrategy == Legal) && (OpStrategy == Legal);
1955 }
1958 };
1959
1960 /// \returns How the target needs this vector-predicated operation to be
1961 /// transformed.
1963 getVPLegalizationStrategy(const VPIntrinsic &PI) const;
1964 /// @}
1965
1966 /// \returns Whether a 32-bit branch instruction is available in Arm or Thumb
1967 /// state.
1968 ///
1969 /// Used by the LowerTypeTests pass, which constructs an IR inline assembler
1970 /// node containing a jump table in a format suitable for the target, so it
1971 /// needs to know what format of jump table it can legally use.
1972 ///
1973 /// For non-Arm targets, this function isn't used. It defaults to returning
1974 /// false, but it shouldn't matter what it returns anyway.
1975 LLVM_ABI bool hasArmWideBranch(bool Thumb) const;
1976
1977 /// Returns a bitmask constructed from the target-features or fmv-features
1978 /// metadata of a function.
1979 LLVM_ABI APInt getFeatureMask(const Function &F) const;
1980
1981 /// Returns true if this is an instance of a function with multiple versions.
1982 LLVM_ABI bool isMultiversionedFunction(const Function &F) const;
1983
1984 /// \return The maximum number of function arguments the target supports.
1985 LLVM_ABI unsigned getMaxNumArgs() const;
1986
1987 /// \return For an array of given Size, return alignment boundary to
1988 /// pad to. Default is no padding.
1989 LLVM_ABI unsigned getNumBytesToPadGlobalArray(unsigned Size,
1990 Type *ArrayType) const;
1991
1992 /// @}
1993
1994 /// Collect kernel launch bounds for \p F into \p LB.
1996 const Function &F,
1997 SmallVectorImpl<std::pair<StringRef, int64_t>> &LB) const;
1998
1999 /// Returns true if GEP should not be used to index into vectors for this
2000 /// target.
2002
2003private:
2004 std::unique_ptr<const TargetTransformInfoImplBase> TTIImpl;
2005};
2006
2007/// Analysis pass providing the \c TargetTransformInfo.
2008///
2009/// The core idea of the TargetIRAnalysis is to expose an interface through
2010/// which LLVM targets can analyze and provide information about the middle
2011/// end's target-independent IR. This supports use cases such as target-aware
2012/// cost modeling of IR constructs.
2013///
2014/// This is a function analysis because much of the cost modeling for targets
2015/// is done in a subtarget specific way and LLVM supports compiling different
2016/// functions targeting different subtargets in order to support runtime
2017/// dispatch according to the observed subtarget.
2018class TargetIRAnalysis : public AnalysisInfoMixin<TargetIRAnalysis> {
2019public:
2021
2022 /// Default construct a target IR analysis.
2023 ///
2024 /// This will use the module's datalayout to construct a baseline
2025 /// conservative TTI result.
2027
2028 /// Construct an IR analysis pass around a target-provide callback.
2029 ///
2030 /// The callback will be called with a particular function for which the TTI
2031 /// is needed and must return a TTI object for that function.
2032 LLVM_ABI
2033 TargetIRAnalysis(std::function<Result(const Function &)> TTICallback);
2034
2035 // Value semantics. We spell out the constructors for MSVC.
2037 : TTICallback(Arg.TTICallback) {}
2039 : TTICallback(std::move(Arg.TTICallback)) {}
2041 TTICallback = RHS.TTICallback;
2042 return *this;
2043 }
2045 TTICallback = std::move(RHS.TTICallback);
2046 return *this;
2047 }
2048
2050
2051private:
2053 LLVM_ABI static AnalysisKey Key;
2054
2055 /// The callback used to produce a result.
2056 ///
2057 /// We use a completely opaque callback so that targets can provide whatever
2058 /// mechanism they desire for constructing the TTI for a given function.
2059 ///
2060 /// FIXME: Should we really use std::function? It's relatively inefficient.
2061 /// It might be possible to arrange for even stateful callbacks to outlive
2062 /// the analysis and thus use a function_ref which would be lighter weight.
2063 /// This may also be less error prone as the callback is likely to reference
2064 /// the external TargetMachine, and that reference needs to never dangle.
2065 std::function<Result(const Function &)> TTICallback;
2066
2067 /// Helper function used as the callback in the default constructor.
2068 static Result getDefaultTTI(const Function &F);
2069};
2070
2071/// Wrapper pass for TargetTransformInfo.
2072///
2073/// This pass can be constructed from a TTI object which it stores internally
2074/// and is queried by passes.
2076 TargetIRAnalysis TIRA;
2077 std::optional<TargetTransformInfo> TTI;
2078
2079 virtual void anchor();
2080
2081public:
2082 static char ID;
2083
2084 /// We must provide a default constructor for the pass but it should
2085 /// never be used.
2086 ///
2087 /// Use the constructor below or call one of the creation routines.
2089
2091
2093};
2094
2095/// Create an analysis pass wrapper around a TTI object.
2096///
2097/// This analysis pass just holds the TTI instance and makes it available to
2098/// clients.
2101
2102} // namespace llvm
2103
2104#endif
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
Analysis containing CSE Info
Definition CSEInfo.cpp:27
#define LLVM_ABI
Definition Compiler.h:213
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
TargetTransformInfo::VPLegalization VPLegalization
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 header defines various interfaces for pass management in LLVM.
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
Value * RHS
Class for arbitrary precision integers.
Definition APInt.h:78
an instruction to allocate memory on the stack
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Class to represent array types.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
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...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:164
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:22
ImmutablePass class - This class is used to provide information that does not need to be run.
Definition Pass.h:285
ImmutablePass(char &pid)
Definition Pass.h:287
The core instruction combiner logic.
static InstructionCost getInvalid(CostType Val=0)
Class to represent integer types.
Drive the analysis of interleaved memory accesses in the loop.
const TargetLibraryInfo * getLibInfo() const
const SmallVectorImpl< Type * > & getArgTypes() const
const SmallVectorImpl< const Value * > & getArgs() const
LLVM_ABI IntrinsicCostAttributes(Intrinsic::ID Id, const CallBase &CI, InstructionCost ScalarCost=InstructionCost::getInvalid(), bool TypeBasedOnly=false, TargetLibraryInfo const *LibInfo=nullptr)
InstructionCost getScalarizationCost() const
const IntrinsicInst * getInst() const
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
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:40
LLVM_ABI MemIntrinsicCostAttributes(Intrinsic::ID Id, Type *DataTy, Align Alignment, unsigned AddressSpace)
The optimization diagnostic interface.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
Analysis providing profile information.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
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...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:30
An instruction for storing to memory.
Multiway switch.
Analysis pass providing the TargetTransformInfo.
TargetIRAnalysis(const TargetIRAnalysis &Arg)
TargetIRAnalysis & operator=(const TargetIRAnalysis &RHS)
LLVM_ABI Result run(const Function &F, FunctionAnalysisManager &)
LLVM_ABI 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.
Base class for use as a mix-in that aids implementing a TargetTransformInfo-compatible class.
TargetTransformInfoWrapperPass()
We must provide a default constructor for the pass but it should never be used.
TargetTransformInfo & getTTI(const Function &F)
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const
LLVM_ABI Value * getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst, Type *ExpectedType, bool CanCreate=true) const
LLVM_ABI bool isLegalToVectorizeLoad(LoadInst *LI) const
LLVM_ABI std::optional< unsigned > getVScaleForTuning() const
static LLVM_ABI CastContextHint getCastContextHint(const Instruction *I)
Calculates a CastContextHint from I.
LLVM_ABI unsigned getMaxNumArgs() const
LLVM_ABI bool addrspacesMayAlias(unsigned AS0, unsigned AS1) const
Return false if a AS0 address cannot possibly alias a AS1 address.
LLVM_ABI bool isLegalMaskedScatter(Type *DataType, Align Alignment) const
Return true if the target supports masked scatter.
LLVM_ABI InstructionCost getStridedMemoryOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask, Align Alignment, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
LLVM_ABI bool shouldBuildLookupTables() const
Return true if switches should be turned into lookup tables for the target.
LLVM_ABI bool isLegalToVectorizeStore(StoreInst *SI) const
LLVM_ABI InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, const Value *Op0=nullptr, const Value *Op1=nullptr) const
LLVM_ABI InstructionCost getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode, 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/...
LLVM_ABI bool areTypesABICompatible(const Function *Caller, const Function *Callee, ArrayRef< Type * > Types) const
LLVM_ABI bool enableAggressiveInterleaving(bool LoopHasReductions) const
Don't restrict interleaved unrolling to small loops.
LLVM_ABI InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}) const
Estimate the overhead of scalarizing an instruction.
LLVM_ABI bool isLegalMaskedLoad(Type *DataType, Align Alignment, unsigned AddressSpace) const
Return true if the target supports masked load.
LLVM_ABI bool isMultiversionedFunction(const Function &F) const
Returns true if this is an instance of a function with multiple versions.
LLVM_ABI 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...
LLVM_ABI bool supportsEfficientVectorElementLoadStore() const
If target has efficient vector element load/store instructions, it can return true here so that inser...
LLVM_ABI bool isAlwaysUniform(const Value *V) const
LLVM_ABI unsigned getAssumedAddrSpace(const Value *V) const
LLVM_ABI bool preferAlternateOpcodeVectorization() const
LLVM_ABI bool shouldDropLSRSolutionIfLessProfitable() const
Return true if LSR should drop a found solution if it's calculated to be less profitable than the bas...
LLVM_ABI bool isLSRCostLess(const TargetTransformInfo::LSRCost &C1, const TargetTransformInfo::LSRCost &C2) const
Return true if LSR cost of C1 is lower than C2.
LLVM_ABI unsigned getPrefetchDistance() const
LLVM_ABI Type * getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length, unsigned SrcAddrSpace, unsigned DestAddrSpace, Align SrcAlign, Align DestAlign, std::optional< uint32_t > AtomicElementSize=std::nullopt) const
LLVM_ABI bool isLegalMaskedExpandLoad(Type *DataType, Align Alignment) const
Return true if the target supports masked expand load.
LLVM_ABI bool prefersVectorizedAddressing() const
Return true if target doesn't mind addresses in vectors.
LLVM_ABI InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, OperandValueInfo Op1Info={OK_AnyValue, OP_None}, OperandValueInfo Op2Info={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
LLVM_ABI bool hasBranchDivergence(const Function *F=nullptr) const
Return true if branch divergence exists.
LLVM_ABI MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const
bool invalidate(Function &, const PreservedAnalyses &, FunctionAnalysisManager::Invalidator &)
Handle the invalidation of this information.
LLVM_ABI void getUnrollingPreferences(Loop *L, ScalarEvolution &, UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE) const
Get target-customized preferences for the generic loop unrolling transformation.
LLVM_ABI bool shouldBuildLookupTablesForConstant(Constant *C) const
Return true if switches should be turned into lookup tables containing this constant value for the ta...
LLVM_ABI bool supportsTailCallFor(const CallBase *CB) const
If target supports tail call on CB.
LLVM_ABI std::optional< Instruction * > instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const
Targets can implement their own combinations for target-specific intrinsics.
LLVM_ABI bool isProfitableLSRChainElement(Instruction *I) const
LLVM_ABI TypeSize getRegisterBitWidth(RegisterKind K) const
LLVM_ABI unsigned getInlineCallPenalty(const Function *F, const CallBase &Call, unsigned DefaultCallPenalty) const
Returns a penalty for invoking call Call in F.
LLVM_ABI bool hasActiveVectorLength() const
LLVM_ABI 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...
LLVM_ABI bool preferFixedOverScalableIfEqualCost(bool IsEpilogue) const
LLVM_ABI bool isLegalMaskedGather(Type *DataType, Align Alignment) const
Return true if the target supports masked gather.
LLVM_ABI 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
LLVM_ABI std::optional< unsigned > getMaxVScale() const
LLVM_ABI InstructionCost getReplicationShuffleCost(Type *EltTy, int ReplicationFactor, int VF, const APInt &DemandedDstElts, TTI::TargetCostKind CostKind) const
LLVM_ABI bool allowVectorElementIndexingUsingGEP() const
Returns true if GEP should not be used to index into vectors for this target.
LLVM_ABI 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
LLVM_ABI bool isSingleThreaded() const
LLVM_ABI 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.
LLVM_ABI 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...
LLVM_ABI unsigned getInliningCostBenefitAnalysisProfitableMultiplier() const
LLVM_ABI InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, ArrayRef< int > Mask={}, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr) const
LLVM_ABI InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
LLVM_ABI InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of vector reduction intrinsics.
LLVM_ABI unsigned getAtomicMemIntrinsicMaxElementSize() const
LLVM_ABI InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
LLVM_ABI bool LSRWithInstrQueries() const
Return true if the loop strength reduce pass should make Instruction* based TTI queries to isLegalAdd...
LLVM_ABI unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize, unsigned ChainSizeInBytes, VectorType *VecTy) const
LLVM_ABI VPLegalization getVPLegalizationStrategy(const VPIntrinsic &PI) const
static LLVM_ABI PartialReductionExtendKind getPartialReductionExtendKind(Instruction *I)
Get the kind of extension that an instruction represents.
LLVM_ABI bool shouldConsiderVectorizationRegPressure() const
LLVM_ABI bool enableWritePrefetching() const
LLVM_ABI bool shouldTreatInstructionLikeSelect(const Instruction *I) const
Should the Select Optimization pass treat the given instruction like a select, potentially converting...
LLVM_ABI bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const
LLVM_ABI bool shouldMaximizeVectorBandwidth(TargetTransformInfo::RegisterKind K) const
LLVM_ABI TailFoldingStyle getPreferredTailFoldingStyle(bool IVUpdateMayOverflow=true) const
Query the target what the preferred style of tail folding is.
LLVM_ABI 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.
LLVM_ABI bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const
LLVM_ABI bool isLegalInterleavedAccessType(VectorType *VTy, unsigned Factor, Align Alignment, unsigned AddrSpace) const
Return true is the target supports interleaved access for the given vector type VTy,...
LLVM_ABI unsigned getRegUsageForType(Type *Ty) const
Returns the estimated number of registers required to represent Ty.
LLVM_ABI bool isLegalBroadcastLoad(Type *ElementTy, ElementCount NumElements) const
\Returns true if the target supports broadcasting a load to a vector of type <NumElements x ElementTy...
LLVM_ABI bool isIndexedStoreLegal(enum MemIndexedMode Mode, Type *Ty) const
LLVM_ABI std::pair< const Value *, unsigned > getPredicatedAddrSpace(const Value *V) const
LLVM_ABI InstructionCost getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of an extended reduction pattern, similar to getArithmeticReductionCost of a reduc...
LLVM_ABI unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const
LLVM_ABI ReductionShuffle getPreferredExpandedReductionShuffle(const IntrinsicInst *II) const
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
LLVM_ABI unsigned getRegisterClassForType(bool Vector, Type *Ty=nullptr) const
LLVM_ABI 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...
LLVM_ABI PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const
Return hardware support for population count.
LLVM_ABI unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) const
LLVM_ABI bool isElementTypeLegalForScalableVector(Type *Ty) const
LLVM_ABI bool forceScalarizeMaskedGather(VectorType *Type, Align Alignment) const
Return true if the target forces scalarizing of llvm.masked.gather intrinsics.
LLVM_ABI unsigned getMaxPrefetchIterationsAhead() const
LLVM_ABI bool canHaveNonUndefGlobalInitializerInAddressSpace(unsigned AS) const
Return true if globals in this address space can have initializers other than undef.
LLVM_ABI ElementCount getMinimumVF(unsigned ElemWidth, bool IsScalable) const
LLVM_ABI InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, const APInt &Imm, Type *Ty, TargetCostKind CostKind) const
LLVM_ABI bool enableMaskedInterleavedAccessVectorization() const
Enable matching of interleaved access groups that contain predicated accesses or gaps and therefore v...
LLVM_ABI 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...
LLVM_ABI bool isLegalStridedLoadStore(Type *DataType, Align Alignment) const
Return true if the target supports strided load.
LLVM_ABI TargetTransformInfo & operator=(TargetTransformInfo &&RHS)
LLVM_ABI 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.
LLVM_ABI 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={}, const Instruction *CxtI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
LLVM_ABI bool enableSelectOptimize() const
Should the Select Optimization pass be enabled and ran.
LLVM_ABI 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.
LLVM_ABI int getInliningLastCallToStaticBonus() const
LLVM_ABI 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...
LLVM_ABI bool isVScaleKnownToBeAPowerOfTwo() const
LLVM_ABI bool isIndexedLoadLegal(enum MemIndexedMode Mode, Type *Ty) const
LLVM_ABI unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const
LLVM_ABI bool isSourceOfDivergence(const Value *V) const
Returns whether V is a source of divergence.
LLVM_ABI bool isLegalICmpImmediate(int64_t Imm) const
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
LLVM_ABI 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...
LLVM_ABI bool isLegalToVectorizeReduction(const RecurrenceDescriptor &RdxDesc, ElementCount VF) const
LLVM_ABI std::optional< unsigned > getCacheAssociativity(CacheLevel Level) const
LLVM_ABI bool isLegalNTLoad(Type *DataType, Align Alignment) const
Return true if the target supports nontemporal load.
LLVM_ABI InstructionCost getMemcpyCost(const Instruction *I) const
LLVM_ABI unsigned adjustInliningThreshold(const CallBase *CB) const
LLVM_ABI bool isLegalAddImmediate(int64_t Imm) const
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
LLVM_ABI bool isTargetIntrinsicWithStructReturnOverloadAtField(Intrinsic::ID ID, int RetIdx) const
Identifies if the vector form of the intrinsic that returns a struct is overloaded at the struct elem...
LLVM_ABI unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize, unsigned ChainSizeInBytes, VectorType *VecTy) const
LLVM_ABI 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...
LLVM_ABI bool isTargetIntrinsicTriviallyScalarizable(Intrinsic::ID ID) const
LLVM_ABI 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...
LLVM_ABI InstructionCost getCostOfKeepingLiveOverCall(ArrayRef< Type * > Tys) const
LLVM_ABI unsigned getMinPrefetchStride(unsigned NumMemAccesses, unsigned NumStridedMemAccesses, unsigned NumPrefetches, bool HasCall) const
Some HW prefetchers can handle accesses up to a certain constant stride.
LLVM_ABI bool shouldPrefetchAddressSpace(unsigned AS) const
LLVM_ABI 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.
LLVM_ABI unsigned getMinVectorRegisterBitWidth() const
LLVM_ABI InstructionCost getAddressComputationCost(Type *PtrTy, ScalarEvolution *SE, const SCEV *Ptr, TTI::TargetCostKind CostKind) const
LLVM_ABI bool isLegalNTStore(Type *DataType, Align Alignment) const
Return true if the target supports nontemporal store.
LLVM_ABI InstructionCost getPartialReductionCost(unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType, ElementCount VF, PartialReductionExtendKind OpAExtend, PartialReductionExtendKind OpBExtend, std::optional< unsigned > BinOp, TTI::TargetCostKind CostKind) const
LLVM_ABI unsigned getFlatAddressSpace() const
Returns the address space ID for a target's 'flat' address space.
LLVM_ABI 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.
LLVM_ABI bool hasArmWideBranch(bool Thumb) const
LLVM_ABI const char * getRegisterClassName(unsigned ClassID) const
LLVM_ABI bool preferEpilogueVectorization() const
Return true if the loop vectorizer should consider vectorizing an otherwise scalar epilogue loop.
LLVM_ABI bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const
LLVM_ABI BranchProbability getPredictableBranchThreshold() const
If a branch or a select condition is skewed in one direction by more than this factor,...
LLVM_ABI TargetTransformInfo(std::unique_ptr< const TargetTransformInfoImplBase > Impl)
Construct a TTI object using a type implementing the Concept API below.
LLVM_ABI bool preferInLoopReduction(RecurKind Kind, Type *Ty) const
LLVM_ABI unsigned getCallerAllocaCost(const CallBase *CB, const AllocaInst *AI) const
LLVM_ABI bool hasConditionalLoadStoreForType(Type *Ty, bool IsStore) const
LLVM_ABI unsigned getCacheLineSize() const
LLVM_ABI InstructionCost getMaskedMemoryOpCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
LLVM_ABI 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.
LLVM_ABI InstructionCost getGatherScatterOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask, Align Alignment, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
LLVM_ABI int getInlinerVectorBonusPercent() const
LLVM_ABI unsigned getEpilogueVectorizationMinVF() const
LLVM_ABI void collectKernelLaunchBounds(const Function &F, SmallVectorImpl< std::pair< StringRef, int64_t > > &LB) const
Collect kernel launch bounds for F into LB.
PopcntSupportKind
Flags indicating the kind of support for population count.
LLVM_ABI bool preferPredicatedReductionSelect() const
LLVM_ABI InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm, Type *Ty) const
Return the expected cost for the given integer when optimising for size.
LLVM_ABI AddressingModeKind getPreferredAddressingMode(const Loop *L, ScalarEvolution *SE) const
Return the preferred addressing mode LSR should make efforts to generate.
LLVM_ABI bool isLoweredToCall(const Function *F) const
Test whether calls to a function lower to actual program function calls.
LLVM_ABI bool isLegalMaskedStore(Type *DataType, Align Alignment, unsigned AddressSpace) const
Return true if the target supports masked store.
LLVM_ABI bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const
LLVM_ABI 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.
LLVM_ABI unsigned getInliningThresholdMultiplier() const
LLVM_ABI InstructionCost getBranchMispredictPenalty() const
Returns estimated penalty of a branch misprediction in latency.
LLVM_ABI unsigned getNumberOfRegisters(unsigned ClassID) const
LLVM_ABI 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...
LLVM_ABI bool isProfitableToHoist(Instruction *I) const
Return true if it is profitable to hoist instruction in the then/else to before if.
LLVM_ABI bool supportsScalableVectors() const
LLVM_ABI bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) const
Return true if the given instruction (assumed to be a memory access instruction) has a volatile varia...
LLVM_ABI bool isLegalMaskedCompressStore(Type *DataType, Align Alignment) const
Return true if the target supports masked compress store.
LLVM_ABI std::optional< unsigned > getMinPageSize() const
LLVM_ABI bool isFPVectorizationPotentiallyUnsafe() const
Indicate that it is potentially unsafe to automatically vectorize floating-point operations because t...
LLVM_ABI InstructionCost getInsertExtractValueCost(unsigned Opcode, TTI::TargetCostKind CostKind) const
LLVM_ABI bool shouldBuildRelLookupTables() const
Return true if lookup tables should be turned into relative lookup tables.
LLVM_ABI unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy, Type *ScalarValTy) const
LLVM_ABI std::optional< unsigned > getCacheSize(CacheLevel Level) const
LLVM_ABI std::optional< Value * > simplifyDemandedUseBitsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed) const
Can be used to implement target-specific instruction combining.
LLVM_ABI bool isLegalAddScalableImmediate(int64_t Imm) const
Return true if adding the specified scalable immediate is legal, that is the target has add instructi...
LLVM_ABI bool isTargetIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx) const
Identifies if the vector form of the intrinsic has a scalar operand.
LLVM_ABI bool hasDivRemOp(Type *DataType, bool IsSigned) const
Return true if the target has a unified operation to calculate division and remainder.
LLVM_ABI 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.
LLVM_ABI bool enableInterleavedAccessVectorization() const
Enable matching of interleaved access groups.
LLVM_ABI unsigned getMinTripCountTailFoldingThreshold() const
LLVM_ABI InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
LLVM_ABI unsigned getMaxInterleaveFactor(ElementCount VF) const
LLVM_ABI bool enableScalableVectorization() const
LLVM_ABI bool isVectorShiftByScalarCheap(Type *Ty) const
Return true if it's significantly cheaper to shift a vector by a uniform scalar than by an amount whi...
LLVM_ABI bool isNumRegsMajorCostOfLSR() const
Return true if LSR major cost is number of registers.
LLVM_ABI unsigned getInliningCostBenefitAnalysisSavingsMultiplier() const
LLVM_ABI bool isLegalMaskedVectorHistogram(Type *AddrType, Type *DataType) const
LLVM_ABI InstructionCost getExpandCompressMemoryOpCost(unsigned Opcode, Type *DataTy, bool VariableMask, Align Alignment, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
LLVM_ABI unsigned getGISelRematGlobalCost() const
LLVM_ABI unsigned getNumBytesToPadGlobalArray(unsigned Size, Type *ArrayType) const
MemIndexedMode
The type of load/store indexing.
LLVM_ABI InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index) const
LLVM_ABI bool areInlineCompatible(const Function *Caller, const Function *Callee) const
LLVM_ABI bool useColdCCForColdCall(Function &F) const
Return true if the input function which is cold at all call sites, should use coldcc calling conventi...
LLVM_ABI InstructionCost getFPOpCost(Type *Ty) const
Return the expected cost of supporting the floating point operation of the specified type.
LLVM_ABI bool supportsTailCalls() const
If the target supports tail calls.
LLVM_ABI bool canMacroFuseCmp() const
Return true if the target can fuse a compare and branch.
LLVM_ABI bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const
Query the target whether the specified address space cast from FromAS to ToAS is valid.
LLVM_ABI unsigned getNumberOfParts(Type *Tp) const
LLVM_ABI InstructionCost getOperandsScalarizationOverhead(ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind) const
Estimate the overhead of scalarizing operands with the given types.
AddressingModeKind
Which addressing mode Loop Strength Reduction will try to generate.
@ AMK_PostIndexed
Prefer post-indexed addressing mode.
@ AMK_All
Consider all addressing modes.
@ AMK_PreIndexed
Prefer pre-indexed addressing mode.
@ AMK_None
Don't prefer any addressing mode.
LLVM_ABI 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,...
LLVM_ABI bool isTruncateFree(Type *Ty1, Type *Ty2) const
Return true if it's free to truncate a value of type Ty1 to type Ty2.
LLVM_ABI bool isProfitableToSinkOperands(Instruction *I, SmallVectorImpl< Use * > &Ops) const
Return true if sinking I's operands to the same basic block as I is profitable, e....
LLVM_ABI void getMemcpyLoopResidualLoweringType(SmallVectorImpl< Type * > &OpsOut, LLVMContext &Context, unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace, Align SrcAlign, Align DestAlign, std::optional< uint32_t > AtomicCpySize=std::nullopt) const
LLVM_ABI bool preferPredicateOverEpilogue(TailFoldingInfo *TFI) const
Query the target whether it would be prefered to create a predicated vector loop, which can avoid the...
LLVM_ABI bool forceScalarizeMaskedScatter(VectorType *Type, Align Alignment) const
Return true if the target forces scalarizing of llvm.masked.scatter intrinsics.
LLVM_ABI bool isTargetIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID, int OpdIdx) const
Identifies if the vector form of the intrinsic is overloaded on the type of the operand at index OpdI...
LLVM_ABI bool haveFastSqrt(Type *Ty) const
Return true if the hardware has a fast square-root instruction.
LLVM_ABI bool shouldExpandReduction(const IntrinsicInst *II) const
LLVM_ABI uint64_t getMaxMemIntrinsicInlineSizeThreshold() const
Returns the maximum memset / memcpy size in bytes that still makes it profitable to inline the call.
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.
LLVM_ABI APInt getFeatureMask(const Function &F) const
Returns a bitmask constructed from the target-features or fmv-features metadata of a function.
LLVM_ABI void getPeelingPreferences(Loop *L, ScalarEvolution &SE, PeelingPreferences &PP) const
Get target-customized preferences for the generic loop peeling transformation.
LLVM_ABI InstructionCost getCallInstrCost(Function *F, Type *RetTy, ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency) const
LLVM_ABI 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.
LLVM_ABI InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy, unsigned Index, TTI::TargetCostKind CostKind) const
OperandValueKind
Additional information about an operand's possible values.
CacheLevel
The possible cache levels.
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:75
Base class of all SIMD vector types.
CallInst * Call
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ 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
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Length
Definition DWP.cpp:532
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ LLVM_MARK_AS_BITMASK_ENUM
Definition ModRef.h:37
TargetTransformInfo TTI
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
LLVM_ABI ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
RecurKind
These are the kinds of recurrences that we support.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
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:1867
@ 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...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:867
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:29
Attributes of a target dependent hardware loop.
LLVM_ABI bool canAnalyze(LoopInfo &LI)
LLVM_ABI bool isHardwareLoopCandidate(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, bool ForceNestedLoop=false, bool ForceHardwareLoopPHI=false)
Information about a load/store intrinsic defined by the target.
SmallVector< InterestingMemoryOperand, 1 > InterestingOperands
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 PeelLast
Peel off the last PeelCount loop iterations.
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.
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...
bool RuntimeUnrollMultiExit
Allow runtime unrolling multi-exit loops.
unsigned SCEVExpansionBudget
Don't allow runtime unrolling if expanding the trip count takes more than SCEVExpansionBudget.
bool AddAdditionalAccumulators
Allow unrolling to add parallel reduction phis.
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)