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