LLVM 24.0.0git
TargetLowering.h
Go to the documentation of this file.
1//===- llvm/CodeGen/TargetLowering.h - Target Lowering Info -----*- 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///
9/// \file
10/// This file describes how to lower LLVM code to machine code. This has two
11/// main components:
12///
13/// 1. Which ValueTypes are natively supported by the target.
14/// 2. Which operations are supported for supported ValueTypes.
15/// 3. Cost thresholds for alternative implementations of certain operations.
16///
17/// In addition it has a few other components, like information about FP
18/// immediates.
19///
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_CODEGEN_TARGETLOWERING_H
23#define LLVM_CODEGEN_TARGETLOWERING_H
24
25#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/StringRef.h"
42#include "llvm/IR/Attributes.h"
43#include "llvm/IR/CallingConv.h"
44#include "llvm/IR/DataLayout.h"
46#include "llvm/IR/Function.h"
47#include "llvm/IR/InlineAsm.h"
48#include "llvm/IR/Instruction.h"
51#include "llvm/IR/Type.h"
58#include <algorithm>
59#include <cassert>
60#include <climits>
61#include <cstdint>
62#include <map>
63#include <string>
64#include <utility>
65#include <vector>
66
67namespace llvm {
68
69class AssumptionCache;
70class CCState;
71class CCValAssign;
74class Constant;
75enum class ExceptionHandling : int;
76class FastISel;
78class GlobalValue;
79class Loop;
81class IntrinsicInst;
82class IRBuilderBase;
83struct KnownBits;
84class LLVMContext;
86class MachineFunction;
87class MachineInstr;
89class MachineLoop;
91class MCContext;
92class MCExpr;
93class Module;
96class TargetMachine;
97class MCRegisterClass;
101class Value;
102class VPIntrinsic;
103
104namespace Sched {
105
107 None, // No preference
108 Source, // Follow source order.
109 RegPressure, // Scheduling for lowest register pressure.
110 Hybrid, // Scheduling for both latency and register pressure.
111 ILP, // Scheduling for ILP in low register pressure mode.
112 VLIW, // Scheduling for VLIW targets.
113 Fast, // Fast suboptimal list scheduling
114 Linearize, // Linearize DAG, no scheduling
115 Last = Linearize // Marker for the last Sched::Preference
116};
117
118} // end namespace Sched
119
120// MemOp models a memory operation, either memset or memcpy/memmove.
121struct MemOp {
122private:
123 enum class MemOpKind {
124 Memset,
125 MemsetWithZero, // memset the memory with zeros
126 Memcpy, // copy memory from source to destination, source and destination do
127 // not overlap
128 MemcpyStrSrc, // memcpy source is an in-register constant, so it does not
129 // need to be loaded
130 Memmove, // memmove: like memcpy, but source and destination regions may
131 // overlap
132 };
133
134 // Shared
135 uint64_t Size;
136 bool DstAlignCanChange; // true if destination alignment can satisfy any
137 // constraint.
138 Align DstAlign; // Specified alignment of the memory operation.
139
140 bool IsVolatile;
141 MemOpKind Kind;
142 Align SrcAlign; // Inferred alignment of the source or default value if the
143 // memory operation does not need to load the value.
144public:
145 static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
146 Align SrcAlign, bool IsVolatile,
147 bool MemcpyStrSrc = false) {
148 MemOp Op;
149 Op.Size = Size;
150 Op.DstAlignCanChange = DstAlignCanChange;
151 Op.DstAlign = DstAlign;
152 Op.IsVolatile = IsVolatile;
153 Op.Kind = MemcpyStrSrc ? MemOpKind::MemcpyStrSrc : MemOpKind::Memcpy;
154 Op.SrcAlign = SrcAlign;
155 return Op;
156 }
157
158 static MemOp Move(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
159 Align SrcAlign, bool IsVolatile) {
160 MemOp Op;
161 Op.Size = Size;
162 Op.DstAlignCanChange = DstAlignCanChange;
163 Op.DstAlign = DstAlign;
164 Op.IsVolatile = IsVolatile;
165 Op.Kind = MemOpKind::Memmove;
166 Op.SrcAlign = SrcAlign;
167 return Op;
168 }
169
170 static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
171 bool IsZeroMemset, bool IsVolatile) {
172 MemOp Op;
173 Op.Size = Size;
174 Op.DstAlignCanChange = DstAlignCanChange;
175 Op.DstAlign = DstAlign;
176 Op.IsVolatile = IsVolatile;
177 Op.Kind = IsZeroMemset ? MemOpKind::MemsetWithZero : MemOpKind::Memset;
178 return Op;
179 }
180
181 uint64_t size() const { return Size; }
183 assert(!DstAlignCanChange);
184 return DstAlign;
185 }
186 bool isFixedDstAlign() const { return !DstAlignCanChange; }
187 bool isVolatile() const { return IsVolatile; }
188 bool isMemset() const {
189 return Kind == MemOpKind::Memset || Kind == MemOpKind::MemsetWithZero;
190 }
191 bool isMemcpy() const {
192 return Kind == MemOpKind::Memcpy || Kind == MemOpKind::MemcpyStrSrc;
193 }
194 bool isMemmove() const { return Kind == MemOpKind::Memmove; }
195 bool isMemcpyOrMemmove() const { return isMemcpy() || isMemmove(); }
197 return isMemcpyOrMemmove() && !DstAlignCanChange;
198 }
199 bool isZeroMemset() const { return Kind == MemOpKind::MemsetWithZero; }
200 bool isMemcpyStrSrc() const { return Kind == MemOpKind::MemcpyStrSrc; }
202 assert(isMemcpyOrMemmove() && "Must be a memcpy or memmove");
203 return SrcAlign;
204 }
205 bool isSrcAligned(Align AlignCheck) const {
206 return isMemset() || llvm::isAligned(AlignCheck, SrcAlign.value());
207 }
208 bool isDstAligned(Align AlignCheck) const {
209 return DstAlignCanChange || llvm::isAligned(AlignCheck, DstAlign.value());
210 }
211 bool isAligned(Align AlignCheck) const {
212 return isSrcAligned(AlignCheck) && isDstAligned(AlignCheck);
213 }
214};
215
216/// This base class for TargetLowering contains the SelectionDAG-independent
217/// parts that can be used from the rest of CodeGen.
219public:
220 /// This enum indicates whether operations are valid for a target, and if not,
221 /// what action should be used to make them valid.
223 Legal, // The target natively supports this operation.
224 Promote, // This operation should be executed in a larger type.
225 Expand, // Try to expand this to other ops, otherwise use a libcall.
226 LibCall, // Don't try to expand this to other ops, always use a libcall.
227 Custom // Use the LowerOperation hook to implement custom lowering.
228 };
229
230 /// This enum indicates whether a types are legal for a target, and if not,
231 /// what action should be used to make them valid.
233 TypeLegal, // The target natively supports this type.
234 TypePromoteInteger, // Replace this integer with a larger one.
235 TypeExpandInteger, // Split this integer into two of half the size.
236 TypeSoftenFloat, // Convert this float to a same size integer type.
237 TypeExpandFloat, // Split this float into two of half the size.
238 TypeScalarizeVector, // Replace this one-element vector with its element.
239 TypeSplitVector, // Split this vector into two of half the size.
240 TypeWidenVector, // This vector should be widened into a larger vector.
241 TypeSoftPromoteHalf, // Soften half to i16 and use float to do arithmetic.
242 TypeScalarizeScalableVector, // This action is explicitly left
243 // unimplemented. While it is theoretically
244 // possible to legalize operations on scalable
245 // types with a loop that handles the vscale *
246 // #lanes of the vector, this is non-trivial at
247 // SelectionDAG level and these types are
248 // better to be widened or promoted.
249 };
250
251 /// LegalizeKind holds the legalization kind that needs to happen to EVT
252 /// in order to type-legalize it.
253 using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
254
255 /// Enum that describes how the target represents true/false values.
257 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
258 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
259 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
260 };
261
262 /// Enum that describes what type of support for selects the target has.
264 ScalarValSelect, // The target supports scalar selects (ex: cmov).
265 ScalarCondVectorVal, // The target supports selects with a scalar condition
266 // and vector values (ex: cmov).
267 VectorMaskSelect // The target supports vector selects with a vector
268 // mask (ex: x86 blends).
269 };
270
271 /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
272 /// to, if at all. Exists because different targets have different levels of
273 /// support for these atomic instructions, and also have different options
274 /// w.r.t. what they should expand to.
276 None, // Don't expand the instruction.
277 CastToInteger, // Cast the atomic instruction to another type, e.g. from
278 // floating-point to integer type.
279 LLSC, // Expand the instruction into loadlinked/storeconditional; used
280 // by ARM/AArch64/PowerPC.
281 LLOnly, // Expand the (load) instruction into just a load-linked, which has
282 // greater atomic guarantees than a normal load.
283 CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
284 MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
285 BitTestIntrinsic, // Use a target-specific intrinsic for special bit
286 // operations; used by X86.
287 CmpArithIntrinsic, // Use a target-specific intrinsic for special compare
288 // operations; used by X86.
289 Expand, // Generic expansion in terms of other atomic operations.
290 CustomExpand, // Custom target-specific expansion using TLI hooks.
291
292 // Rewrite to a non-atomic form for use in a known non-preemptible
293 // environment.
295 };
296
297 /// Enum that specifies when a multiplication should be expanded.
298 enum class MulExpansionKind {
299 Always, // Always expand the instruction.
300 OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
301 // or custom.
302 };
303
304 /// Enum that specifies when a float negation is beneficial.
305 enum class NegatibleCost {
306 Cheaper = 0, // Negated expression is cheaper.
307 Neutral = 1, // Negated expression has the same cost.
308 Expensive = 2 // Negated expression is more expensive.
309 };
310
311 /// Enum that specifies how expensive lowering an EXTRACT_SUBVECTOR is.
313 Free = 0, // Lowers to no instruction at all, e.g. a subregister copy.
314 Cheap = 1, // Lowers to at most one instruction, and may still be free if
315 // the target can fold the extract into the instruction
316 // consuming it (e.g. a widening op that reads the high half of
317 // a register).
318 Expensive = 2 // Needs a shuffle sequence that cannot be folded away.
319 };
320
321 /// Enum of different potentially desirable ways to fold (and/or (setcc ...),
322 /// (setcc ...)).
324 None = 0, // No fold is preferable.
325 AddAnd = 1, // Fold with `Add` op and `And` op is preferable.
326 NotAnd = 2, // Fold with `Not` op and `And` op is preferable.
327 ABS = 4, // Fold with `llvm.abs` op is preferable.
328 };
329
331 public:
334 /// Original unlegalized argument type.
336 /// Same as OrigTy, or partially legalized for soft float libcalls.
338 bool IsSExt : 1;
339 bool IsZExt : 1;
340 bool IsNoExt : 1;
341 bool IsInReg : 1;
342 bool IsSRet : 1;
343 bool IsNest : 1;
344 bool IsByVal : 1;
345 bool IsByRef : 1;
346 bool IsInAlloca : 1;
348 bool IsReturned : 1;
349 bool IsSwiftSelf : 1;
350 bool IsSwiftAsync : 1;
351 bool IsSwiftError : 1;
353 MaybeAlign Alignment = std::nullopt;
354 Type *IndirectType = nullptr;
355
362
365
367
368 LLVM_ABI void setAttributes(const CallBase *Call, unsigned ArgIdx);
369 LLVM_ABI void setAttributes(const AttributeList &Attrs, unsigned ArgIdx);
370 };
371 using ArgListTy = std::vector<ArgListEntry>;
372
374 switch (Content) {
376 // Extend by adding rubbish bits.
377 return ISD::ANY_EXTEND;
379 // Extend by adding zero bits.
380 return ISD::ZERO_EXTEND;
382 // Extend by copying the sign bit.
383 return ISD::SIGN_EXTEND;
384 }
385 llvm_unreachable("Invalid content kind");
386 }
387
388 explicit TargetLoweringBase(const TargetMachine &TM,
389 const TargetSubtargetInfo &STI);
393
394 /// Return true if the target support strict float operation
395 bool isStrictFPEnabled() const {
396 return IsStrictFPEnabled;
397 }
398
399protected:
400 /// Initialize all of the actions to default values.
401 void initActions();
402
403public:
404 const TargetMachine &getTargetMachine() const { return TM; }
405
406 virtual bool useSoftFloat() const { return false; }
407
408 /// Return the pointer type for the given address space, defaults to
409 /// the pointer type from the data layout.
410 /// FIXME: The default needs to be removed once all the code is updated.
411 virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
412 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
413 }
414
415 /// Return the in-memory pointer type for the given address space, defaults to
416 /// the pointer type from the data layout.
417 /// FIXME: The default needs to be removed once all the code is updated.
418 virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS = 0) const {
419 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
420 }
421
422 /// Return the type for frame index, which is determined by
423 /// the alloca address space specified through the data layout.
425 return getPointerTy(DL, DL.getAllocaAddrSpace());
426 }
427
428 /// Return the type for code pointers, which is determined by the program
429 /// address space specified through the data layout.
431 return getPointerTy(DL, DL.getProgramAddressSpace());
432 }
433
434 /// Return the type for operands of fence.
435 /// TODO: Let fence operands be of i32 type and remove this.
436 virtual MVT getFenceOperandTy(const DataLayout &DL) const {
437 return getPointerTy(DL);
438 }
439
440 /// Return the type to use for a scalar shift opcode, given the shifted amount
441 /// type. Targets should return a legal type if the input type is legal.
442 /// Targets can return a type that is too small if the input type is illegal.
443 virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
444
445 /// Returns the type for the shift amount of a shift opcode. For vectors,
446 /// returns the input type. For scalars, calls getScalarShiftAmountTy.
447 /// If getScalarShiftAmountTy type cannot represent all possible shift
448 /// amounts, returns MVT::i32.
449 EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const;
450
451 /// Return the preferred type to use for a shift opcode, given the shifted
452 /// amount type is \p ShiftValueTy.
454 virtual LLT getPreferredShiftAmountTy(LLT ShiftValueTy) const {
455 return ShiftValueTy;
456 }
457
458 /// Returns the type to be used for the index operand vector operations. By
459 /// default we assume it will have the same size as an address space 0
460 /// pointer.
461 virtual unsigned getVectorIdxWidth(const DataLayout &DL) const {
462 return DL.getPointerSizeInBits(0);
463 }
464
465 /// Returns the type to be used for the index operand of:
466 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
467 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
471
472 /// Returns the type to be used for the index operand of:
473 /// G_INSERT_VECTOR_ELT, G_EXTRACT_VECTOR_ELT,
474 /// G_INSERT_SUBVECTOR, and G_EXTRACT_SUBVECTOR
477 }
478
479 /// Returns the type to be used for the EVL/AVL operand of VP nodes:
480 /// ISD::VP_UDIV, ISD::VP_SDIV, etc. It must be a legal scalar integer type,
481 /// and must be at least as large as i32. The EVL is implicitly zero-extended
482 /// to any larger type.
483 virtual MVT getVPExplicitVectorLengthTy() const { return MVT::i32; }
484
485 /// This callback is used to inspect load/store instructions and add
486 /// target-specific MachineMemOperand flags to them. The default
487 /// implementation does nothing.
491
492 /// This callback is used to inspect load/store SDNode.
493 /// The default implementation does nothing.
498
499 MachineMemOperand::Flags getLoadMemOperandFlags(
500 const LoadInst &LI, const DataLayout &DL, AssumptionCache *AC = nullptr,
501 const TargetLibraryInfo *LibInfo = nullptr,
503 MachineMemOperand::Flags getStoreMemOperandFlags(const StoreInst &SI,
504 const DataLayout &DL) const;
505 MachineMemOperand::Flags getAtomicMemOperandFlags(const Instruction &AI,
506 const DataLayout &DL) const;
508 getVPIntrinsicMemOperandFlags(const VPIntrinsic &VPIntrin) const;
509
510 virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
511 return true;
512 }
513
514 /// Return true if the @llvm.get.active.lane.mask intrinsic should be expanded
515 /// using generic code in SelectionDAGBuilder.
516 virtual bool shouldExpandGetActiveLaneMask(EVT VT, EVT OpVT) const {
517 return true;
518 }
519
520 virtual bool shouldExpandGetVectorLength(EVT CountVT, unsigned VF,
521 bool IsScalable) const {
522 return true;
523 }
524
525 /// Return the minimum number of bits required to hold the maximum possible
526 /// number of trailing zero vector elements.
527 unsigned getBitWidthForCttzElements(EVT RetVT, ElementCount EC,
528 bool ZeroIsPoison,
529 const ConstantRange *VScaleRange) const;
530
531 // Return true if op(vecreduce(x), vecreduce(y)) should be reassociated to
532 // vecreduce(op(x, y)) for the reduction opcode RedOpc.
533 virtual bool shouldReassociateReduction(unsigned RedOpc, EVT VT) const {
534 return true;
535 }
536
537 /// Return true if it is profitable to convert a select of FP constants into
538 /// a constant pool load whose address depends on the select condition. The
539 /// parameter may be used to differentiate a select with FP compare from
540 /// integer compare.
541 virtual bool reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
542 return true;
543 }
544
545 /// Does the target have multiple (allocatable) condition registers that
546 /// can be used to store the results of comparisons for use by selects
547 /// and conditional branches. With multiple condition registers, the code
548 /// generator will not aggressively sink comparisons into the blocks of their
549 /// users. \p VT is the type of the condition value, e.g. the type of the
550 /// result of a comparison.
551 virtual bool hasMultipleConditionRegisters(EVT VT) const { return false; }
552
553 /// Return true if the target has BitExtract instructions.
554 bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
555
556 /// Return the preferred vector type legalization action.
559 // The default action for one element vectors is to scalarize
561 return TypeScalarizeVector;
562 // The default action for an odd-width vector is to widen.
563 if (!VT.isPow2VectorType())
564 return TypeWidenVector;
565 // The default action for other vectors is to promote
566 return TypePromoteInteger;
567 }
568
569 // Return true if, for soft-promoted half, the half type should be passed to
570 // and returned from functions as f32. The default behavior is to pass as
571 // i16. If soft-promoted half is not used, this function is ignored and
572 // values are always passed and returned as f32.
573 virtual bool useFPRegsForHalfType() const { return false; }
574
575 // There are two general methods for expanding a BUILD_VECTOR node:
576 // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
577 // them together.
578 // 2. Build the vector on the stack and then load it.
579 // If this function returns true, then method (1) will be used, subject to
580 // the constraint that all of the necessary shuffles are legal (as determined
581 // by isShuffleMaskLegal). If this function returns false, then method (2) is
582 // always used. The vector type, and the number of defined values, are
583 // provided.
584 virtual bool
586 unsigned DefinedValues) const {
587 return DefinedValues < 3;
588 }
589
590 /// Return true if integer divide is usually cheaper than a sequence of
591 /// several shifts, adds, and multiplies for this target.
592 /// The definition of "cheaper" may depend on whether we're optimizing
593 /// for speed or for size.
594 virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
595
596 /// Return true if the target can handle a standalone remainder operation.
597 virtual bool hasStandaloneRem(EVT VT) const {
598 return true;
599 }
600
601 /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
602 virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
603 // Default behavior is to replace SQRT(X) with X*RSQRT(X).
604 return false;
605 }
606
607 /// Reciprocal estimate status values used by the functions below.
612 };
613
614 /// Return a ReciprocalEstimate enum value for a square root of the given type
615 /// based on the function's attributes. If the operation is not overridden by
616 /// the function's attributes, "Unspecified" is returned and target defaults
617 /// are expected to be used for instruction selection.
618 int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const;
619
620 /// Return a ReciprocalEstimate enum value for a division of the given type
621 /// based on the function's attributes. If the operation is not overridden by
622 /// the function's attributes, "Unspecified" is returned and target defaults
623 /// are expected to be used for instruction selection.
624 int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const;
625
626 /// Return the refinement step count for a square root of the given type based
627 /// on the function's attributes. If the operation is not overridden by
628 /// the function's attributes, "Unspecified" is returned and target defaults
629 /// are expected to be used for instruction selection.
630 int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
631
632 /// Return the refinement step count for a division of the given type based
633 /// on the function's attributes. If the operation is not overridden by
634 /// the function's attributes, "Unspecified" is returned and target defaults
635 /// are expected to be used for instruction selection.
636 int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
637
638 /// Returns true if target has indicated at least one type should be bypassed.
639 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
640
641 /// Returns map of slow types for division or remainder with corresponding
642 /// fast types
644 return BypassSlowDivWidths;
645 }
646
647 /// Return true if Flow Control is an expensive operation that should be
648 /// avoided.
649 bool isJumpExpensive() const { return JumpIsExpensive; }
650
651 // Costs parameters used by
652 // SelectionDAGBuilder::shouldKeepJumpConditionsTogether.
653 // shouldKeepJumpConditionsTogether will use these parameter value to
654 // determine if two conditions in the form `br (and/or cond1, cond2)` should
655 // be split into two branches or left as one.
656 //
657 // BaseCost is the cost threshold (in latency). If the estimated latency of
658 // computing both `cond1` and `cond2` is below the cost of just computing
659 // `cond1` + BaseCost, the two conditions will be kept together. Otherwise
660 // they will be split.
661 //
662 // LikelyBias increases BaseCost if branch probability info indicates that it
663 // is likely that both `cond1` and `cond2` will be computed.
664 //
665 // UnlikelyBias decreases BaseCost if branch probability info indicates that
666 // it is likely that both `cond1` and `cond2` will be computed.
667 //
668 // Set any field to -1 to make it ignored (setting BaseCost to -1 results in
669 // `shouldKeepJumpConditionsTogether` always returning false).
675 // Return params for deciding if we should keep two branch conditions merged
676 // or split them into two separate branches.
677 // Arg0: The binary op joining the two conditions (and/or).
678 // Arg1: The first condition (cond1)
679 // Arg2: The second condition (cond2)
680 // Arg3: The containing function.
681 virtual CondMergingParams
683 const Value *, const Function *) const {
684 // -1 will always result in splitting.
685 return {-1, -1, -1};
686 }
687
688 /// Return true if selects are only cheaper than branches if the branch is
689 /// unlikely to be predicted right.
693
694 virtual bool fallBackToDAGISel(const Instruction &Inst) const {
695 return false;
696 }
697
698 /// Return true if the following transform is beneficial:
699 /// fold (conv (load x)) -> (load (conv*)x)
700 /// On architectures that don't natively support some vector loads
701 /// efficiently, casting the load to a smaller vector of larger types and
702 /// loading is more efficient, however, this can be undone by optimizations in
703 /// dag combiner.
704 virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
705 const SelectionDAG &DAG,
706 const MachineMemOperand &MMO) const;
707
708 /// Return true if the following transform is beneficial:
709 /// (store (y (conv x)), y*)) -> (store x, (x*))
710 virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT,
711 const SelectionDAG &DAG,
712 const MachineMemOperand &MMO) const {
713 // Default to the same logic as loads.
714 return isLoadBitCastBeneficial(StoreVT, BitcastVT, DAG, MMO);
715 }
716
717 /// Return true if it is expected to be cheaper to do a store of vector
718 /// constant with the given size and type for the address space than to
719 /// store the individual scalar element constants.
720 virtual bool storeOfVectorConstantIsCheap(bool IsZero, EVT MemVT,
721 unsigned NumElem,
722 unsigned AddrSpace) const {
723 return IsZero;
724 }
725
726 /// Allow store merging for the specified type after legalization in addition
727 /// to before legalization. This may transform stores that do not exist
728 /// earlier (for example, stores created from intrinsics).
729 virtual bool mergeStoresAfterLegalization(EVT MemVT) const {
730 return true;
731 }
732
733 /// Returns if it's reasonable to merge stores to MemVT size.
734 virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
735 const MachineFunction &MF) const {
736 return true;
737 }
738
739 /// Return true if it is cheap to speculate a call to intrinsic cttz.
740 virtual bool isCheapToSpeculateCttz(Type *Ty) const {
741 return false;
742 }
743
744 /// Return true if it is cheap to speculate a call to intrinsic ctlz.
745 virtual bool isCheapToSpeculateCtlz(Type *Ty) const {
746 return false;
747 }
748
749 /// Return true if ctlz instruction is fast.
750 virtual bool isCtlzFast() const {
751 return false;
752 }
753
754 /// Return true if ctpop instruction is fast.
755 virtual bool isCtpopFast(EVT VT) const {
756 return isOperationLegal(ISD::CTPOP, VT);
757 }
758
759 /// Return the maximum number of "x & (x - 1)" operations that can be done
760 /// instead of deferring to a custom CTPOP.
761 virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const {
762 return 1;
763 }
764
765 /// Return true if instruction generated for equality comparison is folded
766 /// with instruction generated for signed comparison.
767 virtual bool isEqualityCmpFoldedWithSignedCmp() const { return true; }
768
769 /// Return true if the heuristic to prefer icmp eq zero should be used in code
770 /// gen prepare.
771 virtual bool preferZeroCompareBranch() const { return false; }
772
773 /// Return true if it is cheaper to split the store of a merged int val
774 /// from a pair of smaller values into multiple stores.
775 virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
776 return false;
777 }
778
779 /// Return if the target supports combining a
780 /// chain like:
781 /// \code
782 /// %andResult = and %val1, #mask
783 /// %icmpResult = icmp %andResult, 0
784 /// \endcode
785 /// into a single machine instruction of a form like:
786 /// \code
787 /// cc = test %register, #mask
788 /// \endcode
789 virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
790 return false;
791 }
792
793 /// Return true if it is valid to merge the TargetMMOFlags in two SDNodes.
794 virtual bool
796 const MemSDNode &NodeY) const {
797 return true;
798 }
799
800 /// Use bitwise logic to make pairs of compares more efficient. For example:
801 /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
802 /// This should be true when it takes more than one instruction to lower
803 /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
804 /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
805 virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
806 return false;
807 }
808
809 /// Return the preferred operand type if the target has a quick way to compare
810 /// integer values of the given size. Assume that any legal integer type can
811 /// be compared efficiently. Targets may override this to allow illegal wide
812 /// types to return a vector type if there is support to compare that type.
813 virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
814 MVT VT = MVT::getIntegerVT(NumBits);
816 }
817
818 /// Return true if the target should transform:
819 /// (X & Y) == Y ---> (~X & Y) == 0
820 /// (X & Y) != Y ---> (~X & Y) != 0
821 ///
822 /// This may be profitable if the target has a bitwise and-not operation that
823 /// sets comparison flags. A target may want to limit the transformation based
824 /// on the type of Y or if Y is a constant.
825 ///
826 /// Note that the transform will not occur if Y is known to be a power-of-2
827 /// because a mask and compare of a single bit can be handled by inverting the
828 /// predicate, for example:
829 /// (X & 8) == 8 ---> (X & 8) != 0
830 virtual bool hasAndNotCompare(SDValue Y) const {
831 return false;
832 }
833
834 /// Return true if the target has a bitwise and-not operation:
835 /// X = ~A & B
836 /// This can be used to simplify select or other instructions.
837 virtual bool hasAndNot(SDValue X) const {
838 // If the target has the more complex version of this operation, assume that
839 // it has this operation too.
840 return hasAndNotCompare(X);
841 }
842
843 /// Return true if the target has a bit-test instruction:
844 /// (X & (1 << Y)) ==/!= 0
845 /// This knowledge can be used to prevent breaking the pattern,
846 /// or creating it if it could be recognized.
847 virtual bool hasBitTest(SDValue X, SDValue Y) const { return false; }
848
849 /// There are two ways to clear extreme bits (either low or high):
850 /// Mask: x & (-1 << y) (the instcombine canonical form)
851 /// Shifts: x >> y << y
852 /// Return true if the variant with 2 variable shifts is preferred.
853 /// Return false if there is no preference.
855 // By default, let's assume that no one prefers shifts.
856 return false;
857 }
858
859 /// Return true if it is profitable to fold a pair of shifts into a mask.
860 /// This is usually true on most targets. But some targets, like Thumb1,
861 /// have immediate shift instructions, but no immediate "and" instruction;
862 /// this makes the fold unprofitable.
863 virtual bool shouldFoldConstantShiftPairToMask(const SDNode *N) const {
864 return true;
865 }
866
867 /// Should we tranform the IR-optimal check for whether given truncation
868 /// down into KeptBits would be truncating or not:
869 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
870 /// Into it's more traditional form:
871 /// ((%x << C) a>> C) dstcond %x
872 /// Return true if we should transform.
873 /// Return false if there is no preference.
875 unsigned KeptBits) const {
876 // By default, let's assume that no one prefers shifts.
877 return false;
878 }
879
880 /// Given the pattern
881 /// (X & (C l>>/<< Y)) ==/!= 0
882 /// return true if it should be transformed into:
883 /// ((X <</l>> Y) & C) ==/!= 0
884 /// WARNING: if 'X' is a constant, the fold may deadlock!
885 /// FIXME: we could avoid passing XC, but we can't use isConstOrConstSplat()
886 /// here because it can end up being not linked in.
889 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
890 SelectionDAG &DAG) const {
891 if (hasBitTest(X, Y)) {
892 // One interesting pattern that we'd want to form is 'bit test':
893 // ((1 << Y) & C) ==/!= 0
894 // But we also need to be careful not to try to reverse that fold.
895
896 // Is this '1 << Y' ?
897 if (OldShiftOpcode == ISD::SHL && CC->isOne())
898 return false; // Keep the 'bit test' pattern.
899
900 // Will it be '1 << Y' after the transform ?
901 if (XC && NewShiftOpcode == ISD::SHL && XC->isOne())
902 return true; // Do form the 'bit test' pattern.
903 }
904
905 // If 'X' is a constant, and we transform, then we will immediately
906 // try to undo the fold, thus causing endless combine loop.
907 // So by default, let's assume everyone prefers the fold
908 // iff 'X' is not a constant.
909 return !XC;
910 }
911
912 // Return true if its desirable to perform the following transform:
913 // (fmul C, (uitofp Pow2))
914 // -> (bitcast_to_FP (add (bitcast_to_INT C), Log2(Pow2) << mantissa))
915 // (fdiv C, (uitofp Pow2))
916 // -> (bitcast_to_FP (sub (bitcast_to_INT C), Log2(Pow2) << mantissa))
917 //
918 // This is only queried after we have verified the transform will be bitwise
919 // equals.
920 //
921 // SDNode *N : The FDiv/FMul node we want to transform.
922 // SDValue FPConst: The Float constant operand in `N`.
923 // SDValue IntPow2: The Integer power of 2 operand in `N`.
925 SDValue IntPow2) const {
926 // Default to avoiding fdiv which is often very expensive.
927 return N->getOpcode() == ISD::FDIV;
928 }
929
930 // Given:
931 // (icmp eq/ne (and X, C0), (shift X, C1))
932 // or
933 // (icmp eq/ne X, (rotate X, C1))
934
935 // If C0 is a mask or shifted mask and the shift amt (C1) isolates the
936 // remaining bits (i.e something like `(x64 & UINT32_MAX) == (x64 >> 32)`)
937 // Do we prefer the shift to be shift-right, shift-left, or rotate.
938 // Note: It's only valid to convert between the rotate and shift versions iff
939 // the shift-amt (`C1`) divides the bit width.
940 // If ShiftOpc (current Opcode) is returned, do nothing.
942 EVT VT, unsigned ShiftOpc, bool MayTransformRotate,
943 const APInt &ShiftOrRotateAmt,
944 const std::optional<APInt> &AndMask) const {
945 return ShiftOpc;
946 }
947
948 /// These two forms are equivalent:
949 /// sub %y, (xor %x, -1)
950 /// add (add %x, 1), %y
951 /// The variant with two add's is IR-canonical.
952 /// Some targets may prefer one to the other.
953 virtual bool preferIncOfAddToSubOfNot(EVT VT) const {
954 // By default, let's assume that everyone prefers the form with two add's.
955 return true;
956 }
957
958 // By default prefer folding (abs (sub nsw x, y)) -> abds(x, y). Some targets
959 // may want to avoid this to prevent loss of sub_nsw pattern.
960 virtual bool preferABDSToABSWithNSW(EVT VT) const {
961 return true;
962 }
963
964 // Return true if the target wants to transform Op(Splat(X)) -> Splat(Op(X))
965 virtual bool preferScalarizeSplat(SDNode *N) const { return true; }
966
967 // Return true if the target wants to transform:
968 // (TruncVT truncate(sext_in_reg(VT X, ExtVT))
969 // -> (TruncVT sext_in_reg(truncate(VT X), ExtVT))
970 // Some targets might prefer pre-sextinreg to improve truncation/saturation.
971 virtual bool preferSextInRegOfTruncate(EVT TruncVT, EVT VT, EVT ExtVT) const {
972 return true;
973 }
974
975 /// Return true if the target wants to use the optimization that
976 /// turns ext(promotableInst1(...(promotableInstN(load)))) into
977 /// promotedInst1(...(promotedInstN(ext(load)))).
979
980 /// Return true if the target can combine store(extractelement VectorTy,
981 /// Idx).
982 /// \p Cost[out] gives the cost of that transformation when this is true.
983 virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
984 unsigned &Cost) const {
985 return false;
986 }
987
988 /// Return true if the target shall perform extract vector element and store
989 /// given that the vector is known to be splat of constant.
990 /// \p Index[out] gives the index of the vector element to be extracted when
991 /// this is true.
993 Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const {
994 return false;
995 }
996
997 /// Return true if inserting a scalar into a variable element of an undef
998 /// vector is more efficiently handled by splatting the scalar instead.
999 virtual bool shouldSplatInsEltVarIndex(EVT) const {
1000 return false;
1001 }
1002
1003 /// Return true if target always benefits from combining into FMA for a
1004 /// given value type. This must typically return false on targets where FMA
1005 /// takes more cycles to execute than FADD.
1006 virtual bool enableAggressiveFMAFusion(EVT VT) const { return false; }
1007
1008 /// Return true if target always benefits from combining into FMA for a
1009 /// given value type. This must typically return false on targets where FMA
1010 /// takes more cycles to execute than FADD.
1011 virtual bool enableAggressiveFMAFusion(LLT Ty) const { return false; }
1012
1013 /// Return the ValueType of the result of SETCC operations.
1014 virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
1015 EVT VT) const;
1016
1017 /// Return the ValueType for comparison libcalls. Comparison libcalls include
1018 /// floating point comparison calls, and Ordered/Unordered check calls on
1019 /// floating point numbers.
1021 return MVT::i32; // return the default value
1022 }
1023
1024 /// For targets without i1 registers, this gives the nature of the high-bits
1025 /// of boolean values held in types wider than i1.
1026 ///
1027 /// "Boolean values" are special true/false values produced by nodes like
1028 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
1029 /// Not to be confused with general values promoted from i1. Some cpus
1030 /// distinguish between vectors of boolean and scalars; the isVec parameter
1031 /// selects between the two kinds. For example on X86 a scalar boolean should
1032 /// be zero extended from i1, while the elements of a vector of booleans
1033 /// should be sign extended from i1.
1034 ///
1035 /// Some cpus also treat floating point types the same way as they treat
1036 /// vectors instead of the way they treat scalars.
1037 BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
1038 if (isVec)
1039 return BooleanVectorContents;
1040 return isFloat ? BooleanFloatContents : BooleanContents;
1041 }
1042
1044 return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
1045 }
1046
1047 /// Promote the given target boolean to a target boolean of the given type.
1048 /// A target boolean is an integer value, not necessarily of type i1, the bits
1049 /// of which conform to getBooleanContents.
1050 ///
1051 /// ValVT is the type of values that produced the boolean.
1053 EVT ValVT) const {
1054 SDLoc dl(Bool);
1055 EVT BoolVT =
1056 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ValVT);
1058 return DAG.getNode(ExtendCode, dl, BoolVT, Bool);
1059 }
1060
1061 /// Return target scheduling preference.
1063 return SchedPreferenceInfo;
1064 }
1065
1066 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
1067 /// for different nodes. This function returns the preference (or none) for
1068 /// the given node.
1070 return Sched::None;
1071 }
1072
1073 /// Return the register class that should be used for the specified value
1074 /// type.
1075 virtual const TargetRegisterClass *getRegClassFor(MVT VT, bool isDivergent = false) const {
1076 (void)isDivergent;
1077 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
1078 assert(RC && "This value type is not natively supported!");
1079 return RC;
1080 }
1081
1082 /// Allows target to decide about the register class of the
1083 /// specific value that is live outside the defining block.
1084 /// Returns true if the value needs uniform register class.
1086 const Value *) const {
1087 return false;
1088 }
1089
1090 /// Return the 'representative' register class for the specified value
1091 /// type.
1092 ///
1093 /// The 'representative' register class is the largest legal super-reg
1094 /// register class for the register class of the value type. For example, on
1095 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
1096 /// register class is GR64 on x86_64.
1097 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
1098 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
1099 return RC;
1100 }
1101
1102 /// Return the cost of the 'representative' register class for the specified
1103 /// value type.
1105 return RepRegClassCostForVT[VT.SimpleTy];
1106 }
1107
1108 /// Return the preferred strategy to legalize tihs SHIFT instruction, with
1109 /// \p ExpansionFactor being the recursion depth - how many expansion needed.
1115 virtual ShiftLegalizationStrategy
1117 unsigned ExpansionFactor) const {
1118 if (ExpansionFactor == 1)
1121 }
1122
1123 /// Return true if the target has native support for the specified value type.
1124 /// This means that it has a register that directly holds it without
1125 /// promotions or expansions.
1126 bool isTypeLegal(EVT VT) const {
1127 assert(!VT.isSimple() ||
1128 (unsigned)VT.getSimpleVT().SimpleTy < std::size(RegClassForVT));
1129 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
1130 }
1131
1133 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
1134 /// that indicates how instruction selection should deal with the type.
1135 LegalizeTypeAction ValueTypeActions[MVT::VALUETYPE_SIZE];
1136
1137 public:
1138 ValueTypeActionImpl() { llvm::fill(ValueTypeActions, TypeLegal); }
1139
1141 return ValueTypeActions[VT.SimpleTy];
1142 }
1143
1145 ValueTypeActions[VT.SimpleTy] = Action;
1146 }
1147 };
1148
1150 return ValueTypeActions;
1151 }
1152
1153 /// Return pair that represents the legalization kind (first) that needs to
1154 /// happen to EVT (second) in order to type-legalize it.
1155 ///
1156 /// First: how we should legalize values of this type, either it is already
1157 /// legal (return 'Legal') or we need to promote it to a larger type (return
1158 /// 'Promote'), or we need to expand it into multiple registers of smaller
1159 /// integer type (return 'Expand'). 'Custom' is not an option.
1160 ///
1161 /// Second: for types supported by the target, this is an identity function.
1162 /// For types that must be promoted to larger types, this returns the larger
1163 /// type to promote to. For integer types that are larger than the largest
1164 /// integer register, this contains one step in the expansion to get to the
1165 /// smaller register. For illegal floating point types, this returns the
1166 /// integer type to transform to.
1167 LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
1168
1169 /// Return how we should legalize values of this type, either it is already
1170 /// legal (return 'Legal') or we need to promote it to a larger type (return
1171 /// 'Promote'), or we need to expand it into multiple registers of smaller
1172 /// integer type (return 'Expand'). 'Custom' is not an option.
1174 return getTypeConversion(Context, VT).first;
1175 }
1177 return ValueTypeActions.getTypeAction(VT);
1178 }
1179
1180 /// For types supported by the target, this is an identity function. For
1181 /// types that must be promoted to larger types, this returns the larger type
1182 /// to promote to. For integer types that are larger than the largest integer
1183 /// register, this contains one step in the expansion to get to the smaller
1184 /// register. For illegal floating point types, this returns the integer type
1185 /// to transform to.
1186 virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
1187 return getTypeConversion(Context, VT).second;
1188 }
1189
1190 /// Perform getTypeToTransformTo repeatedly until a legal type is obtained.
1191 /// Useful for vector operations that might take multiple steps to legalize.
1193 EVT LegalVT = getTypeToTransformTo(Context, VT);
1194 while (LegalVT != VT) {
1195 VT = LegalVT;
1196 LegalVT = getTypeToTransformTo(Context, VT);
1197 }
1198 return LegalVT;
1199 }
1200
1201 /// For types supported by the target, this is an identity function. For
1202 /// types that must be expanded (i.e. integer types that are larger than the
1203 /// largest integer register or illegal floating point types), this returns
1204 /// the largest legal type it will be expanded to.
1205 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
1206 assert(!VT.isVector());
1207 while (true) {
1208 switch (getTypeAction(Context, VT)) {
1209 case TypeLegal:
1210 return VT;
1211 case TypeExpandInteger:
1212 VT = getTypeToTransformTo(Context, VT);
1213 break;
1214 default:
1215 llvm_unreachable("Type is not legal nor is it to be expanded!");
1216 }
1217 }
1218 }
1219
1220 /// Vector types are broken down into some number of legal first class types.
1221 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
1222 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
1223 /// turns into 4 EVT::i32 values with both PPC and X86.
1224 ///
1225 /// This method returns the number of registers needed, and the VT for each
1226 /// register. It also returns the VT and quantity of the intermediate values
1227 /// before they are promoted/expanded.
1229 EVT &IntermediateVT,
1230 unsigned &NumIntermediates,
1231 MVT &RegisterVT) const {
1232 return getVectorTypeBreakdownImpl(Context, VT, IntermediateVT,
1233 NumIntermediates, RegisterVT,
1234 /*ForCallingConv=*/false);
1235 }
1236
1237 /// Return true if fixed-length, non-power-of-two vectors should be broken
1238 /// down into legal vector parts instead of scalars for internal values.
1240 return false;
1241 }
1242
1243 bool shouldUseDynamicVectorTypeBreakdown(EVT VT, bool ForCallingConv) const {
1244 return preferVectorizedNonPowerOfTwoTypeBreakdown() && !ForCallingConv &&
1245 VT.isFixedLengthVector() &&
1247 }
1248
1249 /// Certain targets such as MIPS require that some types such as vectors are
1250 /// always broken down into scalars in some contexts. This occurs even if the
1251 /// vector type is legal.
1253 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
1254 unsigned &NumIntermediates, MVT &RegisterVT) const {
1255 return getVectorTypeBreakdownImpl(Context, VT, IntermediateVT,
1256 NumIntermediates, RegisterVT,
1257 /*ForCallingConv=*/true);
1258 }
1259
1261 unsigned opc = 0; // target opcode
1262 EVT memVT; // memory VT
1263
1264 // value representing memory location
1266
1267 // Fallback address space for use if ptrVal is nullptr. std::nullopt means
1268 // unknown address space.
1269 std::optional<unsigned> fallbackAddressSpace;
1270
1271 int offset = 0; // offset off of ptrVal
1272 uint64_t size = 0; // the size of the memory location
1273 // (taken from memVT if zero)
1274 MaybeAlign align = Align(1); // alignment
1275
1280 IntrinsicInfo() = default;
1281 };
1282
1283 /// Given an intrinsic, checks if on the target the intrinsic will need to map
1284 /// to a MemIntrinsicNode (touches memory). If this is the case, it stores
1285 /// the intrinsic information into the IntrinsicInfo vector passed to the
1286 /// function. The vector may contain multiple entries for intrinsics that
1287 /// access multiple memory locations.
1289 const CallBase &I, MachineFunction &MF,
1290 unsigned Intrinsic) const {}
1291
1292 /// Returns true if the target can instruction select the specified FP
1293 /// immediate natively. If false, the legalizer will materialize the FP
1294 /// immediate as a load from a constant pool.
1295 virtual bool isFPImmLegal(const APFloat & /*Imm*/, EVT /*VT*/,
1296 bool ForCodeSize = false) const {
1297 return false;
1298 }
1299
1300 /// Targets can use this to indicate that they only support *some*
1301 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
1302 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
1303 /// legal.
1304 virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
1305 return true;
1306 }
1307
1308 /// Returns true if the operation can trap for the value type.
1309 ///
1310 /// VT must be a legal type. By default, we optimistically assume most
1311 /// operations don't trap except for integer divide and remainder.
1312 virtual bool canOpTrap(unsigned Op, EVT VT) const;
1313
1314 /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
1315 /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
1316 /// constant pool entry.
1318 EVT /*VT*/) const {
1319 return false;
1320 }
1321
1322 /// How to legalize this custom operation?
1324 return Legal;
1325 }
1326
1327 /// Return how this operation should be treated: either it is legal, needs to
1328 /// be promoted to a larger size, needs to be expanded to some other code
1329 /// sequence, or the target has a custom expander for it.
1331 // If a target-specific SDNode requires legalization, require the target
1332 // to provide custom legalization for it.
1333 if (Op >= std::size(OpActions[0]))
1334 return Custom;
1335 if (VT.isExtended())
1336 return Expand;
1337 return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
1338 }
1339
1340 /// Custom method defined by each target to indicate if an operation which
1341 /// may require a scale is supported natively by the target.
1342 /// If not, the operation is illegal.
1343 virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT,
1344 unsigned Scale) const {
1345 return false;
1346 }
1347
1348 /// Some fixed point operations may be natively supported by the target but
1349 /// only for specific scales. This method allows for checking
1350 /// if the width is supported by the target for a given operation that may
1351 /// depend on scale.
1353 unsigned Scale) const {
1354 auto Action = getOperationAction(Op, VT);
1355 if (Action != Legal)
1356 return Action;
1357
1358 // This operation is supported in this type but may only work on specific
1359 // scales.
1360 bool Supported;
1361 switch (Op) {
1362 default:
1363 llvm_unreachable("Unexpected fixed point operation.");
1364 case ISD::SMULFIX:
1365 case ISD::SMULFIXSAT:
1366 case ISD::UMULFIX:
1367 case ISD::UMULFIXSAT:
1368 case ISD::SDIVFIX:
1369 case ISD::SDIVFIXSAT:
1370 case ISD::UDIVFIX:
1371 case ISD::UDIVFIXSAT:
1372 Supported = isSupportedFixedPointOperation(Op, VT, Scale);
1373 break;
1374 }
1375
1376 return Supported ? Action : Expand;
1377 }
1378
1379 // If Op is a strict floating-point operation, return the result
1380 // of getOperationAction for the equivalent non-strict operation.
1382 unsigned EqOpc;
1383 switch (Op) {
1384 default: llvm_unreachable("Unexpected FP pseudo-opcode");
1385#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1386 case ISD::STRICT_##DAGN: EqOpc = ISD::DAGN; break;
1387#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1388 case ISD::STRICT_##DAGN: EqOpc = ISD::SETCC; break;
1389#include "llvm/IR/ConstrainedOps.def"
1390 }
1391
1392 return getOperationAction(EqOpc, VT);
1393 }
1394
1395 /// Return true if the specified operation is legal on this target or can be
1396 /// made legal with custom lowering. This is used to help guide high-level
1397 /// lowering decisions. LegalOnly is an optional convenience for code paths
1398 /// traversed pre and post legalisation.
1400 bool LegalOnly = false) const {
1401 if (LegalOnly)
1402 return isOperationLegal(Op, VT);
1403
1404 return (VT == MVT::Other || isTypeLegal(VT)) &&
1405 (getOperationAction(Op, VT) == Legal ||
1406 getOperationAction(Op, VT) == Custom);
1407 }
1408
1409 /// Return true if the specified operation is legal on this target or can be
1410 /// made legal using promotion. This is used to help guide high-level lowering
1411 /// decisions. LegalOnly is an optional convenience for code paths traversed
1412 /// pre and post legalisation.
1414 bool LegalOnly = false) const {
1415 if (LegalOnly)
1416 return isOperationLegal(Op, VT);
1417
1418 return (VT == MVT::Other || isTypeLegal(VT)) &&
1419 (getOperationAction(Op, VT) == Legal ||
1420 getOperationAction(Op, VT) == Promote);
1421 }
1422
1423 /// Return true if the specified operation is legal on this target or can be
1424 /// made legal with custom lowering or using promotion. This is used to help
1425 /// guide high-level lowering decisions. LegalOnly is an optional convenience
1426 /// for code paths traversed pre and post legalisation.
1428 bool LegalOnly = false) const {
1429 if (LegalOnly)
1430 return isOperationLegal(Op, VT);
1431
1432 return (VT == MVT::Other || isTypeLegal(VT)) &&
1433 (getOperationAction(Op, VT) == Legal ||
1434 getOperationAction(Op, VT) == Custom ||
1435 getOperationAction(Op, VT) == Promote);
1436 }
1437
1438 /// Return true if the operation uses custom lowering, regardless of whether
1439 /// the type is legal or not.
1440 bool isOperationCustom(unsigned Op, EVT VT) const {
1441 return getOperationAction(Op, VT) == Custom;
1442 }
1443
1444 /// Return true if lowering to a jump table is allowed.
1445 virtual bool areJTsAllowed(const Function *Fn) const {
1446 if (Fn->getFnAttribute("no-jump-tables").getValueAsBool())
1447 return false;
1448
1449 return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1451 }
1452
1453 /// Check whether the range [Low,High] fits in a machine word.
1454 bool rangeFitsInWord(const APInt &Low, const APInt &High,
1455 const DataLayout &DL) const {
1456 // FIXME: Using the pointer type doesn't seem ideal.
1457 uint64_t BW = DL.getIndexSizeInBits(0u);
1458 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
1459 return Range <= BW;
1460 }
1461
1462 /// Return true if lowering to a jump table is suitable for a set of case
1463 /// clusters which may contain \p NumCases cases, \p Range range of values.
1464 virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
1466 BlockFrequencyInfo *BFI) const;
1467
1468 /// Returns preferred type for switch condition.
1469 virtual MVT getPreferredSwitchConditionType(LLVMContext &Context,
1470 EVT ConditionVT) const;
1471
1472 /// Return true if lowering to a bit test is suitable for a set of case
1473 /// clusters which contains \p NumDests unique destinations, \p Low and
1474 /// \p High as its lowest and highest case values, and expects \p NumCmps
1475 /// case value comparisons. Check if the number of destinations, comparison
1476 /// metric, and range are all suitable.
1479 const APInt &Low, const APInt &High, const DataLayout &DL) const {
1480 // FIXME: I don't think NumCmps is the correct metric: a single case and a
1481 // range of cases both require only one branch to lower. Just looking at the
1482 // number of clusters and destinations should be enough to decide whether to
1483 // build bit tests.
1484
1485 // To lower a range with bit tests, the range must fit the bitwidth of a
1486 // machine word.
1487 if (!rangeFitsInWord(Low, High, DL))
1488 return false;
1489
1490 unsigned NumDests = DestCmps.size();
1491 unsigned NumCmps = 0;
1492 unsigned int MaxBitTestEntry = 0;
1493 for (auto &DestCmp : DestCmps) {
1494 NumCmps += DestCmp.second;
1495 if (DestCmp.second > MaxBitTestEntry)
1496 MaxBitTestEntry = DestCmp.second;
1497 }
1498
1499 // Comparisons might be cheaper for small number of comparisons, which can
1500 // be Arch Target specific.
1501 if (MaxBitTestEntry < getMinimumBitTestCmps())
1502 return false;
1503
1504 // Decide whether it's profitable to lower this range with bit tests. Each
1505 // destination requires a bit test and branch, and there is an overall range
1506 // check branch. For a small number of clusters, separate comparisons might
1507 // be cheaper, and for many destinations, splitting the range might be
1508 // better.
1509 return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
1510 (NumDests == 3 && NumCmps >= 6);
1511 }
1512
1513 /// Return true if the specified operation is illegal on this target or
1514 /// unlikely to be made legal with custom lowering. This is used to help guide
1515 /// high-level lowering decisions.
1516 bool isOperationExpand(unsigned Op, EVT VT) const {
1517 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
1518 }
1519
1520 /// Return true if the specified operation is legal on this target.
1521 bool isOperationLegal(unsigned Op, EVT VT) const {
1522 return (VT == MVT::Other || isTypeLegal(VT)) &&
1523 getOperationAction(Op, VT) == Legal;
1524 }
1525
1526 bool isOperationExpandOrLibCall(unsigned Op, EVT VT) const {
1527 return isOperationExpand(Op, VT) || getOperationAction(Op, VT) == LibCall;
1528 }
1529
1530 /// Returns an alternative action to use when the coarser lookups (configured
1531 /// through `setLoadExtAction` and `setAtomicLoadExtAction`) yield
1532 /// `LegalizeAction::Custom`. Allows targets to use builtin behaviors (e.g.
1533 /// Legal, Promote) specialized by Alignment and AddrSpace, rather than just
1534 /// types.
1535 virtual LegalizeAction
1536 getCustomLoadAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace,
1537 unsigned ExtType, bool Atomic) const {
1539 }
1540
1541 /// Return how this load with extension should be treated: either it is legal,
1542 /// needs to be promoted to a larger size, needs to be expanded to some other
1543 /// code sequence, or the target has a custom expander for it.
1544 LegalizeAction getLoadAction(EVT ValVT, EVT MemVT, Align Alignment,
1545 unsigned AddrSpace, unsigned ExtType,
1546 bool Atomic) const {
1547 if (ValVT.isExtended() || MemVT.isExtended())
1548 return Expand;
1549 unsigned ValI = (unsigned)ValVT.getSimpleVT().SimpleTy;
1550 unsigned MemI = (unsigned)MemVT.getSimpleVT().SimpleTy;
1552 MemI < MVT::VALUETYPE_SIZE && "Table isn't big enough!");
1553 unsigned Shift = 4 * ExtType;
1554
1555 LegalizeAction Action;
1556 if (Atomic) {
1557 Action =
1558 (LegalizeAction)((AtomicLoadExtActions[ValI][MemI] >> Shift) & 0xf);
1559 assert((Action == Legal || Action == Expand) &&
1560 "Unsupported atomic load extension action.");
1561 } else {
1562 Action = (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
1563 }
1564
1565 if (Action == LegalizeAction::Custom) {
1566 return getCustomLoadAction(ValVT, MemVT, Alignment, AddrSpace, ExtType,
1567 Atomic);
1568 }
1569
1570 return Action;
1571 }
1572
1573 /// Return true if the specified load with extension is legal on this target.
1574 bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace,
1575 unsigned ExtType, bool Atomic) const {
1576 return getLoadAction(ValVT, MemVT, Alignment, AddrSpace, ExtType, Atomic) ==
1577 Legal;
1578 }
1579
1580 /// Return true if the specified load with extension is legal or custom
1581 /// on this target.
1582 bool isLoadLegalOrCustom(EVT ValVT, EVT MemVT, Align Alignment,
1583 unsigned AddrSpace, unsigned ExtType,
1584 bool Atomic) const {
1585 LegalizeAction Action =
1586 getLoadAction(ValVT, MemVT, Alignment, AddrSpace, ExtType, Atomic);
1587 return Action == Legal || Action == Custom;
1588 }
1589
1590 /// Returns an alternative action to use when the coarser lookups (configured
1591 /// through `setTruncStoreAction` yield
1592 /// `LegalizeAction::Custom`. Allows targets to use builtin behaviors (e.g.
1593 /// Legal, Promote) specialized by Alignment and AddrSpace, rather than just
1594 /// types.
1596 Align Alignment,
1597 unsigned AddrSpace) const {
1599 }
1600
1601 /// Return how this store with truncation should be treated: either it is
1602 /// legal, needs to be promoted to a larger size, needs to be expanded to some
1603 /// other code sequence, or the target has a custom expander for it.
1605 unsigned AddrSpace) const {
1606 if (ValVT.isExtended() || MemVT.isExtended())
1607 return Expand;
1608 unsigned ValI = (unsigned)ValVT.getSimpleVT().SimpleTy;
1609 unsigned MemI = (unsigned)MemVT.getSimpleVT().SimpleTy;
1611 "Table isn't big enough!");
1612
1613 LegalizeAction Action = TruncStoreActions[ValI][MemI];
1614
1615 if (Action == LegalizeAction::Custom) {
1616 return getCustomTruncStoreAction(ValVT, MemVT, Alignment, AddrSpace);
1617 }
1618
1619 return Action;
1620 }
1621
1622 /// Return true if the specified store with truncation is legal on this
1623 /// target.
1624 bool isTruncStoreLegal(EVT ValVT, EVT MemVT, Align Alignment,
1625 unsigned AddrSpace) const {
1626 return isTypeLegal(ValVT) &&
1627 getTruncStoreAction(ValVT, MemVT, Alignment, AddrSpace) == Legal;
1628 }
1629
1630 /// Return true if the specified store with truncation has solution on this
1631 /// target.
1632 bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT, Align Alignment,
1633 unsigned AddrSpace) const {
1634 if (!isTypeLegal(ValVT))
1635 return false;
1636
1637 LegalizeAction Action =
1638 getTruncStoreAction(ValVT, MemVT, Alignment, AddrSpace);
1639 return (Action == Legal || Action == Custom);
1640 }
1641
1642 virtual bool canCombineTruncStore(EVT ValVT, EVT MemVT, Align Alignment,
1643 unsigned AddrSpace, bool LegalOnly) const {
1644 if (LegalOnly)
1645 return isTruncStoreLegal(ValVT, MemVT, Alignment, AddrSpace);
1646
1647 return isTruncStoreLegalOrCustom(ValVT, MemVT, Alignment, AddrSpace);
1648 }
1649
1650 /// Return how the indexed load should be treated: either it is legal, needs
1651 /// to be promoted to a larger size, needs to be expanded to some other code
1652 /// sequence, or the target has a custom expander for it.
1653 LegalizeAction getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
1654 return getIndexedModeAction(IdxMode, VT, IMAB_Load);
1655 }
1656
1657 /// Return true if the specified indexed load is legal on this target.
1658 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
1659 return VT.isSimple() &&
1660 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1661 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1662 }
1663
1664 /// Return how the indexed store should be treated: either it is legal, needs
1665 /// to be promoted to a larger size, needs to be expanded to some other code
1666 /// sequence, or the target has a custom expander for it.
1667 LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
1668 return getIndexedModeAction(IdxMode, VT, IMAB_Store);
1669 }
1670
1671 /// Return true if the specified indexed load is legal on this target.
1672 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
1673 return VT.isSimple() &&
1674 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1675 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1676 }
1677
1678 /// Return how the indexed load should be treated: either it is legal, needs
1679 /// to be promoted to a larger size, needs to be expanded to some other code
1680 /// sequence, or the target has a custom expander for it.
1681 LegalizeAction getIndexedMaskedLoadAction(unsigned IdxMode, MVT VT) const {
1682 return getIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad);
1683 }
1684
1685 /// Return true if the specified indexed load is legal on this target.
1686 bool isIndexedMaskedLoadLegal(unsigned IdxMode, EVT VT) const {
1687 return VT.isSimple() &&
1688 (getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1690 }
1691
1692 /// Return how the indexed store should be treated: either it is legal, needs
1693 /// to be promoted to a larger size, needs to be expanded to some other code
1694 /// sequence, or the target has a custom expander for it.
1695 LegalizeAction getIndexedMaskedStoreAction(unsigned IdxMode, MVT VT) const {
1696 return getIndexedModeAction(IdxMode, VT, IMAB_MaskedStore);
1697 }
1698
1699 /// Return true if the specified indexed load is legal on this target.
1700 bool isIndexedMaskedStoreLegal(unsigned IdxMode, EVT VT) const {
1701 return VT.isSimple() &&
1702 (getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1704 }
1705
1706 /// Returns true if the index type for a masked gather/scatter requires
1707 /// extending
1708 virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const { return false; }
1709
1710 // Returns true if Extend can be folded into the index of a masked gathers/scatters
1711 // on this target.
1712 virtual bool shouldRemoveExtendFromGSIndex(SDValue Extend, EVT DataVT) const {
1713 return false;
1714 }
1715
1716 // Return true if the target supports a scatter/gather instruction with
1717 // indices which are scaled by the particular value. Note that all targets
1718 // must by definition support scale of 1.
1720 uint64_t ElemSize) const {
1721 // MGATHER/MSCATTER are only required to support scaling by one or by the
1722 // element size.
1723 if (Scale != ElemSize && Scale != 1)
1724 return false;
1725 return true;
1726 }
1727
1728 /// Return how the condition code should be treated: either it is legal, needs
1729 /// to be expanded to some other code sequence, or the target has a custom
1730 /// expander for it.
1733 assert((unsigned)CC < std::size(CondCodeActions) &&
1734 ((unsigned)VT.SimpleTy >> 3) < std::size(CondCodeActions[0]) &&
1735 "Table isn't big enough!");
1736 // See setCondCodeAction for how this is encoded.
1737 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1738 uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
1739 LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
1740 assert(Action != Promote && "Can't promote condition code!");
1741 return Action;
1742 }
1743
1744 /// Return true if the specified condition code is legal for a comparison of
1745 /// the specified types on this target.
1746 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
1747 return getCondCodeAction(CC, VT) == Legal;
1748 }
1749
1750 /// Return true if the specified condition code is legal or custom for a
1751 /// comparison of the specified types on this target.
1753 return getCondCodeAction(CC, VT) == Legal ||
1754 getCondCodeAction(CC, VT) == Custom;
1755 }
1756
1757 /// Return how a PARTIAL_REDUCE_U/SMLA node with Acc type AccVT and Input type
1758 /// InputVT should be treated. Either it's legal, needs to be promoted to a
1759 /// larger size, needs to be expanded to some other code sequence, or the
1760 /// target has a custom expander for it.
1762 EVT InputVT) const {
1765 PartialReduceActionTypes Key = {Opc, AccVT.getSimpleVT().SimpleTy,
1766 InputVT.getSimpleVT().SimpleTy};
1767 auto It = PartialReduceMLAActions.find(Key);
1768 return It != PartialReduceMLAActions.end() ? It->second : Expand;
1769 }
1770
1771 /// Return true if a PARTIAL_REDUCE_U/SMLA node with the specified types is
1772 /// legal or custom for this target.
1774 EVT InputVT) const {
1775 LegalizeAction Action = getPartialReduceMLAAction(Opc, AccVT, InputVT);
1776 return Action == Legal || Action == Custom;
1777 }
1778
1779 /// Return how a VECTOR_INTERLEAVE or VECTOR_DEINTERLEAVE node with the
1780 /// given interleave factor and VT should be handled.
1782 EVT VT) const {
1784 VectorInterleaveActionKey Key = {Opc, Factor, VT.getSimpleVT().SimpleTy};
1785 auto It = VectorInterleaveActions.find(Key);
1786 return It != VectorInterleaveActions.end() ? It->second : Expand;
1787 }
1788
1789 /// Return true if a VECTOR_INTERLEAVE or VECTOR_DEINTERLEAVE node with the
1790 /// given interleave factor and fragment type is legal or custom.
1791 bool isVectorInterleaveLegalOrCustom(unsigned Opc, unsigned Factor,
1792 EVT VT) const {
1793 LegalizeAction Action = getVectorInterleaveAction(Opc, Factor, VT);
1794 return Action == Legal || Action == Custom;
1795 }
1796
1797 /// If the action for this operation is to promote, this method returns the
1798 /// ValueType to promote to.
1799 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
1801 "This operation isn't promoted!");
1802
1803 // See if this has an explicit type specified.
1804 std::map<std::pair<unsigned, MVT::SimpleValueType>,
1806 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1807 if (PTTI != PromoteToType.end()) return PTTI->second;
1808
1809 assert((VT.isInteger() || VT.isFloatingPoint()) &&
1810 "Cannot autopromote this type, add it with AddPromotedToType.");
1811
1812 uint64_t VTBits = VT.getScalarSizeInBits();
1813 MVT NVT = VT;
1814 do {
1815 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1816 assert(NVT.isInteger() == VT.isInteger() &&
1817 NVT.isFloatingPoint() == VT.isFloatingPoint() &&
1818 "Didn't find type to promote to!");
1819 } while (VTBits >= NVT.getScalarSizeInBits() || !isTypeLegal(NVT) ||
1820 getOperationAction(Op, NVT) == Promote);
1821 return NVT;
1822 }
1823
1825 bool AllowUnknown = false) const {
1826 return getValueType(DL, Ty, AllowUnknown);
1827 }
1828
1829 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1830 /// operations except for the pointer size. If AllowUnknown is true, this
1831 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1832 /// otherwise it will assert.
1834 bool AllowUnknown = false) const {
1835 // Lower scalar pointers to native pointer types.
1836 if (auto *PTy = dyn_cast<PointerType>(Ty))
1837 return getPointerTy(DL, PTy->getAddressSpace());
1838
1839 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1840 Type *EltTy = VTy->getElementType();
1841 // Lower vectors of pointers to native pointer types.
1842 EVT EltVT;
1843 if (auto *PTy = dyn_cast<PointerType>(EltTy))
1844 EltVT = getPointerTy(DL, PTy->getAddressSpace());
1845 else
1846 EltVT = EVT::getEVT(EltTy, false);
1847 return EVT::getVectorVT(Ty->getContext(), EltVT, VTy->getElementCount());
1848 }
1849
1850 return EVT::getEVT(Ty, AllowUnknown);
1851 }
1852
1854 bool AllowUnknown = false) const {
1855 // Lower scalar pointers to native pointer types.
1856 if (auto *PTy = dyn_cast<PointerType>(Ty))
1857 return getPointerMemTy(DL, PTy->getAddressSpace());
1858
1859 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1860 Type *EltTy = VTy->getElementType();
1861 EVT EltVT;
1862 if (auto *PTy = dyn_cast<PointerType>(EltTy))
1863 EltVT = getPointerMemTy(DL, PTy->getAddressSpace());
1864 else
1865 EltVT = EVT::getEVT(EltTy, false);
1866 return EVT::getVectorVT(Ty->getContext(), EltVT, VTy->getElementCount());
1867 }
1868
1869 return getValueType(DL, Ty, AllowUnknown);
1870 }
1871
1872
1873 /// Return the MVT corresponding to this LLVM type. See getValueType.
1875 bool AllowUnknown = false) const {
1876 return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1877 }
1878
1879 /// Returns the desired alignment for ByVal or InAlloca aggregate function
1880 /// arguments in the caller parameter area.
1881 virtual Align getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1882
1883 /// Return the type of registers that this ValueType will eventually require.
1884 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1885 return getRegisterTypeImpl(Context, VT, /*ForCallingConv=*/false);
1886 }
1887
1888 /// Return the number of registers that this ValueType will eventually
1889 /// require.
1890 ///
1891 /// This is one for any types promoted to live in larger registers, but may be
1892 /// more than one for types (like i64) that are split into pieces. For types
1893 /// like i140, which are first promoted then expanded, it is the number of
1894 /// registers needed to hold all the bits of the original type. For an i140
1895 /// on a 32 bit machine this means 5 registers.
1896 ///
1897 /// RegisterVT may be passed as a way to override the default settings, for
1898 /// instance with i128 inline assembly operands on SystemZ.
1899 virtual unsigned
1901 std::optional<MVT> RegisterVT = std::nullopt) const {
1902 return getNumRegistersImpl(Context, VT, /*ForCallingConv=*/false);
1903 }
1904
1905 /// Certain combinations of ABIs, Targets and features require that types
1906 /// are legal for some operations and not for other operations.
1907 /// For MIPS all vector types must be passed through the integer register set.
1909 CallingConv::ID CC, EVT VT) const {
1910 return getRegisterTypeImpl(Context, VT, /*ForCallingConv=*/true);
1911 }
1912
1913 /// Certain targets require unusual breakdowns of certain types. For MIPS,
1914 /// this occurs when a vector type is used, as vector are passed through the
1915 /// integer register set.
1917 CallingConv::ID CC,
1918 EVT VT) const {
1919 return getNumRegistersImpl(Context, VT, /*ForCallingConv=*/true);
1920 }
1921
1922 /// Certain targets have context sensitive alignment requirements, where one
1923 /// type has the alignment requirement of another type.
1925 const DataLayout &DL) const {
1926 return DL.getABITypeAlign(ArgTy);
1927 }
1928
1929 /// If true, then instruction selection should seek to shrink the FP constant
1930 /// of the specified type to a smaller type in order to save space and / or
1931 /// reduce runtime.
1932 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1933
1934 /// Return true if it is profitable to reduce a load to a smaller type.
1935 /// \p ByteOffset is only set if we know the pointer offset at compile time
1936 /// otherwise we should assume that additional pointer math is required.
1937 /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
1938 /// Example: (i16 (trunc (srl (i32 (load x)), 16)) -> i16 load x+2
1940 SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT,
1941 std::optional<unsigned> ByteOffset = std::nullopt) const {
1942 // By default, assume that it is cheaper to extract a subvector from a wide
1943 // vector load rather than creating multiple narrow vector loads.
1944 if (NewVT.isVector() && !SDValue(Load, 0).hasOneUse())
1945 return false;
1946
1947 return true;
1948 }
1949
1950 /// Return true (the default) if it is profitable to remove a sext_inreg(x)
1951 /// where the sext is redundant, and use x directly.
1952 virtual bool shouldRemoveRedundantExtend(SDValue Op) const { return true; }
1953
1954 /// Indicates if any padding is guaranteed to go at the most significant bits
1955 /// when storing the type to memory and the type size isn't equal to the store
1956 /// size.
1958 return VT.isScalarInteger() && !VT.isByteSized();
1959 }
1960
1961 /// When splitting a value of the specified type into parts, does the Lo
1962 /// or Hi part come first? This usually follows the endianness, except
1963 /// for ppcf128, where the Hi part always comes first.
1965 return DL.isBigEndian() || VT == MVT::ppcf128;
1966 }
1967
1968 /// If true, the target has custom DAG combine transformations that it can
1969 /// perform for the specified node.
1971 assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
1972 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1973 }
1974
1977 }
1978
1979 /// Returns the size of the platform's va_list object.
1980 virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1981 return getPointerTy(DL).getSizeInBits();
1982 }
1983
1984 /// Get maximum # of store operations permitted for llvm.memset
1985 ///
1986 /// This function returns the maximum number of store operations permitted
1987 /// to replace a call to llvm.memset. The value is set by the target at the
1988 /// performance threshold for such a replacement. If OptSize is true,
1989 /// return the limit for functions that have OptSize attribute.
1990 unsigned getMaxStoresPerMemset(bool OptSize) const;
1991
1992 /// Get maximum # of store operations permitted for llvm.memcpy
1993 ///
1994 /// This function returns the maximum number of store operations permitted
1995 /// to replace a call to llvm.memcpy. The value is set by the target at the
1996 /// performance threshold for such a replacement. If OptSize is true,
1997 /// return the limit for functions that have OptSize attribute.
1998 unsigned getMaxStoresPerMemcpy(bool OptSize) const;
1999
2000 /// \brief Get maximum # of store operations to be glued together
2001 ///
2002 /// This function returns the maximum number of store operations permitted
2003 /// to glue together during lowering of llvm.memcpy. The value is set by
2004 // the target at the performance threshold for such a replacement.
2005 virtual unsigned getMaxGluedStoresPerMemcpy() const {
2007 }
2008
2009 /// Get maximum # of load operations permitted for memcmp
2010 ///
2011 /// This function returns the maximum number of load operations permitted
2012 /// to replace a call to memcmp. The value is set by the target at the
2013 /// performance threshold for such a replacement. If OptSize is true,
2014 /// return the limit for functions that have OptSize attribute.
2015 unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
2017 }
2018
2019 /// Get maximum # of store operations permitted for llvm.memmove
2020 ///
2021 /// This function returns the maximum number of store operations permitted
2022 /// to replace a call to llvm.memmove. The value is set by the target at the
2023 /// performance threshold for such a replacement. If OptSize is true,
2024 /// return the limit for functions that have OptSize attribute.
2025 unsigned getMaxStoresPerMemmove(bool OptSize) const;
2026
2027 /// Determine if the target supports unaligned memory accesses.
2028 ///
2029 /// This function returns true if the target allows unaligned memory accesses
2030 /// of the specified type in the given address space. If true, it also returns
2031 /// a relative speed of the unaligned memory access in the last argument by
2032 /// reference. The higher the speed number the faster the operation comparing
2033 /// to a number returned by another such call. This is used, for example, in
2034 /// situations where an array copy/move/set is converted to a sequence of
2035 /// store operations. Its use helps to ensure that such replacements don't
2036 /// generate code that causes an alignment error (trap) on the target machine.
2038 EVT, unsigned AddrSpace = 0, Align Alignment = Align(1),
2040 unsigned * /*Fast*/ = nullptr) const {
2041 return false;
2042 }
2043
2044 /// LLT handling variant.
2046 LLT, unsigned AddrSpace = 0, Align Alignment = Align(1),
2048 unsigned * /*Fast*/ = nullptr) const {
2049 return false;
2050 }
2051
2052 /// This function returns true if the memory access is aligned or if the
2053 /// target allows this specific unaligned memory access. If the access is
2054 /// allowed, the optional final parameter returns a relative speed of the
2055 /// access (as defined by the target).
2056 bool allowsMemoryAccessForAlignment(
2057 LLVMContext &Context, const DataLayout &DL, EVT VT,
2058 unsigned AddrSpace = 0, Align Alignment = Align(1),
2060 unsigned *Fast = nullptr) const;
2061
2062 /// Return true if the memory access of this type is aligned or if the target
2063 /// allows this specific unaligned access for the given MachineMemOperand.
2064 /// If the access is allowed, the optional final parameter returns a relative
2065 /// speed of the access (as defined by the target).
2066 bool allowsMemoryAccessForAlignment(LLVMContext &Context,
2067 const DataLayout &DL, EVT VT,
2068 const MachineMemOperand &MMO,
2069 unsigned *Fast = nullptr) const;
2070
2071 /// Return true if the target supports a memory access of this type for the
2072 /// given address space and alignment. If the access is allowed, the optional
2073 /// final parameter returns the relative speed of the access (as defined by
2074 /// the target).
2075 virtual bool
2076 allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
2077 unsigned AddrSpace = 0, Align Alignment = Align(1),
2079 unsigned *Fast = nullptr) const;
2080
2081 /// Return true if the target supports a memory access of this type for the
2082 /// given MachineMemOperand. If the access is allowed, the optional
2083 /// final parameter returns the relative access speed (as defined by the
2084 /// target).
2085 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
2086 const MachineMemOperand &MMO,
2087 unsigned *Fast = nullptr) const;
2088
2089 /// LLT handling variant.
2090 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, LLT Ty,
2091 const MachineMemOperand &MMO,
2092 unsigned *Fast = nullptr) const;
2093
2094 /// Returns the target specific optimal type for load and store operations as
2095 /// a result of memset, memcpy, and memmove lowering.
2096 /// It returns EVT::Other if the type should be determined using generic
2097 /// target-independent logic.
2098 virtual EVT
2100 const AttributeList & /*FuncAttributes*/) const {
2101 return MVT::Other;
2102 }
2103
2104 /// LLT returning variant.
2105 virtual LLT
2107 const AttributeList & /*FuncAttributes*/) const {
2108 return LLT();
2109 }
2110
2111 /// Returns true if it's safe to use load / store of the specified type to
2112 /// expand memcpy / memset inline.
2113 ///
2114 /// This is mostly true for all types except for some special cases. For
2115 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
2116 /// fstpl which also does type conversion. Note the specified type doesn't
2117 /// have to be legal as the hook is used before type legalization.
2118 virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
2119
2120 /// Return lower limit for number of blocks in a jump table.
2121 virtual unsigned getMinimumJumpTableEntries() const;
2122
2123 /// Return lower limit of the density in a jump table.
2124 unsigned getMinimumJumpTableDensity(bool OptForSize) const;
2125
2126 /// Return upper limit for number of entries in a jump table.
2127 /// Zero if no limit.
2128 unsigned getMaximumJumpTableSize() const;
2129
2130 virtual bool isJumpTableRelative() const;
2131
2132 /// Retuen the minimum of largest number of comparisons in BitTest.
2133 unsigned getMinimumBitTestCmps() const;
2134
2135 /// Return maximum known-legal store size, which can be guaranteed for
2136 /// scalable vectors.
2138 return MaximumLegalStoreInBits;
2139 }
2140
2141 /// If a physical register, this specifies the register that
2142 /// llvm.savestack/llvm.restorestack should save and restore.
2144 return StackPointerRegisterToSaveRestore;
2145 }
2146
2147 /// If a physical register, this returns the register that receives the
2148 /// exception address on entry to an EH pad.
2149 virtual Register
2151 const Constant *PersonalityFn) const {
2152 return Register();
2153 }
2154
2155 /// If a physical register, this returns the register that receives the
2156 /// exception typeid on entry to a landing pad.
2157 virtual Register
2159 const Constant *PersonalityFn) const {
2160 return Register();
2161 }
2162
2163 virtual bool needsFixedCatchObjects() const {
2164 reportFatalUsageError("Funclet EH is not implemented for this target");
2165 }
2166
2167 /// Return the minimum stack alignment of an argument.
2169 return MinStackArgumentAlignment;
2170 }
2171
2172 /// Return the minimum function alignment.
2173 Align getMinFunctionAlignment() const { return MinFunctionAlignment; }
2174
2175 /// Return the preferred function alignment.
2176 Align getPrefFunctionAlignment() const { return PrefFunctionAlignment; }
2177
2178 /// Return the preferred loop alignment. \p BlockToAlign, when non-null, is
2179 /// the block that will actually be aligned; after loop rotation this need not
2180 /// be the LoopInfo header. Targets whose alignment depends on the block
2181 /// contents should use it. Callers that are not aligning a particular block,
2182 /// such as llvm-exegesis and ARM constant islands, leave it null.
2183 virtual Align
2184 getPrefLoopAlignment(MachineLoop *ML = nullptr,
2185 const MachineBasicBlock *BlockToAlign = nullptr) const;
2186
2187 /// Return the maximum amount of bytes allowed to be emitted when padding for
2188 /// alignment
2189 virtual unsigned
2190 getMaxPermittedBytesForAlignment(MachineBasicBlock *MBB) const;
2191
2192 /// Should loops be aligned even when the function is marked OptSize (but not
2193 /// MinSize).
2194 virtual bool alignLoopsWithOptSize() const { return false; }
2195
2196 /// If the target has a standard location for the stack protector guard,
2197 /// returns the address of that location. Otherwise, returns nullptr.
2198 /// DEPRECATED: please override useLoadStackGuardNode and customize
2199 /// LOAD_STACK_GUARD, or customize \@llvm.stackguard().
2200 virtual Value *getIRStackGuard(IRBuilderBase &IRB,
2201 const LibcallLoweringInfo &Libcalls) const;
2202
2203 /// Inserts necessary declarations for SSP (stack protection) purpose.
2204 /// Should be used only when getIRStackGuard returns nullptr.
2205 virtual void insertSSPDeclarations(Module &M,
2206 const LibcallLoweringInfo &Libcalls) const;
2207
2208 /// Return the variable that's previously inserted by insertSSPDeclarations,
2209 /// if any, otherwise return nullptr. Should be used only when
2210 /// getIRStackGuard returns nullptr.
2211 virtual Value *getSDagStackGuard(const Module &M,
2212 const LibcallLoweringInfo &Libcalls) const;
2213
2214 /// If this function returns true, stack protection checks should mix the
2215 /// frame pointer (or whichever pointer is used to address locals) into the
2216 /// stack guard value before checking it. getIRStackGuard must return nullptr
2217 /// if this returns true.
2218 virtual bool useStackGuardMixFP() const { return false; }
2219
2220 /// If the target has a standard stack protection check function that
2221 /// performs validation and error handling, returns the function. Otherwise,
2222 /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
2223 /// Should be used only when getIRStackGuard returns nullptr.
2224 Function *getSSPStackGuardCheck(const Module &M,
2225 const LibcallLoweringInfo &Libcalls) const;
2226
2227protected:
2228 Value *getDefaultSafeStackPointerLocation(IRBuilderBase &IRB,
2229 bool UseTLS) const;
2230
2231public:
2232 /// Returns the target-specific address of the unsafe stack pointer.
2233 virtual Value *
2234 getSafeStackPointerLocation(IRBuilderBase &IRB,
2235 const LibcallLoweringInfo &Libcalls) const;
2236
2237 /// Returns the name of the symbol used to emit stack probes or the empty
2238 /// string if not applicable.
2239 virtual bool hasStackProbeSymbol(const MachineFunction &MF) const { return false; }
2240
2241 virtual bool hasInlineStackProbe(const MachineFunction &MF) const { return false; }
2242
2244 return "";
2245 }
2246
2247 /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
2248 /// are happy to sink it into basic blocks. A cast may be free, but not
2249 /// necessarily a no-op. e.g. a free truncate from a 64-bit to 32-bit pointer.
2250 virtual bool isFreeAddrSpaceCast(const DataLayout &DL, unsigned SrcAS,
2251 unsigned DestAS) const;
2252
2253 /// Return true if the pointer arguments to CI should be aligned by aligning
2254 /// the object whose address is being passed. If so then MinSize is set to the
2255 /// minimum size the object must be to be aligned and PrefAlign is set to the
2256 /// preferred alignment.
2257 virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
2258 Align & /*PrefAlign*/) const {
2259 return false;
2260 }
2261
2262 //===--------------------------------------------------------------------===//
2263 /// \name Helpers for TargetTransformInfo implementations
2264 /// @{
2265
2266 /// Get the ISD node that corresponds to the Instruction class opcode.
2267 int InstructionOpcodeToISD(unsigned Opcode) const;
2268
2269 /// Get the ISD node that corresponds to the Intrinsic ID. Returns
2270 /// ISD::DELETED_NODE by default for an unsupported Intrinsic ID.
2271 int IntrinsicIDToISD(Intrinsic::ID ID) const;
2272
2273 /// @}
2274
2275 //===--------------------------------------------------------------------===//
2276 /// \name Helpers for atomic expansion.
2277 /// @{
2278
2279 /// Returns the maximum atomic operation size (in bits) supported by
2280 /// the backend. Atomic operations greater than this size (as well
2281 /// as ones that are not naturally aligned), will be expanded by
2282 /// AtomicExpandPass into an __atomic_* library call.
2284 return MaxAtomicSizeInBitsSupported;
2285 }
2286
2287 /// Returns the size in bits of the maximum div/rem the backend supports.
2288 /// Larger operations will be expanded by ExpandIRInsts.
2290 return MaxDivRemBitWidthSupported;
2291 }
2292
2293 /// Returns the size in bits of the maximum fp to/from int conversion the
2294 /// backend supports. Larger operations will be expanded by ExpandIRInsts.
2296 return MaxLargeFPConvertBitWidthSupported;
2297 }
2298
2299 /// Returns the size of the smallest cmpxchg or ll/sc instruction
2300 /// the backend supports. Any smaller operations are widened in
2301 /// AtomicExpandPass.
2302 ///
2303 /// Note that *unlike* operations above the maximum size, atomic ops
2304 /// are still natively supported below the minimum; they just
2305 /// require a more complex expansion.
2306 unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
2307
2308 /// Return true if the target supports an atomic access of \p SizeInBytes
2309 /// bytes at the given \p Alignment. The default implementation only allows
2310 /// naturally aligned atomics, unless setSupportsUnalignedAtomics(true) was
2311 /// called.
2312 virtual bool isAtomicAlignmentSupported(Align Alignment,
2313 uint64_t SizeInBytes) const {
2314 return SupportsUnalignedAtomics || Alignment.value() >= SizeInBytes;
2315 }
2316
2317 /// Whether AtomicExpandPass should automatically insert fences and reduce
2318 /// ordering for this atomic. This should be true for most architectures with
2319 /// weak memory ordering. Defaults to false.
2320 virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
2321 return false;
2322 }
2323
2324 /// Whether AtomicExpandPass should automatically insert a seq_cst trailing
2325 /// fence without reducing the ordering for this atomic store. Defaults to
2326 /// false.
2327 virtual bool
2329 return false;
2330 }
2331
2332 // The memory ordering that AtomicExpandPass should assign to a atomic
2333 // instruction that it has lowered by adding fences. This can be used
2334 // to "fold" one of the fences into the atomic instruction.
2335 virtual AtomicOrdering
2339
2340 // Whether to issue an atomic load for the initial word value before the
2341 // atomicrmw/cmpxchg emulation loop.
2342 // TODO: For correctness, an atomic load should be issued for all targets.
2343 // Remove this API once this is achieved
2345 return true;
2346 }
2347
2348 /// Perform a load-linked operation on Addr, returning a "Value *" with the
2349 /// corresponding pointee type. This may entail some non-trivial operations to
2350 /// truncate or reconstruct types that will be illegal in the backend. See
2351 /// ARMISelLowering for an example implementation.
2352 virtual Value *emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy,
2353 Value *Addr, AtomicOrdering Ord) const {
2354 llvm_unreachable("Load linked unimplemented on this target");
2355 }
2356
2357 /// Perform a store-conditional operation to Addr. Return the status of the
2358 /// store. This should be 0 if the store succeeded, non-zero otherwise.
2360 Value *Addr, AtomicOrdering Ord) const {
2361 llvm_unreachable("Store conditional unimplemented on this target");
2362 }
2363
2364 /// Perform a masked atomicrmw using a target-specific intrinsic. This
2365 /// represents the core LL/SC loop which will be lowered at a late stage by
2366 /// the backend. The target-specific intrinsic returns the loaded value and
2367 /// is not responsible for masking and shifting the result.
2369 AtomicRMWInst *AI,
2370 Value *AlignedAddr, Value *Incr,
2371 Value *Mask, Value *ShiftAmt,
2372 AtomicOrdering Ord) const {
2373 llvm_unreachable("Masked atomicrmw expansion unimplemented on this target");
2374 }
2375
2376 /// Perform a atomicrmw expansion using a target-specific way. This is
2377 /// expected to be called when masked atomicrmw and bit test atomicrmw don't
2378 /// work, and the target supports another way to lower atomicrmw.
2379 virtual void emitExpandAtomicRMW(AtomicRMWInst *AI) const {
2381 "Generic atomicrmw expansion unimplemented on this target");
2382 }
2383
2384 /// Perform a atomic store using a target-specific way.
2385 virtual void emitExpandAtomicStore(StoreInst *SI) const {
2387 "Generic atomic store expansion unimplemented on this target");
2388 }
2389
2390 /// Perform a atomic load using a target-specific way.
2391 virtual void emitExpandAtomicLoad(LoadInst *LI) const {
2393 "Generic atomic load expansion unimplemented on this target");
2394 }
2395
2396 /// Perform a cmpxchg expansion using a target-specific method.
2398 llvm_unreachable("Generic cmpxchg expansion unimplemented on this target");
2399 }
2400
2401 /// Perform a bit test atomicrmw using a target-specific intrinsic. This
2402 /// represents the combined bit test intrinsic which will be lowered at a late
2403 /// stage by the backend.
2406 "Bit test atomicrmw expansion unimplemented on this target");
2407 }
2408
2409 /// Perform a atomicrmw which the result is only used by comparison, using a
2410 /// target-specific intrinsic. This represents the combined atomic and compare
2411 /// intrinsic which will be lowered at a late stage by the backend.
2414 "Compare arith atomicrmw expansion unimplemented on this target");
2415 }
2416
2417 /// Perform a masked cmpxchg using a target-specific intrinsic. This
2418 /// represents the core LL/SC loop which will be lowered at a late stage by
2419 /// the backend. The target-specific intrinsic returns the loaded value and
2420 /// is not responsible for masking and shifting the result.
2422 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
2423 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
2424 llvm_unreachable("Masked cmpxchg expansion unimplemented on this target");
2425 }
2426
2427 //===--------------------------------------------------------------------===//
2428 /// \name KCFI check lowering.
2429 /// @{
2430
2433 const TargetInstrInfo *TII) const {
2434 llvm_unreachable("KCFI is not supported on this target");
2435 }
2436
2437 /// @}
2438
2439 //===--------------------------------------------------------------------===//
2440 /// \name Speculative load lowering.
2441 /// @{
2442
2443 /// Emit code to check if a speculative load of the given size from Ptr is
2444 /// safe. Returns a Value* representing the check result (i1), or nullptr
2445 /// to use the default lowering (which returns false). Targets can override
2446 /// to provide their own safety check (e.g., alignment-based page boundary
2447 /// check).
2448 /// \param Builder IRBuilder positioned at the intrinsic call site
2449 /// \param Ptr the pointer operand
2450 /// \param Size the size in bytes (constant or runtime value for scalable)
2452 Value *Size) const {
2453 return nullptr;
2454 }
2455
2456 /// @}
2457
2458 /// Inserts in the IR a target-specific intrinsic specifying a fence.
2459 /// It is called by AtomicExpandPass before expanding an
2460 /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
2461 /// if shouldInsertFencesForAtomic returns true.
2462 ///
2463 /// Inst is the original atomic instruction, prior to other expansions that
2464 /// may be performed.
2465 ///
2466 /// This function should either return a nullptr, or a pointer to an IR-level
2467 /// Instruction*. Even complex fence sequences can be represented by a
2468 /// single Instruction* through an intrinsic to be lowered later.
2469 ///
2470 /// The default implementation emits an IR fence before any release (or
2471 /// stronger) operation that stores, and after any acquire (or stronger)
2472 /// operation. This is generally a correct implementation, but backends may
2473 /// override if they wish to use alternative schemes (e.g. the PowerPC
2474 /// standard ABI uses a fence before a seq_cst load instead of after a
2475 /// seq_cst store).
2476 /// @{
2477 virtual Instruction *emitLeadingFence(IRBuilderBase &Builder,
2478 Instruction *Inst,
2479 AtomicOrdering Ord) const;
2480
2481 virtual Instruction *emitTrailingFence(IRBuilderBase &Builder,
2482 Instruction *Inst,
2483 AtomicOrdering Ord) const;
2484 /// @}
2485
2486 // Emits code that executes when the comparison result in the ll/sc
2487 // expansion of a cmpxchg instruction is such that the store-conditional will
2488 // not execute. This makes it possible to balance out the load-linked with
2489 // a dedicated instruction, if desired.
2490 // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
2491 // be unnecessarily held, except if clrex, inserted by this hook, is executed.
2492 virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilderBase &Builder) const {}
2493
2494 /// Returns true if arguments should be sign-extended in lib calls.
2495 virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const {
2496 return IsSigned;
2497 }
2498
2499 /// Returns true if arguments should be extended in lib calls.
2500 virtual bool shouldExtendTypeInLibCall(EVT Type) const {
2501 return true;
2502 }
2503
2504 /// Returns how the given (atomic) load should be expanded by the
2505 /// IR-level AtomicExpand pass.
2509
2510 /// Returns how the given (atomic) load should be cast by the IR-level
2511 /// AtomicExpand pass.
2517
2518 /// Returns how the given (atomic) store should be expanded by the IR-level
2519 /// AtomicExpand pass into. For instance AtomicExpansionKind::CustomExpand
2520 /// will try to use an atomicrmw xchg.
2524
2525 /// Returns how the given (atomic) store should be cast by the IR-level
2526 /// AtomicExpand pass into. For instance AtomicExpansionKind::CastToInteger
2527 /// will try to cast the operands to integer values.
2529 if (SI->getValueOperand()->getType()->isFloatingPointTy())
2532 }
2533
2534 /// Returns how the given atomic cmpxchg should be expanded by the IR-level
2535 /// AtomicExpand pass.
2536 virtual AtomicExpansionKind
2540
2541 /// Returns how the IR-level AtomicExpand pass should expand the given
2542 /// AtomicRMW, if at all. Default is to never expand.
2543 virtual AtomicExpansionKind
2545 if (RMW->isFloatingPointOperation())
2547 if (RMW->getType()->isVectorTy())
2550 }
2551
2552 /// Returns how the given atomic atomicrmw should be cast by the IR-level
2553 /// AtomicExpand pass.
2554 virtual AtomicExpansionKind
2556 Type *ValTy = RMWI->getValOperand()->getType();
2557 if (RMWI->getOperation() == AtomicRMWInst::Xchg &&
2558 (ValTy->isFloatingPointTy() || ValTy->isPointerTy() ||
2559 ValTy->isVectorTy()))
2561
2563 }
2564
2565 /// On some platforms, an AtomicRMW that never actually modifies the value
2566 /// (such as fetch_add of 0) can be turned into a fence followed by an
2567 /// atomic load. This may sound useless, but it makes it possible for the
2568 /// processor to keep the cacheline shared, dramatically improving
2569 /// performance. And such idempotent RMWs are useful for implementing some
2570 /// kinds of locks, see for example (justification + benchmarks):
2571 /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
2572 /// This method tries doing that transformation, returning the atomic load if
2573 /// it succeeds, and nullptr otherwise.
2574 /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
2575 /// another round of expansion.
2576 virtual LoadInst *
2578 return nullptr;
2579 }
2580
2581 /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
2582 /// SIGN_EXTEND, or ANY_EXTEND).
2584 return ISD::ZERO_EXTEND;
2585 }
2586
2587 /// Returns how the platform's atomic compare and swap expects its comparison
2588 /// value to be extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND). This is
2589 /// separate from getExtendForAtomicOps, which is concerned with the
2590 /// sign-extension of the instruction's output, whereas here we are concerned
2591 /// with the sign-extension of the input. For targets with compare-and-swap
2592 /// instructions (or sub-word comparisons in their LL/SC loop expansions),
2593 /// the input can be ANY_EXTEND, but the output will still have a specific
2594 /// extension.
2596 return ISD::ANY_EXTEND;
2597 }
2598
2599 /// Returns how the platform's atomic rmw operations expect their input
2600 /// argument to be extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND).
2602 return ISD::ANY_EXTEND;
2603 }
2604
2605 /// @}
2606
2607 /// Returns true if we should normalize
2608 /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
2609 /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
2610 /// that it saves us from materializing N0 and N1 in an integer register.
2611 /// Targets that are able to perform and/or on flags should return false here.
2612 /// \p VT is the type of the select (and X and Y). \p CCVT is the type of its
2613 /// condition (N0 and N1).
2615 EVT CCVT) const {
2616 // If a target has multiple condition registers, then it likely has logical
2617 // operations on those registers.
2619 return false;
2620 // Only do the transform if the value won't be split into multiple
2621 // registers.
2622 LegalizeTypeAction Action = getTypeAction(Context, VT);
2623 return Action != TypeExpandInteger && Action != TypeExpandFloat &&
2624 Action != TypeSplitVector;
2625 }
2626
2627 virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const { return true; }
2628
2629 /// Return true if a select of constants (select Cond, C1, C2) should be
2630 /// transformed into simple math ops with the condition value. For example:
2631 /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
2632 virtual bool convertSelectOfConstantsToMath(EVT VT) const {
2633 return false;
2634 }
2635
2636 /// Return true if it is profitable to transform an integer
2637 /// multiplication-by-constant into simpler operations like shifts and adds.
2638 /// This may be true if the target does not directly support the
2639 /// multiplication operation for the specified type or the sequence of simpler
2640 /// ops is faster than the multiply.
2642 EVT VT, SDValue C) const {
2643 return false;
2644 }
2645
2646 /// Return true if it may be profitable to transform
2647 /// (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
2648 /// This may not be true if c1 and c2 can be represented as immediates but
2649 /// c1*c2 cannot, for example.
2650 /// The target should check if c1, c2 and c1*c2 can be represented as
2651 /// immediates, or have to be materialized into registers. If it is not sure
2652 /// about some cases, a default true can be returned to let the DAGCombiner
2653 /// decide.
2654 /// AddNode is (add x, c1), and ConstNode is c2.
2656 SDValue ConstNode) const {
2657 return true;
2658 }
2659
2660 /// Return true if it is more correct/profitable to use strict FP_TO_INT
2661 /// conversion operations - canonicalizing the FP source value instead of
2662 /// converting all cases and then selecting based on value.
2663 /// This may be true if the target throws exceptions for out of bounds
2664 /// conversions or has fast FP CMOV.
2665 virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
2666 bool IsSigned) const {
2667 return false;
2668 }
2669
2670 /// Return true if it is beneficial to expand an @llvm.powi.* intrinsic.
2671 /// If not optimizing for size, expanding @llvm.powi.* intrinsics is always
2672 /// considered beneficial.
2673 /// If optimizing for size, expansion is only considered beneficial for upto
2674 /// 5 multiplies and a divide (if the exponent is negative).
2675 bool isBeneficialToExpandPowI(int64_t Exponent, bool OptForSize) const {
2676 if (Exponent < 0)
2677 Exponent = -Exponent;
2678 uint64_t E = static_cast<uint64_t>(Exponent);
2679 return !OptForSize || (llvm::popcount(E) + Log2_64(E) < 7);
2680 }
2681
2682 //===--------------------------------------------------------------------===//
2683 // TargetLowering Configuration Methods - These methods should be invoked by
2684 // the derived class constructor to configure this object for the target.
2685 //
2686protected:
2687 /// Specify how the target extends the result of integer and floating point
2688 /// boolean values from i1 to a wider type. See getBooleanContents.
2690 BooleanContents = Ty;
2691 BooleanFloatContents = Ty;
2692 }
2693
2694 /// Specify how the target extends the result of integer and floating point
2695 /// boolean values from i1 to a wider type. See getBooleanContents.
2697 BooleanContents = IntTy;
2698 BooleanFloatContents = FloatTy;
2699 }
2700
2701 /// Specify how the target extends the result of a vector boolean value from a
2702 /// vector of i1 to a wider type. See getBooleanContents.
2704 BooleanVectorContents = Ty;
2705 }
2706
2707 /// Specify the target scheduling preference.
2709 SchedPreferenceInfo = Pref;
2710 }
2711
2712 /// Indicate the minimum number of blocks to generate jump tables.
2713 void setMinimumJumpTableEntries(unsigned Val);
2714
2715 /// Indicate the maximum number of entries in jump tables.
2716 /// Set to zero to generate unlimited jump tables.
2717 void setMaximumJumpTableSize(unsigned);
2718
2719 /// Set the minimum of largest of number of comparisons to generate BitTest.
2720 void setMinimumBitTestCmps(unsigned Val);
2721
2722 /// If set to a physical register, this specifies the register that
2723 /// llvm.savestack/llvm.restorestack should save and restore.
2725 StackPointerRegisterToSaveRestore = R;
2726 }
2727
2728 /// Tells the code generator that the target has BitExtract instructions.
2729 /// The code generator will aggressively sink "shift"s into the blocks of
2730 /// their users if the users will generate "and" instructions which can be
2731 /// combined with "shift" to BitExtract instructions.
2732 void setHasExtractBitsInsn(bool hasExtractInsn = true) {
2733 HasExtractBitsInsn = hasExtractInsn;
2734 }
2735
2736 /// Tells the code generator not to expand logic operations on comparison
2737 /// predicates into separate sequences that increase the amount of flow
2738 /// control.
2739 void setJumpIsExpensive(bool isExpensive = true);
2740
2741 /// Tells the code generator which bitwidths to bypass.
2742 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
2743 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
2744 }
2745
2746 /// Add the specified register class as an available regclass for the
2747 /// specified value type. This indicates the selector can handle values of
2748 /// that class natively.
2750 assert((unsigned)VT.SimpleTy < std::size(RegClassForVT));
2751 RegClassForVT[VT.SimpleTy] = RC;
2752 }
2753
2754 /// Return the largest legal super-reg register class of the register class
2755 /// for the specified type and its associated "cost".
2756 virtual std::pair<const TargetRegisterClass *, uint8_t>
2757 findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
2758
2759 /// Once all of the register classes are added, this allows us to compute
2760 /// derived properties we expose.
2761 void computeRegisterProperties(const TargetRegisterInfo *TRI);
2762
2763 /// Indicate that the specified operation does not work with the specified
2764 /// type and indicate what to do about it. Note that VT may refer to either
2765 /// the type of a result or that of an operand of Op.
2766 void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action) {
2767 assert(Op < std::size(OpActions[0]) && "Table isn't big enough!");
2768 OpActions[(unsigned)VT.SimpleTy][Op] = Action;
2769 }
2771 LegalizeAction Action) {
2772 for (auto Op : Ops)
2773 setOperationAction(Op, VT, Action);
2774 }
2776 LegalizeAction Action) {
2777 for (auto VT : VTs)
2778 setOperationAction(Ops, VT, Action);
2779 }
2780
2781 /// Indicate that the specified load with extension does not work with the
2782 /// specified type and indicate what to do about it.
2783 void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
2784 LegalizeAction Action) {
2785 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
2786 MemVT.isValid() && "Table isn't big enough!");
2787 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2788 unsigned Shift = 4 * ExtType;
2789 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
2790 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
2791 }
2792 void setLoadExtAction(ArrayRef<unsigned> ExtTypes, MVT ValVT, MVT MemVT,
2793 LegalizeAction Action) {
2794 for (auto ExtType : ExtTypes)
2795 setLoadExtAction(ExtType, ValVT, MemVT, Action);
2796 }
2798 ArrayRef<MVT> MemVTs, LegalizeAction Action) {
2799 for (auto MemVT : MemVTs)
2800 setLoadExtAction(ExtTypes, ValVT, MemVT, Action);
2801 }
2802
2803 /// Let target indicate that an extending atomic load of the specified type
2804 /// is legal.
2805 void setAtomicLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
2806 LegalizeAction Action) {
2807 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
2808 MemVT.isValid() && "Table isn't big enough!");
2809 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2810 unsigned Shift = 4 * ExtType;
2811 AtomicLoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &=
2812 ~((uint16_t)0xF << Shift);
2813 AtomicLoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |=
2814 ((uint16_t)Action << Shift);
2815 }
2817 LegalizeAction Action) {
2818 for (auto ExtType : ExtTypes)
2819 setAtomicLoadExtAction(ExtType, ValVT, MemVT, Action);
2820 }
2822 ArrayRef<MVT> MemVTs, LegalizeAction Action) {
2823 for (auto MemVT : MemVTs)
2824 setAtomicLoadExtAction(ExtTypes, ValVT, MemVT, Action);
2825 }
2826
2827 /// Indicate that the specified truncating store does not work with the
2828 /// specified type and indicate what to do about it.
2829 void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action) {
2830 assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
2831 TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
2832 }
2833
2834 /// Indicate that the specified indexed load does or does not work with the
2835 /// specified type and indicate what to do abort it.
2836 ///
2837 /// NOTE: All indexed mode loads are initialized to Expand in
2838 /// TargetLowering.cpp
2840 LegalizeAction Action) {
2841 for (auto IdxMode : IdxModes)
2842 setIndexedModeAction(IdxMode, VT, IMAB_Load, Action);
2843 }
2844
2846 LegalizeAction Action) {
2847 for (auto VT : VTs)
2848 setIndexedLoadAction(IdxModes, VT, Action);
2849 }
2850
2851 /// Indicate that the specified indexed store does or does not work with the
2852 /// specified type and indicate what to do about it.
2853 ///
2854 /// NOTE: All indexed mode stores are initialized to Expand in
2855 /// TargetLowering.cpp
2857 LegalizeAction Action) {
2858 for (auto IdxMode : IdxModes)
2859 setIndexedModeAction(IdxMode, VT, IMAB_Store, Action);
2860 }
2861
2863 LegalizeAction Action) {
2864 for (auto VT : VTs)
2865 setIndexedStoreAction(IdxModes, VT, Action);
2866 }
2867
2868 /// Indicate that the specified indexed masked load does or does not work with
2869 /// the specified type and indicate what to do about it.
2870 ///
2871 /// NOTE: All indexed mode masked loads are initialized to Expand in
2872 /// TargetLowering.cpp
2873 void setIndexedMaskedLoadAction(unsigned IdxMode, MVT VT,
2874 LegalizeAction Action) {
2875 setIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad, Action);
2876 }
2877
2878 /// Indicate that the specified indexed masked store does or does not work
2879 /// with the specified type and indicate what to do about it.
2880 ///
2881 /// NOTE: All indexed mode masked stores are initialized to Expand in
2882 /// TargetLowering.cpp
2883 void setIndexedMaskedStoreAction(unsigned IdxMode, MVT VT,
2884 LegalizeAction Action) {
2885 setIndexedModeAction(IdxMode, VT, IMAB_MaskedStore, Action);
2886 }
2887
2888 /// Indicate that the specified condition code is or isn't supported on the
2889 /// target and indicate what to do about it.
2891 LegalizeAction Action) {
2892 for (auto CC : CCs) {
2893 assert(VT.isValid() && (unsigned)CC < std::size(CondCodeActions) &&
2894 "Table isn't big enough!");
2895 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2896 /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the
2897 /// 32-bit value and the upper 29 bits index into the second dimension of
2898 /// the array to select what 32-bit value to use.
2899 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
2900 CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
2901 CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
2902 }
2903 }
2905 LegalizeAction Action) {
2906 for (auto VT : VTs)
2907 setCondCodeAction(CCs, VT, Action);
2908 }
2909
2910 /// Indicate how a PARTIAL_REDUCE_U/SMLA node with Acc type AccVT and Input
2911 /// type InputVT should be treated by the target. Either it's legal, needs to
2912 /// be promoted to a larger size, needs to be expanded to some other code
2913 /// sequence, or the target has a custom expander for it.
2914 void setPartialReduceMLAAction(unsigned Opc, MVT AccVT, MVT InputVT,
2915 LegalizeAction Action) {
2918 assert(AccVT.isValid() && InputVT.isValid() &&
2919 "setPartialReduceMLAAction types aren't valid");
2920 PartialReduceActionTypes Key = {Opc, AccVT.SimpleTy, InputVT.SimpleTy};
2921 PartialReduceMLAActions[Key] = Action;
2922 }
2924 MVT InputVT, LegalizeAction Action) {
2925 for (unsigned Opc : Opcodes)
2926 setPartialReduceMLAAction(Opc, AccVT, InputVT, Action);
2927 }
2928
2929 /// Indicate how a VECTOR_INTERLEAVE or VECTOR_DEINTERLEAVE node with the
2930 /// given interleave factor Factor and type VT should be treated.
2931 void setVectorInterleaveAction(unsigned Opc, unsigned Factor, MVT VT,
2932 LegalizeAction Action) {
2934 VectorInterleaveActionKey Key = {Opc, Factor, VT.SimpleTy};
2935 VectorInterleaveActions[Key] = Action;
2936 }
2937
2939 ArrayRef<unsigned> Factors, MVT VT,
2940 LegalizeAction Action) {
2941 for (unsigned Opc : Opcodes)
2942 for (unsigned Factor : Factors)
2943 setVectorInterleaveAction(Opc, Factor, VT, Action);
2944 }
2945
2946 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
2947 /// to trying a larger integer/fp until it can find one that works. If that
2948 /// default is insufficient, this method can be used by the target to override
2949 /// the default.
2950 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2951 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
2952 }
2953
2954 /// Convenience method to set an operation to Promote and specify the type
2955 /// in a single call.
2956 void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2957 setOperationAction(Opc, OrigVT, Promote);
2958 AddPromotedToType(Opc, OrigVT, DestVT);
2959 }
2961 MVT DestVT) {
2962 for (auto Op : Ops) {
2963 setOperationAction(Op, OrigVT, Promote);
2964 AddPromotedToType(Op, OrigVT, DestVT);
2965 }
2966 }
2967
2968 /// Targets should invoke this method for each target independent node that
2969 /// they want to provide a custom DAG combiner for by implementing the
2970 /// PerformDAGCombine virtual method.
2972 for (auto NT : NTs) {
2973 assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
2974 TargetDAGCombineArray[NT >> 3] |= 1 << (NT & 7);
2975 }
2976 }
2977
2978 /// Set the target's minimum function alignment.
2980 MinFunctionAlignment = Alignment;
2981 }
2982
2983 /// Set the target's preferred function alignment. This should be set if
2984 /// there is a performance benefit to higher-than-minimum alignment
2986 PrefFunctionAlignment = Alignment;
2987 }
2988
2989 /// Set the target's preferred loop alignment. Default alignment is one, it
2990 /// means the target does not care about loop alignment. The target may also
2991 /// override getPrefLoopAlignment to provide per-loop values.
2992 void setPrefLoopAlignment(Align Alignment) { PrefLoopAlignment = Alignment; }
2993 void setMaxBytesForAlignment(unsigned MaxBytes) {
2994 MaxBytesForAlignment = MaxBytes;
2995 }
2996
2997 /// Set the minimum stack alignment of an argument.
2999 MinStackArgumentAlignment = Alignment;
3000 }
3001
3002 /// Set the maximum atomic operation size supported by the
3003 /// backend. Atomic operations greater than this size (as well as
3004 /// ones that are not naturally aligned), will be expanded by
3005 /// AtomicExpandPass into an __atomic_* library call.
3006 void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
3007 MaxAtomicSizeInBitsSupported = SizeInBits;
3008 }
3009
3010 /// Set the size in bits of the maximum div/rem the backend supports.
3011 /// Larger operations will be expanded by ExpandIRInsts.
3012 void setMaxDivRemBitWidthSupported(unsigned SizeInBits) {
3013 MaxDivRemBitWidthSupported = SizeInBits;
3014 }
3015
3016 /// Set the size in bits of the maximum fp to/from int conversion the backend
3017 /// supports. Larger operations will be expanded by ExpandIRInsts.
3018 void setMaxLargeFPConvertBitWidthSupported(unsigned SizeInBits) {
3019 MaxLargeFPConvertBitWidthSupported = SizeInBits;
3020 }
3021
3022 /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
3023 void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
3024 MinCmpXchgSizeInBits = SizeInBits;
3025 }
3026
3027 /// Sets whether unaligned atomic operations are supported.
3028 void setSupportsUnalignedAtomics(bool UnalignedSupported) {
3029 SupportsUnalignedAtomics = UnalignedSupported;
3030 }
3031
3032public:
3033 //===--------------------------------------------------------------------===//
3034 // Addressing mode description hooks (used by LSR etc).
3035 //
3036
3037 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
3038 /// instructions reading the address. This allows as much computation as
3039 /// possible to be done in the address mode for that operand. This hook lets
3040 /// targets also pass back when this should be done on intrinsics which
3041 /// load/store.
3042 virtual bool getAddrModeArguments(const IntrinsicInst * /*I*/,
3043 SmallVectorImpl<Value *> & /*Ops*/,
3044 Type *& /*AccessTy*/) const {
3045 return false;
3046 }
3047
3048 /// This represents an addressing mode of:
3049 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*vscale
3050 /// If BaseGV is null, there is no BaseGV.
3051 /// If BaseOffs is zero, there is no base offset.
3052 /// If HasBaseReg is false, there is no base register.
3053 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
3054 /// no scale.
3055 /// If ScalableOffset is zero, there is no scalable offset.
3056 struct AddrMode {
3058 int64_t BaseOffs = 0;
3059 bool HasBaseReg = false;
3060 int64_t Scale = 0;
3061 int64_t ScalableOffset = 0;
3062 AddrMode() = default;
3063 };
3064
3065 /// Return true if the addressing mode represented by AM is legal for this
3066 /// target, for a load/store of the specified type.
3067 ///
3068 /// The type may be VoidTy, in which case only return true if the addressing
3069 /// mode is legal for a load/store of any legal type. TODO: Handle
3070 /// pre/postinc as well.
3071 ///
3072 /// If the address space cannot be determined, it will be -1.
3073 ///
3074 /// TODO: Remove default argument
3075 virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
3076 Type *Ty, unsigned AddrSpace,
3077 Instruction *I = nullptr) const;
3078
3079 /// Returns true if the targets addressing mode can target thread local
3080 /// storage (TLS).
3081 virtual bool addressingModeSupportsTLS(const GlobalValue &) const {
3082 return false;
3083 }
3084
3085 /// Return the prefered common base offset.
3086 virtual int64_t getPreferredLargeGEPBaseOffset(int64_t MinOffset,
3087 int64_t MaxOffset) const {
3088 return 0;
3089 }
3090
3091 /// Return true if the specified immediate is legal icmp immediate, that is
3092 /// the target has icmp instructions which can compare a register against the
3093 /// immediate without having to materialize the immediate into a register.
3094 virtual bool isLegalICmpImmediate(int64_t) const {
3095 return true;
3096 }
3097
3098 /// Return true if the specified immediate is legal add immediate, that is the
3099 /// target has add instructions which can add a register with the immediate
3100 /// without having to materialize the immediate into a register.
3101 virtual bool isLegalAddImmediate(int64_t) const {
3102 return true;
3103 }
3104
3105 /// Return true if adding the specified scalable immediate is legal, that is
3106 /// the target has add instructions which can add a register with the
3107 /// immediate (multiplied by vscale) without having to materialize the
3108 /// immediate into a register.
3109 virtual bool isLegalAddScalableImmediate(int64_t) const { return false; }
3110
3111 /// Return true if the specified immediate is legal for the value input of a
3112 /// store instruction.
3113 virtual bool isLegalStoreImmediate(int64_t Value) const {
3114 // Default implementation assumes that at least 0 works since it is likely
3115 // that a zero register exists or a zero immediate is allowed.
3116 return Value == 0;
3117 }
3118
3119 /// Given a shuffle vector SVI representing a vector splat, return a new
3120 /// scalar type of size equal to SVI's scalar type if the new type is more
3121 /// profitable. Returns nullptr otherwise. For example under MVE float splats
3122 /// are converted to integer to prevent the need to move from SPR to GPR
3123 /// registers.
3125 return nullptr;
3126 }
3127
3128 /// Given a set in interconnected phis of type 'From' that are loaded/stored
3129 /// or bitcast to type 'To', return true if the set should be converted to
3130 /// 'To'.
3131 virtual bool shouldConvertPhiType(Type *From, Type *To) const {
3132 return (From->isIntegerTy() || From->isFloatingPointTy()) &&
3133 (To->isIntegerTy() || To->isFloatingPointTy());
3134 }
3135
3136 /// Returns true if the opcode is a commutative binary operation.
3137 virtual bool isCommutativeBinOp(unsigned Opcode) const {
3138 // FIXME: This should get its info from the td file.
3139 switch (Opcode) {
3140 case ISD::ADD:
3141 case ISD::SMIN:
3142 case ISD::SMAX:
3143 case ISD::UMIN:
3144 case ISD::UMAX:
3145 case ISD::MUL:
3146 case ISD::CLMUL:
3147 case ISD::CLMULH:
3148 case ISD::CLMULR:
3149 case ISD::MULHU:
3150 case ISD::MULHS:
3151 case ISD::SMUL_LOHI:
3152 case ISD::UMUL_LOHI:
3153 case ISD::FADD:
3154 case ISD::FMUL:
3155 case ISD::AND:
3156 case ISD::OR:
3157 case ISD::XOR:
3158 case ISD::SADDO:
3159 case ISD::UADDO:
3160 case ISD::ADDC:
3161 case ISD::ADDE:
3162 case ISD::SADDSAT:
3163 case ISD::UADDSAT:
3164 case ISD::FMINNUM:
3165 case ISD::FMAXNUM:
3166 case ISD::FMINNUM_IEEE:
3167 case ISD::FMAXNUM_IEEE:
3168 case ISD::FMINIMUM:
3169 case ISD::FMAXIMUM:
3170 case ISD::FMINIMUMNUM:
3171 case ISD::FMAXIMUMNUM:
3172 case ISD::AVGFLOORS:
3173 case ISD::AVGFLOORU:
3174 case ISD::AVGCEILS:
3175 case ISD::AVGCEILU:
3176 case ISD::ABDS:
3177 case ISD::ABDU:
3178 return true;
3179 default: return false;
3180 }
3181 }
3182
3183 /// Return true if the node is a math/logic binary operator.
3184 virtual bool isBinOp(unsigned Opcode) const {
3185 // A commutative binop must be a binop.
3186 if (isCommutativeBinOp(Opcode))
3187 return true;
3188 // These are non-commutative binops.
3189 switch (Opcode) {
3190 case ISD::SUB:
3191 case ISD::SHL:
3192 case ISD::SRL:
3193 case ISD::SRA:
3194 case ISD::ROTL:
3195 case ISD::ROTR:
3196 case ISD::SDIV:
3197 case ISD::UDIV:
3198 case ISD::SREM:
3199 case ISD::UREM:
3200 case ISD::SSUBSAT:
3201 case ISD::USUBSAT:
3202 case ISD::FSUB:
3203 case ISD::FDIV:
3204 case ISD::FREM:
3205 case ISD::PSEUDO_FMIN:
3206 case ISD::PSEUDO_FMAX:
3207 return true;
3208 default:
3209 return false;
3210 }
3211 }
3212
3213 /// Return true if it's free to truncate a value of type FromTy to type
3214 /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
3215 /// by referencing its sub-register AX.
3216 /// Targets must return false when FromTy <= ToTy.
3217 virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
3218 return false;
3219 }
3220
3221 /// Return true if a truncation from FromTy to ToTy is permitted when deciding
3222 /// whether a call is in tail position. Typically this means that both results
3223 /// would be assigned to the same register or stack slot, but it could mean
3224 /// the target performs adequate checks of its own before proceeding with the
3225 /// tail call. Targets must return false when FromTy <= ToTy.
3226 virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
3227 return false;
3228 }
3229
3230 virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const { return false; }
3231 virtual bool isTruncateFree(LLT FromTy, LLT ToTy, LLVMContext &Ctx) const {
3232 return isTruncateFree(getApproximateEVTForLLT(FromTy, Ctx),
3233 getApproximateEVTForLLT(ToTy, Ctx));
3234 }
3235
3236 /// Return true if truncating the specific node Val to type VT2 is free.
3237 virtual bool isTruncateFree(SDValue Val, EVT VT2) const {
3238 // Fallback to type matching.
3239 return isTruncateFree(Val.getValueType(), VT2);
3240 }
3241
3242 virtual bool isProfitableToHoist(Instruction *I) const { return true; }
3243
3244 /// Return true if the extension represented by \p I is free.
3245 /// Unlikely the is[Z|FP]ExtFree family which is based on types,
3246 /// this method can use the context provided by \p I to decide
3247 /// whether or not \p I is free.
3248 /// This method extends the behavior of the is[Z|FP]ExtFree family.
3249 /// In other words, if is[Z|FP]Free returns true, then this method
3250 /// returns true as well. The converse is not true.
3251 /// The target can perform the adequate checks by overriding isExtFreeImpl.
3252 /// \pre \p I must be a sign, zero, or fp extension.
3253 bool isExtFree(const Instruction *I) const {
3254 switch (I->getOpcode()) {
3255 case Instruction::FPExt:
3256 if (isFPExtFree(EVT::getEVT(I->getType()),
3257 EVT::getEVT(I->getOperand(0)->getType())))
3258 return true;
3259 break;
3260 case Instruction::ZExt:
3261 if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
3262 return true;
3263 break;
3264 case Instruction::SExt:
3265 break;
3266 default:
3267 llvm_unreachable("Instruction is not an extension");
3268 }
3269 return isExtFreeImpl(I);
3270 }
3271
3272 /// Return true if \p Load and \p Ext can form an ExtLoad.
3273 /// For example, in AArch64
3274 /// %L = load i8, i8* %ptr
3275 /// %E = zext i8 %L to i32
3276 /// can be lowered into one load instruction
3277 /// ldrb w0, [x0]
3278 bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
3279 const DataLayout &DL) const {
3280 EVT VT = getValueType(DL, Ext->getType());
3281 EVT LoadVT = getValueType(DL, Load->getType());
3282
3283 // If the load has other users and the truncate is not free, the ext
3284 // probably isn't free.
3285 if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
3286 !isTruncateFree(Ext->getType(), Load->getType()))
3287 return false;
3288
3289 // Check whether the target supports casts folded into loads.
3290 unsigned LType;
3291 if (isa<ZExtInst>(Ext))
3292 LType = ISD::ZEXTLOAD;
3293 else {
3294 assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
3295 LType = ISD::SEXTLOAD;
3296 }
3297
3298 return isLoadLegal(VT, LoadVT, Load->getAlign(),
3299 Load->getPointerAddressSpace(), LType, false);
3300 }
3301
3302 /// Return true if any actual instruction that defines a value of type FromTy
3303 /// implicitly zero-extends the value to ToTy in the result register.
3304 ///
3305 /// The function should return true when it is likely that the truncate can
3306 /// be freely folded with an instruction defining a value of FromTy. If
3307 /// the defining instruction is unknown (because you're looking at a
3308 /// function argument, PHI, etc.) then the target may require an
3309 /// explicit truncate, which is not necessarily free, but this function
3310 /// does not deal with those cases.
3311 /// Targets must return false when FromTy >= ToTy.
3312 virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
3313 return false;
3314 }
3315
3316 virtual bool isZExtFree(EVT FromTy, EVT ToTy) const { return false; }
3317 virtual bool isZExtFree(LLT FromTy, LLT ToTy, LLVMContext &Ctx) const {
3318 return isZExtFree(getApproximateEVTForLLT(FromTy, Ctx),
3319 getApproximateEVTForLLT(ToTy, Ctx));
3320 }
3321
3322 /// Return true if zero-extending the specific node Val to type VT2 is free
3323 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
3324 /// because it's folded such as X86 zero-extending loads).
3325 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
3326 return isZExtFree(Val.getValueType(), VT2);
3327 }
3328
3329 /// Return true is an anyext is free from FromTy to ToTy. Usually true for
3330 /// scalar types when not trying to pack elements into vector lanes.
3331 virtual bool isAnyExtFree(EVT FromTy, EVT ToTy) const {
3332 return !FromTy.isVector();
3333 }
3334
3335 /// Return true if sign-extension from FromTy to ToTy is cheaper than
3336 /// zero-extension.
3337 virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const {
3338 return false;
3339 }
3340
3341 /// Return true if this constant should be sign extended when promoting to
3342 /// a larger type.
3343 virtual bool signExtendConstant(const ConstantInt *C) const { return false; }
3344
3345 /// Try to optimize extending or truncating conversion instructions (like
3346 /// zext, trunc, fptoui, uitofp) for the target.
3347 virtual bool
3349 const TargetTransformInfo &TTI) const {
3350 return false;
3351 }
3352
3353 /// Return true if the target supplies and combines to a paired load
3354 /// two loaded values of type LoadedType next to each other in memory.
3355 /// RequiredAlignment gives the minimal alignment constraints that must be met
3356 /// to be able to select this paired load.
3357 ///
3358 /// This information is *not* used to generate actual paired loads, but it is
3359 /// used to generate a sequence of loads that is easier to combine into a
3360 /// paired load.
3361 /// For instance, something like this:
3362 /// a = load i64* addr
3363 /// b = trunc i64 a to i32
3364 /// c = lshr i64 a, 32
3365 /// d = trunc i64 c to i32
3366 /// will be optimized into:
3367 /// b = load i32* addr1
3368 /// d = load i32* addr2
3369 /// Where addr1 = addr2 +/- sizeof(i32).
3370 ///
3371 /// In other words, unless the target performs a post-isel load combining,
3372 /// this information should not be provided because it will generate more
3373 /// loads.
3374 virtual bool hasPairedLoad(EVT /*LoadedType*/,
3375 Align & /*RequiredAlignment*/) const {
3376 return false;
3377 }
3378
3379 /// Return true if the target has a vector blend instruction.
3380 virtual bool hasVectorBlend() const { return false; }
3381
3382 /// Get the maximum supported factor for interleaved memory accesses.
3383 /// Default to be the minimum interleave factor: 2.
3384 virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
3385
3386 /// Lower an interleaved load to target specific intrinsics. Return
3387 /// true on success.
3388 ///
3389 /// \p Load is the vector load instruction. Can be either a plain load
3390 /// instruction or a vp.load intrinsic.
3391 /// \p Mask is a per-segment (i.e. number of lanes equal to that of one
3392 /// component being interwoven) mask. Can be nullptr, in which case the
3393 /// result is uncondiitional.
3394 /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
3395 /// \p Indices is the corresponding indices for each shufflevector.
3396 /// \p Factor is the interleave factor.
3397 /// \p GapMask is a mask with zeros for components / fields that may not be
3398 /// accessed.
3401 ArrayRef<unsigned> Indices, unsigned Factor,
3402 const APInt &GapMask) const {
3403 return false;
3404 }
3405
3406 /// Lower an interleaved store to target specific intrinsics. Return
3407 /// true on success.
3408 ///
3409 /// \p SI is the vector store instruction. Can be either a plain store
3410 /// or a vp.store.
3411 /// \p Mask is a per-segment (i.e. number of lanes equal to that of one
3412 /// component being interwoven) mask. Can be nullptr, in which case the
3413 /// result is unconditional.
3414 /// \p SVI is the shufflevector to RE-interleave the stored vector.
3415 /// \p Factor is the interleave factor.
3416 /// \p GapMask is a mask with zeros for components / fields that may not be
3417 /// accessed.
3419 ShuffleVectorInst *SVI, unsigned Factor,
3420 const APInt &GapMask) const {
3421 return false;
3422 }
3423
3424 /// Lower a deinterleave intrinsic to a target specific load intrinsic.
3425 /// Return true on success. Currently only supports
3426 /// llvm.vector.deinterleave{2,3,5,7}
3427 ///
3428 /// \p Load is the accompanying load instruction. Can be either a plain load
3429 /// instruction or a vp.load intrinsic.
3430 /// \p DI represents the deinterleaveN intrinsic.
3431 /// \p GapMask is a mask with zeros for components / fields that may not be
3432 /// accessed.
3434 IntrinsicInst *DI,
3435 const APInt &GapMask) const {
3436 return false;
3437 }
3438
3439 /// Lower an interleave intrinsic to a target specific store intrinsic.
3440 /// Return true on success. Currently only supports
3441 /// llvm.vector.interleave{2,3,5,7}
3442 ///
3443 /// \p Store is the accompanying store instruction. Can be either a plain
3444 /// store or a vp.store intrinsic.
3445 /// \p Mask is a per-segment (i.e. number of lanes equal to that of one
3446 /// component being interwoven) mask. Can be nullptr, in which case the
3447 /// result is uncondiitional.
3448 /// \p InterleaveValues contains the interleaved values.
3449 virtual bool
3451 ArrayRef<Value *> InterleaveValues) const {
3452 return false;
3453 }
3454
3455 /// Return true if an fpext operation is free (for instance, because
3456 /// single-precision floating-point numbers are implicitly extended to
3457 /// double-precision).
3458 virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
3459 assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&
3460 "invalid fpext types");
3461 return false;
3462 }
3463
3464 /// Return true if an fpext operation input to an \p Opcode operation is free
3465 /// (for instance, because half-precision floating-point numbers are
3466 /// implicitly extended to float-precision) for an FMA instruction.
3467 virtual bool isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
3468 LLT DestTy, LLT SrcTy) const {
3469 return false;
3470 }
3471
3472 /// Return true if an fpext operation input to an \p Opcode operation is free
3473 /// (for instance, because half-precision floating-point numbers are
3474 /// implicitly extended to float-precision) for an FMA instruction.
3475 virtual bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
3476 EVT DestVT, EVT SrcVT) const {
3477 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
3478 "invalid fpext types");
3479 return isFPExtFree(DestVT, SrcVT);
3480 }
3481
3482 /// Return true if folding a vector load into ExtVal (a sign, zero, or any
3483 /// extend node) is profitable.
3484 virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
3485
3486 /// Return true if an fneg operation is free to the point where it is never
3487 /// worthwhile to replace it with a bitwise operation.
3488 virtual bool isFNegFree(EVT VT) const {
3489 assert(VT.isFloatingPoint());
3490 return false;
3491 }
3492
3493 /// Return true if an fabs operation is free to the point where it is never
3494 /// worthwhile to replace it with a bitwise operation.
3495 virtual bool isFAbsFree(EVT VT) const {
3496 assert(VT.isFloatingPoint());
3497 return false;
3498 }
3499
3500 /// Return true if an FMA operation is faster than a pair of fmul and fadd
3501 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
3502 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
3503 ///
3504 /// NOTE: This may be called before legalization on types for which FMAs are
3505 /// not legal, but should return true if those types will eventually legalize
3506 /// to types that support FMAs. After legalization, it will only be called on
3507 /// types that support FMAs (via Legal or Custom actions)
3508 ///
3509 /// Targets that care about soft float support should return false when soft
3510 /// float code is being generated (i.e. use-soft-float).
3512 EVT) const {
3513 return false;
3514 }
3515
3516 /// Return true if an FMA operation is faster than a pair of fmul and fadd
3517 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
3518 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
3519 ///
3520 /// NOTE: This may be called before legalization on types for which FMAs are
3521 /// not legal, but should return true if those types will eventually legalize
3522 /// to types that support FMAs. After legalization, it will only be called on
3523 /// types that support FMAs (via Legal or Custom actions)
3525 LLT) const {
3526 return false;
3527 }
3528
3529 /// IR version
3530 virtual bool isFMAFasterThanFMulAndFAdd(const Function &F, Type *) const {
3531 return false;
3532 }
3533
3534 /// Returns true if \p MI can be combined with another instruction to
3535 /// form TargetOpcode::G_FMAD. \p N may be an TargetOpcode::G_FADD,
3536 /// TargetOpcode::G_FSUB, or an TargetOpcode::G_FMUL which will be
3537 /// distributed into an fadd/fsub.
3538 virtual bool isFMADLegal(const MachineInstr &MI, LLT Ty) const {
3539 assert((MI.getOpcode() == TargetOpcode::G_FADD ||
3540 MI.getOpcode() == TargetOpcode::G_FSUB ||
3541 MI.getOpcode() == TargetOpcode::G_FMUL) &&
3542 "unexpected node in FMAD forming combine");
3543 switch (Ty.getScalarSizeInBits()) {
3544 case 16:
3545 return isOperationLegal(TargetOpcode::G_FMAD, MVT::f16);
3546 case 32:
3547 return isOperationLegal(TargetOpcode::G_FMAD, MVT::f32);
3548 case 64:
3549 return isOperationLegal(TargetOpcode::G_FMAD, MVT::f64);
3550 default:
3551 break;
3552 }
3553
3554 return false;
3555 }
3556
3557 /// Returns true if be combined with to form an ISD::FMAD. \p N may be an
3558 /// ISD::FADD, ISD::FSUB, or an ISD::FMUL which will be distributed into an
3559 /// fadd/fsub.
3560 virtual bool isFMADLegal(const SelectionDAG &DAG, const SDNode *N) const {
3561 assert((N->getOpcode() == ISD::FADD || N->getOpcode() == ISD::FSUB ||
3562 N->getOpcode() == ISD::FMUL) &&
3563 "unexpected node in FMAD forming combine");
3564 return isOperationLegal(ISD::FMAD, N->getValueType(0));
3565 }
3566
3567 // Return true when the decision to generate FMA's (or FMS, FMLA etc) rather
3568 // than FMUL and ADD is delegated to the machine combiner.
3570 CodeGenOptLevel OptLevel) const {
3571 return false;
3572 }
3573
3574 /// Return true if it's profitable to narrow operations of type SrcVT to
3575 /// DestVT. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
3576 /// i32 to i16.
3577 virtual bool isNarrowingProfitable(SDNode *N, EVT SrcVT, EVT DestVT) const {
3578 return false;
3579 }
3580
3581 /// Return true if pulling a binary operation into a select with an identity
3582 /// constant is profitable. This is the inverse of an IR transform.
3583 /// Example: X + (Cond ? Y : 0) --> Cond ? (X + Y) : X
3584 virtual bool shouldFoldSelectWithIdentityConstant(unsigned BinOpcode, EVT VT,
3585 unsigned SelectOpcode,
3586 SDValue X,
3587 SDValue Y) const {
3588 return false;
3589 }
3590
3591 /// Return true if it is beneficial to convert a load of a constant to
3592 /// just the constant itself.
3593 /// On some targets it might be more efficient to use a combination of
3594 /// arithmetic instructions to materialize the constant instead of loading it
3595 /// from a constant pool.
3597 Type *Ty) const {
3598 return false;
3599 }
3600
3601 /// Return the cost of extracting a subvector of type \p ResVT from a vector
3602 /// of type \p SrcVT, starting at element \p Index.
3603 ///
3604 /// Most callers only create a new EXTRACT_SUBVECTOR when the cost is at most
3605 /// ExtractSubvectorCost::Cheap. This hook exists because EXTRACT_SUBVECTOR
3606 /// usually has custom lowering that depends on the index of the first
3607 /// element, so only the target knows which lowering is cheap.
3609 unsigned Index) const {
3611 }
3612
3613 /// Try to convert an extract element of a vector binary operation into an
3614 /// extract element followed by a scalar operation.
3615 virtual bool shouldScalarizeBinop(SDValue VecOp) const {
3616 return false;
3617 }
3618
3619 /// Return true if extraction of a scalar element from the given vector type
3620 /// at the given index is cheap. For example, if scalar operations occur on
3621 /// the same register file as vector operations, then an extract element may
3622 /// be a sub-register rename rather than an actual instruction.
3623 virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const {
3624 return false;
3625 }
3626
3627 /// Try to convert math with an overflow comparison into the corresponding DAG
3628 /// node operation. Targets may want to override this independently of whether
3629 /// the operation is legal/custom for the given type because it may obscure
3630 /// matching of other patterns.
3631 virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT,
3632 bool MathUsed) const {
3633 // Form it if it is legal.
3634 if (isOperationLegal(Opcode, VT))
3635 return true;
3636
3637 // TODO: The default logic is inherited from code in CodeGenPrepare.
3638 // The opcode should not make a difference by default?
3639 if (Opcode != ISD::UADDO)
3640 return false;
3641
3642 // Allow the transform as long as we have an integer type that is not
3643 // obviously illegal and unsupported and if the math result is used
3644 // besides the overflow check. On some targets (e.g. SPARC), it is
3645 // not profitable to form on overflow op if the math result has no
3646 // concrete users.
3647 if (VT.isVector())
3648 return false;
3649 return MathUsed && (VT.isSimple() || !isOperationExpand(Opcode, VT));
3650 }
3651
3652 // Return true if the target wants to optimize the mul overflow intrinsic
3653 // for the given \p VT.
3655 EVT VT) const {
3656 return false;
3657 }
3658
3659 // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
3660 // even if the vector itself has multiple uses.
3661 virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
3662 return false;
3663 }
3664
3665 // Return true if CodeGenPrepare should consider splitting large offset of a
3666 // GEP to make the GEP fit into the addressing mode and can be sunk into the
3667 // same blocks of its users.
3668 virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
3669
3670 /// Return true if creating a shift of the type by the given
3671 /// amount is not profitable.
3672 virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const {
3673 return false;
3674 }
3675
3676 // Should we fold (select_cc seteq (and x, y), 0, 0, A) -> (and (sra (shl x))
3677 // A) where y has a single bit set?
3679 const APInt &AndMask) const {
3680 unsigned ShCt = AndMask.getBitWidth() - 1;
3681 return !shouldAvoidTransformToShift(VT, ShCt);
3682 }
3683
3684 /// Does this target require the clearing of high-order bits in a register
3685 /// passed to the fp16 to fp conversion library function.
3686 virtual bool shouldKeepZExtForFP16Conv() const { return false; }
3687
3688 /// Should we generate fp_to_si_sat and fp_to_ui_sat from type FPVT to type
3689 /// VT. Used when folding idioms into a saturating fp-to-int conversion, such
3690 /// as min(max(fptoi)) clamps or NaN-guarded selects.
3691 virtual bool shouldConvertFpToSat(unsigned Op, EVT FPVT, EVT VT) const {
3692 return isOperationLegalOrCustom(Op, VT);
3693 }
3694
3695 /// Should we prefer selects to doing arithmetic on boolean types
3697 return false;
3698 }
3699
3700 /// True if target has some particular form of dealing with pointer arithmetic
3701 /// semantics for pointers with the given value type. False if pointer
3702 /// arithmetic should not be preserved for passes such as instruction
3703 /// selection, and can fallback to regular arithmetic.
3704 /// This should be removed when PTRADD nodes are widely supported by backends.
3705 virtual bool shouldPreservePtrArith(const Function &F, EVT PtrVT) const {
3706 return false;
3707 }
3708
3709 /// True if the target allows transformations of in-bounds pointer
3710 /// arithmetic that cause out-of-bounds intermediate results.
3712 EVT PtrVT) const {
3713 return false;
3714 }
3715
3716 /// Does this target support complex deinterleaving
3717 virtual bool isComplexDeinterleavingSupported() const { return false; }
3718
3719 /// Does this target support complex deinterleaving with the given operation
3720 /// and type
3723 return false;
3724 }
3725
3726 // Get the preferred opcode for FP_TO_XINT nodes.
3727 // By default, this checks if the provded operation is an illegal FP_TO_UINT
3728 // and if so, checks if FP_TO_SINT is legal or custom for use as a
3729 // replacement. If both UINT and SINT conversions are Custom, we choose SINT
3730 // by default because that's the right thing on PPC.
3731 virtual unsigned getPreferredFPToIntOpcode(unsigned Op, EVT FromVT,
3732 EVT ToVT) const {
3733 if (isOperationLegal(Op, ToVT))
3734 return Op;
3735 switch (Op) {
3736 case ISD::FP_TO_UINT:
3738 return ISD::FP_TO_SINT;
3739 break;
3743 break;
3744 default:
3745 break;
3746 }
3747 return Op;
3748 }
3749
3750 /// Create the IR node for the given complex deinterleaving operation.
3751 /// If one cannot be created using all the given inputs, nullptr should be
3752 /// returned.
3755 ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB,
3756 Value *Accumulator = nullptr) const {
3757 return nullptr;
3758 }
3759
3761 return RuntimeLibcallInfo;
3762 }
3763
3764 const LibcallLoweringInfo &getLibcallLoweringInfo() const { return Libcalls; }
3765
3766 void setLibcallImpl(RTLIB::Libcall Call, RTLIB::LibcallImpl Impl) {
3767 Libcalls.setLibcallImpl(Call, Impl);
3768 }
3769
3770 /// Get the libcall impl routine name for the specified libcall.
3771 RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const {
3772 return Libcalls.getLibcallImpl(Call);
3773 }
3774
3775 /// Get the libcall routine name for the specified libcall.
3776 // FIXME: This should be removed. Only LibcallImpl should have a name.
3777 const char *getLibcallName(RTLIB::Libcall Call) const {
3778 return Libcalls.getLibcallName(Call);
3779 }
3780
3781 /// Get the libcall routine name for the specified libcall implementation
3785
3786 RTLIB::LibcallImpl getMemcpyImpl() const { return Libcalls.getMemcpyImpl(); }
3787
3788 /// Get the CallingConv that should be used for the specified libcall
3789 /// implementation.
3791 return Libcalls.getLibcallImplCallingConv(Call);
3792 }
3793
3794 /// Get the CallingConv that should be used for the specified libcall.
3795 // FIXME: Remove this wrapper and directly use the used LibcallImpl
3797 return Libcalls.getLibcallCallingConv(Call);
3798 }
3799
3800 /// Execute target specific actions to finalize target lowering.
3801 /// This is used to set extra flags in MachineFrameInformation and freezing
3802 /// the set of reserved registers.
3803 /// The default implementation just freezes the set of reserved registers.
3804 virtual void finalizeLowering(MachineFunction &MF) const;
3805
3806 /// Returns true if it's profitable to allow merging store of loads when there
3807 /// are functions calls between the load and the store.
3808 virtual bool shouldMergeStoreOfLoadsOverCall(EVT, EVT) const { return true; }
3809
3810 //===----------------------------------------------------------------------===//
3811 // GlobalISel Hooks
3812 //===----------------------------------------------------------------------===//
3813 /// Check whether or not \p MI needs to be moved close to its uses.
3814 virtual bool shouldLocalize(const MachineInstr &MI, const TargetTransformInfo *TTI) const;
3815
3816
3817private:
3818 const TargetMachine &TM;
3819
3820 /// Tells the code generator that the target has BitExtract instructions.
3821 /// The code generator will aggressively sink "shift"s into the blocks of
3822 /// their users if the users will generate "and" instructions which can be
3823 /// combined with "shift" to BitExtract instructions.
3824 bool HasExtractBitsInsn;
3825
3826 /// Tells the code generator to bypass slow divide or remainder
3827 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
3828 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
3829 /// div/rem when the operands are positive and less than 256.
3830 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
3831
3832 /// Tells the code generator that it shouldn't generate extra flow control
3833 /// instructions and should attempt to combine flow control instructions via
3834 /// predication.
3835 bool JumpIsExpensive;
3836
3837 /// Information about the contents of the high-bits in boolean values held in
3838 /// a type wider than i1. See getBooleanContents.
3839 BooleanContent BooleanContents;
3840
3841 /// Information about the contents of the high-bits in boolean values held in
3842 /// a type wider than i1. See getBooleanContents.
3843 BooleanContent BooleanFloatContents;
3844
3845 /// Information about the contents of the high-bits in boolean vector values
3846 /// when the element type is wider than i1. See getBooleanContents.
3847 BooleanContent BooleanVectorContents;
3848
3849 /// The target scheduling preference: shortest possible total cycles or lowest
3850 /// register usage.
3851 Sched::Preference SchedPreferenceInfo;
3852
3853 /// The minimum alignment that any argument on the stack needs to have.
3854 Align MinStackArgumentAlignment;
3855
3856 /// The minimum function alignment (used when optimizing for size, and to
3857 /// prevent explicitly provided alignment from leading to incorrect code).
3858 Align MinFunctionAlignment;
3859
3860 /// The preferred function alignment (used when alignment unspecified and
3861 /// optimizing for speed).
3862 Align PrefFunctionAlignment;
3863
3864 /// The preferred loop alignment (in log2 bot in bytes).
3865 Align PrefLoopAlignment;
3866 /// The maximum amount of bytes permitted to be emitted for alignment.
3867 unsigned MaxBytesForAlignment;
3868
3869 /// Size in bits of the maximum atomics size the backend supports.
3870 /// Accesses larger than this will be expanded by AtomicExpandPass.
3871 unsigned MaxAtomicSizeInBitsSupported;
3872
3873 /// Size in bits of the maximum div/rem size the backend supports.
3874 /// Larger operations will be expanded by ExpandIRInsts.
3875 unsigned MaxDivRemBitWidthSupported;
3876
3877 /// Size in bits of the maximum fp to/from int conversion size the
3878 /// backend supports. Larger operations will be expanded by
3879 /// ExpandIRInsts.
3880 unsigned MaxLargeFPConvertBitWidthSupported;
3881
3882 /// Size in bits of the minimum cmpxchg or ll/sc operation the
3883 /// backend supports.
3884 unsigned MinCmpXchgSizeInBits;
3885
3886 /// The minimum of largest number of comparisons to use bit test for switch.
3887 unsigned MinimumBitTestCmps;
3888
3889 /// Maximum known-legal store size, which can be guaranteed for scalable
3890 /// vectors.
3891 unsigned MaximumLegalStoreInBits;
3892
3893 /// This indicates if the target supports unaligned atomic operations.
3894 bool SupportsUnalignedAtomics;
3895
3896 /// If set to a physical register, this specifies the register that
3897 /// llvm.savestack/llvm.restorestack should save and restore.
3898 Register StackPointerRegisterToSaveRestore;
3899
3900 /// This indicates the default register class to use for each ValueType the
3901 /// target supports natively.
3902 const TargetRegisterClass *RegClassForVT[MVT::VALUETYPE_SIZE];
3903 uint16_t NumRegistersForVT[MVT::VALUETYPE_SIZE];
3904 MVT RegisterTypeForVT[MVT::VALUETYPE_SIZE];
3905
3906 /// This indicates the "representative" register class to use for each
3907 /// ValueType the target supports natively. This information is used by the
3908 /// scheduler to track register pressure. By default, the representative
3909 /// register class is the largest legal super-reg register class of the
3910 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
3911 /// representative class would be GR32.
3912 const TargetRegisterClass *RepRegClassForVT[MVT::VALUETYPE_SIZE] = {nullptr};
3913
3914 /// This indicates the "cost" of the "representative" register class for each
3915 /// ValueType. The cost is used by the scheduler to approximate register
3916 /// pressure.
3917 uint8_t RepRegClassCostForVT[MVT::VALUETYPE_SIZE];
3918
3919 /// For any value types we are promoting or expanding, this contains the value
3920 /// type that we are changing to. For Expanded types, this contains one step
3921 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
3922 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
3923 /// the same type (e.g. i32 -> i32).
3924 MVT TransformToType[MVT::VALUETYPE_SIZE];
3925
3926 /// For each operation and each value type, keep a LegalizeAction that
3927 /// indicates how instruction selection should deal with the operation. Most
3928 /// operations are Legal (aka, supported natively by the target), but
3929 /// operations that are not should be described. Note that operations on
3930 /// non-legal value types are not described here.
3931 LegalizeAction OpActions[MVT::VALUETYPE_SIZE][ISD::BUILTIN_OP_END];
3932
3933 /// For each load extension type and each value type, keep a LegalizeAction
3934 /// that indicates how instruction selection should deal with a load of a
3935 /// specific value type and extension type. Uses 4-bits to store the action
3936 /// for each of the 4 load ext types.
3937 uint16_t LoadExtActions[MVT::VALUETYPE_SIZE][MVT::VALUETYPE_SIZE];
3938
3939 /// Similar to LoadExtActions, but for atomic loads. Only Legal or Expand
3940 /// (default) values are supported.
3941 uint16_t AtomicLoadExtActions[MVT::VALUETYPE_SIZE][MVT::VALUETYPE_SIZE];
3942
3943 /// For each value type pair keep a LegalizeAction that indicates whether a
3944 /// truncating store of a specific value type and truncating type is legal.
3945 LegalizeAction TruncStoreActions[MVT::VALUETYPE_SIZE][MVT::VALUETYPE_SIZE];
3946
3947 /// For each indexed mode and each value type, keep a quad of LegalizeAction
3948 /// that indicates how instruction selection should deal with the load /
3949 /// store / maskedload / maskedstore.
3950 ///
3951 /// The first dimension is the value_type for the reference. The second
3952 /// dimension represents the various modes for load store.
3953 uint16_t IndexedModeActions[MVT::VALUETYPE_SIZE][ISD::LAST_INDEXED_MODE];
3954
3955 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
3956 /// indicates how instruction selection should deal with the condition code.
3957 ///
3958 /// Because each CC action takes up 4 bits, we need to have the array size be
3959 /// large enough to fit all of the value types. This can be done by rounding
3960 /// up the MVT::VALUETYPE_SIZE value to the next multiple of 8.
3961 uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::VALUETYPE_SIZE + 7) / 8];
3962
3964 std::tuple<unsigned, MVT::SimpleValueType, MVT::SimpleValueType>;
3965 /// For each partial reduce opcode, result type and input type combination,
3966 /// keep a LegalizeAction which indicates how instruction selection should
3967 /// deal with this operation.
3968 DenseMap<PartialReduceActionTypes, LegalizeAction> PartialReduceMLAActions;
3969
3971 std::tuple<unsigned, unsigned, MVT::SimpleValueType>;
3972 /// For each vector (de)interleave opcode, interleave factor and fragment
3973 /// type combination, keep the corresponding LegalizeAction.
3974 DenseMap<VectorInterleaveActionKey, LegalizeAction> VectorInterleaveActions;
3975
3976 ValueTypeActionImpl ValueTypeActions;
3977
3978private:
3979 /// Targets can specify ISD nodes that they would like PerformDAGCombine
3980 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
3981 /// array.
3982 unsigned char
3983 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
3984
3985 /// For operations that must be promoted to a specific type, this holds the
3986 /// destination type. This map should be sparse, so don't hold it as an
3987 /// array.
3988 ///
3989 /// Targets add entries to this map with AddPromotedToType(..), clients access
3990 /// this with getTypeToPromoteTo(..).
3991 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
3992 PromoteToType;
3993
3994 /// FIXME: This should not live here; it should come from an analysis.
3995 const RTLIB::RuntimeLibcallsInfo RuntimeLibcallInfo;
3996
3997 /// The list of libcalls that the target will use.
3998 /// FIXME: This should not live here; it should come from an analysis.
3999 LibcallLoweringInfo Libcalls;
4000
4001 /// The bits of IndexedModeActions used to store the legalisation actions
4002 /// We store the data as | ML | MS | L | S | each taking 4 bits.
4003 enum IndexedModeActionsBits {
4004 IMAB_Store = 0,
4005 IMAB_Load = 4,
4006 IMAB_MaskedStore = 8,
4007 IMAB_MaskedLoad = 12
4008 };
4009
4010 void setIndexedModeAction(unsigned IdxMode, MVT VT, unsigned Shift,
4011 LegalizeAction Action) {
4012 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
4013 (unsigned)Action < 0xf && "Table isn't big enough!");
4014 unsigned Ty = (unsigned)VT.SimpleTy;
4015 IndexedModeActions[Ty][IdxMode] &= ~(0xf << Shift);
4016 IndexedModeActions[Ty][IdxMode] |= ((uint16_t)Action) << Shift;
4017 }
4018
4019 LegalizeAction getIndexedModeAction(unsigned IdxMode, MVT VT,
4020 unsigned Shift) const {
4021 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
4022 "Table isn't big enough!");
4023 unsigned Ty = (unsigned)VT.SimpleTy;
4024 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] >> Shift) & 0xf);
4025 }
4026
4027 unsigned getVectorTypeBreakdownImpl(LLVMContext &Context, EVT VT,
4028 EVT &IntermediateVT,
4029 unsigned &NumIntermediates,
4030 MVT &RegisterVT,
4031 bool ForCallingConv) const;
4032
4033 unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
4034 unsigned &NumIntermediates,
4035 MVT &RegisterVT);
4036
4037 /// Return the type of registers that this ValueType will eventually require.
4038 MVT getCachedRegisterType(MVT VT) const {
4039 assert((unsigned)VT.SimpleTy < std::size(RegisterTypeForVT));
4040 return RegisterTypeForVT[VT.SimpleTy];
4041 }
4042
4043 MVT getRegisterTypeImpl(LLVMContext &Context, EVT VT,
4044 bool ForCallingConv) const {
4045 if (VT.isSimple() &&
4046 !shouldUseDynamicVectorTypeBreakdown(VT, ForCallingConv))
4047 return getCachedRegisterType(VT.getSimpleVT());
4048 if (VT.isVector()) {
4049 EVT VT1;
4050 MVT RegisterVT;
4051 unsigned NumIntermediates;
4052 (void)getVectorTypeBreakdownImpl(Context, VT, VT1, NumIntermediates,
4053 RegisterVT, ForCallingConv);
4054 return RegisterVT;
4055 }
4056 if (VT.isInteger()) {
4057 return getRegisterTypeImpl(Context, getTypeToTransformTo(Context, VT),
4058 ForCallingConv);
4059 }
4060 llvm_unreachable("Unsupported extended type!");
4061 }
4062
4063 unsigned getNumRegistersImpl(LLVMContext &Context, EVT VT,
4064 bool ForCallingConv) const {
4065 if (VT.isSimple() &&
4066 !shouldUseDynamicVectorTypeBreakdown(VT, ForCallingConv)) {
4067 assert((unsigned)VT.getSimpleVT().SimpleTy <
4068 std::size(NumRegistersForVT));
4069 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
4070 }
4071 if (VT.isVector()) {
4072 EVT VT1;
4073 MVT VT2;
4074 unsigned NumIntermediates;
4075 return getVectorTypeBreakdownImpl(Context, VT, VT1, NumIntermediates, VT2,
4076 ForCallingConv);
4077 }
4078 if (VT.isInteger()) {
4079 unsigned BitWidth = VT.getSizeInBits();
4080 unsigned RegWidth =
4081 getRegisterTypeImpl(Context, VT, ForCallingConv).getSizeInBits();
4082 return (BitWidth + RegWidth - 1) / RegWidth;
4083 }
4084 llvm_unreachable("Unsupported extended type!");
4085 }
4086
4087protected:
4088 /// Return true if the extension represented by \p I is free.
4089 /// \pre \p I is a sign, zero, or fp extension and
4090 /// is[Z|FP]ExtFree of the related types is not true.
4091 virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
4092
4093 /// Depth that GatherAllAliases should continue looking for chain
4094 /// dependencies when trying to find a more preferable chain. As an
4095 /// approximation, this should be more than the number of consecutive stores
4096 /// expected to be merged.
4098
4099 /// \brief Specify maximum number of store instructions per memset call.
4100 ///
4101 /// When lowering \@llvm.memset this field specifies the maximum number of
4102 /// store operations that may be substituted for the call to memset. Targets
4103 /// must set this value based on the cost threshold for that target. Targets
4104 /// should assume that the memset will be done using as many of the largest
4105 /// store operations first, followed by smaller ones, if necessary, per
4106 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
4107 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
4108 /// store. This only applies to setting a constant array of a constant size.
4110 /// Likewise for functions with the OptSize attribute.
4112
4113 /// \brief Specify maximum number of store instructions per memcpy call.
4114 ///
4115 /// When lowering \@llvm.memcpy this field specifies the maximum number of
4116 /// store operations that may be substituted for a call to memcpy. Targets
4117 /// must set this value based on the cost threshold for that target. Targets
4118 /// should assume that the memcpy will be done using as many of the largest
4119 /// store operations first, followed by smaller ones, if necessary, per
4120 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
4121 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
4122 /// and one 1-byte store. This only applies to copying a constant array of
4123 /// constant size.
4125 /// Likewise for functions with the OptSize attribute.
4127 /// \brief Specify max number of store instructions to glue in inlined memcpy.
4128 ///
4129 /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
4130 /// of store instructions to keep together. This helps in pairing and
4131 // vectorization later on.
4133
4134 /// \brief Specify maximum number of load instructions per memcmp call.
4135 ///
4136 /// When lowering \@llvm.memcmp this field specifies the maximum number of
4137 /// pairs of load operations that may be substituted for a call to memcmp.
4138 /// Targets must set this value based on the cost threshold for that target.
4139 /// Targets should assume that the memcmp will be done using as many of the
4140 /// largest load operations first, followed by smaller ones, if necessary, per
4141 /// alignment restrictions. For example, loading 7 bytes on a 32-bit machine
4142 /// with 32-bit alignment would result in one 4-byte load, a one 2-byte load
4143 /// and one 1-byte load. This only applies to copying a constant array of
4144 /// constant size.
4146 /// Likewise for functions with the OptSize attribute.
4148
4149 /// \brief Specify maximum number of store instructions per memmove call.
4150 ///
4151 /// When lowering \@llvm.memmove this field specifies the maximum number of
4152 /// store instructions that may be substituted for a call to memmove. Targets
4153 /// must set this value based on the cost threshold for that target. Targets
4154 /// should assume that the memmove will be done using as many of the largest
4155 /// store operations first, followed by smaller ones, if necessary, per
4156 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
4157 /// with 8-bit alignment would result in nine 1-byte stores. This only
4158 /// applies to copying a constant array of constant size.
4160 /// Likewise for functions with the OptSize attribute.
4162
4163 /// Tells the code generator that select is more expensive than a branch if
4164 /// the branch is usually predicted right.
4166
4167 /// \see enableExtLdPromotion.
4169
4170 /// Return true if the value types that can be represented by the specified
4171 /// register class are all legal.
4172 bool isLegalRC(const TargetRegisterInfo &TRI,
4173 const TargetRegisterClass &RC) const;
4174
4175 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
4176 /// sequence of memory operands that is recognized by PrologEpilogInserter.
4178 MachineBasicBlock *MBB) const;
4179
4181};
4182
4183/// This class defines information used to lower LLVM code to legal SelectionDAG
4184/// operators that the target instruction selector can accept natively.
4185///
4186/// This class also defines callbacks that targets must implement to lower
4187/// target-specific constructs to SelectionDAG operators.
4189public:
4190 struct DAGCombinerInfo;
4191 struct MakeLibCallOptions;
4192
4195
4196 explicit TargetLowering(const TargetMachine &TM,
4197 const TargetSubtargetInfo &STI);
4199
4200 bool isPositionIndependent() const;
4201
4202 // If set to true, SelectionDAG nodes will be consistently processed in
4203 // topological order. This is a temporary hook until sorting can be
4204 // enabled globally.
4205 virtual bool useTopologicalSorting() const { return false; }
4206
4209 UniformityInfo *UA) const {
4210 return false;
4211 }
4212
4213 // Lets target to control the following reassociation of operands: (op (op x,
4214 // c1), y) -> (op (op x, y), c1) where N0 is (op x, c1) and N1 is y. By
4215 // default consider profitable any case where N0 has single use. This
4216 // behavior reflects the condition replaced by this target hook call in the
4217 // DAGCombiner. Any particular target can implement its own heuristic to
4218 // restrict common combiner.
4220 SDValue N1) const {
4221 return N0.hasOneUse();
4222 }
4223
4224 // Lets target to control the following reassociation of operands: (op (op x,
4225 // c1), y) -> (op (op x, y), c1) where N0 is (op x, c1) and N1 is y. By
4226 // default consider profitable any case where N0 has single use. This
4227 // behavior reflects the condition replaced by this target hook call in the
4228 // combiner. Any particular target can implement its own heuristic to
4229 // restrict common combiner.
4231 Register N1) const {
4232 return MRI.hasOneNonDBGUse(N0);
4233 }
4234
4235 virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
4236 return false;
4237 }
4238
4239 /// Returns true by value, base pointer and offset pointer and addressing mode
4240 /// by reference if the node's address can be legally represented as
4241 /// pre-indexed load / store address.
4242 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
4243 SDValue &/*Offset*/,
4244 ISD::MemIndexedMode &/*AM*/,
4245 SelectionDAG &/*DAG*/) const {
4246 return false;
4247 }
4248
4249 /// Returns true by value, base pointer and offset pointer and addressing mode
4250 /// by reference if this node can be combined with a load / store to form a
4251 /// post-indexed load / store.
4252 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
4253 SDValue &/*Base*/,
4254 SDValue &/*Offset*/,
4255 ISD::MemIndexedMode &/*AM*/,
4256 SelectionDAG &/*DAG*/) const {
4257 return false;
4258 }
4259
4260 /// Returns true if the specified base+offset is a legal indexed addressing
4261 /// mode for this target. \p MI is the load or store instruction that is being
4262 /// considered for transformation.
4264 bool IsPre, MachineRegisterInfo &MRI) const {
4265 return false;
4266 }
4267
4268 /// Return the entry encoding for a jump table in the current function. The
4269 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
4270 virtual unsigned getJumpTableEncoding() const;
4271
4272 virtual MVT getJumpTableRegTy(const DataLayout &DL) const {
4273 return getPointerTy(DL);
4274 }
4275
4276 virtual const MCExpr *
4278 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
4279 MCContext &/*Ctx*/) const {
4280 llvm_unreachable("Need to implement this hook if target has custom JTIs");
4281 }
4282
4283 /// Returns relocation base for the given PIC jumptable.
4284 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
4285 SelectionDAG &DAG) const;
4286
4287 /// This returns the relocation base for the given PIC jumptable, the same as
4288 /// getPICJumpTableRelocBase, but as an MCExpr.
4289 virtual const MCExpr *
4290 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
4291 unsigned JTI, MCContext &Ctx) const;
4292
4293 /// Return true if folding a constant offset with the given GlobalAddress is
4294 /// legal. It is frequently not legal in PIC relocation models.
4295 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
4296
4297 /// On x86, return true if the operand with index OpNo is a CALL or JUMP
4298 /// instruction, which can use either a memory constraint or an address
4299 /// constraint. -fasm-blocks "__asm call foo" lowers to
4300 /// call void asm sideeffect inteldialect "call ${0:P}", "*m..."
4301 ///
4302 /// This function is used by a hack to choose the address constraint,
4303 /// lowering to a direct call.
4304 virtual bool
4306 unsigned OpNo) const {
4307 return false;
4308 }
4309
4311 SDValue &Chain) const;
4312
4313 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
4314 SDValue &NewRHS, ISD::CondCode &CCCode,
4315 const SDLoc &DL, const SDValue OldLHS,
4316 const SDValue OldRHS) const;
4317
4318 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
4319 SDValue &NewRHS, ISD::CondCode &CCCode,
4320 const SDLoc &DL, const SDValue OldLHS,
4321 const SDValue OldRHS, SDValue &Chain,
4322 bool IsSignaling = false) const;
4323
4325 SDValue Chain, MachineMemOperand *MMO,
4326 SDValue &NewLoad, SDValue Ptr,
4327 SDValue PassThru, SDValue Mask) const {
4328 llvm_unreachable("Not Implemented");
4329 }
4330
4332 SDValue Chain, MachineMemOperand *MMO,
4333 SDValue Ptr, SDValue Val,
4334 SDValue Mask) const {
4335 llvm_unreachable("Not Implemented");
4336 }
4337
4338 /// Returns a pair of (return value, chain).
4339 /// It is an error to pass RTLIB::Unsupported as \p LibcallImpl
4340 std::pair<SDValue, SDValue>
4341 makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT,
4342 ArrayRef<SDValue> Ops, MakeLibCallOptions CallOptions,
4343 const SDLoc &dl, SDValue Chain = SDValue()) const;
4344
4345 /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
4346 std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
4347 EVT RetVT, ArrayRef<SDValue> Ops,
4348 MakeLibCallOptions CallOptions,
4349 const SDLoc &dl,
4350 SDValue Chain = SDValue()) const {
4351 return makeLibCall(DAG, getLibcallImpl(LC), RetVT, Ops, CallOptions, dl,
4352 Chain);
4353 }
4354
4355 /// Build a call argument list for \p FuncTy, taking the argument node values
4356 /// from \p Ops and the parameter types and ABI attributes from \p FuncTy and
4357 /// \p FuncAttrs. \p Ops must have one entry per parameter of \p FuncTy.
4358 static ArgListTy getArgListForFunctionType(FunctionType *FuncTy,
4359 const AttributeList &FuncAttrs,
4361
4362 /// Check whether parameters to a call that are passed in callee saved
4363 /// registers are the same as from the calling function. This needs to be
4364 /// checked for tail call eligibility.
4365 bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
4366 const uint32_t *CallerPreservedMask,
4367 const SmallVectorImpl<CCValAssign> &ArgLocs,
4368 const SmallVectorImpl<SDValue> &OutVals) const;
4369
4370 //===--------------------------------------------------------------------===//
4371 // TargetLowering Optimization Methods
4372 //
4373
4374 /// A convenience struct that encapsulates a DAG, and two SDValues for
4375 /// returning information from TargetLowering to its clients that want to
4376 /// combine.
4383
4385 bool LT, bool LO) :
4386 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
4387
4388 bool LegalTypes() const { return LegalTys; }
4389 bool LegalOperations() const { return LegalOps; }
4390
4392 Old = O;
4393 New = N;
4394 return true;
4395 }
4396 };
4397
4398 /// Determines the optimal series of memory ops to replace the memset /
4399 /// memcpy. Return true if the number of memory ops is below the threshold
4400 /// (Limit). Note that this is always the case when Limit is ~0. It returns
4401 /// the types of the sequence of memory ops to perform memset / memcpy by
4402 /// reference. If LargestVT is non-null, the target may set it to the largest
4403 /// EVT that should be used for generating the memset value (e.g., for vector
4404 /// splats). If LargestVT is null or left unchanged, the caller will compute
4405 /// it from MemOps.
4406 virtual bool findOptimalMemOpLowering(LLVMContext &Context,
4407 std::vector<EVT> &MemOps,
4408 unsigned Limit, const MemOp &Op,
4409 unsigned DstAS, unsigned SrcAS,
4410 const AttributeList &FuncAttributes,
4411 EVT *LargestVT = nullptr) const;
4412
4413 /// Check to see if the specified operand of the specified instruction is a
4414 /// constant integer. If so, check to see if there are any bits set in the
4415 /// constant that are not demanded. If so, shrink the constant and return
4416 /// true.
4418 const APInt &DemandedElts,
4419 TargetLoweringOpt &TLO) const;
4420
4421 /// Helper wrapper around ShrinkDemandedConstant, demanding all elements.
4423 TargetLoweringOpt &TLO) const;
4424
4425 // Target hook to do target-specific const optimization, which is called by
4426 // ShrinkDemandedConstant. This function should return true if the target
4427 // doesn't want ShrinkDemandedConstant to further optimize the constant.
4429 const APInt &DemandedBits,
4430 const APInt &DemandedElts,
4431 TargetLoweringOpt &TLO) const {
4432 return false;
4433 }
4434
4435 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
4436 /// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast,
4437 /// but it could be generalized for targets with other types of implicit
4438 /// widening casts.
4439 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
4440 const APInt &DemandedBits,
4441 TargetLoweringOpt &TLO) const;
4442
4443 /// Look at Op. At this point, we know that only the DemandedBits bits of the
4444 /// result of Op are ever used downstream. If we can use this information to
4445 /// simplify Op, create a new simplified DAG node and return true, returning
4446 /// the original and new nodes in Old and New. Otherwise, analyze the
4447 /// expression and return a mask of KnownOne and KnownZero bits for the
4448 /// expression (used to simplify the caller). The KnownZero/One bits may only
4449 /// be accurate for those bits in the Demanded masks.
4450 /// \p AssumeSingleUse When this parameter is true, this function will
4451 /// attempt to simplify \p Op even if there are multiple uses.
4452 /// Callers are responsible for correctly updating the DAG based on the
4453 /// results of this function, because simply replacing TLO.Old
4454 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
4455 /// has multiple uses.
4456 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
4457 const APInt &DemandedElts, KnownBits &Known,
4458 TargetLoweringOpt &TLO, unsigned Depth = 0,
4459 bool AssumeSingleUse = false) const;
4460
4461 /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
4462 /// Adds Op back to the worklist upon success.
4463 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
4464 KnownBits &Known, TargetLoweringOpt &TLO,
4465 unsigned Depth = 0,
4466 bool AssumeSingleUse = false) const;
4467
4468 /// Helper wrapper around SimplifyDemandedBits.
4469 /// Adds Op back to the worklist upon success.
4470 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
4471 DAGCombinerInfo &DCI) const;
4472
4473 /// Helper wrapper around SimplifyDemandedBits.
4474 /// Adds Op back to the worklist upon success.
4475 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
4476 const APInt &DemandedElts,
4477 DAGCombinerInfo &DCI) const;
4478
4479 /// More limited version of SimplifyDemandedBits that can be used to "look
4480 /// through" ops that don't contribute to the DemandedBits/DemandedElts -
4481 /// bitwise ops etc.
4482 SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits,
4483 const APInt &DemandedElts,
4484 SelectionDAG &DAG,
4485 unsigned Depth = 0) const;
4486
4487 /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
4488 /// elements.
4489 SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits,
4490 SelectionDAG &DAG,
4491 unsigned Depth = 0) const;
4492
4493 /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
4494 /// bits from only some vector elements.
4495 SDValue SimplifyMultipleUseDemandedVectorElts(SDValue Op,
4496 const APInt &DemandedElts,
4497 SelectionDAG &DAG,
4498 unsigned Depth = 0) const;
4499
4500 /// Look at Vector Op. At this point, we know that only the DemandedElts
4501 /// elements of the result of Op are ever used downstream. If we can use
4502 /// this information to simplify Op, create a new simplified DAG node and
4503 /// return true, storing the original and new nodes in TLO.
4504 /// Otherwise, analyze the expression and return a mask of KnownUndef and
4505 /// KnownZero elements for the expression (used to simplify the caller).
4506 /// The KnownUndef/Zero elements may only be accurate for those bits
4507 /// in the DemandedMask.
4508 /// \p AssumeSingleUse When this parameter is true, this function will
4509 /// attempt to simplify \p Op even if there are multiple uses.
4510 /// Callers are responsible for correctly updating the DAG based on the
4511 /// results of this function, because simply replacing TLO.Old
4512 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
4513 /// has multiple uses.
4514 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask,
4515 APInt &KnownUndef, APInt &KnownZero,
4516 TargetLoweringOpt &TLO, unsigned Depth = 0,
4517 bool AssumeSingleUse = false) const;
4518
4519 /// Helper wrapper around SimplifyDemandedVectorElts.
4520 /// Adds Op back to the worklist upon success.
4521 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
4522 DAGCombinerInfo &DCI) const;
4523
4524 /// Return true if the target supports simplifying demanded vector elements by
4525 /// converting them to undefs.
4526 virtual bool
4528 const TargetLoweringOpt &TLO) const {
4529 return true;
4530 }
4531
4532 /// If only low elements of a vector are demanded, shrink the operation to the
4533 /// returned size in bits by converting
4534 /// (op x) to insert_subvector (op (extract_subvector x)).
4535 ///
4536 /// The returned size must be a multiple of the element size, greater than or
4537 /// equal to the demanded part of the vector and less than the original
4538 /// vector size. Return 0 to disable shrinking.
4539 virtual unsigned
4541 const APInt &DemandedElts) const {
4542 return 0;
4543 }
4544
4545 /// Determine which of the bits specified in Mask are known to be either zero
4546 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
4547 /// argument allows us to only collect the known bits that are shared by the
4548 /// requested vector elements.
4549 virtual void computeKnownBitsForTargetNode(const SDValue Op,
4551 const APInt &DemandedElts,
4552 const SelectionDAG &DAG,
4553 unsigned Depth = 0) const;
4554
4555 /// Determine which of the bits specified in Mask are known to be either zero
4556 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
4557 /// argument allows us to only collect the known bits that are shared by the
4558 /// requested vector elements. This is for GISel.
4559 virtual void computeKnownBitsForTargetInstr(GISelValueTracking &Analysis,
4561 const APInt &DemandedElts,
4562 const MachineRegisterInfo &MRI,
4563 unsigned Depth = 0) const;
4564
4565 virtual void computeKnownFPClassForTargetInstr(GISelValueTracking &Analysis,
4566 Register R,
4568 const APInt &DemandedElts,
4569 const MachineRegisterInfo &MRI,
4570 unsigned Depth = 0) const;
4571
4572 /// Determine the known alignment for the pointer value \p R. This is can
4573 /// typically be inferred from the number of low known 0 bits. However, for a
4574 /// pointer with a non-integral address space, the alignment value may be
4575 /// independent from the known low bits.
4576 virtual Align computeKnownAlignForTargetInstr(GISelValueTracking &Analysis,
4577 Register R,
4578 const MachineRegisterInfo &MRI,
4579 unsigned Depth = 0) const;
4580
4581 /// Determine known bits of a pointer to a known valid stack object.
4582 /// The default implementation computes low bits based on alignment.
4583 virtual void computeKnownBitsForStackObjectPointer(KnownBits &Known,
4584 const MachineFunction &MF,
4585 Align Alignment) const;
4586
4587 /// This method can be implemented by targets that want to expose additional
4588 /// information about sign bits to the DAG Combiner. The DemandedElts
4589 /// argument allows us to only collect the minimum sign bits that are shared
4590 /// by the requested vector elements.
4591 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
4592 const APInt &DemandedElts,
4593 const SelectionDAG &DAG,
4594 unsigned Depth = 0) const;
4595
4596 /// This method can be implemented by targets that want to expose additional
4597 /// information about sign bits to GlobalISel combiners. The DemandedElts
4598 /// argument allows us to only collect the minimum sign bits that are shared
4599 /// by the requested vector elements.
4600 virtual unsigned computeNumSignBitsForTargetInstr(
4601 GISelValueTracking &Analysis, Register R, const APInt &DemandedElts,
4602 const MachineRegisterInfo &MRI, unsigned Depth = 0) const;
4603
4604 /// Attempt to simplify any target nodes based on the demanded vector
4605 /// elements, returning true on success. Otherwise, analyze the expression and
4606 /// return a mask of KnownUndef and KnownZero elements for the expression
4607 /// (used to simplify the caller). The KnownUndef/Zero elements may only be
4608 /// accurate for those bits in the DemandedMask.
4609 virtual bool SimplifyDemandedVectorEltsForTargetNode(
4610 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef,
4611 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth = 0) const;
4612
4613 /// Attempt to simplify any target nodes based on the demanded bits/elts,
4614 /// returning true on success. Otherwise, analyze the
4615 /// expression and return a mask of KnownOne and KnownZero bits for the
4616 /// expression (used to simplify the caller). The KnownZero/One bits may only
4617 /// be accurate for those bits in the Demanded masks.
4618 virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op,
4619 const APInt &DemandedBits,
4620 const APInt &DemandedElts,
4622 TargetLoweringOpt &TLO,
4623 unsigned Depth = 0) const;
4624
4625 /// More limited version of SimplifyDemandedBits that can be used to "look
4626 /// through" ops that don't contribute to the DemandedBits/DemandedElts -
4627 /// bitwise ops etc.
4628 virtual SDValue SimplifyMultipleUseDemandedBitsForTargetNode(
4629 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4630 SelectionDAG &DAG, unsigned Depth) const;
4631
4632 /// Return true if this function can prove that \p Op is never poison
4633 /// and, \p Kind can be used to track poison and/or undef bits. The
4634 /// DemandedElts argument limits the check to the requested vector elements.
4635 virtual bool isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4636 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4637 UndefPoisonKind Kind, unsigned Depth) const;
4638
4639 /// Return true if Op can create undef or poison from non-undef & non-poison
4640 /// operands. The DemandedElts argument limits the check to the requested
4641 /// vector elements.
4642 virtual bool canCreateUndefOrPoisonForTargetNode(
4643 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4644 UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const;
4645
4646 /// Tries to build a legal vector shuffle using the provided parameters
4647 /// or equivalent variations. The Mask argument maybe be modified as the
4648 /// function tries different variations.
4649 /// Returns an empty SDValue if the operation fails.
4650 SDValue buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
4652 SelectionDAG &DAG) const;
4653
4654 /// This method returns the constant pool value that will be loaded by LD.
4655 /// NOTE: You must check for implicit extensions of the constant by LD.
4656 virtual const Constant *getTargetConstantFromLoad(LoadSDNode *LD) const;
4657
4658 /// Determine floating-point class information for a target node. The
4659 /// DemandedElts argument allows us to only collect the known FP classes
4660 /// that are shared by the requested vector elements.
4661 virtual void computeKnownFPClassForTargetNode(const SDValue Op,
4663 const APInt &DemandedElts,
4664 const SelectionDAG &DAG,
4665 unsigned Depth = 0) const;
4666
4667 /// If \p SNaN is false, \returns true if \p Op is known to never be any
4668 /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
4669 /// NaN.
4670 virtual bool isKnownNeverNaNForTargetNode(SDValue Op,
4671 const APInt &DemandedElts,
4672 const SelectionDAG &DAG,
4673 bool SNaN = false,
4674 unsigned Depth = 0) const;
4675
4676 /// Return true if vector \p Op has the same value across all \p DemandedElts,
4677 /// indicating any elements which may be undef in the output \p UndefElts.
4678 virtual bool isSplatValueForTargetNode(SDValue Op, const APInt &DemandedElts,
4679 APInt &UndefElts,
4680 const SelectionDAG &DAG,
4681 unsigned Depth = 0) const;
4682
4683 /// Returns true if the given Opc is considered a canonical constant for the
4684 /// target, which should not be transformed back into a BUILD_VECTOR.
4686 return Op.getOpcode() == ISD::SPLAT_VECTOR ||
4687 Op.getOpcode() == ISD::SPLAT_VECTOR_PARTS;
4688 }
4689
4690 /// Return true if the given select/vselect should be considered canonical and
4691 /// not be transformed. Currently only used for "vselect (not Cond), N1, N2 ->
4692 /// vselect Cond, N2, N1".
4693 virtual bool isTargetCanonicalSelect(SDNode *N) const { return false; }
4694
4696 void *DC; // The DAG Combiner object.
4699
4700 public:
4702
4703 DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
4704 : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
4705
4706 bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
4708 bool isAfterLegalizeDAG() const { return Level >= AfterLegalizeDAG; }
4711
4712 LLVM_ABI void AddToWorklist(SDNode *N);
4713 LLVM_ABI SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To,
4714 bool AddTo = true);
4715 LLVM_ABI SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
4716 LLVM_ABI SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
4717 bool AddTo = true);
4718
4719 LLVM_ABI bool recursivelyDeleteUnusedNodes(SDNode *N);
4720
4721 LLVM_ABI void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
4722 };
4723
4724 /// Return if the N is a constant or constant vector equal to the true value
4725 /// from getBooleanContents().
4726 bool isConstTrueVal(SDValue N) const;
4727
4728 /// Return if the N is a constant or constant vector equal to the false value
4729 /// from getBooleanContents().
4730 bool isConstFalseVal(SDValue N) const;
4731
4732 /// Return if \p N is a True value when extended to \p VT.
4733 bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const;
4734
4735 /// Try to simplify a setcc built with the specified operands and cc. If it is
4736 /// unable to simplify it, return a null SDValue.
4737 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
4738 bool foldBooleans, DAGCombinerInfo &DCI,
4739 const SDLoc &dl) const;
4740
4741 // For targets which wrap address, unwrap for analysis.
4742 virtual SDValue unwrapAddress(SDValue N) const { return N; }
4743
4744 /// Returns true (and the GlobalValue and the offset) if the node is a
4745 /// GlobalAddress + offset.
4746 virtual bool
4747 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
4748
4749 /// This method will be invoked for all target nodes and for any
4750 /// target-independent nodes that the target has registered with invoke it
4751 /// for.
4752 ///
4753 /// The semantics are as follows:
4754 /// Return Value:
4755 /// SDValue.Val == 0 - No change was made
4756 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
4757 /// otherwise - N should be replaced by the returned Operand.
4758 ///
4759 /// In addition, methods provided by DAGCombinerInfo may be used to perform
4760 /// more complex transformations.
4761 ///
4762 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
4763
4764 /// Return true if it is profitable to move this shift by a constant amount
4765 /// through its operand, adjusting any immediate operands as necessary to
4766 /// preserve semantics. This transformation may not be desirable if it
4767 /// disrupts a particularly auspicious target-specific tree (e.g. bitfield
4768 /// extraction in AArch64). By default, it returns true.
4769 ///
4770 /// @param N the shift node
4771 /// @param Level the current DAGCombine legalization level.
4773 CombineLevel Level) const {
4774 SDValue ShiftLHS = N->getOperand(0);
4775 if (!ShiftLHS->hasOneUse())
4776 return false;
4777 if (ShiftLHS.getOpcode() == ISD::SIGN_EXTEND &&
4778 !ShiftLHS.getOperand(0)->hasOneUse())
4779 return false;
4780 return true;
4781 }
4782
4783 /// GlobalISel - return true if it is profitable to move this shift by a
4784 /// constant amount through its operand, adjusting any immediate operands as
4785 /// necessary to preserve semantics. This transformation may not be desirable
4786 /// if it disrupts a particularly auspicious target-specific tree (e.g.
4787 /// bitfield extraction in AArch64). By default, it returns true.
4788 ///
4789 /// @param MI the shift instruction
4790 /// @param IsAfterLegal true if running after legalization.
4792 bool IsAfterLegal) const {
4793 return true;
4794 }
4795
4796 /// GlobalISel - return true if it's profitable to perform the combine:
4797 /// shl ([sza]ext x), y => zext (shl x, y)
4798 virtual bool isDesirableToPullExtFromShl(const MachineInstr &MI) const {
4799 return true;
4800 }
4801
4802 // Return AndOrSETCCFoldKind::{AddAnd, ABS} if its desirable to try and
4803 // optimize LogicOp(SETCC0, SETCC1). An example (what is implemented as of
4804 // writing this) is:
4805 // With C as a power of 2 and C != 0 and C != INT_MIN:
4806 // AddAnd:
4807 // (icmp eq A, C) | (icmp eq A, -C)
4808 // -> (icmp eq and(add(A, C), ~(C + C)), 0)
4809 // (icmp ne A, C) & (icmp ne A, -C)w
4810 // -> (icmp ne and(add(A, C), ~(C + C)), 0)
4811 // ABS:
4812 // (icmp eq A, C) | (icmp eq A, -C)
4813 // -> (icmp eq Abs(A), C)
4814 // (icmp ne A, C) & (icmp ne A, -C)w
4815 // -> (icmp ne Abs(A), C)
4816 //
4817 // @param LogicOp the logic op
4818 // @param SETCC0 the first of the SETCC nodes
4819 // @param SETCC0 the second of the SETCC nodes
4821 const SDNode *LogicOp, const SDNode *SETCC0, const SDNode *SETCC1) const {
4823 }
4824
4825 /// Return true if it is profitable to combine an XOR of a logical shift
4826 /// to create a logical shift of NOT. This transformation may not be desirable
4827 /// if it disrupts a particularly auspicious target-specific tree (e.g.
4828 /// BIC on ARM/AArch64). By default, it returns true.
4829 virtual bool isDesirableToCommuteXorWithShift(const SDNode *N) const {
4830 return true;
4831 }
4832
4833 /// Return true if the target has native support for the specified value type
4834 /// and it is 'desirable' to use the type for the given node type. e.g. On x86
4835 /// i16 is legal, but undesirable since i16 instruction encodings are longer
4836 /// and some i16 instructions are slow.
4837 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
4838 // By default, assume all legal types are desirable.
4839 return isTypeLegal(VT);
4840 }
4841
4842 /// Overload that takes the specific node being optimized.
4843 virtual bool isTypeDesirableForOp(SDNode *N, EVT VT) const {
4844 return isTypeDesirableForOp(N->getOpcode(), VT);
4845 }
4846
4847 /// Return true if it is profitable for dag combiner to transform a floating
4848 /// point op of specified opcode to a equivalent op of an integer
4849 /// type. e.g. f32 load -> i32 load can be profitable on ARM.
4850 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
4851 EVT /*VT*/) const {
4852 return false;
4853 }
4854
4855 /// This method query the target whether it is beneficial for dag combiner to
4856 /// promote the specified node. If true, it should return the desired
4857 /// promotion type by reference.
4858 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
4859 return false;
4860 }
4861
4862 /// Return true if the target supports swifterror attribute. It optimizes
4863 /// loads and stores to reading and writing a specific register.
4864 virtual bool supportSwiftError() const {
4865 return false;
4866 }
4867
4868 /// Return true if the target supports that a subset of CSRs for the given
4869 /// machine function is handled explicitly via copies.
4870 virtual bool supportSplitCSR(MachineFunction *MF) const {
4871 return false;
4872 }
4873
4874 /// Return true if the target supports kcfi operand bundles.
4875 virtual bool supportKCFIBundles() const { return false; }
4876
4877 /// Return true if the target supports ptrauth operand bundles.
4878 virtual bool supportPtrAuthBundles() const { return false; }
4879
4880 /// Perform necessary initialization to handle a subset of CSRs explicitly
4881 /// via copies. This function is called at the beginning of instruction
4882 /// selection.
4883 virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
4884 llvm_unreachable("Not Implemented");
4885 }
4886
4887 /// Insert explicit copies in entry and exit blocks. We copy a subset of
4888 /// CSRs to virtual registers in the entry block, and copy them back to
4889 /// physical registers in the exit blocks. This function is called at the end
4890 /// of instruction selection.
4892 MachineBasicBlock *Entry,
4893 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
4894 llvm_unreachable("Not Implemented");
4895 }
4896
4897 /// Return the newly negated expression if the cost is not expensive and
4898 /// set the cost in \p Cost to indicate that if it is cheaper or neutral to
4899 /// do the negation.
4900 virtual SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG,
4901 bool LegalOps, bool OptForSize,
4902 NegatibleCost &Cost,
4903 unsigned Depth = 0) const;
4904
4906 SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize,
4908 unsigned Depth = 0) const {
4910 SDValue Neg =
4911 getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
4912 if (!Neg)
4913 return SDValue();
4914
4915 if (Cost <= CostThreshold)
4916 return Neg;
4917
4918 // Remove the new created node to avoid the side effect to the DAG.
4919 if (Neg->use_empty())
4920 DAG.RemoveDeadNode(Neg.getNode());
4921 return SDValue();
4922 }
4923
4924 /// This is the helper function to return the newly negated expression only
4925 /// when the cost is cheaper.
4927 bool LegalOps, bool OptForSize,
4928 unsigned Depth = 0) const {
4929 return getCheaperOrNeutralNegatedExpression(Op, DAG, LegalOps, OptForSize,
4931 }
4932
4933 /// This is the helper function to return the newly negated expression if
4934 /// the cost is not expensive.
4936 bool OptForSize, unsigned Depth = 0) const {
4938 return getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
4939 }
4940
4941 //===--------------------------------------------------------------------===//
4942 // Lowering methods - These methods must be implemented by targets so that
4943 // the SelectionDAGBuilder code knows how to lower these.
4944 //
4945
4946 /// Target-specific splitting of values into parts that fit a register
4947 /// storing a legal type
4949 SelectionDAG & DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4950 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4951 return false;
4952 }
4953
4954 /// Target-specific combining of register parts into its original value
4955 virtual SDValue
4957 const SDValue *Parts, unsigned NumParts,
4958 MVT PartVT, EVT ValueVT,
4959 std::optional<CallingConv::ID> CC) const {
4960 return SDValue();
4961 }
4962
4963 /// This hook must be implemented to lower the incoming (formal) arguments,
4964 /// described by the Ins array, into the specified DAG. The implementation
4965 /// should fill in the InVals array with legal-type argument values, and
4966 /// return the resulting token chain value.
4968 SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
4969 const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
4970 SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
4971 llvm_unreachable("Not Implemented");
4972 }
4973
4974 /// Optional target hook to add target-specific actions when entering EH pad
4975 /// blocks. The implementation should return the resulting token chain value.
4976 virtual SDValue lowerEHPadEntry(SDValue Chain, const SDLoc &DL,
4977 SelectionDAG &DAG) const {
4978 return SDValue();
4979 }
4980
4981 virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
4982 ArgListTy &Args) const {}
4983
4984 /// This structure contains the information necessary for lowering
4985 /// pointer-authenticating indirect calls. It is equivalent to the "ptrauth"
4986 /// operand bundle found on the call instruction, if any.
4991
4992 /// This structure contains all information that is necessary for lowering
4993 /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
4994 /// needs to lower a call, and targets will see this struct in their LowerCall
4995 /// implementation.
4998 /// Original unlegalized return type.
4999 Type *OrigRetTy = nullptr;
5000 /// Same as OrigRetTy, or partially legalized for soft float libcalls.
5001 Type *RetTy = nullptr;
5002 bool RetSExt : 1;
5003 bool RetZExt : 1;
5004 bool IsVarArg : 1;
5005 bool IsInReg : 1;
5011 bool NoMerge : 1;
5012
5013 // IsTailCall should be modified by implementations of
5014 // TargetLowering::LowerCall that perform tail call conversions.
5015 bool IsTailCall = false;
5016
5017 // Is Call lowering done post SelectionDAG type legalization.
5019
5020 unsigned NumFixedArgs = -1;
5026 const CallBase *CB = nullptr;
5031 const ConstantInt *CFIType = nullptr;
5034
5035 std::optional<PtrAuthInfo> PAI;
5036
5042
5044 DL = dl;
5045 return *this;
5046 }
5047
5049 Chain = InChain;
5050 return *this;
5051 }
5052
5053 // setCallee with target/module-specific attributes
5055 SDValue Target, ArgListTy &&ArgsList) {
5056 return setLibCallee(CC, ResultType, ResultType, Target,
5057 std::move(ArgsList));
5058 }
5059
5061 Type *OrigResultType, SDValue Target,
5062 ArgListTy &&ArgsList) {
5063 OrigRetTy = OrigResultType;
5064 RetTy = ResultType;
5065 Callee = Target;
5066 CallConv = CC;
5067 NumFixedArgs = ArgsList.size();
5068 Args = std::move(ArgsList);
5069
5070 DAG.getTargetLoweringInfo().markLibCallAttributes(
5071 &(DAG.getMachineFunction()), CC, Args);
5072 return *this;
5073 }
5074
5076 SDValue Target, ArgListTy &&ArgsList,
5077 AttributeSet ResultAttrs = {}) {
5078 RetTy = OrigRetTy = ResultType;
5079 IsInReg = ResultAttrs.hasAttribute(Attribute::InReg);
5080 RetSExt = ResultAttrs.hasAttribute(Attribute::SExt);
5081 RetZExt = ResultAttrs.hasAttribute(Attribute::ZExt);
5082 NoMerge = ResultAttrs.hasAttribute(Attribute::NoMerge);
5083
5084 Callee = Target;
5085 CallConv = CC;
5086 NumFixedArgs = ArgsList.size();
5087 Args = std::move(ArgsList);
5088 return *this;
5089 }
5090
5092 SDValue Target, ArgListTy &&ArgsList,
5093 const CallBase &Call) {
5094 RetTy = OrigRetTy = ResultType;
5095
5096 IsInReg = Call.hasRetAttr(Attribute::InReg);
5098 Call.doesNotReturn() ||
5099 (!isa<InvokeInst>(Call) && isa<UnreachableInst>(Call.getNextNode()));
5100 IsVarArg = FTy->isVarArg();
5101 IsReturnValueUsed = !Call.use_empty();
5102 RetSExt = Call.hasRetAttr(Attribute::SExt);
5103 RetZExt = Call.hasRetAttr(Attribute::ZExt);
5104 NoMerge = Call.hasFnAttr(Attribute::NoMerge);
5105
5106 Callee = Target;
5107
5108 CallConv = Call.getCallingConv();
5109 NumFixedArgs = FTy->getNumParams();
5110 Args = std::move(ArgsList);
5111
5112 CB = &Call;
5113
5114 return *this;
5115 }
5116
5118 IsInReg = Value;
5119 return *this;
5120 }
5121
5124 return *this;
5125 }
5126
5128 IsVarArg = Value;
5129 return *this;
5130 }
5131
5133 IsTailCall = Value;
5134 return *this;
5135 }
5136
5139 return *this;
5140 }
5141
5144 return *this;
5145 }
5146
5148 RetSExt = Value;
5149 return *this;
5150 }
5151
5153 RetZExt = Value;
5154 return *this;
5155 }
5156
5159 return *this;
5160 }
5161
5164 return *this;
5165 }
5166
5168 PAI = Value;
5169 return *this;
5170 }
5171
5174 return *this;
5175 }
5176
5178 CFIType = Type;
5179 return *this;
5180 }
5181
5184 return *this;
5185 }
5186
5188 DeactivationSymbol = Sym;
5189 return *this;
5190 }
5191
5193 return Args;
5194 }
5195 };
5196
5197 /// This structure is used to pass arguments to makeLibCall function.
5199 // By passing type list before soften to makeLibCall, the target hook
5200 // shouldExtendTypeInLibCall can get the original type before soften.
5204
5205 bool IsSigned : 1;
5209 bool IsSoften : 1;
5210
5214
5216 IsSigned = Value;
5217 return *this;
5218 }
5219
5222 return *this;
5223 }
5224
5227 return *this;
5228 }
5229
5232 return *this;
5233 }
5234
5236 OpsVTBeforeSoften = OpsVT;
5237 RetVTBeforeSoften = RetVT;
5238 IsSoften = true;
5239 return *this;
5240 }
5241
5242 /// Override the argument type for an operand. Leave the type as null to use
5243 /// the type from the operand's node.
5245 OpsTypeOverrides = OpsTypes;
5246 return *this;
5247 }
5248 };
5249
5250 /// This function lowers an abstract call to a function into an actual call.
5251 /// This returns a pair of operands. The first element is the return value
5252 /// for the function (if RetTy is not VoidTy). The second element is the
5253 /// outgoing token chain. It calls LowerCall to do the actual lowering.
5254 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
5255
5256 /// This hook must be implemented to lower calls into the specified
5257 /// DAG. The outgoing arguments to the call are described by the Outs array,
5258 /// and the values to be returned by the call are described by the Ins
5259 /// array. The implementation should fill in the InVals array with legal-type
5260 /// return values from the call, and return the resulting token chain value.
5261 virtual SDValue
5263 SmallVectorImpl<SDValue> &/*InVals*/) const {
5264 llvm_unreachable("Not Implemented");
5265 }
5266
5267 /// Target-specific cleanup for formal ByVal parameters.
5268 virtual void HandleByVal(CCState *, unsigned &, Align) const {}
5269
5270 /// This hook should be implemented to check whether the return values
5271 /// described by the Outs array can fit into the return registers. If false
5272 /// is returned, an sret-demotion is performed.
5273 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
5274 MachineFunction &/*MF*/, bool /*isVarArg*/,
5275 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
5276 LLVMContext &/*Context*/, const Type *RetTy) const
5277 {
5278 // Return true by default to get preexisting behavior.
5279 return true;
5280 }
5281
5282 /// Annotate a stack object pointer with known-bits assertions.
5283 SDValue annotateStackObjectPointer(SDValue Ptr, SelectionDAG &DAG,
5284 const SDLoc &DL, Align Alignment) const;
5285
5286 /// This hook must be implemented to lower outgoing return values, described
5287 /// by the Outs array, into the specified DAG. The implementation should
5288 /// return the resulting token chain value.
5289 virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
5290 bool /*isVarArg*/,
5291 const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
5292 const SmallVectorImpl<SDValue> & /*OutVals*/,
5293 const SDLoc & /*dl*/,
5294 SelectionDAG & /*DAG*/) const {
5295 llvm_unreachable("Not Implemented");
5296 }
5297
5298 /// Return true if result of the specified node is used by a return node
5299 /// only. It also compute and return the input chain for the tail call.
5300 ///
5301 /// This is used to determine whether it is possible to codegen a libcall as
5302 /// tail call at legalization time.
5303 virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
5304 return false;
5305 }
5306
5307 /// Return true if the target may be able emit the call instruction as a tail
5308 /// call. This is used by optimization passes to determine if it's profitable
5309 /// to duplicate return instructions to enable tailcall optimization.
5310 virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
5311 return false;
5312 }
5313
5314 /// Return the register ID of the name passed in. Used by named register
5315 /// global variables extension. There is no target-independent behaviour
5316 /// so the default action is to bail.
5317 virtual Register getRegisterByName(const char* RegName, LLT Ty,
5318 const MachineFunction &MF) const {
5319 reportFatalUsageError("Named registers not implemented for this target");
5320 }
5321
5322 /// Return the type that should be used to zero or sign extend a
5323 /// zeroext/signext integer return value. FIXME: Some C calling conventions
5324 /// require the return type to be promoted, but this is not true all the time,
5325 /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
5326 /// conventions. The frontend should handle this and include all of the
5327 /// necessary information.
5329 ISD::NodeType /*ExtendKind*/) const {
5330 EVT MinVT = getRegisterType(Context, MVT::i32);
5331 return VT.bitsLT(MinVT) ? MinVT : VT;
5332 }
5333
5334 /// For some targets, an LLVM struct type must be broken down into multiple
5335 /// simple types, but the calling convention specifies that the entire struct
5336 /// must be passed in a block of consecutive registers.
5337 virtual bool
5339 bool isVarArg,
5340 const DataLayout &DL) const {
5341 return false;
5342 }
5343
5344 /// For most targets, an LLVM type must be broken down into multiple
5345 /// smaller types. Usually the halves are ordered according to the endianness
5346 /// but for some platform that would break. So this method will default to
5347 /// matching the endianness but can be overridden.
5348 virtual bool
5350 return DL.isLittleEndian();
5351 }
5352
5353 /// Returns a 0 terminated array of registers that can be safely used as
5354 /// scratch registers.
5356 return nullptr;
5357 }
5358
5359 /// Returns a 0 terminated array of rounding control registers that can be
5360 /// attached into strict FP call.
5364
5365 /// This callback is used to prepare for a volatile or atomic load.
5366 /// It takes a chain node as input and returns the chain for the load itself.
5367 ///
5368 /// Having a callback like this is necessary for targets like SystemZ,
5369 /// which allows a CPU to reuse the result of a previous load indefinitely,
5370 /// even if a cache-coherent store is performed by another CPU. The default
5371 /// implementation does nothing.
5373 SelectionDAG &DAG) const {
5374 return Chain;
5375 }
5376
5377 /// This callback is invoked by the type legalizer to legalize nodes with an
5378 /// illegal operand type but legal result types. It replaces the
5379 /// LowerOperation callback in the type Legalizer. The reason we can not do
5380 /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
5381 /// use this callback.
5382 ///
5383 /// TODO: Consider merging with ReplaceNodeResults.
5384 ///
5385 /// The target places new result values for the node in Results (their number
5386 /// and types must exactly match those of the original return values of
5387 /// the node), or leaves Results empty, which indicates that the node is not
5388 /// to be custom lowered after all.
5389 /// The default implementation calls LowerOperation.
5390 virtual void LowerOperationWrapper(SDNode *N,
5392 SelectionDAG &DAG) const;
5393
5394 /// This callback is invoked for operations that are unsupported by the
5395 /// target, which are registered to use 'custom' lowering, and whose defined
5396 /// values are all legal. If the target has no operations that require custom
5397 /// lowering, it need not implement this. The default implementation of this
5398 /// aborts.
5399 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
5400
5401 /// This callback is invoked when a node result type is illegal for the
5402 /// target, and the operation was registered to use 'custom' lowering for that
5403 /// result type. The target places new result values for the node in Results
5404 /// (their number and types must exactly match those of the original return
5405 /// values of the node), or leaves Results empty, which indicates that the
5406 /// node is not to be custom lowered after all.
5407 ///
5408 /// If the target has no operations that require custom lowering, it need not
5409 /// implement this. The default implementation aborts.
5410 virtual void ReplaceNodeResults(SDNode * /*N*/,
5411 SmallVectorImpl<SDValue> &/*Results*/,
5412 SelectionDAG &/*DAG*/) const {
5413 llvm_unreachable("ReplaceNodeResults not implemented for this target!");
5414 }
5415
5416 /// This method returns the name of a target specific DAG node.
5417 virtual const char *getTargetNodeName(unsigned Opcode) const;
5418
5419 /// This method returns a target specific FastISel object, or null if the
5420 /// target does not support "fast" ISel.
5422 const TargetLibraryInfo *,
5423 const LibcallLoweringInfo *) const {
5424 return nullptr;
5425 }
5426
5427 //===--------------------------------------------------------------------===//
5428 // Inline Asm Support hooks
5429 //
5430
5432 C_Register, // Constraint represents specific register(s).
5433 C_RegisterClass, // Constraint represents any of register(s) in class.
5434 C_Memory, // Memory constraint.
5435 C_Address, // Address constraint.
5436 C_Immediate, // Requires an immediate.
5437 C_Other, // Something else.
5438 C_Unknown // Unsupported constraint.
5439 };
5440
5442 // Generic weights.
5443 CW_Invalid = -1, // No match.
5444 CW_Okay = 0, // Acceptable.
5445 CW_Good = 1, // Good weight.
5446 CW_Better = 2, // Better weight.
5447 CW_Best = 3, // Best weight.
5448
5449 // Well-known weights.
5450 CW_SpecificReg = CW_Okay, // Specific register operands.
5451 CW_Register = CW_Good, // Register operands.
5452 CW_Memory = CW_Better, // Memory operands.
5453 CW_Constant = CW_Best, // Constant operand.
5454 CW_Default = CW_Okay // Default or don't know type.
5455 };
5456
5457 /// This contains information for each constraint that we are lowering.
5459 /// This contains the actual string for the code, like "m". TargetLowering
5460 /// picks the 'best' code from ConstraintInfo::Codes that most closely
5461 /// matches the operand.
5462 std::string ConstraintCode;
5463
5464 /// Information about the constraint code, e.g. Register, RegisterClass,
5465 /// Memory, Other, Unknown.
5467
5468 /// If this is the result output operand or a clobber, this is null,
5469 /// otherwise it is the incoming operand to the CallInst. This gets
5470 /// modified as the asm is processed.
5472
5473 /// The ValueType for the operand value.
5474 MVT ConstraintVT = MVT::Other;
5475
5476 /// Copy constructor for copying from a ConstraintInfo.
5479
5480 /// Return true of this is an input operand that is a matching constraint
5481 /// like "4".
5482 LLVM_ABI bool isMatchingInputConstraint() const;
5483
5484 /// If this is an input matching constraint, this method returns the output
5485 /// operand it matches.
5486 LLVM_ABI unsigned getMatchedOperand() const;
5487 };
5488
5489 using AsmOperandInfoVector = std::vector<AsmOperandInfo>;
5490
5491 /// Split up the constraint string from the inline assembly value into the
5492 /// specific constraints and their prefixes, and also tie in the associated
5493 /// operand values. If this returns an empty vector, and if the constraint
5494 /// string itself isn't empty, there was an error parsing.
5496 const TargetRegisterInfo *TRI,
5497 const CallBase &Call) const;
5498
5499 /// Examine constraint type and operand type and determine a weight value.
5500 /// The operand object must already have been set up with the operand type.
5502 AsmOperandInfo &info, int maIndex) const;
5503
5504 /// Examine constraint string and operand type and determine a weight value.
5505 /// The operand object must already have been set up with the operand type.
5507 AsmOperandInfo &info, const char *constraint) const;
5508
5509 /// Determines the constraint code and constraint type to use for the specific
5510 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
5511 /// If the actual operand being passed in is available, it can be passed in as
5512 /// Op, otherwise an empty SDValue can be passed.
5513 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
5514 SDValue Op,
5515 SelectionDAG *DAG = nullptr) const;
5516
5517 /// Given a constraint, return the type of constraint it is for this target.
5518 virtual ConstraintType getConstraintType(StringRef Constraint) const;
5519
5520 using ConstraintPair = std::pair<StringRef, TargetLowering::ConstraintType>;
5522 /// Given an OpInfo with list of constraints codes as strings, return a
5523 /// sorted Vector of pairs of constraint codes and their types in priority of
5524 /// what we'd prefer to lower them as. This may contain immediates that
5525 /// cannot be lowered, but it is meant to be a machine agnostic order of
5526 /// preferences.
5528
5529 /// Given a physical register constraint (e.g. {edx}), return the register
5530 /// number and the register class for the register.
5531 ///
5532 /// Given a register class constraint, like 'r', if this corresponds directly
5533 /// to an LLVM register class, return a register of 0 and the register class
5534 /// pointer.
5535 ///
5536 /// This should only be used for C_Register constraints. On error, this
5537 /// returns a register number of 0 and a null register class pointer.
5538 virtual std::pair<unsigned, const TargetRegisterClass *>
5540 StringRef Constraint, MVT VT) const;
5541
5543 getInlineAsmMemConstraint(StringRef ConstraintCode) const {
5544 if (ConstraintCode == "m")
5546 if (ConstraintCode == "o")
5548 if (ConstraintCode == "X")
5550 if (ConstraintCode == "p")
5553 }
5554
5555 /// Try to replace an X constraint, which matches anything, with another that
5556 /// has more specific requirements based on the type of the corresponding
5557 /// operand. This returns null if there is no replacement to make.
5558 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
5559
5560 /// Lower the specified operand into the Ops vector. If it is invalid, don't
5561 /// add anything to Ops.
5562 virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint,
5563 std::vector<SDValue> &Ops,
5564 SelectionDAG &DAG) const;
5565
5566 // Lower custom output constraints. If invalid, return SDValue().
5567 virtual SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Glue,
5568 const SDLoc &DL,
5569 const AsmOperandInfo &OpInfo,
5570 SelectionDAG &DAG) const;
5571
5572 // Targets may override this function to collect operands from the CallInst
5573 // and for example, lower them into the SelectionDAG operands.
5574 virtual void CollectTargetIntrinsicOperands(const CallInst &I,
5576 SelectionDAG &DAG) const;
5577
5578 //===--------------------------------------------------------------------===//
5579 // Div utility functions
5580 //
5581
5582 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
5583 bool IsAfterLegalTypes,
5584 SmallVectorImpl<SDNode *> &Created) const;
5585 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
5586 bool IsAfterLegalTypes,
5587 SmallVectorImpl<SDNode *> &Created) const;
5588 // Build sdiv by power-of-2 with conditional move instructions
5589 SDValue buildSDIVPow2WithCMov(SDNode *N, const APInt &Divisor,
5590 SelectionDAG &DAG,
5591 SmallVectorImpl<SDNode *> &Created) const;
5592
5593 /// Targets may override this function to provide custom SDIV lowering for
5594 /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
5595 /// assumes SDIV is expensive and replaces it with a series of other integer
5596 /// operations.
5597 virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
5598 SelectionDAG &DAG,
5599 SmallVectorImpl<SDNode *> &Created) const;
5600
5601 /// Targets may override this function to provide custom SREM lowering for
5602 /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
5603 /// assumes SREM is expensive and replaces it with a series of other integer
5604 /// operations.
5605 virtual SDValue BuildSREMPow2(SDNode *N, const APInt &Divisor,
5606 SelectionDAG &DAG,
5607 SmallVectorImpl<SDNode *> &Created) const;
5608
5609 /// Indicate whether this target prefers to combine FDIVs with the same
5610 /// divisor. If the transform should never be done, return zero. If the
5611 /// transform should be done, return the minimum number of divisor uses
5612 /// that must exist.
5613 virtual unsigned combineRepeatedFPDivisors() const {
5614 return 0;
5615 }
5616
5617 /// Hooks for building estimates in place of slower divisions and square
5618 /// roots.
5619
5620 /// Return either a square root or its reciprocal estimate value for the input
5621 /// operand.
5622 /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
5623 /// 'Enabled' as set by a potential default override attribute.
5624 /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
5625 /// refinement iterations required to generate a sufficient (though not
5626 /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
5627 /// The boolean UseOneConstNR output is used to select a Newton-Raphson
5628 /// algorithm implementation that uses either one or two constants.
5629 /// The boolean Reciprocal is used to select whether the estimate is for the
5630 /// square root of the input operand or the reciprocal of its square root.
5631 /// A target may choose to implement its own refinement within this function.
5632 /// If that's true, then return '0' as the number of RefinementSteps to avoid
5633 /// any further refinement of the estimate.
5634 /// An empty SDValue return means no estimate sequence can be created.
5636 int Enabled, int &RefinementSteps,
5637 bool &UseOneConstNR, bool Reciprocal) const {
5638 return SDValue();
5639 }
5640
5641 /// Try to convert the fminnum/fmaxnum to a compare/select sequence. This is
5642 /// required for correctness since InstCombine might have canonicalized a
5643 /// fcmp+select sequence to a FMINNUM/FMAXNUM intrinsic. If we were to fall
5644 /// through to the default expansion/soften to libcall, we might introduce a
5645 /// link-time dependency on libm into a file that originally did not have one.
5646 SDValue createSelectForFMINNUM_FMAXNUM(SDNode *Node, SelectionDAG &DAG) const;
5647
5648 /// Return a reciprocal estimate value for the input operand.
5649 /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
5650 /// 'Enabled' as set by a potential default override attribute.
5651 /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
5652 /// refinement iterations required to generate a sufficient (though not
5653 /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
5654 /// A target may choose to implement its own refinement within this function.
5655 /// If that's true, then return '0' as the number of RefinementSteps to avoid
5656 /// any further refinement of the estimate.
5657 /// An empty SDValue return means no estimate sequence can be created.
5659 int Enabled, int &RefinementSteps) const {
5660 return SDValue();
5661 }
5662
5663 /// Return a target-dependent comparison result if the input operand is
5664 /// suitable for use with a square root estimate calculation. For example, the
5665 /// comparison may check if the operand is NAN, INF, zero, normal, etc. The
5666 /// result should be used as the condition operand for a select or branch.
5667 virtual SDValue getSqrtInputTest(SDValue Operand, SelectionDAG &DAG,
5668 const DenormalMode &Mode,
5669 SDNodeFlags Flags = {}) const;
5670
5671 /// Return a target-dependent result if the input operand is not suitable for
5672 /// use with a square root estimate calculation.
5674 SelectionDAG &DAG) const {
5675 return DAG.getConstantFP(0.0, SDLoc(Operand), Operand.getValueType());
5676 }
5677
5678 //===--------------------------------------------------------------------===//
5679 // Legalization utility functions
5680 //
5681
5682 /// Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes,
5683 /// respectively, each computing an n/2-bit part of the result.
5684 /// \param Result A vector that will be filled with the parts of the result
5685 /// in little-endian order.
5686 /// \param LL Low bits of the LHS of the MUL. You can use this parameter
5687 /// if you want to control how low bits are extracted from the LHS.
5688 /// \param LH High bits of the LHS of the MUL. See LL for meaning.
5689 /// \param RL Low bits of the RHS of the MUL. See LL for meaning
5690 /// \param RH High bits of the RHS of the MUL. See LL for meaning.
5691 /// \returns true if the node has been expanded, false if it has not
5692 bool expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, SDValue LHS,
5693 SDValue RHS, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
5694 SelectionDAG &DAG, MulExpansionKind Kind,
5695 SDValue LL = SDValue(), SDValue LH = SDValue(),
5696 SDValue RL = SDValue(), SDValue RH = SDValue()) const;
5697
5698 /// Expand a MUL into two nodes. One that computes the high bits of
5699 /// the result and one that computes the low bits.
5700 /// \param HiLoVT The value type to use for the Lo and Hi nodes.
5701 /// \param LL Low bits of the LHS of the MUL. You can use this parameter
5702 /// if you want to control how low bits are extracted from the LHS.
5703 /// \param LH High bits of the LHS of the MUL. See LL for meaning.
5704 /// \param RL Low bits of the RHS of the MUL. See LL for meaning
5705 /// \param RH High bits of the RHS of the MUL. See LL for meaning.
5706 /// \returns true if the node has been expanded. false if it has not
5707 bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
5708 SelectionDAG &DAG, MulExpansionKind Kind,
5709 SDValue LL = SDValue(), SDValue LH = SDValue(),
5710 SDValue RL = SDValue(), SDValue RH = SDValue()) const;
5711
5712 /// Attempt to expand an n-bit div/rem/divrem by constant using an n/2-bit
5713 /// algorithm. First, attempt to expand the division using a n/2-bit urem by
5714 /// constant and other arithmetic ops. The n/2-bit urem by constant will be
5715 /// expanded by DAGCombiner. As this is not possible for all constant
5716 /// divisors, this method falls back to an implementation of the magic
5717 /// algorithm using n/2-bit operations.
5718 /// \param N Node to expand
5719 /// \param Result A vector that will be filled with the lo and high parts of
5720 /// the results. For *DIVREM, this will be the quotient parts followed
5721 /// by the remainder parts.
5722 /// \param HiLoVT The value type to use for the Lo and Hi parts. Should be
5723 /// half of VT.
5724 /// \param LL Low bits of the LHS of the operation. You can use this
5725 /// parameter if you want to control how low bits are extracted from
5726 /// the LHS.
5727 /// \param LH High bits of the LHS of the operation. See LL for meaning.
5728 /// \returns true if the node has been expanded, false if it has not.
5729 bool expandDIVREMByConstant(SDNode *N, SmallVectorImpl<SDValue> &Result,
5730 EVT HiLoVT, SelectionDAG &DAG,
5731 SDValue LL = SDValue(),
5732 SDValue LH = SDValue()) const;
5733
5734 /// Expand funnel shift.
5735 /// \param N Node to expand
5736 /// \returns The expansion if successful, SDValue() otherwise
5737 SDValue expandFunnelShift(SDNode *N, SelectionDAG &DAG) const;
5738
5739 /// Expand carryless multiply.
5740 /// \param N Node to expand
5741 /// \returns The expansion if successful, SDValue() otherwise
5742 SDValue expandCLMUL(SDNode *N, SelectionDAG &DAG) const;
5743
5744 /// Expand parallel bit extract (compress).
5745 /// \param N Node to expand
5746 /// \returns The expansion if successful, SDValue() otherwise
5747 SDValue expandPEXT(SDNode *N, SelectionDAG &DAG) const;
5748
5749 /// Expand parallel bit deposit (expand).
5750 /// \param N Node to expand
5751 /// \returns The expansion if successful, SDValue() otherwise
5752 SDValue expandPDEP(SDNode *N, SelectionDAG &DAG) const;
5753
5754 /// Expand rotations.
5755 /// \param N Node to expand
5756 /// \param AllowVectorOps expand vector rotate, this should only be performed
5757 /// if the legalization is happening outside of LegalizeVectorOps
5758 /// \returns The expansion if successful, SDValue() otherwise
5759 SDValue expandROT(SDNode *N, bool AllowVectorOps, SelectionDAG &DAG) const;
5760
5761 /// Expand shift-by-parts.
5762 /// \param N Node to expand
5763 /// \param Lo lower-output-part after conversion
5764 /// \param Hi upper-output-part after conversion
5765 void expandShiftParts(SDNode *N, SDValue &Lo, SDValue &Hi,
5766 SelectionDAG &DAG) const;
5767
5768 /// Expand float(f32) to SINT(i64) conversion
5769 /// \param N Node to expand
5770 /// \param Result output after conversion
5771 /// \returns True, if the expansion was successful, false otherwise
5772 bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
5773
5774 /// Expand float to UINT conversion
5775 /// \param N Node to expand
5776 /// \param Result output after conversion
5777 /// \param Chain output chain after conversion
5778 /// \returns True, if the expansion was successful, false otherwise
5779 bool expandFP_TO_UINT(SDNode *N, SDValue &Result, SDValue &Chain,
5780 SelectionDAG &DAG) const;
5781
5782 /// Expand UINT(i64) to double(f64) conversion
5783 /// \param N Node to expand
5784 /// \param Result output after conversion
5785 /// \param Chain output chain after conversion
5786 /// \returns True, if the expansion was successful, false otherwise
5787 bool expandUINT_TO_FP(SDNode *N, SDValue &Result, SDValue &Chain,
5788 SelectionDAG &DAG) const;
5789
5790 /// Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
5791 SDValue expandFMINNUM_FMAXNUM(SDNode *N, SelectionDAG &DAG) const;
5792
5793 /// Expand fminimum/fmaximum into multiple comparison with selects.
5794 SDValue expandFMINIMUM_FMAXIMUM(SDNode *N, SelectionDAG &DAG) const;
5795
5796 /// Expand fminimumnum/fmaximumnum into multiple comparison with selects.
5797 SDValue expandFMINIMUMNUM_FMAXIMUMNUM(SDNode *N, SelectionDAG &DAG) const;
5798
5799 /// Expand FP_TO_[US]INT_SAT into FP_TO_[US]INT and selects or min/max.
5800 /// \param N Node to expand
5801 /// \returns The expansion result
5802 SDValue expandFP_TO_INT_SAT(SDNode *N, SelectionDAG &DAG) const;
5803
5804 /// Truncate Op to ResultVT. If the result is exact, leave it alone. If it is
5805 /// not exact, force the result to be odd.
5806 /// \param ResultVT The type of result.
5807 /// \param Op The value to round.
5808 /// \returns The expansion result
5809 SDValue expandRoundInexactToOdd(EVT ResultVT, SDValue Op, const SDLoc &DL,
5810 SelectionDAG &DAG) const;
5811
5812 /// Expand round(fp) to fp conversion
5813 /// \param N Node to expand
5814 /// \returns The expansion result
5815 SDValue expandFP_ROUND(SDNode *Node, SelectionDAG &DAG) const;
5816
5817 /// Expand check for floating point class.
5818 /// \param ResultVT The type of intrinsic call result.
5819 /// \param Op The tested value.
5820 /// \param Test The test to perform.
5821 /// \param Flags The optimization flags.
5822 /// \returns The expansion result or SDValue() if it fails.
5823 SDValue expandIS_FPCLASS(EVT ResultVT, SDValue Op, FPClassTest Test,
5824 SDNodeFlags Flags, const SDLoc &DL,
5825 SelectionDAG &DAG) const;
5826
5827 /// Expand FCANONICALIZE to FMUL with 1.
5828 /// \param NodeNode to expand
5829 /// \returns The expansion result
5830 SDValue expandFCANONICALIZE(SDNode *Node, SelectionDAG &DAG) const;
5831
5832 /// Expand CONVERT_TO_ARBITRARY_FP using bit manipulation.
5833 /// \param Node Node to expand.
5834 /// \returns The expansion result, or SDValue() if fails.
5835 SDValue expandCONVERT_TO_ARBITRARY_FP(SDNode *Node, SelectionDAG &DAG) const;
5836
5837 /// Expand CONVERT_FROM_ARBITRARY_FP using bit manipulation.
5838 /// \param Node Node to expand.
5839 /// \returns The expansion result, or SDValue() if fails.
5840 SDValue expandCONVERT_FROM_ARBITRARY_FP(SDNode *Node,
5841 SelectionDAG &DAG) const;
5842
5843 /// Expand CTPOP nodes. Expands vector/scalar CTPOP nodes,
5844 /// vector nodes can only succeed if all operations are legal/custom.
5845 /// \param N Node to expand
5846 /// \returns The expansion result or SDValue() if it fails.
5847 SDValue expandCTPOP(SDNode *N, SelectionDAG &DAG) const;
5848
5849 /// Expand CTLZ/CTLZ_ZERO_POISON nodes. Expands vector/scalar CTLZ nodes,
5850 /// vector nodes can only succeed if all operations are legal/custom.
5851 /// \param N Node to expand
5852 /// \returns The expansion result or SDValue() if it fails.
5853 SDValue expandCTLZ(SDNode *N, SelectionDAG &DAG) const;
5854
5855 /// Expand CTLS (count leading sign bits) nodes.
5856 /// CTLS(x) = CTLZ(OR(SHL(XOR(x, SRA(x, BW-1)), 1), 1))
5857 /// \param N Node to expand
5858 /// \returns The expansion result or SDValue() if it fails.
5859 SDValue expandCTLS(SDNode *N, SelectionDAG &DAG) const;
5860
5861 /// Expand CTTZ via Table Lookup.
5862 /// \param N Node to expand
5863 /// \returns The expansion result or SDValue() if it fails.
5864 SDValue CTTZTableLookup(SDNode *N, SelectionDAG &DAG, const SDLoc &DL, EVT VT,
5865 SDValue Op, unsigned NumBitsPerElt) const;
5866
5867 /// Expand CTTZ/CTTZ_ZERO_POISON nodes. Expands vector/scalar CTTZ nodes,
5868 /// vector nodes can only succeed if all operations are legal/custom.
5869 /// \param N Node to expand
5870 /// \returns The expansion result or SDValue() if it fails.
5871 SDValue expandCTTZ(SDNode *N, SelectionDAG &DAG) const;
5872
5873 /// Expand VP_CTTZ_ELTS/VP_CTTZ_ELTS_ZERO_POISON nodes.
5874 /// \param N Node to expand
5875 /// \returns The expansion result or SDValue() if it fails.
5876 SDValue expandVPCTTZElements(SDNode *N, SelectionDAG &DAG) const;
5877
5878 /// Expand VECTOR_MATCH nodes.
5879 /// \param N Node to expand
5880 /// \returns The expansion result or SDValue() if it fails.
5881 SDValue expandVectorMatch(SDNode *N, SelectionDAG &DAG) const;
5882
5883 /// Expand VECTOR_FIND_LAST_ACTIVE nodes
5884 /// \param N Node to expand
5885 /// \returns The expansion result or SDValue() if it fails.
5886 SDValue expandVectorFindLastActive(SDNode *N, SelectionDAG &DAG) const;
5887
5888 /// Expand LOOP_DEPENDENCE_MASK nodes
5889 /// \param N Node to expand
5890 /// \returns The expansion result or SDValue() if it fails.
5891 SDValue expandLoopDependenceMask(SDNode *N, SelectionDAG &DAG) const;
5892
5893 /// Expand ABS nodes. Expands vector/scalar ABS nodes,
5894 /// vector nodes can only succeed if all operations are legal/custom.
5895 /// (ABS x) -> (XOR (ADD x, (SRA x, type_size)), (SRA x, type_size))
5896 /// \param N Node to expand
5897 /// \param IsNegative indicate negated abs
5898 /// \returns The expansion result or SDValue() if it fails.
5899 SDValue expandABS(SDNode *N, SelectionDAG &DAG,
5900 bool IsNegative = false) const;
5901
5902 /// Expand ABDS/ABDU nodes. Expands vector/scalar ABDS/ABDU nodes.
5903 /// \param N Node to expand
5904 /// \returns The expansion result or SDValue() if it fails.
5905 SDValue expandABD(SDNode *N, SelectionDAG &DAG) const;
5906
5907 /// Expand vector/scalar AVGCEILS/AVGCEILU/AVGFLOORS/AVGFLOORU nodes.
5908 /// \param N Node to expand
5909 /// \returns The expansion result or SDValue() if it fails.
5910 SDValue expandAVG(SDNode *N, SelectionDAG &DAG) const;
5911
5912 /// Expand BSWAP nodes. Expands scalar/vector BSWAP nodes with i16/i32/i64
5913 /// scalar types. Returns SDValue() if expand fails.
5914 /// \param N Node to expand
5915 /// \returns The expansion result or SDValue() if it fails.
5916 SDValue expandBSWAP(SDNode *N, SelectionDAG &DAG) const;
5917
5918 /// Expand BITREVERSE nodes. Expands scalar/vector BITREVERSE nodes.
5919 /// Returns SDValue() if expand fails.
5920 /// \param N Node to expand
5921 /// \returns The expansion result or SDValue() if it fails.
5922 SDValue expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const;
5923
5924 /// Turn load of vector type into a load of the individual elements.
5925 /// \param LD load to expand
5926 /// \returns BUILD_VECTOR and TokenFactor nodes.
5927 std::pair<SDValue, SDValue> scalarizeVectorLoad(LoadSDNode *LD,
5928 SelectionDAG &DAG) const;
5929
5930 // Turn a store of a vector type into stores of the individual elements.
5931 /// \param ST Store with a vector value type
5932 /// \returns TokenFactor of the individual store chains.
5934
5935 /// Expands an unaligned load to 2 half-size loads for an integer, and
5936 /// possibly more for vectors.
5937 std::pair<SDValue, SDValue> expandUnalignedLoad(LoadSDNode *LD,
5938 SelectionDAG &DAG) const;
5939
5940 /// Expands an unaligned store to 2 half-size stores for integer values, and
5941 /// possibly more for vectors.
5942 SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const;
5943
5944 /// Increments memory address \p Addr according to the type of the value
5945 /// \p DataVT that should be stored. If the data is stored in compressed
5946 /// form, the memory address should be incremented according to the number of
5947 /// the stored elements. This number is equal to the number of '1's bits
5948 /// in the \p Mask.
5949 /// \p DataVT is a vector type. \p Mask is a vector value.
5950 /// \p DataVT and \p Mask have the same number of vector elements.
5951 SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL,
5952 EVT DataVT, SelectionDAG &DAG,
5953 bool IsCompressedMemory) const;
5954
5955 /// Get a pointer to vector element \p Idx located in memory for a vector of
5956 /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
5957 /// bounds the returned pointer is unspecified, but will be within the vector
5958 /// bounds. \p PtrArithFlags can be used to mark that arithmetic within the
5959 /// vector in memory is known to not wrap or to be inbounds.
5960 SDValue getVectorElementPointer(
5961 SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, SDValue Index,
5962 const SDNodeFlags PtrArithFlags = SDNodeFlags()) const;
5963
5964 /// Get a pointer to vector element \p Idx located in memory for a vector of
5965 /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
5966 /// bounds the returned pointer is unspecified, but will be within the vector
5967 /// bounds. \p VecPtr is guaranteed to point to the beginning of a memory
5968 /// location large enough for the vector.
5970 EVT VecVT, SDValue Index) const {
5971 return getVectorElementPointer(DAG, VecPtr, VecVT, Index,
5974 }
5975
5976 /// Get a pointer to a sub-vector of type \p SubVecVT at index \p Idx located
5977 /// in memory for a vector of type \p VecVT starting at a base address of
5978 /// \p VecPtr. If \p Idx plus the size of \p SubVecVT is out of bounds the
5979 /// returned pointer is unspecified, but the value returned will be such that
5980 /// the entire subvector would be within the vector bounds. \p PtrArithFlags
5981 /// can be used to mark that arithmetic within the vector in memory is known
5982 /// to not wrap or to be inbounds.
5983 SDValue
5984 getVectorSubVecPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT,
5985 EVT SubVecVT, SDValue Index,
5986 const SDNodeFlags PtrArithFlags = SDNodeFlags()) const;
5987
5988 /// Method for building the DAG expansion of ISD::[US][MIN|MAX]. This
5989 /// method accepts integers as its arguments.
5990 SDValue expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const;
5991
5992 /// Method for building the DAG expansion of ISD::[US][ADD|SUB]SAT. This
5993 /// method accepts integers as its arguments.
5994 SDValue expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const;
5995
5996 /// Method for building the DAG expansion of ISD::[US]CMP. This
5997 /// method accepts integers as its arguments
5998 SDValue expandCMP(SDNode *Node, SelectionDAG &DAG) const;
5999
6000 /// Method for building the DAG expansion of ISD::[US]SHLSAT. This
6001 /// method accepts integers as its arguments.
6002 SDValue expandShlSat(SDNode *Node, SelectionDAG &DAG) const;
6003
6004 /// Method for building the DAG expansion of ISD::[U|S]MULFIX[SAT]. This
6005 /// method accepts integers as its arguments.
6006 SDValue expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const;
6007
6008 /// Method for building the DAG expansion of ISD::[US]DIVFIX[SAT]. This
6009 /// method accepts integers as its arguments.
6010 /// Note: This method may fail if the division could not be performed
6011 /// within the type. Clients must retry with a wider type if this happens.
6012 SDValue expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
6014 unsigned Scale, SelectionDAG &DAG) const;
6015
6016 /// Method for building the DAG expansion of ISD::U(ADD|SUB)O. Expansion
6017 /// always suceeds and populates the Result and Overflow arguments.
6018 void expandUADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
6019 SelectionDAG &DAG) const;
6020
6021 /// Method for building the DAG expansion of ISD::S(ADD|SUB)O. Expansion
6022 /// always suceeds and populates the Result and Overflow arguments.
6023 void expandSADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
6024 SelectionDAG &DAG) const;
6025
6026 /// Method for building the DAG expansion of ISD::[US]MULO. Returns whether
6027 /// expansion was successful and populates the Result and Overflow arguments.
6028 bool expandMULO(SDNode *Node, SDValue &Result, SDValue &Overflow,
6029 SelectionDAG &DAG) const;
6030
6031 // Expand ISD::MULH[SU]. Can expand to MUL_LOHI or wide MUL if available.
6032 SDValue expandMULH(SDNode *Node, SelectionDAG &DAG) const;
6033
6034 /// Calculate the product twice the width of LHS and RHS. If HiLHS/HiRHS are
6035 /// non-null they will be included in the multiplication. The expansion works
6036 /// by splitting the 2 inputs into 4 pieces that we can multiply and add
6037 /// together without neding MULH or MUL_LOHI.
6038 void forceExpandMultiply(SelectionDAG &DAG, const SDLoc &dl, bool Signed,
6040 SDValue HiLHS = SDValue(),
6041 SDValue HiRHS = SDValue()) const;
6042
6043 /// Calculate full product of LHS and RHS either via a libcall or through
6044 /// brute force expansion of the multiplication. The expansion works by
6045 /// splitting the 2 inputs into 4 pieces that we can multiply and add together
6046 /// without needing MULH or MUL_LOHI.
6047 void forceExpandWideMUL(SelectionDAG &DAG, const SDLoc &dl, bool Signed,
6048 const SDValue LHS, const SDValue RHS, SDValue &Lo,
6049 SDValue &Hi) const;
6050
6051 /// Expand a VECREDUCE_* into an explicit calculation. If Count is specified,
6052 /// only the first Count elements of the vector are used.
6053 SDValue expandVecReduce(SDNode *Node, SelectionDAG &DAG) const;
6054
6055 /// Expand a VECREDUCE_SEQ_* into an explicit ordered calculation.
6056 SDValue expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const;
6057
6058 /// Expand an SREM or UREM using SDIV/UDIV or SDIVREM/UDIVREM, if legal.
6059 /// Returns true if the expansion was successful.
6060 bool expandREM(SDNode *Node, SDValue &Result, SelectionDAG &DAG) const;
6061
6062 /// Method for building the DAG expansion of ISD::VECTOR_SPLICE. This
6063 /// method accepts vectors as its arguments.
6064 SDValue expandVectorSplice(SDNode *Node, SelectionDAG &DAG) const;
6065
6066 /// Expand a vector VECTOR_COMPRESS into a sequence of extract element, store
6067 /// temporarily, advance store position, before re-loading the final vector.
6068 SDValue expandVECTOR_COMPRESS(SDNode *Node, SelectionDAG &DAG) const;
6069
6070 /// Expand a CTTZ_ELTS or CTTZ_ELTS_ZERO_POISON by calculating (VL - i) for
6071 /// each active lane (i), getting the maximum and subtracting it from VL.
6072 SDValue expandCttzElts(SDNode *Node, SelectionDAG &DAG) const;
6073
6074 /// Expands PARTIAL_REDUCE_S/UMLA nodes to a series of simpler operations,
6075 /// consisting of zext/sext, extract_subvector, mul and add operations.
6076 SDValue expandPartialReduceMLA(SDNode *Node, SelectionDAG &DAG) const;
6077
6078 /// Expands a node with multiple results to an FP or vector libcall. The
6079 /// libcall is expected to take all the operands of the \p Node followed by
6080 /// output pointers for each of the results. \p CallRetResNo can be optionally
6081 /// set to indicate that one of the results comes from the libcall's return
6082 /// value.
6083 bool expandMultipleResultFPLibCall(
6084 SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node,
6086 std::optional<unsigned> CallRetResNo = {}) const;
6087
6088 /// Legalize a SETCC with given LHS and RHS and condition code CC on the
6089 /// current target.
6090 ///
6091 /// If the SETCC has been legalized using AND / OR, then the legalized node
6092 /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert
6093 /// will be set to false.
6094 ///
6095 /// If the SETCC has been legalized by using getSetCCSwappedOperands(), then
6096 /// the values of LHS and RHS will be swapped, CC will be set to the new
6097 /// condition, and NeedInvert will be set to false.
6098 ///
6099 /// If the SETCC has been legalized using the inverse condcode, then LHS and
6100 /// RHS will be unchanged, CC will set to the inverted condcode, and
6101 /// NeedInvert will be set to true. The caller must invert the result of the
6102 /// SETCC with SelectionDAG::getLogicalNOT() or take equivalent action to swap
6103 /// the effect of a true/false result.
6104 ///
6105 /// \returns true if the SETCC has been legalized, false if it hasn't.
6106 bool LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, SDValue &LHS,
6107 SDValue &RHS, SDValue &CC, bool &NeedInvert,
6108 const SDLoc &dl, SDValue &Chain,
6109 bool IsSignaling = false) const;
6110
6111 //===--------------------------------------------------------------------===//
6112 // Instruction Emitting Hooks
6113 //
6114
6115 /// This method should be implemented by targets that mark instructions with
6116 /// the 'usesCustomInserter' flag. These instructions are special in various
6117 /// ways, which require special support to insert. The specified MachineInstr
6118 /// is created but not inserted into any basic blocks, and this method is
6119 /// called to expand it into a sequence of instructions, potentially also
6120 /// creating new basic blocks and control flow.
6121 /// As long as the returned basic block is different (i.e., we created a new
6122 /// one), the custom inserter is free to modify the rest of \p MBB.
6123 virtual MachineBasicBlock *
6124 EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const;
6125
6126 /// This method should be implemented by targets that mark instructions with
6127 /// the 'hasPostISelHook' flag. These instructions must be adjusted after
6128 /// instruction selection by target hooks. e.g. To fill in optional defs for
6129 /// ARM 's' setting instructions.
6130 virtual void AdjustInstrPostInstrSelection(MachineInstr &MI,
6131 SDNode *Node) const;
6132
6133 /// If this function returns true, SelectionDAGBuilder emits a
6134 /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
6135 virtual bool useLoadStackGuardNode(const Module &M) const { return false; }
6136
6138 const SDLoc &DL) const {
6139 llvm_unreachable("not implemented for this target");
6140 }
6141
6142 /// Lower TLS global address SDNode for target independent emulated TLS model.
6143 virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
6144 SelectionDAG &DAG) const;
6145
6146 /// Expands target specific indirect branch for the case of JumpTable
6147 /// expansion.
6148 virtual SDValue expandIndirectJTBranch(const SDLoc &dl, SDValue Value,
6149 SDValue Addr, int JTI,
6150 SelectionDAG &DAG) const;
6151
6152 // seteq(x, 0) -> truncate(srl(ctlz(zext(x)), log2(#bits)))
6153 // If we're comparing for equality to zero and isCtlzFast is true, expose the
6154 // fact that this can be implemented as a ctlz/srl pair, so that the dag
6155 // combiner can fold the new nodes.
6156 SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const;
6157
6158 // Return true if `X & Y eq/ne 0` is preferable to `X & Y ne/eq Y`
6160 return true;
6161 }
6162
6163 // Expand vector operation by dividing it into smaller length operations and
6164 // joining their results. SDValue() is returned when expansion did not happen.
6165 SDValue expandVectorNaryOpBySplitting(SDNode *Node, SelectionDAG &DAG) const;
6166
6167 /// Replace an extraction of a load with a narrowed load.
6168 ///
6169 /// \param ResultVT type of the result extraction.
6170 /// \param InVecVT type of the input vector to with bitcasts resolved.
6171 /// \param EltNo index of the vector element to load.
6172 /// \param OriginalLoad vector load that to be replaced.
6173 /// \returns \p ResultVT Load on success SDValue() on failure.
6174 SDValue scalarizeExtractedVectorLoad(EVT ResultVT, const SDLoc &DL,
6175 EVT InVecVT, SDValue EltNo,
6176 LoadSDNode *OriginalLoad,
6177 SelectionDAG &DAG) const;
6178
6179protected:
6180 void setTypeIdForCallsiteInfo(const CallBase *CB, MachineFunction &MF,
6181 MachineFunction::CallSiteInfo &CSInfo) const;
6182
6183private:
6184 SDValue foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
6185 const SDLoc &DL, DAGCombinerInfo &DCI) const;
6186 SDValue foldSetCCWithOr(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
6187 const SDLoc &DL, DAGCombinerInfo &DCI) const;
6188 SDValue foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
6189 const SDLoc &DL, DAGCombinerInfo &DCI) const;
6190
6191 SDValue optimizeSetCCOfSignedTruncationCheck(EVT SCCVT, SDValue N0,
6193 DAGCombinerInfo &DCI,
6194 const SDLoc &DL) const;
6195
6196 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
6197 SDValue optimizeSetCCByHoistingAndByConstFromLogicalShift(
6198 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
6199 DAGCombinerInfo &DCI, const SDLoc &DL) const;
6200
6201 SDValue prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
6202 SDValue CompTargetNode, ISD::CondCode Cond,
6203 DAGCombinerInfo &DCI, const SDLoc &DL,
6204 SmallVectorImpl<SDNode *> &Created) const;
6205 SDValue buildUREMEqFold(EVT SETCCVT, SDValue REMNode, SDValue CompTargetNode,
6206 ISD::CondCode Cond, DAGCombinerInfo &DCI,
6207 const SDLoc &DL) const;
6208
6209 SDValue prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
6210 SDValue CompTargetNode, ISD::CondCode Cond,
6211 DAGCombinerInfo &DCI, const SDLoc &DL,
6212 SmallVectorImpl<SDNode *> &Created) const;
6213 SDValue buildSREMEqFold(EVT SETCCVT, SDValue REMNode, SDValue CompTargetNode,
6214 ISD::CondCode Cond, DAGCombinerInfo &DCI,
6215 const SDLoc &DL) const;
6216
6217 bool expandUDIVREMByConstantViaUREMDecomposition(
6218 SDNode *N, APInt Divisor, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
6219 SelectionDAG &DAG, SDValue LL, SDValue LH) const;
6220
6221 bool expandUDIVREMByConstantViaUMulHiMagic(SDNode *N, const APInt &Divisor,
6223 EVT HiLoVT, SelectionDAG &DAG,
6224 SDValue LL, SDValue LH) const;
6225};
6226
6227/// Given an LLVM IR type and return type attributes, compute the return value
6228/// EVTs and flags, and optionally also the offsets, if the return value is
6229/// being lowered to memory.
6230LLVM_ABI void GetReturnInfo(CallingConv::ID CC, Type *ReturnType,
6231 AttributeList attr,
6232 SmallVectorImpl<ISD::OutputArg> &Outs,
6233 const TargetLowering &TLI, const DataLayout &DL);
6234
6235} // end namespace llvm
6236
6237#endif // LLVM_CODEGEN_TARGETLOWERING_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
Function Alias Analysis Results
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
block Block Frequency Analysis
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_READONLY
Definition Compiler.h:338
This file defines the DenseMap class.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, const APInt &Demanded)
Check to see if the specified operand of the specified instruction is a constant integer.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
lazy value info
Implement a low-level type suitable for MachineInstr level instruction selection.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
const uint64_t BitWidth
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
PowerPC Reduce CR logical Operation
const SmallVectorImpl< MachineOperand > & Cond
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")))
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT, SelectionDAG &DAG)
Scalarize a vector store, bitcasting to TargetVT to determine the scalar type.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
bool isFloatingPointOperation() const
BinOp getOperation() const
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:410
LLVM_ABI bool getValueAsBool() const
Return the attribute's value as a boolean.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
CCState - This class holds information needed while lowering arguments and return values.
CCValAssign - Represent assignment of one arg/retval to a location.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class represents a function call, abstracting a target machine's calling convention.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This class represents a range of values.
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:64
unsigned size() const
Definition DenseMap.h:718
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:316
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:67
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Class to represent function types.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
bool isVarArg() const
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:765
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
A wrapper class for inspecting calls to intrinsic functions.
static LLT integer(unsigned SizeInBits)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Tracks which library functions to use for a particular subtarget or function.
An instruction for reading from memory.
This class is used to represent ISD::LOAD nodes.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Context object for machine code objects.
Definition MCContext.h:83
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
MCRegisterClass - Base class of TargetRegisterClass.
Machine Value Type.
@ INVALID_SIMPLE_VALUE_TYPE
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
bool isInteger() const
Return true if this is an integer or a vector integer type.
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
ElementCount getVectorElementCount() const
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
bool isValid() const
Return true if this is a valid simple valuetype.
static MVT getIntegerVT(unsigned BitWidth)
Instructions::iterator instr_iterator
Representation of each machine instruction.
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
This is an abstract virtual class for memory operations.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
Analysis providing profile information.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
bool hasOneUse() const
Return true if there is exactly one use of this node.
bool use_empty() const
Return true if there are no uses of this node.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
EVT getValueType() const
Return the ValueType of the referenced return value.
const SDValue & getOperand(unsigned i) const
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
const DataLayout & getDataLayout() const
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVMContext * getContext() const
This instruction constructs a fixed permutation of two input vectors.
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.
An instruction for storing to memory.
This class is used to represent ISD::STORE nodes.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Multiway switch.
TargetInstrInfo - Interface to description of machine instruction set.
Provides information about what library functions are available for the current target.
ArgListEntry(Value *Val, SDValue Node=SDValue())
ArgListEntry(Value *Val, SDValue Node, Type *Ty)
Type * Ty
Same as OrigTy, or partially legalized for soft float libcalls.
Type * OrigTy
Original unlegalized argument type.
LegalizeTypeAction getTypeAction(MVT VT) const
void setTypeAction(MVT VT, LegalizeTypeAction Action)
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
virtual Value * emitStoreConditional(IRBuilderBase &Builder, Value *Val, Value *Addr, AtomicOrdering Ord) const
Perform a store-conditional operation to Addr.
virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT) const
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
bool isOperationExpand(unsigned Op, EVT VT) const
Return true if the specified operation is illegal on this target or unlikely to be made legal with cu...
EVT getMemValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
virtual bool enableAggressiveFMAFusion(LLT Ty) const
Return true if target always benefits from combining into FMA for a given value type.
virtual void emitBitTestAtomicRMWIntrinsic(AtomicRMWInst *AI) const
Perform a bit test atomicrmw using a target-specific intrinsic.
void setOperationAction(ArrayRef< unsigned > Ops, ArrayRef< MVT > VTs, LegalizeAction Action)
virtual bool requiresUniformRegister(MachineFunction &MF, const Value *) const
Allows target to decide about the register class of the specific value that is live outside the defin...
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
virtual unsigned getVaListSizeInBits(const DataLayout &DL) const
Returns the size of the platform's va_list object.
virtual bool lowerDeinterleaveIntrinsicToLoad(Instruction *Load, Value *Mask, IntrinsicInst *DI, const APInt &GapMask) const
Lower a deinterleave intrinsic to a target specific load intrinsic.
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
virtual bool preferSextInRegOfTruncate(EVT TruncVT, EVT VT, EVT ExtVT) const
virtual bool decomposeMulByConstant(LLVMContext &Context, EVT VT, SDValue C) const
Return true if it is profitable to transform an integer multiplication-by-constant into simpler opera...
void setMaxDivRemBitWidthSupported(unsigned SizeInBits)
Set the size in bits of the maximum div/rem the backend supports.
virtual bool hasAndNot(SDValue X) const
Return true if the target has a bitwise and-not operation: X = ~A & B This can be used to simplify se...
ReciprocalEstimate
Reciprocal estimate status values used by the functions below.
bool PredictableSelectIsExpensive
Tells the code generator that select is more expensive than a branch if the branch is usually predict...
virtual bool isShuffleMaskLegal(ArrayRef< int >, EVT) const
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations,...
virtual bool isAtomicAlignmentSupported(Align Alignment, uint64_t SizeInBytes) const
Return true if the target supports an atomic access of SizeInBytes bytes at the given Alignment.
virtual bool enableAggressiveFMAFusion(EVT VT) const
Return true if target always benefits from combining into FMA for a given value type.
virtual bool isComplexDeinterleavingOperationSupported(ComplexDeinterleavingOperation Operation, Type *Ty) const
Does this target support complex deinterleaving with the given operation and type.
virtual bool shouldRemoveRedundantExtend(SDValue Op) const
Return true (the default) if it is profitable to remove a sext_inreg(x) where the sext is redundant,...
bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
SDValue promoteTargetBoolean(SelectionDAG &DAG, SDValue Bool, EVT ValVT) const
Promote the given target boolean to a target boolean of the given type.
virtual bool isFMADLegal(const SelectionDAG &DAG, const SDNode *N) const
Returns true if be combined with to form an ISD::FMAD.
virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT, std::optional< unsigned > ByteOffset=std::nullopt) const
Return true if it is profitable to reduce a load to a smaller type.
virtual bool hasStandaloneRem(EVT VT) const
Return true if the target can handle a standalone remainder operation.
virtual bool isExtFreeImpl(const Instruction *I) const
Return true if the extension represented by I is free.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
LegalizeAction
This enum indicates whether operations are valid for a target, and if not, what action should be used...
virtual bool shouldExpandBuildVectorWithShuffles(EVT, unsigned DefinedValues) const
LegalizeAction getIndexedMaskedStoreAction(unsigned IdxMode, MVT VT) const
Return how the indexed store should be treated: either it is legal, needs to be promoted to a larger ...
virtual bool isSelectSupported(SelectSupportKind) const
CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const
Get the CallingConv that should be used for the specified libcall.
unsigned MaxStoresPerMemcpyOptSize
Likewise for functions with the OptSize attribute.
MachineBasicBlock * emitPatchPoint(MachineInstr &MI, MachineBasicBlock *MBB) const
Replace/modify any TargetFrameIndex operands with a targte-dependent sequence of memory operands that...
virtual bool isEqualityCmpFoldedWithSignedCmp() const
Return true if instruction generated for equality comparison is folded with instruction generated for...
virtual bool preferSelectsOverBooleanArithmetic(EVT VT) const
Should we prefer selects to doing arithmetic on boolean types.
virtual bool isLegalICmpImmediate(int64_t) const
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const
Use bitwise logic to make pairs of compares more efficient.
void setAtomicLoadExtAction(ArrayRef< unsigned > ExtTypes, MVT ValVT, ArrayRef< MVT > MemVTs, LegalizeAction Action)
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT, bool MathUsed) const
Try to convert math with an overflow comparison into the corresponding DAG node operation.
ShiftLegalizationStrategy
Return the preferred strategy to legalize tihs SHIFT instruction, with ExpansionFactor being the recu...
virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const
Return true if folding a vector load into ExtVal (a sign, zero, or any extend node) is profitable.
virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const
Return if the target supports combining a chain like:
virtual Value * createComplexDeinterleavingIR(IRBuilderBase &B, ComplexDeinterleavingOperation OperationType, ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB, Value *Accumulator=nullptr) const
Create the IR node for the given complex deinterleaving operation.
virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const
Return true if it is beneficial to convert a load of a constant to just the constant itself.
virtual MVT::SimpleValueType getCmpLibcallReturnType() const
Return the ValueType for comparison libcalls.
virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT, unsigned Scale) const
Custom method defined by each target to indicate if an operation which may require a scale is support...
void setLoadExtAction(ArrayRef< unsigned > ExtTypes, MVT ValVT, MVT MemVT, LegalizeAction Action)
unsigned getMaximumLegalStoreInBits() const
Return maximum known-legal store size, which can be guaranteed for scalable vectors.
virtual bool shouldOptimizeMulOverflowWithZeroHighBits(LLVMContext &Context, EVT VT) const
virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *RMW) const
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
virtual Sched::Preference getSchedulingPreference(SDNode *) const
Some scheduler, e.g.
virtual MachineInstr * EmitKCFICheck(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator &MBBI, const TargetInstrInfo *TII) const
void setMinStackArgumentAlignment(Align Alignment)
Set the minimum stack alignment of an argument.
bool isExtLoad(const LoadInst *Load, const Instruction *Ext, const DataLayout &DL) const
Return true if Load and Ext can form an ExtLoad.
LegalizeTypeAction getTypeAction(MVT VT) const
virtual bool isLegalScaleForGatherScatter(uint64_t Scale, uint64_t ElemSize) const
EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
virtual bool shouldInsertFencesForAtomic(const Instruction *I) const
Whether AtomicExpandPass should automatically insert fences and reduce ordering for this atomic.
virtual AtomicOrdering atomicOperationOrderAfterFenceSplit(const Instruction *I) const
MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
bool isOperationExpandOrLibCall(unsigned Op, EVT VT) const
virtual bool allowsMisalignedMemoryAccesses(LLT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
LLT handling variant.
virtual bool isSafeMemOpType(MVT) const
Returns true if it's safe to use load / store of the specified type to expand memcpy / memset inline.
virtual void emitExpandAtomicCmpXchg(AtomicCmpXchgInst *CI) const
Perform a cmpxchg expansion using a target-specific method.
virtual ISD::NodeType getExtendForAtomicRMWArg(unsigned Op) const
Returns how the platform's atomic rmw operations expect their input argument to be extended (ZERO_EXT...
const TargetMachine & getTargetMachine() const
unsigned MaxLoadsPerMemcmp
Specify maximum number of load instructions per memcmp call.
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
bool rangeFitsInWord(const APInt &Low, const APInt &High, const DataLayout &DL) const
Check whether the range [Low,High] fits in a machine word.
virtual bool isCtpopFast(EVT VT) const
Return true if ctpop instruction is fast.
virtual MachineMemOperand::Flags getTargetMMOFlags(const Instruction &I) const
This callback is used to inspect load/store instructions and add target-specific MachineMemOperand fl...
virtual Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception typeid on entry to a la...
unsigned MaxGluedStoresPerMemcpy
Specify max number of store instructions to glue in inlined memcpy.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
bool isPaddedAtMostSignificantBitsWhenStored(EVT VT) const
Indicates if any padding is guaranteed to go at the most significant bits when storing the type to me...
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
Convenience method to set an operation to Promote and specify the type in a single call.
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
virtual bool useStackGuardMixFP() const
If this function returns true, stack protection checks should mix the frame pointer (or whichever poi...
unsigned getMinCmpXchgSizeInBits() const
Returns the size of the smallest cmpxchg or ll/sc instruction the backend supports.
virtual Value * emitMaskedAtomicRMWIntrinsic(IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const
Perform a masked atomicrmw using a target-specific intrinsic.
virtual bool areJTsAllowed(const Function *Fn) const
Return true if lowering to a jump table is allowed.
virtual LegalizeAction getCustomTruncStoreAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace) const
Returns an alternative action to use when the coarser lookups (configured through setTruncStoreAction...
bool enableExtLdPromotion() const
Return true if the target wants to use the optimization that turns ext(promotableInst1(....
virtual bool isFPExtFoldable(const MachineInstr &MI, unsigned Opcode, LLT DestTy, LLT SrcTy) const
Return true if an fpext operation input to an Opcode operation is free (for instance,...
void setIndexedMaskedLoadAction(unsigned IdxMode, MVT VT, LegalizeAction Action)
Indicate that the specified indexed masked load does or does not work with the specified type and ind...
void setMaxBytesForAlignment(unsigned MaxBytes)
bool isOperationLegalOrPromote(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal using promotion.
void setHasExtractBitsInsn(bool hasExtractInsn=true)
Tells the code generator that the target has BitExtract instructions.
void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth)
Tells the code generator which bitwidths to bypass.
virtual bool hasBitTest(SDValue X, SDValue Y) const
Return true if the target has a bit-test instruction: (X & (1 << Y)) ==/!= 0 This knowledge can be us...
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
virtual AtomicExpansionKind shouldExpandAtomicCmpXchgInIR(const AtomicCmpXchgInst *AI) const
Returns how the given atomic cmpxchg should be expanded by the IR-level AtomicExpand pass.
virtual bool needsFixedCatchObjects() const
virtual bool isAnyExtFree(EVT FromTy, EVT ToTy) const
Return true is an anyext is free from FromTy to ToTy.
EVT getLegalTypeToTransformTo(LLVMContext &Context, EVT VT) const
Perform getTypeToTransformTo repeatedly until a legal type is obtained.
virtual Value * emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy, Value *Addr, AtomicOrdering Ord) const
Perform a load-linked operation on Addr, returning a "Value *" with the corresponding pointee type.
void setMaxLargeFPConvertBitWidthSupported(unsigned SizeInBits)
Set the size in bits of the maximum fp to/from int conversion the backend supports.
const LibcallLoweringInfo & getLibcallLoweringInfo() const
virtual unsigned getNumRegisters(LLVMContext &Context, EVT VT, std::optional< MVT > RegisterVT=std::nullopt) const
Return the number of registers that this ValueType will eventually require.
virtual bool isCheapToSpeculateCttz(Type *Ty) const
Return true if it is cheap to speculate a call to intrinsic cttz.
unsigned getMinimumBitTestCmps() const
Retuen the minimum of largest number of comparisons in BitTest.
bool isJumpExpensive() const
Return true if Flow Control is an expensive operation that should be avoided.
virtual bool useFPRegsForHalfType() const
LegalizeAction getCondCodeAction(ISD::CondCode CC, MVT VT) const
Return how the condition code should be treated: either it is legal, needs to be expanded to some oth...
bool hasExtractBitsInsn() const
Return true if the target has BitExtract instructions.
virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT, const SelectionDAG &DAG, const MachineMemOperand &MMO) const
Return true if the following transform is beneficial: fold (conv (load x)) -> (load (conv*)x) On arch...
LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const
Return how the indexed store should be treated: either it is legal, needs to be promoted to a larger ...
void setIndexedLoadAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed load does or does not work with the specified type and indicate w...
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall implementation.
void setPrefLoopAlignment(Align Alignment)
Set the target's preferred loop alignment.
virtual bool areTwoSDNodeTargetMMOFlagsMergeable(const MemSDNode &NodeX, const MemSDNode &NodeY) const
Return true if it is valid to merge the TargetMMOFlags in two SDNodes.
virtual bool isCommutativeBinOp(unsigned Opcode) const
Returns true if the opcode is a commutative binary operation.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
virtual bool isFPImmLegal(const APFloat &, EVT, bool ForCodeSize=false) const
Returns true if the target can instruction select the specified FP immediate natively.
LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace) const
Return how this store with truncation should be treated: either it is legal, needs to be promoted to ...
virtual unsigned getPreferredFPToIntOpcode(unsigned Op, EVT FromVT, EVT ToVT) const
virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const
Return true if extraction of a scalar element from the given vector type at the given index is cheap.
virtual Value * emitCanLoadSpeculatively(IRBuilderBase &Builder, Value *Ptr, Value *Size) const
Emit code to check if a speculative load of the given size from Ptr is safe.
void setOperationAction(ArrayRef< unsigned > Ops, MVT VT, LegalizeAction Action)
virtual bool optimizeFMulOrFDivAsShiftAddBitcast(SDNode *N, SDValue FPConst, SDValue IntPow2) const
SelectSupportKind
Enum that describes what type of support for selects the target has.
RTLIB::LibcallImpl getMemcpyImpl() const
LegalizeAction getIndexedLoadAction(unsigned IdxMode, MVT VT) const
Return how the indexed load should be treated: either it is legal, needs to be promoted to a larger s...
virtual bool shouldTransformSignedTruncationCheck(EVT XVT, unsigned KeptBits) const
Should we tranform the IR-optimal check for whether given truncation down into KeptBits would be trun...
virtual bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, EVT DestVT, EVT SrcVT) const
Return true if an fpext operation input to an Opcode operation is free (for instance,...
bool isLegalRC(const TargetRegisterInfo &TRI, const TargetRegisterClass &RC) const
Return true if the value types that can be represented by the specified register class are all legal.
virtual TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const
Return the preferred vector type legalization action.
virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const
Return true if a truncation from FromTy to ToTy is permitted when deciding whether a call is in tail ...
void setAtomicLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Let target indicate that an extending atomic load of the specified type is legal.
virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const
Returns true if the index type for a masked gather/scatter requires extending.
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
virtual StringRef getStackProbeSymbolName(const MachineFunction &MF) const
LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT, unsigned Scale) const
Some fixed point operations may be natively supported by the target but only for specific scales.
virtual bool preferScalarizeSplat(SDNode *N) const
void setVectorInterleaveAction(unsigned Opc, unsigned Factor, MVT VT, LegalizeAction Action)
Indicate how a VECTOR_INTERLEAVE or VECTOR_DEINTERLEAVE node with the given interleave factor Factor ...
bool isIndexedMaskedLoadLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
virtual ISD::NodeType getExtendForAtomicOps() const
Returns how the platform's atomic operations are extended (ZERO_EXTEND, SIGN_EXTEND,...
Sched::Preference getSchedulingPreference() const
Return target scheduling preference.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
virtual LLT getOptimalMemOpLLT(const MemOp &Op, const AttributeList &) const
LLT returning variant.
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not.
virtual ExtractSubvectorCost getExtractSubvectorCost(EVT ResVT, EVT SrcVT, unsigned Index) const
Return the cost of extracting a subvector of type ResVT from a vector of type SrcVT,...
virtual void emitExpandAtomicRMW(AtomicRMWInst *AI) const
Perform a atomicrmw expansion using a target-specific way.
unsigned MaxStoresPerMemsetOptSize
Likewise for functions with the OptSize attribute.
virtual bool reduceSelectOfFPConstantLoads(EVT CmpOpVT) const
Return true if it is profitable to convert a select of FP constants into a constant pool load whose a...
bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const
When splitting a value of the specified type into parts, does the Lo or Hi part come first?
virtual bool hasStackProbeSymbol(const MachineFunction &MF) const
Returns the name of the symbol used to emit stack probes or the empty string if not applicable.
bool isSlowDivBypassed() const
Returns true if target has indicated at least one type should be bypassed.
virtual Align getABIAlignmentForCallingConv(Type *ArgTy, const DataLayout &DL) const
Certain targets have context sensitive alignment requirements, where one type has the alignment requi...
virtual bool isMulAddWithConstProfitable(SDValue AddNode, SDValue ConstNode) const
Return true if it may be profitable to transform (mul (add x, c1), c2) -> (add (mul x,...
virtual bool shouldExtendTypeInLibCall(EVT Type) const
Returns true if arguments should be extended in lib calls.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
void setVectorInterleaveAction(ArrayRef< unsigned > Opcodes, ArrayRef< unsigned > Factors, MVT VT, LegalizeAction Action)
bool isPartialReduceMLALegalOrCustom(unsigned Opc, EVT AccVT, EVT InputVT) const
Return true if a PARTIAL_REDUCE_U/SMLA node with the specified types is legal or custom for this targ...
virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const
Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
unsigned MaxStoresPerMemmove
Specify maximum number of store instructions per memmove call.
virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context, EVT VT, EVT CCVT) const
Returns true if we should normalize select(N0&N1, X, Y) => select(N0, select(N1, X,...
bool isSuitableForBitTests(const DenseMap< const BasicBlock *, unsigned int > &DestCmps, const APInt &Low, const APInt &High, const DataLayout &DL) const
Return true if lowering to a bit test is suitable for a set of case clusters which contains NumDests ...
virtual bool shouldExpandGetActiveLaneMask(EVT VT, EVT OpVT) const
Return true if the @llvm.get.active.lane.mask intrinsic should be expanded using generic code in Sele...
virtual bool shallExtractConstSplatVectorElementToStore(Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const
Return true if the target shall perform extract vector element and store given that the vector is kno...
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
virtual bool hasMultipleConditionRegisters(EVT VT) const
Does the target have multiple (allocatable) condition registers that can be used to store the results...
unsigned getMaxExpandSizeMemcmp(bool OptSize) const
Get maximum # of load operations permitted for memcmp.
bool isStrictFPEnabled() const
Return true if the target support strict float operation.
virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const
Return true if creating a shift of the type by the given amount is not profitable.
virtual bool shouldPreservePtrArith(const Function &F, EVT PtrVT) const
True if target has some particular form of dealing with pointer arithmetic semantics for pointers wit...
virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const
Return true if an fpext operation is free (for instance, because single-precision floating-point numb...
virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const
Return the ValueType of the result of SETCC operations.
virtual bool lowerInterleavedStore(Instruction *Store, Value *Mask, ShuffleVectorInst *SVI, unsigned Factor, const APInt &GapMask) const
Lower an interleaved store to target specific intrinsics.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
unsigned MaxStoresPerMemmoveOptSize
Likewise for functions with the OptSize attribute.
virtual bool shouldFoldSelectWithSingleBitTest(EVT VT, const APInt &AndMask) const
MVT getSimpleValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the MVT corresponding to this LLVM type. See getValueType.
BooleanContent getBooleanContents(bool isVec, bool isFloat) const
For targets without i1 registers, this gives the nature of the high-bits of boolean values held in ty...
bool isVectorInterleaveLegalOrCustom(unsigned Opc, unsigned Factor, EVT VT) const
Return true if a VECTOR_INTERLEAVE or VECTOR_DEINTERLEAVE node with the given interleave factor and f...
LegalizeAction getVectorInterleaveAction(unsigned Opc, unsigned Factor, EVT VT) const
Return how a VECTOR_INTERLEAVE or VECTOR_DEINTERLEAVE node with the given interleave factor and VT sh...
virtual bool shouldReassociateReduction(unsigned RedOpc, EVT VT) const
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
virtual CondMergingParams getJumpConditionMergingParams(Instruction::BinaryOps, const Value *, const Value *, const Function *) const
bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal for a comparison of the specified types on this ...
virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx, unsigned &Cost) const
Return true if the target can combine store(extractelement VectorTy,Idx).
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual bool shouldFoldConstantShiftPairToMask(const SDNode *N) const
Return true if it is profitable to fold a pair of shifts into a mask.
MVT getProgramPointerTy(const DataLayout &DL) const
Return the type for code pointers, which is determined by the program address space specified through...
void setIndexedStoreAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed store does or does not work with the specified type and indicate ...
ExtractSubvectorCost
Enum that specifies how expensive lowering an EXTRACT_SUBVECTOR is.
virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilderBase &Builder) const
void setSupportsUnalignedAtomics(bool UnalignedSupported)
Sets whether unaligned atomic operations are supported.
void setLoadExtAction(ArrayRef< unsigned > ExtTypes, MVT ValVT, ArrayRef< MVT > MemVTs, LegalizeAction Action)
virtual void emitExpandAtomicStore(StoreInst *SI) const
Perform a atomic store using a target-specific way.
virtual bool preferIncOfAddToSubOfNot(EVT VT) const
These two forms are equivalent: sub y, (xor x, -1) add (add x, 1), y The variant with two add's is IR...
virtual bool ShouldShrinkFPConstant(EVT) const
If true, then instruction selection should seek to shrink the FP constant of the specified type to a ...
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setPrefFunctionAlignment(Align Alignment)
Set the target's preferred function alignment.
unsigned getMaxDivRemBitWidthSupported() const
Returns the size in bits of the maximum div/rem the backend supports.
virtual bool isLegalAddImmediate(int64_t) const
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
virtual unsigned getMaxSupportedInterleaveFactor() const
Get the maximum supported factor for interleaved memory accesses.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
virtual bool shouldKeepZExtForFP16Conv() const
Does this target require the clearing of high-order bits in a register passed to the fp16 to fp conve...
virtual AtomicExpansionKind shouldCastAtomicRMWIInIR(AtomicRMWInst *RMWI) const
Returns how the given atomic atomicrmw should be cast by the IR-level AtomicExpand pass.
void setIndexedMaskedStoreAction(unsigned IdxMode, MVT VT, LegalizeAction Action)
Indicate that the specified indexed masked store does or does not work with the specified type and in...
virtual bool canTransformPtrArithOutOfBounds(const Function &F, EVT PtrVT) const
True if the target allows transformations of in-bounds pointer arithmetic that cause out-of-bounds in...
virtual bool shouldConsiderGEPOffsetSplit() const
const ValueTypeActionImpl & getValueTypeActions() const
virtual bool canCombineTruncStore(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, bool LegalOnly) const
TargetLoweringBase(const TargetMachine &TM, const TargetSubtargetInfo &STI)
NOTE: The TargetMachine owns TLOF.
unsigned MaxStoresPerMemset
Specify maximum number of store instructions per memset call.
virtual bool isTruncateFree(SDValue Val, EVT VT2) const
Return true if truncating the specific node Val to type VT2 is free.
virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const
virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const
Return the maximum number of "x & (x - 1)" operations that can be done instead of deferring to a cust...
virtual bool shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, unsigned OldShiftOpcode, unsigned NewShiftOpcode, SelectionDAG &DAG) const
Given the pattern (X & (C l>>/<< Y)) ==/!= 0 return true if it should be transformed into: ((X <</l>>...
virtual bool shouldInsertTrailingSeqCstFenceForAtomicStore(const Instruction *I) const
Whether AtomicExpandPass should automatically insert a seq_cst trailing fence without reducing the or...
virtual bool isFNegFree(EVT VT) const
Return true if an fneg operation is free to the point where it is never worthwhile to replace it with...
void setPartialReduceMLAAction(unsigned Opc, MVT AccVT, MVT InputVT, LegalizeAction Action)
Indicate how a PARTIAL_REDUCE_U/SMLA node with Acc type AccVT and Input type InputVT should be treate...
virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const
Returns how the given (atomic) load should be expanded by the IR-level AtomicExpand pass.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
bool isExtFree(const Instruction *I) const
Return true if the extension represented by I is free.
virtual MVT getFenceOperandTy(const DataLayout &DL) const
Return the type for operands of fence.
virtual Value * emitMaskedAtomicCmpXchgIntrinsic(IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const
Perform a masked cmpxchg using a target-specific intrinsic.
virtual bool isZExtFree(EVT FromTy, EVT ToTy) const
virtual ISD::NodeType getExtendForAtomicCmpSwapArg() const
Returns how the platform's atomic compare and swap expects its comparison value to be extended (ZERO_...
virtual bool shouldFoldSelectWithIdentityConstant(unsigned BinOpcode, EVT VT, unsigned SelectOpcode, SDValue X, SDValue Y) const
Return true if pulling a binary operation into a select with an identity constant is profitable.
BooleanContent
Enum that describes how the target represents true/false values.
virtual bool shouldExpandGetVectorLength(EVT CountVT, unsigned VF, bool IsScalable) const
virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const
Return true if integer divide is usually cheaper than a sequence of several shifts,...
virtual ShiftLegalizationStrategy preferredShiftLegalizationStrategy(SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const
virtual uint8_t getRepRegClassCostFor(MVT VT) const
Return the cost of the 'representative' register class for the specified value type.
virtual bool isZExtFree(LLT FromTy, LLT ToTy, LLVMContext &Ctx) const
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
LegalizeAction getPartialReduceMLAAction(unsigned Opc, EVT AccVT, EVT InputVT) const
Return how a PARTIAL_REDUCE_U/SMLA node with Acc type AccVT and Input type InputVT should be treated.
bool isPredictableSelectExpensive() const
Return true if selects are only cheaper than branches if the branch is unlikely to be predicted right...
virtual bool mergeStoresAfterLegalization(EVT MemVT) const
Allow store merging for the specified type after legalization in addition to before legalization.
unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Vector types are broken down into some number of legal first class types.
virtual bool shouldIssueAtomicLoadForAtomicEmulationLoop(void) const
virtual bool shouldMergeStoreOfLoadsOverCall(EVT, EVT) const
Returns true if it's profitable to allow merging store of loads when there are functions calls betwee...
virtual bool isProfitableToHoist(Instruction *I) const
unsigned getGatherAllAliasesMaxDepth() const
virtual LegalizeAction getCustomOperationAction(SDNode &Op) const
How to legalize this custom operation?
virtual bool isFMAFasterThanFMulAndFAdd(const Function &F, Type *) const
IR version.
virtual bool hasAndNotCompare(SDValue Y) const
Return true if the target should transform: (X & Y) == Y ---> (~X & Y) == 0 (X & Y) !...
virtual bool storeOfVectorConstantIsCheap(bool IsZero, EVT MemVT, unsigned NumElem, unsigned AddrSpace) const
Return true if it is expected to be cheaper to do a store of vector constant with the given size and ...
unsigned MaxLoadsPerMemcmpOptSize
Likewise for functions with the OptSize attribute.
virtual MVT hasFastEqualityCompare(unsigned NumBits) const
Return the preferred operand type if the target has a quick way to compare integer values of the give...
virtual const TargetRegisterClass * getRepRegClassFor(MVT VT) const
Return the 'representative' register class for the specified value type.
virtual bool isNarrowingProfitable(SDNode *N, EVT SrcVT, EVT DestVT) const
Return true if it's profitable to narrow operations of type SrcVT to DestVT.
LegalizeAction getLoadAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return how this load with extension should be treated: either it is legal, needs to be promoted to a ...
virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const
Return true if it is cheaper to split the store of a merged int val from a pair of smaller values int...
bool shouldUseDynamicVectorTypeBreakdown(EVT VT, bool ForCallingConv) const
TargetLoweringBase(const TargetLoweringBase &)=delete
virtual unsigned getMaxGluedStoresPerMemcpy() const
Get maximum # of store operations to be glued together.
virtual bool isBinOp(unsigned Opcode) const
Return true if the node is a math/logic binary operator.
virtual bool shouldFoldMaskToVariableShiftPair(SDValue X) const
There are two ways to clear extreme bits (either low or high): Mask: x & (-1 << y) (the instcombine c...
virtual bool alignLoopsWithOptSize() const
Should loops be aligned even when the function is marked OptSize (but not MinSize).
unsigned getMaxAtomicSizeInBitsSupported() const
Returns the maximum atomic operation size (in bits) supported by the backend.
bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
void setMinCmpXchgSizeInBits(unsigned SizeInBits)
Sets the minimum cmpxchg or ll/sc size supported by the backend.
virtual bool canMergeStoresTo(unsigned AS, EVT MemVT, const MachineFunction &MF) const
Returns if it's reasonable to merge stores to MemVT size.
void setPartialReduceMLAAction(ArrayRef< unsigned > Opcodes, MVT AccVT, MVT InputVT, LegalizeAction Action)
LegalizeAction getStrictFPOperationAction(unsigned Op, EVT VT) const
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
virtual bool preferABDSToABSWithNSW(EVT VT) const
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
If Opc/OrigVT is specified as being promoted, the promotion code defaults to trying a larger integer/...
virtual bool getAddrModeArguments(const IntrinsicInst *, SmallVectorImpl< Value * > &, Type *&) const
CodeGenPrepare sinks address calculations into the same BB as Load/Store instructions reading the add...
virtual bool hasInlineStackProbe(const MachineFunction &MF) const
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setCondCodeAction(ArrayRef< ISD::CondCode > CCs, MVT VT, LegalizeAction Action)
Indicate that the specified condition code is or isn't supported on the target and indicate what to d...
void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
const DenseMap< unsigned int, unsigned int > & getBypassSlowDivWidths() const
Returns map of slow types for division or remainder with corresponding fast types.
void setOperationPromotedToType(ArrayRef< unsigned > Ops, MVT OrigVT, MVT DestVT)
unsigned getMaxLargeFPConvertBitWidthSupported() const
Returns the size in bits of the maximum fp to/from int conversion the backend supports.
virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, LLT) const
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const
bool isTruncStoreLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace) const
Return true if the specified store with truncation is legal on this target.
virtual bool isCheapToSpeculateCtlz(Type *Ty) const
Return true if it is cheap to speculate a call to intrinsic ctlz.
virtual void getTgtMemIntrinsic(SmallVectorImpl< IntrinsicInfo > &Infos, const CallBase &I, MachineFunction &MF, unsigned Intrinsic) const
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
virtual bool signExtendConstant(const ConstantInt *C) const
Return true if this constant should be sign extended when promoting to a larger type.
virtual bool lowerInterleaveIntrinsicToStore(Instruction *Store, Value *Mask, ArrayRef< Value * > InterleaveValues) const
Lower an interleave intrinsic to a target specific store intrinsic.
virtual bool isTruncateFree(LLT FromTy, LLT ToTy, LLVMContext &Ctx) const
AndOrSETCCFoldKind
Enum of different potentially desirable ways to fold (and/or (setcc ...), (setcc ....
virtual bool shouldScalarizeBinop(SDValue VecOp) const
Try to convert an extract element of a vector binary operation into an extract element followed by a ...
Align getPrefFunctionAlignment() const
Return the preferred function alignment.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Get the libcall impl routine name for the specified libcall.
virtual void emitExpandAtomicLoad(LoadInst *LI) const
Perform a atomic load using a target-specific way.
Align getMinFunctionAlignment() const
Return the minimum function alignment.
virtual AtomicExpansionKind shouldExpandAtomicStoreInIR(StoreInst *SI) const
Returns how the given (atomic) store should be expanded by the IR-level AtomicExpand pass into.
virtual bool preferVectorizedNonPowerOfTwoTypeBreakdown() const
Return true if fixed-length, non-power-of-two vectors should be broken down into legal vector parts i...
static StringRef getLibcallImplName(RTLIB::LibcallImpl Call)
Get the libcall routine name for the specified libcall implementation.
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
virtual bool isCtlzFast() const
Return true if ctlz instruction is fast.
virtual bool useSoftFloat() const
virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT, const SelectionDAG &DAG, const MachineMemOperand &MMO) const
Return true if the following transform is beneficial: (store (y (conv x)), y*)) -> (store x,...
BooleanContent getBooleanContents(EVT Type) const
virtual LegalizeAction getCustomLoadAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Returns an alternative action to use when the coarser lookups (configured through setLoadExtAction an...
bool isIndexedMaskedStoreLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
virtual int64_t getPreferredLargeGEPBaseOffset(int64_t MinOffset, int64_t MaxOffset) const
Return the prefered common base offset.
virtual bool isVectorClearMaskLegal(ArrayRef< int >, EVT) const
Similar to isShuffleMaskLegal.
LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const
Return pair that represents the legalization kind (first) that needs to happen to EVT (second) in ord...
Align getMinStackArgumentAlignment() const
Return the minimum stack alignment of an argument.
virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT, bool IsSigned) const
Return true if it is more correct/profitable to use strict FP_TO_INT conversion operations - canonica...
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
bool hasTargetDAGCombine(ISD::NodeType NT) const
If true, the target has custom DAG combine transformations that it can perform for the specified node...
void setLibcallImpl(RTLIB::Libcall Call, RTLIB::LibcallImpl Impl)
virtual bool fallBackToDAGISel(const Instruction &Inst) const
unsigned GatherAllAliasesMaxDepth
Depth that GatherAllAliases should continue looking for chain dependencies when trying to find a more...
virtual bool shouldSplatInsEltVarIndex(EVT) const
Return true if inserting a scalar into a variable element of an undef vector is more efficiently hand...
LegalizeAction getIndexedMaskedLoadAction(unsigned IdxMode, MVT VT) const
Return how the indexed load should be treated: either it is legal, needs to be promoted to a larger s...
NegatibleCost
Enum that specifies when a float negation is beneficial.
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
virtual unsigned preferedOpcodeForCmpEqPiecesOfOperand(EVT VT, unsigned ShiftOpc, bool MayTransformRotate, const APInt &ShiftOrRotateAmt, const std::optional< APInt > &AndMask) const
virtual void emitCmpArithAtomicRMWIntrinsic(AtomicRMWInst *AI) const
Perform a atomicrmw which the result is only used by comparison, using a target-specific intrinsic.
virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
virtual bool isFMADLegal(const MachineInstr &MI, LLT Ty) const
Returns true if MI can be combined with another instruction to form TargetOpcode::G_FMAD.
void setCondCodeAction(ArrayRef< ISD::CondCode > CCs, ArrayRef< MVT > VTs, LegalizeAction Action)
const char * getLibcallName(RTLIB::Libcall Call) const
Get the libcall routine name for the specified libcall.
virtual bool isLegalAddScalableImmediate(int64_t) const
Return true if adding the specified scalable immediate is legal, that is the target has add instructi...
std::vector< ArgListEntry > ArgListTy
virtual bool shouldAlignPointerArgs(CallInst *, unsigned &, Align &) const
Return true if the pointer arguments to CI should be aligned by aligning the object whose address is ...
virtual bool hasVectorBlend() const
Return true if the target has a vector blend instruction.
virtual AtomicExpansionKind shouldCastAtomicStoreInIR(StoreInst *SI) const
Returns how the given (atomic) store should be cast by the IR-level AtomicExpand pass into.
bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace) const
Return true if the specified store with truncation has solution on this target.
void setIndexedStoreAction(ArrayRef< unsigned > IdxModes, ArrayRef< MVT > VTs, LegalizeAction Action)
virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const
virtual Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception address on entry to an ...
virtual MachineMemOperand::Flags getTargetMMOFlags(const MemSDNode &Node) const
This callback is used to inspect load/store SDNode.
virtual EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &) const
Returns the target specific optimal type for load and store operations as a result of memset,...
virtual Type * shouldConvertSplatType(ShuffleVectorInst *SVI) const
Given a shuffle vector SVI representing a vector splat, return a new scalar type of size equal to SVI...
virtual bool isZExtFree(SDValue Val, EVT VT2) const
Return true if zero-extending the specific node Val to type VT2 is free (either because it's implicit...
void setAtomicLoadExtAction(ArrayRef< unsigned > ExtTypes, MVT ValVT, MVT MemVT, LegalizeAction Action)
virtual bool shouldRemoveExtendFromGSIndex(SDValue Extend, EVT DataVT) const
virtual LLVM_READONLY LLT getPreferredShiftAmountTy(LLT ShiftValueTy) const
Return the preferred type to use for a shift opcode, given the shifted amount type is ShiftValueTy.
bool isBeneficialToExpandPowI(int64_t Exponent, bool OptForSize) const
Return true if it is beneficial to expand an @llvm.powi.
LLT getVectorIdxLLT(const DataLayout &DL) const
Returns the type to be used for the index operand of: G_INSERT_VECTOR_ELT, G_EXTRACT_VECTOR_ELT,...
virtual EVT getAsmOperandValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
void setIndexedLoadAction(ArrayRef< unsigned > IdxModes, ArrayRef< MVT > VTs, LegalizeAction Action)
virtual AtomicExpansionKind shouldCastAtomicLoadInIR(LoadInst *LI) const
Returns how the given (atomic) load should be cast by the IR-level AtomicExpand pass.
bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal or custom for a comparison of the specified type...
virtual bool isComplexDeinterleavingSupported() const
Does this target support complex deinterleaving.
unsigned MaxStoresPerMemcpy
Specify maximum number of store instructions per memcpy call.
MVT getFrameIndexTy(const DataLayout &DL) const
Return the type for frame index, which is determined by the alloca address space specified through th...
virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS=0) const
Return the in-memory pointer type for the given address space, defaults to the pointer type from the ...
bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal on this target.
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
virtual bool addressingModeSupportsTLS(const GlobalValue &) const
Returns true if the targets addressing mode can target thread local storage (TLS).
bool isLoadLegalOrCustom(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal or custom on this target.
virtual bool shouldConvertPhiType(Type *From, Type *To) const
Given a set in interconnected phis of type 'From' that are loaded/stored or bitcast to type 'To',...
virtual bool isFAbsFree(EVT VT) const
Return true if an fabs operation is free to the point where it is never worthwhile to replace it with...
virtual bool isLegalStoreImmediate(int64_t Value) const
Return true if the specified immediate is legal for the value input of a store instruction.
virtual bool preferZeroCompareBranch() const
Return true if the heuristic to prefer icmp eq zero should be used in code gen prepare.
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
virtual bool lowerInterleavedLoad(Instruction *Load, Value *Mask, ArrayRef< ShuffleVectorInst * > Shuffles, ArrayRef< unsigned > Indices, unsigned Factor, const APInt &GapMask) const
Lower an interleaved load to target specific intrinsics.
virtual unsigned getVectorIdxWidth(const DataLayout &DL) const
Returns the type to be used for the index operand vector operations.
MVT getTypeToPromoteTo(unsigned Op, MVT VT) const
If the action for this operation is to promote, this method returns the ValueType to promote to.
virtual bool generateFMAsInMachineCombiner(EVT VT, CodeGenOptLevel OptLevel) const
virtual LoadInst * lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const
On some platforms, an AtomicRMW that never actually modifies the value (such as fetch_add of 0) can b...
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace, Instruction *I=nullptr) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
virtual bool hasPairedLoad(EVT, Align &) const
Return true if the target supplies and combines to a paired load two loaded values of type LoadedType...
virtual bool convertSelectOfConstantsToMath(EVT VT) const
Return true if a select of constants (select Cond, C1, C2) should be transformed into simple math ops...
bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool optimizeExtendOrTruncateConversion(Instruction *I, Loop *L, const TargetTransformInfo &TTI) const
Try to optimize extending or truncating conversion instructions (like zext, trunc,...
virtual MVT getVPExplicitVectorLengthTy() const
Returns the type to be used for the EVL/AVL operand of VP nodes: ISD::VP_UDIV, ISD::VP_SDIV,...
std::pair< LegalizeTypeAction, EVT > LegalizeKind
LegalizeKind holds the legalization kind that needs to happen to EVT in order to type-legalize it.
TargetLoweringBase & operator=(const TargetLoweringBase &)=delete
MulExpansionKind
Enum that specifies when a multiplication should be expanded.
static ISD::NodeType getExtendForContent(BooleanContent Content)
const RTLIB::RuntimeLibcallsInfo & getRuntimeLibcallsInfo() const
virtual bool shouldConvertFpToSat(unsigned Op, EVT FPVT, EVT VT) const
Should we generate fp_to_si_sat and fp_to_ui_sat from type FPVT to type VT.
virtual bool supportKCFIBundles() const
Return true if the target supports kcfi operand bundles.
virtual ConstraintWeight getMultipleConstraintMatchWeight(AsmOperandInfo &info, int maIndex) const
Examine constraint type and operand type and determine a weight value.
SmallVector< ConstraintPair > ConstraintGroup
virtual SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &RefinementSteps, bool &UseOneConstNR, bool Reciprocal) const
Hooks for building estimates in place of slower divisions and square roots.
virtual bool isDesirableToCommuteWithShift(const MachineInstr &MI, bool IsAfterLegal) const
GlobalISel - return true if it is profitable to move this shift by a constant amount through its oper...
virtual bool supportPtrAuthBundles() const
Return true if the target supports ptrauth operand bundles.
virtual void ReplaceNodeResults(SDNode *, SmallVectorImpl< SDValue > &, SelectionDAG &) const
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
virtual bool isUsedByReturnOnly(SDNode *, SDValue &) const
Return true if result of the specified node is used by a return node only.
virtual bool supportSwiftError() const
Return true if the target supports swifterror attribute.
virtual SDValue visitMaskedLoad(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, MachineMemOperand *MMO, SDValue &NewLoad, SDValue Ptr, SDValue PassThru, SDValue Mask) const
virtual unsigned getPreferredShrunkVectorSizeInBits(SDValue Op, const APInt &DemandedElts) const
If only low elements of a vector are demanded, shrink the operation to the returned size in bits by c...
SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, unsigned Depth=0) const
This is the helper function to return the newly negated expression if the cost is not expensive.
virtual bool isReassocProfitable(SelectionDAG &DAG, SDValue N0, SDValue N1) const
virtual bool isTypeDesirableForOp(SDNode *N, EVT VT) const
Overload that takes the specific node being optimized.
virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT, ISD::NodeType) const
Return the type that should be used to zero or sign extend a zeroext/signext integer return value.
SDValue getCheaperOrNeutralNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, const NegatibleCost CostThreshold=NegatibleCost::Neutral, unsigned Depth=0) const
virtual Register getRegisterByName(const char *RegName, LLT Ty, const MachineFunction &MF) const
Return the register ID of the name passed in.
virtual InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const
virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, TargetLoweringOpt &TLO) const
std::vector< AsmOperandInfo > AsmOperandInfoVector
virtual bool isTargetCanonicalConstantNode(SDValue Op) const
Returns true if the given Opc is considered a canonical constant for the target, which should not be ...
virtual bool isTargetCanonicalSelect(SDNode *N) const
Return true if the given select/vselect should be considered canonical and not be transformed.
SDValue getCheaperNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, unsigned Depth=0) const
This is the helper function to return the newly negated expression only when the cost is cheaper.
virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL, SelectionDAG &DAG) const
This callback is used to prepare for a volatile or atomic load.
virtual SDValue emitStackGuardMixFP(SelectionDAG &DAG, SDValue Val, const SDLoc &DL) const
virtual SDValue lowerEHPadEntry(SDValue Chain, const SDLoc &DL, SelectionDAG &DAG) const
Optional target hook to add target-specific actions when entering EH pad blocks.
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual SDValue unwrapAddress(SDValue N) const
virtual bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, std::optional< CallingConv::ID > CC) const
Target-specific splitting of values into parts that fit a register storing a legal type.
virtual bool IsDesirableToPromoteOp(SDValue, EVT &) const
This method query the target whether it is beneficial for dag combiner to promote the specified node.
virtual SDValue joinRegisterPartsIntoValue(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, std::optional< CallingConv::ID > CC) const
Target-specific combining of register parts into its original value.
virtual void insertCopiesSplitCSR(MachineBasicBlock *Entry, const SmallVectorImpl< MachineBasicBlock * > &Exits) const
Insert explicit copies in entry and exit blocks.
virtual SDValue LowerCall(CallLoweringInfo &, SmallVectorImpl< SDValue > &) const
This hook must be implemented to lower calls into the specified DAG.
virtual bool isTypeDesirableForOp(unsigned, EVT VT) const
Return true if the target has native support for the specified value type and it is 'desirable' to us...
~TargetLowering() override
TargetLowering & operator=(const TargetLowering &)=delete
virtual bool isDesirableToPullExtFromShl(const MachineInstr &MI) const
GlobalISel - return true if it's profitable to perform the combine: shl ([sza]ext x),...
bool isPositionIndependent() const
std::pair< StringRef, TargetLowering::ConstraintType > ConstraintPair
virtual SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, NegatibleCost &Cost, unsigned Depth=0) const
Return the newly negated expression if the cost is not expensive and set the cost in Cost to indicate...
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
virtual bool isIndexingLegal(MachineInstr &MI, Register Base, Register Offset, bool IsPre, MachineRegisterInfo &MRI) const
Returns true if the specified base+offset is a legal indexed addressing mode for this target.
ConstraintGroup getConstraintPreferences(AsmOperandInfo &OpInfo) const
Given an OpInfo with list of constraints codes as strings, return a sorted Vector of pairs of constra...
virtual void initializeSplitCSR(MachineBasicBlock *Entry) const
Perform necessary initialization to handle a subset of CSRs explicitly via copies.
virtual bool isSDNodeSourceOfDivergence(const SDNode *N, FunctionLoweringInfo *FLI, UniformityInfo *UA) const
virtual SDValue getRecipEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &RefinementSteps) const
Return a reciprocal estimate value for the input operand.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
virtual bool isSDNodeAlwaysUniform(const SDNode *N) const
virtual bool isDesirableToCommuteXorWithShift(const SDNode *N) const
Return true if it is profitable to combine an XOR of a logical shift to create a logical shift of NOT...
TargetLowering(const TargetLowering &)=delete
virtual bool shouldSimplifyDemandedVectorElts(SDValue Op, const TargetLoweringOpt &TLO) const
Return true if the target supports simplifying demanded vector elements by converting them to undefs.
virtual SDValue LowerFormalArguments(SDValue, CallingConv::ID, bool, const SmallVectorImpl< ISD::InputArg > &, const SDLoc &, SelectionDAG &, SmallVectorImpl< SDValue > &) const
This hook must be implemented to lower the incoming (formal) arguments, described by the Ins array,...
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, const CallBase &Call) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
virtual SDValue getSqrtResultForDenormInput(SDValue Operand, SelectionDAG &DAG) const
Return a target-dependent result if the input operand is not suitable for use with a square root esti...
virtual bool getPostIndexedAddressParts(SDNode *, SDNode *, SDValue &, SDValue &, ISD::MemIndexedMode &, SelectionDAG &) const
Returns true by value, base pointer and offset pointer and addressing mode by reference if this node ...
virtual bool shouldSplitFunctionArgumentsAsLittleEndian(const DataLayout &DL) const
For most targets, an LLVM type must be broken down into multiple smaller types.
virtual ArrayRef< MCPhysReg > getRoundingControlRegisters() const
Returns a 0 terminated array of rounding control registers that can be attached into strict FP call.
virtual SDValue LowerReturn(SDValue, CallingConv::ID, bool, const SmallVectorImpl< ISD::OutputArg > &, const SmallVectorImpl< SDValue > &, const SDLoc &, SelectionDAG &) const
This hook must be implemented to lower outgoing return values, described by the Outs array,...
virtual bool functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv, bool isVarArg, const DataLayout &DL) const
For some targets, an LLVM struct type must be broken down into multiple simple types,...
virtual bool isDesirableToCommuteWithShift(const SDNode *N, CombineLevel Level) const
Return true if it is profitable to move this shift by a constant amount through its operand,...
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo,...
virtual SDValue visitMaskedStore(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, MachineMemOperand *MMO, SDValue Ptr, SDValue Val, SDValue Mask) const
virtual const MCExpr * LowerCustomJumpTableEntry(const MachineJumpTableInfo *, const MachineBasicBlock *, unsigned, MCContext &) const
virtual bool useTopologicalSorting() const
virtual bool useLoadStackGuardNode(const Module &M) const
If this function returns true, SelectionDAGBuilder emits a LOAD_STACK_GUARD node when it is lowering ...
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
It is an error to pass RTLIB::UNKNOWN_LIBCALL as LC.
virtual FastISel * createFastISel(FunctionLoweringInfo &, const TargetLibraryInfo *, const LibcallLoweringInfo *) const
This method returns a target specific FastISel object, or null if the target does not support "fast" ...
virtual unsigned combineRepeatedFPDivisors() const
Indicate whether this target prefers to combine FDIVs with the same divisor.
virtual AndOrSETCCFoldKind isDesirableToCombineLogicOpOfSETCC(const SDNode *LogicOp, const SDNode *SETCC0, const SDNode *SETCC1) const
virtual void HandleByVal(CCState *, unsigned &, Align) const
Target-specific cleanup for formal ByVal parameters.
virtual const MCPhysReg * getScratchRegisters(CallingConv::ID CC) const
Returns a 0 terminated array of registers that can be safely used as scratch registers.
virtual bool getPreIndexedAddressParts(SDNode *, SDValue &, SDValue &, ISD::MemIndexedMode &, SelectionDAG &) const
Returns true by value, base pointer and offset pointer and addressing mode by reference if the node's...
SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, SDValue Index, const SDNodeFlags PtrArithFlags=SDNodeFlags()) const
Get a pointer to vector element Idx located in memory for a vector of type VecVT starting at a base a...
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
virtual bool supportSplitCSR(MachineFunction *MF) const
Return true if the target supports that a subset of CSRs for the given machine function is handled ex...
virtual bool isReassocProfitable(MachineRegisterInfo &MRI, Register N0, Register N1) const
virtual bool mayBeEmittedAsTailCall(const CallInst *) const
Return true if the target may be able emit the call instruction as a tail call.
virtual bool isInlineAsmTargetBranch(const SmallVectorImpl< StringRef > &AsmStrs, unsigned OpNo) const
On x86, return true if the operand with index OpNo is a CALL or JUMP instruction, which can use eithe...
SDValue getInboundsVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, SDValue Index) const
Get a pointer to vector element Idx located in memory for a vector of type VecVT starting at a base a...
virtual MVT getJumpTableRegTy(const DataLayout &DL) const
virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC, ArgListTy &Args) const
virtual bool CanLowerReturn(CallingConv::ID, MachineFunction &, bool, const SmallVectorImpl< ISD::OutputArg > &, LLVMContext &, const Type *RetTy) const
This hook should be implemented to check whether the return values described by the Outs array can fi...
virtual bool isXAndYEqZeroPreferableToXAndYEqY(ISD::CondCode, EVT) const
virtual bool isDesirableToTransformToIntegerOp(unsigned, EVT) const
Return true if it is profitable for dag combiner to transform a floating point op of specified opcode...
Primary interface to the complete machine description for the target machine.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
This is the common base class for vector predication intrinsics.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
CallInst * Call
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:397
@ ADDC
Carry-setting nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:296
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:527
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ SMULFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:403
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:871
@ PSEUDO_FMIN
PSEUDO_FMIN is strictly equivalent to op0 olt op1 ?
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:788
@ SDIVFIX
RESULT = [US]DIVFIX(LHS, RHS, SCALE) - Perform fixed point division on 2 integers with the same width...
Definition ISDOpcodes.h:410
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:862
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:725
@ PARTIAL_REDUCE_FMLA
@ BRIND
BRIND - Indirect branch.
@ BR_JT
BR_JT - Jumptable branch.
@ VECTOR_INTERLEAVE
VECTOR_INTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor to...
Definition ISDOpcodes.h:640
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:682
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:714
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:779
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Perform floating-point minimumNumber or maximumNumber on two values,...
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:868
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:737
@ SDIVFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:416
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:483
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:482
@ FMINIMUM
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:944
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:749
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:720
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:306
@ SPLAT_VECTOR_PARTS
SPLAT_VECTOR_PARTS(SCALAR1, SCALAR2, ...) - Returns a vector with the scalar values joined together a...
Definition ISDOpcodes.h:691
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ VECTOR_DEINTERLEAVE
VECTOR_DEINTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor ...
Definition ISDOpcodes.h:629
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:732
static const int LAST_LOADEXT_TYPE
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
This namespace contains all of the command line option processing machinery.
Definition MCSchedule.h:35
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:577
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
LLVM_ABI void GetReturnInfo(CallingConv::ID CC, Type *ReturnType, AttributeList attr, SmallVectorImpl< ISD::OutputArg > &Outs, const TargetLowering &TLI, const DataLayout &DL)
Given an LLVM IR type and return type attributes, compute the return value EVTs and flags,...
InstructionCost Cost
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:134
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
LLVM_ABI bool isConstTrueVal(const TargetLowering &TLI, int64_t Val, bool IsVector, bool IsFP)
Returns true if given the TargetLowering's boolean contents information, the value Val contains a tru...
Definition Utils.cpp:1605
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:227
@ Default
-O2, -Os, -Oz
Definition CodeGen.h:230
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
LLVM_ABI EVT getApproximateEVTForLLT(LLT Ty, LLVMContext &Ctx)
TargetTransformInfo TTI
CombineLevel
Definition DAGCombine.h:15
@ AfterLegalizeDAG
Definition DAGCombine.h:19
@ AfterLegalizeVectorOps
Definition DAGCombine.h:18
@ BeforeLegalizeTypes
Definition DAGCombine.h:16
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
@ Fast
Assign the register banks as fast as possible (default).
LLVM_ABI bool isInTailCallPosition(const CallBase &Call, const TargetMachine &TM, bool ReturnsFirstArg=false)
Test if the given instruction is in a position to be optimized with a tail-call.
Definition Analysis.cpp:656
DWARFExpression::Operation Op
LLVM_ABI bool isConstFalseVal(const TargetLowering &TLI, int64_t Val, bool IsVector, bool IsFP)
Definition Utils.cpp:1618
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:1933
ExceptionHandling
Definition CodeGen.h:54
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
static cl::opt< unsigned > CostThreshold("dfa-cost-threshold", cl::desc("Maximum cost accepted for the transformation"), cl::Hidden, cl::init(50))
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Represent subnormal handling kind for floating point instruction inputs and outputs.
Extended Value Type.
Definition ValueTypes.h:35
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition ValueTypes.h:266
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
bool isFixedLengthVector() const
Definition ValueTypes.h:199
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
bool isExtended() const
Test if the given EVT is extended (as opposed to being simple).
Definition ValueTypes.h:150
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
ConstraintInfo()=default
Default constructor.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
bool isDstAligned(Align AlignCheck) const
bool isFixedDstAlign() const
uint64_t size() const
static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign, bool IsZeroMemset, bool IsVolatile)
Align getDstAlign() const
bool isMemcpyStrSrc() const
bool isAligned(Align AlignCheck) const
static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile, bool MemcpyStrSrc=false)
bool isSrcAligned(Align AlignCheck) const
bool isMemcpyOrMemmoveWithFixedDstAlign() const
bool isMemcpyOrMemmove() const
bool isMemmove() const
bool isMemset() const
bool isMemcpy() const
static MemOp Move(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile)
bool isZeroMemset() const
bool isVolatile() const
Align getSrcAlign() const
A simple container for information about the supported runtime calls.
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.
These are IR-level optimization flags that may be propagated to SDNodes.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
std::optional< unsigned > fallbackAddressSpace
PointerUnion< const Value *, const PseudoSourceValue * > ptrVal
This contains information for each constraint that we are lowering.
AsmOperandInfo(InlineAsm::ConstraintInfo Info)
Copy constructor for copying from a ConstraintInfo.
MVT ConstraintVT
The ValueType for the operand value.
TargetLowering::ConstraintType ConstraintType
Information about the constraint code, e.g.
std::string ConstraintCode
This contains the actual string for the code, like "m".
Value * CallOperandVal
If this is the result output operand or a clobber, this is null, otherwise it is the incoming operand...
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setConvergent(bool Value=true)
CallLoweringInfo & setIsPostTypeLegalization(bool Value=true)
CallLoweringInfo & setDeactivationSymbol(GlobalValue *Sym)
CallLoweringInfo & setCallee(Type *ResultType, FunctionType *FTy, SDValue Target, ArgListTy &&ArgsList, const CallBase &Call)
CallLoweringInfo & setCFIType(const ConstantInt *Type)
CallLoweringInfo & setInRegister(bool Value=true)
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
SmallVector< ISD::InputArg, 32 > Ins
CallLoweringInfo & setVarArg(bool Value=true)
Type * OrigRetTy
Original unlegalized return type.
std::optional< PtrAuthInfo > PAI
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setZExtResult(bool Value=true)
CallLoweringInfo & setIsPatchPoint(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, Type *OrigResultType, SDValue Target, ArgListTy &&ArgsList)
CallLoweringInfo & setTailCall(bool Value=true)
CallLoweringInfo & setIsPreallocated(bool Value=true)
CallLoweringInfo & setSExtResult(bool Value=true)
CallLoweringInfo & setNoReturn(bool Value=true)
CallLoweringInfo & setConvergenceControlToken(SDValue Token)
SmallVector< ISD::OutputArg, 32 > Outs
Type * RetTy
Same as OrigRetTy, or partially legalized for soft float libcalls.
CallLoweringInfo & setChain(SDValue InChain)
CallLoweringInfo & setPtrAuth(PtrAuthInfo Value)
CallLoweringInfo & setCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList, AttributeSet ResultAttrs={})
DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
This structure is used to pass arguments to makeLibCall function.
MakeLibCallOptions & setIsPostTypeLegalization(bool Value=true)
MakeLibCallOptions & setDiscardResult(bool Value=true)
MakeLibCallOptions & setTypeListBeforeSoften(ArrayRef< EVT > OpsVT, EVT RetVT)
MakeLibCallOptions & setIsSigned(bool Value=true)
MakeLibCallOptions & setNoReturn(bool Value=true)
MakeLibCallOptions & setOpsTypeOverrides(ArrayRef< Type * > OpsTypes)
Override the argument type for an operand.
This structure contains the information necessary for lowering pointer-authenticating indirect calls.
A convenience struct that encapsulates a DAG, and two SDValues for returning information from TargetL...
TargetLoweringOpt(SelectionDAG &InDAG, bool LT, bool LO)