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