LLVM 19.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"
48#include "llvm/IR/Type.h"
53#include <algorithm>
54#include <cassert>
55#include <climits>
56#include <cstdint>
57#include <iterator>
58#include <map>
59#include <string>
60#include <utility>
61#include <vector>
62
63namespace llvm {
64
65class AssumptionCache;
66class CCState;
67class CCValAssign;
70class Constant;
71class FastISel;
72class FunctionLoweringInfo;
73class GlobalValue;
74class Loop;
75class GISelKnownBits;
76class IntrinsicInst;
77class IRBuilderBase;
78struct KnownBits;
79class LLVMContext;
80class MachineBasicBlock;
81class MachineFunction;
82class MachineInstr;
83class MachineJumpTableInfo;
84class MachineLoop;
85class MachineRegisterInfo;
86class MCContext;
87class MCExpr;
88class Module;
89class ProfileSummaryInfo;
90class TargetLibraryInfo;
91class TargetMachine;
92class TargetRegisterClass;
93class TargetRegisterInfo;
94class TargetTransformInfo;
95class Value;
96
97namespace Sched {
98
100 None, // No preference
101 Source, // Follow source order.
102 RegPressure, // Scheduling for lowest register pressure.
103 Hybrid, // Scheduling for both latency and register pressure.
104 ILP, // Scheduling for ILP in low register pressure mode.
105 VLIW, // Scheduling for VLIW targets.
106 Fast, // Fast suboptimal list scheduling
107 Linearize // Linearize DAG, no scheduling
109
110} // end namespace Sched
111
112// MemOp models a memory operation, either memset or memcpy/memmove.
113struct MemOp {
114private:
115 // Shared
116 uint64_t Size;
117 bool DstAlignCanChange; // true if destination alignment can satisfy any
118 // constraint.
119 Align DstAlign; // Specified alignment of the memory operation.
120
121 bool AllowOverlap;
122 // memset only
123 bool IsMemset; // If setthis memory operation is a memset.
124 bool ZeroMemset; // If set clears out memory with zeros.
125 // memcpy only
126 bool MemcpyStrSrc; // Indicates whether the memcpy source is an in-register
127 // constant so it does not need to be loaded.
128 Align SrcAlign; // Inferred alignment of the source or default value if the
129 // memory operation does not need to load the value.
130public:
131 static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
132 Align SrcAlign, bool IsVolatile,
133 bool MemcpyStrSrc = false) {
134 MemOp Op;
135 Op.Size = Size;
136 Op.DstAlignCanChange = DstAlignCanChange;
137 Op.DstAlign = DstAlign;
138 Op.AllowOverlap = !IsVolatile;
139 Op.IsMemset = false;
140 Op.ZeroMemset = false;
141 Op.MemcpyStrSrc = MemcpyStrSrc;
142 Op.SrcAlign = SrcAlign;
143 return Op;
144 }
145
146 static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
147 bool IsZeroMemset, bool IsVolatile) {
148 MemOp Op;
149 Op.Size = Size;
150 Op.DstAlignCanChange = DstAlignCanChange;
151 Op.DstAlign = DstAlign;
152 Op.AllowOverlap = !IsVolatile;
153 Op.IsMemset = true;
154 Op.ZeroMemset = IsZeroMemset;
155 Op.MemcpyStrSrc = false;
156 return Op;
157 }
158
159 uint64_t size() const { return Size; }
161 assert(!DstAlignCanChange);
162 return DstAlign;
163 }
164 bool isFixedDstAlign() const { return !DstAlignCanChange; }
165 bool allowOverlap() const { return AllowOverlap; }
166 bool isMemset() const { return IsMemset; }
167 bool isMemcpy() const { return !IsMemset; }
169 return isMemcpy() && !DstAlignCanChange;
170 }
171 bool isZeroMemset() const { return isMemset() && ZeroMemset; }
172 bool isMemcpyStrSrc() const {
173 assert(isMemcpy() && "Must be a memcpy");
174 return MemcpyStrSrc;
175 }
177 assert(isMemcpy() && "Must be a memcpy");
178 return SrcAlign;
179 }
180 bool isSrcAligned(Align AlignCheck) const {
181 return isMemset() || llvm::isAligned(AlignCheck, SrcAlign.value());
182 }
183 bool isDstAligned(Align AlignCheck) const {
184 return DstAlignCanChange || llvm::isAligned(AlignCheck, DstAlign.value());
185 }
186 bool isAligned(Align AlignCheck) const {
187 return isSrcAligned(AlignCheck) && isDstAligned(AlignCheck);
188 }
189};
190
191/// This base class for TargetLowering contains the SelectionDAG-independent
192/// parts that can be used from the rest of CodeGen.
194public:
195 /// This enum indicates whether operations are valid for a target, and if not,
196 /// what action should be used to make them valid.
197 enum LegalizeAction : uint8_t {
198 Legal, // The target natively supports this operation.
199 Promote, // This operation should be executed in a larger type.
200 Expand, // Try to expand this to other ops, otherwise use a libcall.
201 LibCall, // Don't try to expand this to other ops, always use a libcall.
202 Custom // Use the LowerOperation hook to implement custom lowering.
203 };
204
205 /// This enum indicates whether a types are legal for a target, and if not,
206 /// what action should be used to make them valid.
207 enum LegalizeTypeAction : uint8_t {
208 TypeLegal, // The target natively supports this type.
209 TypePromoteInteger, // Replace this integer with a larger one.
210 TypeExpandInteger, // Split this integer into two of half the size.
211 TypeSoftenFloat, // Convert this float to a same size integer type.
212 TypeExpandFloat, // Split this float into two of half the size.
213 TypeScalarizeVector, // Replace this one-element vector with its element.
214 TypeSplitVector, // Split this vector into two of half the size.
215 TypeWidenVector, // This vector should be widened into a larger vector.
216 TypePromoteFloat, // Replace this float with a larger one.
217 TypeSoftPromoteHalf, // Soften half to i16 and use float to do arithmetic.
218 TypeScalarizeScalableVector, // This action is explicitly left unimplemented.
219 // While it is theoretically possible to
220 // legalize operations on scalable types with a
221 // loop that handles the vscale * #lanes of the
222 // vector, this is non-trivial at SelectionDAG
223 // level and these types are better to be
224 // widened or promoted.
225 };
226
227 /// LegalizeKind holds the legalization kind that needs to happen to EVT
228 /// in order to type-legalize it.
229 using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
230
231 /// Enum that describes how the target represents true/false values.
233 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
234 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
235 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
236 };
237
238 /// Enum that describes what type of support for selects the target has.
240 ScalarValSelect, // The target supports scalar selects (ex: cmov).
241 ScalarCondVectorVal, // The target supports selects with a scalar condition
242 // and vector values (ex: cmov).
243 VectorMaskSelect // The target supports vector selects with a vector
244 // mask (ex: x86 blends).
245 };
246
247 /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
248 /// to, if at all. Exists because different targets have different levels of
249 /// support for these atomic instructions, and also have different options
250 /// w.r.t. what they should expand to.
252 None, // Don't expand the instruction.
253 CastToInteger, // Cast the atomic instruction to another type, e.g. from
254 // floating-point to integer type.
255 LLSC, // Expand the instruction into loadlinked/storeconditional; used
256 // by ARM/AArch64.
257 LLOnly, // Expand the (load) instruction into just a load-linked, which has
258 // greater atomic guarantees than a normal load.
259 CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
260 MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
261 BitTestIntrinsic, // Use a target-specific intrinsic for special bit
262 // operations; used by X86.
263 CmpArithIntrinsic,// Use a target-specific intrinsic for special compare
264 // operations; used by X86.
265 Expand, // Generic expansion in terms of other atomic operations.
266
267 // Rewrite to a non-atomic form for use in a known non-preemptible
268 // environment.
270 };
271
272 /// Enum that specifies when a multiplication should be expanded.
273 enum class MulExpansionKind {
274 Always, // Always expand the instruction.
275 OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
276 // or custom.
277 };
278
279 /// Enum that specifies when a float negation is beneficial.
280 enum class NegatibleCost {
281 Cheaper = 0, // Negated expression is cheaper.
282 Neutral = 1, // Negated expression has the same cost.
283 Expensive = 2 // Negated expression is more expensive.
284 };
285
286 /// Enum of different potentially desirable ways to fold (and/or (setcc ...),
287 /// (setcc ...)).
288 enum AndOrSETCCFoldKind : uint8_t {
289 None = 0, // No fold is preferable.
290 AddAnd = 1, // Fold with `Add` op and `And` op is preferable.
291 NotAnd = 2, // Fold with `Not` op and `And` op is preferable.
292 ABS = 4, // Fold with `llvm.abs` op is preferable.
293 };
294
296 public:
297 Value *Val = nullptr;
299 Type *Ty = nullptr;
300 bool IsSExt : 1;
301 bool IsZExt : 1;
302 bool IsInReg : 1;
303 bool IsSRet : 1;
304 bool IsNest : 1;
305 bool IsByVal : 1;
306 bool IsByRef : 1;
307 bool IsInAlloca : 1;
309 bool IsReturned : 1;
310 bool IsSwiftSelf : 1;
311 bool IsSwiftAsync : 1;
312 bool IsSwiftError : 1;
314 MaybeAlign Alignment = std::nullopt;
315 Type *IndirectType = nullptr;
316
322
323 void setAttributes(const CallBase *Call, unsigned ArgIdx);
324 };
325 using ArgListTy = std::vector<ArgListEntry>;
326
327 virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
328 ArgListTy &Args) const {};
329
331 switch (Content) {
333 // Extend by adding rubbish bits.
334 return ISD::ANY_EXTEND;
336 // Extend by adding zero bits.
337 return ISD::ZERO_EXTEND;
339 // Extend by copying the sign bit.
340 return ISD::SIGN_EXTEND;
341 }
342 llvm_unreachable("Invalid content kind");
343 }
344
345 explicit TargetLoweringBase(const TargetMachine &TM);
348 virtual ~TargetLoweringBase() = default;
349
350 /// Return true if the target support strict float operation
351 bool isStrictFPEnabled() const {
352 return IsStrictFPEnabled;
353 }
354
355protected:
356 /// Initialize all of the actions to default values.
357 void initActions();
358
359public:
360 const TargetMachine &getTargetMachine() const { return TM; }
361
362 virtual bool useSoftFloat() const { return false; }
363
364 /// Return the pointer type for the given address space, defaults to
365 /// the pointer type from the data layout.
366 /// FIXME: The default needs to be removed once all the code is updated.
367 virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
368 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
369 }
370
371 /// Return the in-memory pointer type for the given address space, defaults to
372 /// the pointer type from the data layout.
373 /// FIXME: The default needs to be removed once all the code is updated.
374 virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS = 0) const {
375 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
376 }
377
378 /// Return the type for frame index, which is determined by
379 /// the alloca address space specified through the data layout.
381 return getPointerTy(DL, DL.getAllocaAddrSpace());
382 }
383
384 /// Return the type for code pointers, which is determined by the program
385 /// address space specified through the data layout.
387 return getPointerTy(DL, DL.getProgramAddressSpace());
388 }
389
390 /// Return the type for operands of fence.
391 /// TODO: Let fence operands be of i32 type and remove this.
392 virtual MVT getFenceOperandTy(const DataLayout &DL) const {
393 return getPointerTy(DL);
394 }
395
396 /// Return the type to use for a scalar shift opcode, given the shifted amount
397 /// type. Targets should return a legal type if the input type is legal.
398 /// Targets can return a type that is too small if the input type is illegal.
399 virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
400
401 /// Returns the type for the shift amount of a shift opcode. For vectors,
402 /// returns the input type. For scalars, behavior depends on \p LegalTypes. If
403 /// \p LegalTypes is true, calls getScalarShiftAmountTy, otherwise uses
404 /// pointer type. If getScalarShiftAmountTy or pointer type cannot represent
405 /// all possible shift amounts, returns MVT::i32. In general, \p LegalTypes
406 /// should be set to true for calls during type legalization and after type
407 /// legalization has been completed.
408 EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
409 bool LegalTypes = true) const;
410
411 /// Return the preferred type to use for a shift opcode, given the shifted
412 /// amount type is \p ShiftValueTy.
414 virtual LLT getPreferredShiftAmountTy(LLT ShiftValueTy) const {
415 return ShiftValueTy;
416 }
417
418 /// Returns the type to be used for the index operand of:
419 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
420 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
421 virtual MVT getVectorIdxTy(const DataLayout &DL) const {
422 return getPointerTy(DL);
423 }
424
425 /// Returns the type to be used for the EVL/AVL operand of VP nodes:
426 /// ISD::VP_ADD, ISD::VP_SUB, etc. It must be a legal scalar integer type,
427 /// and must be at least as large as i32. The EVL is implicitly zero-extended
428 /// to any larger type.
429 virtual MVT getVPExplicitVectorLengthTy() const { return MVT::i32; }
430
431 /// This callback is used to inspect load/store instructions and add
432 /// target-specific MachineMemOperand flags to them. The default
433 /// implementation does nothing.
436 }
437
438 /// This callback is used to inspect load/store SDNode.
439 /// The default implementation does nothing.
443 }
444
447 AssumptionCache *AC = nullptr,
448 const TargetLibraryInfo *LibInfo = nullptr) const;
450 const DataLayout &DL) const;
452 const DataLayout &DL) const;
453
454 virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
455 return true;
456 }
457
458 /// Return true if the @llvm.get.active.lane.mask intrinsic should be expanded
459 /// using generic code in SelectionDAGBuilder.
460 virtual bool shouldExpandGetActiveLaneMask(EVT VT, EVT OpVT) const {
461 return true;
462 }
463
464 virtual bool shouldExpandGetVectorLength(EVT CountVT, unsigned VF,
465 bool IsScalable) const {
466 return true;
467 }
468
469 /// Return true if the @llvm.experimental.cttz.elts intrinsic should be
470 /// expanded using generic code in SelectionDAGBuilder.
471 virtual bool shouldExpandCttzElements(EVT VT) const { return true; }
472
473 // Return true if op(vecreduce(x), vecreduce(y)) should be reassociated to
474 // vecreduce(op(x, y)) for the reduction opcode RedOpc.
475 virtual bool shouldReassociateReduction(unsigned RedOpc, EVT VT) const {
476 return true;
477 }
478
479 /// Return true if it is profitable to convert a select of FP constants into
480 /// a constant pool load whose address depends on the select condition. The
481 /// parameter may be used to differentiate a select with FP compare from
482 /// integer compare.
483 virtual bool reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
484 return true;
485 }
486
487 /// Return true if multiple condition registers are available.
489 return HasMultipleConditionRegisters;
490 }
491
492 /// Return true if the target has BitExtract instructions.
493 bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
494
495 /// Return the preferred vector type legalization action.
498 // The default action for one element vectors is to scalarize
500 return TypeScalarizeVector;
501 // The default action for an odd-width vector is to widen.
502 if (!VT.isPow2VectorType())
503 return TypeWidenVector;
504 // The default action for other vectors is to promote
505 return TypePromoteInteger;
506 }
507
508 // Return true if the half type should be promoted using soft promotion rules
509 // where each operation is promoted to f32 individually, then converted to
510 // fp16. The default behavior is to promote chains of operations, keeping
511 // intermediate results in f32 precision and range.
512 virtual bool softPromoteHalfType() const { return false; }
513
514 // Return true if, for soft-promoted half, the half type should be passed
515 // passed to and returned from functions as f32. The default behavior is to
516 // pass as i16. If soft-promoted half is not used, this function is ignored
517 // and values are always passed and returned as f32.
518 virtual bool useFPRegsForHalfType() const { return false; }
519
520 // There are two general methods for expanding a BUILD_VECTOR node:
521 // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
522 // them together.
523 // 2. Build the vector on the stack and then load it.
524 // If this function returns true, then method (1) will be used, subject to
525 // the constraint that all of the necessary shuffles are legal (as determined
526 // by isShuffleMaskLegal). If this function returns false, then method (2) is
527 // always used. The vector type, and the number of defined values, are
528 // provided.
529 virtual bool
531 unsigned DefinedValues) const {
532 return DefinedValues < 3;
533 }
534
535 /// Return true if integer divide is usually cheaper than a sequence of
536 /// several shifts, adds, and multiplies for this target.
537 /// The definition of "cheaper" may depend on whether we're optimizing
538 /// for speed or for size.
539 virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
540
541 /// Return true if the target can handle a standalone remainder operation.
542 virtual bool hasStandaloneRem(EVT VT) const {
543 return true;
544 }
545
546 /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
547 virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
548 // Default behavior is to replace SQRT(X) with X*RSQRT(X).
549 return false;
550 }
551
552 /// Reciprocal estimate status values used by the functions below.
556 Enabled = 1
557 };
558
559 /// Return a ReciprocalEstimate enum value for a square root of the given type
560 /// based on the function's attributes. If the operation is not overridden by
561 /// the function's attributes, "Unspecified" is returned and target defaults
562 /// are expected to be used for instruction selection.
564
565 /// Return a ReciprocalEstimate enum value for a division of the given type
566 /// based on the function's attributes. If the operation is not overridden by
567 /// the function's attributes, "Unspecified" is returned and target defaults
568 /// are expected to be used for instruction selection.
570
571 /// Return the refinement step count for a square root of the given type based
572 /// on the function's attributes. If the operation is not overridden by
573 /// the function's attributes, "Unspecified" is returned and target defaults
574 /// are expected to be used for instruction selection.
575 int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
576
577 /// Return the refinement step count for a division of the given type based
578 /// on the function's attributes. If the operation is not overridden by
579 /// the function's attributes, "Unspecified" is returned and target defaults
580 /// are expected to be used for instruction selection.
581 int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
582
583 /// Returns true if target has indicated at least one type should be bypassed.
584 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
585
586 /// Returns map of slow types for division or remainder with corresponding
587 /// fast types
589 return BypassSlowDivWidths;
590 }
591
592 /// Return true only if vscale must be a power of two.
593 virtual bool isVScaleKnownToBeAPowerOfTwo() const { return false; }
594
595 /// Return true if Flow Control is an expensive operation that should be
596 /// avoided.
597 bool isJumpExpensive() const { return JumpIsExpensive; }
598
599 /// Return true if selects are only cheaper than branches if the branch is
600 /// unlikely to be predicted right.
603 }
604
605 virtual bool fallBackToDAGISel(const Instruction &Inst) const {
606 return false;
607 }
608
609 /// Return true if the following transform is beneficial:
610 /// fold (conv (load x)) -> (load (conv*)x)
611 /// On architectures that don't natively support some vector loads
612 /// efficiently, casting the load to a smaller vector of larger types and
613 /// loading is more efficient, however, this can be undone by optimizations in
614 /// dag combiner.
615 virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
616 const SelectionDAG &DAG,
617 const MachineMemOperand &MMO) const;
618
619 /// Return true if the following transform is beneficial:
620 /// (store (y (conv x)), y*)) -> (store x, (x*))
621 virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT,
622 const SelectionDAG &DAG,
623 const MachineMemOperand &MMO) const {
624 // Default to the same logic as loads.
625 return isLoadBitCastBeneficial(StoreVT, BitcastVT, DAG, MMO);
626 }
627
628 /// Return true if it is expected to be cheaper to do a store of vector
629 /// constant with the given size and type for the address space than to
630 /// store the individual scalar element constants.
631 virtual bool storeOfVectorConstantIsCheap(bool IsZero, EVT MemVT,
632 unsigned NumElem,
633 unsigned AddrSpace) const {
634 return IsZero;
635 }
636
637 /// Allow store merging for the specified type after legalization in addition
638 /// to before legalization. This may transform stores that do not exist
639 /// earlier (for example, stores created from intrinsics).
640 virtual bool mergeStoresAfterLegalization(EVT MemVT) const {
641 return true;
642 }
643
644 /// Returns if it's reasonable to merge stores to MemVT size.
645 virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
646 const MachineFunction &MF) const {
647 return true;
648 }
649
650 /// Return true if it is cheap to speculate a call to intrinsic cttz.
651 virtual bool isCheapToSpeculateCttz(Type *Ty) const {
652 return false;
653 }
654
655 /// Return true if it is cheap to speculate a call to intrinsic ctlz.
656 virtual bool isCheapToSpeculateCtlz(Type *Ty) const {
657 return false;
658 }
659
660 /// Return true if ctlz instruction is fast.
661 virtual bool isCtlzFast() const {
662 return false;
663 }
664
665 /// Return true if ctpop instruction is fast.
666 virtual bool isCtpopFast(EVT VT) const {
667 return isOperationLegal(ISD::CTPOP, VT);
668 }
669
670 /// Return the maximum number of "x & (x - 1)" operations that can be done
671 /// instead of deferring to a custom CTPOP.
672 virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const {
673 return 1;
674 }
675
676 /// Return true if instruction generated for equality comparison is folded
677 /// with instruction generated for signed comparison.
678 virtual bool isEqualityCmpFoldedWithSignedCmp() const { return true; }
679
680 /// Return true if the heuristic to prefer icmp eq zero should be used in code
681 /// gen prepare.
682 virtual bool preferZeroCompareBranch() const { return false; }
683
684 /// Return true if it is cheaper to split the store of a merged int val
685 /// from a pair of smaller values into multiple stores.
686 virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
687 return false;
688 }
689
690 /// Return if the target supports combining a
691 /// chain like:
692 /// \code
693 /// %andResult = and %val1, #mask
694 /// %icmpResult = icmp %andResult, 0
695 /// \endcode
696 /// into a single machine instruction of a form like:
697 /// \code
698 /// cc = test %register, #mask
699 /// \endcode
700 virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
701 return false;
702 }
703
704 /// Return true if it is valid to merge the TargetMMOFlags in two SDNodes.
705 virtual bool
707 const MemSDNode &NodeY) const {
708 return true;
709 }
710
711 /// Use bitwise logic to make pairs of compares more efficient. For example:
712 /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
713 /// This should be true when it takes more than one instruction to lower
714 /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
715 /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
716 virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
717 return false;
718 }
719
720 /// Return the preferred operand type if the target has a quick way to compare
721 /// integer values of the given size. Assume that any legal integer type can
722 /// be compared efficiently. Targets may override this to allow illegal wide
723 /// types to return a vector type if there is support to compare that type.
724 virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
725 MVT VT = MVT::getIntegerVT(NumBits);
727 }
728
729 /// Return true if the target should transform:
730 /// (X & Y) == Y ---> (~X & Y) == 0
731 /// (X & Y) != Y ---> (~X & Y) != 0
732 ///
733 /// This may be profitable if the target has a bitwise and-not operation that
734 /// sets comparison flags. A target may want to limit the transformation based
735 /// on the type of Y or if Y is a constant.
736 ///
737 /// Note that the transform will not occur if Y is known to be a power-of-2
738 /// because a mask and compare of a single bit can be handled by inverting the
739 /// predicate, for example:
740 /// (X & 8) == 8 ---> (X & 8) != 0
741 virtual bool hasAndNotCompare(SDValue Y) const {
742 return false;
743 }
744
745 /// Return true if the target has a bitwise and-not operation:
746 /// X = ~A & B
747 /// This can be used to simplify select or other instructions.
748 virtual bool hasAndNot(SDValue X) const {
749 // If the target has the more complex version of this operation, assume that
750 // it has this operation too.
751 return hasAndNotCompare(X);
752 }
753
754 /// Return true if the target has a bit-test instruction:
755 /// (X & (1 << Y)) ==/!= 0
756 /// This knowledge can be used to prevent breaking the pattern,
757 /// or creating it if it could be recognized.
758 virtual bool hasBitTest(SDValue X, SDValue Y) const { return false; }
759
760 /// There are two ways to clear extreme bits (either low or high):
761 /// Mask: x & (-1 << y) (the instcombine canonical form)
762 /// Shifts: x >> y << y
763 /// Return true if the variant with 2 variable shifts is preferred.
764 /// Return false if there is no preference.
766 // By default, let's assume that no one prefers shifts.
767 return false;
768 }
769
770 /// Return true if it is profitable to fold a pair of shifts into a mask.
771 /// This is usually true on most targets. But some targets, like Thumb1,
772 /// have immediate shift instructions, but no immediate "and" instruction;
773 /// this makes the fold unprofitable.
775 CombineLevel Level) const {
776 return true;
777 }
778
779 /// Should we tranform the IR-optimal check for whether given truncation
780 /// down into KeptBits would be truncating or not:
781 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
782 /// Into it's more traditional form:
783 /// ((%x << C) a>> C) dstcond %x
784 /// Return true if we should transform.
785 /// Return false if there is no preference.
787 unsigned KeptBits) const {
788 // By default, let's assume that no one prefers shifts.
789 return false;
790 }
791
792 /// Given the pattern
793 /// (X & (C l>>/<< Y)) ==/!= 0
794 /// return true if it should be transformed into:
795 /// ((X <</l>> Y) & C) ==/!= 0
796 /// WARNING: if 'X' is a constant, the fold may deadlock!
797 /// FIXME: we could avoid passing XC, but we can't use isConstOrConstSplat()
798 /// here because it can end up being not linked in.
801 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
802 SelectionDAG &DAG) const {
803 if (hasBitTest(X, Y)) {
804 // One interesting pattern that we'd want to form is 'bit test':
805 // ((1 << Y) & C) ==/!= 0
806 // But we also need to be careful not to try to reverse that fold.
807
808 // Is this '1 << Y' ?
809 if (OldShiftOpcode == ISD::SHL && CC->isOne())
810 return false; // Keep the 'bit test' pattern.
811
812 // Will it be '1 << Y' after the transform ?
813 if (XC && NewShiftOpcode == ISD::SHL && XC->isOne())
814 return true; // Do form the 'bit test' pattern.
815 }
816
817 // If 'X' is a constant, and we transform, then we will immediately
818 // try to undo the fold, thus causing endless combine loop.
819 // So by default, let's assume everyone prefers the fold
820 // iff 'X' is not a constant.
821 return !XC;
822 }
823
824 // Return true if its desirable to perform the following transform:
825 // (fmul C, (uitofp Pow2))
826 // -> (bitcast_to_FP (add (bitcast_to_INT C), Log2(Pow2) << mantissa))
827 // (fdiv C, (uitofp Pow2))
828 // -> (bitcast_to_FP (sub (bitcast_to_INT C), Log2(Pow2) << mantissa))
829 //
830 // This is only queried after we have verified the transform will be bitwise
831 // equals.
832 //
833 // SDNode *N : The FDiv/FMul node we want to transform.
834 // SDValue FPConst: The Float constant operand in `N`.
835 // SDValue IntPow2: The Integer power of 2 operand in `N`.
837 SDValue IntPow2) const {
838 // Default to avoiding fdiv which is often very expensive.
839 return N->getOpcode() == ISD::FDIV;
840 }
841
842 // Given:
843 // (icmp eq/ne (and X, C0), (shift X, C1))
844 // or
845 // (icmp eq/ne X, (rotate X, CPow2))
846
847 // If C0 is a mask or shifted mask and the shift amt (C1) isolates the
848 // remaining bits (i.e something like `(x64 & UINT32_MAX) == (x64 >> 32)`)
849 // Do we prefer the shift to be shift-right, shift-left, or rotate.
850 // Note: Its only valid to convert the rotate version to the shift version iff
851 // the shift-amt (`C1`) is a power of 2 (including 0).
852 // If ShiftOpc (current Opcode) is returned, do nothing.
854 EVT VT, unsigned ShiftOpc, bool MayTransformRotate,
855 const APInt &ShiftOrRotateAmt,
856 const std::optional<APInt> &AndMask) const {
857 return ShiftOpc;
858 }
859
860 /// These two forms are equivalent:
861 /// sub %y, (xor %x, -1)
862 /// add (add %x, 1), %y
863 /// The variant with two add's is IR-canonical.
864 /// Some targets may prefer one to the other.
865 virtual bool preferIncOfAddToSubOfNot(EVT VT) const {
866 // By default, let's assume that everyone prefers the form with two add's.
867 return true;
868 }
869
870 // By default prefer folding (abs (sub nsw x, y)) -> abds(x, y). Some targets
871 // may want to avoid this to prevent loss of sub_nsw pattern.
872 virtual bool preferABDSToABSWithNSW(EVT VT) const {
873 return true;
874 }
875
876 // Return true if the target wants to transform Op(Splat(X)) -> Splat(Op(X))
877 virtual bool preferScalarizeSplat(SDNode *N) const { return true; }
878
879 // Return true if the target wants to transform:
880 // (TruncVT truncate(sext_in_reg(VT X, ExtVT))
881 // -> (TruncVT sext_in_reg(truncate(VT X), ExtVT))
882 // Some targets might prefer pre-sextinreg to improve truncation/saturation.
883 virtual bool preferSextInRegOfTruncate(EVT TruncVT, EVT VT, EVT ExtVT) const {
884 return true;
885 }
886
887 /// Return true if the target wants to use the optimization that
888 /// turns ext(promotableInst1(...(promotableInstN(load)))) into
889 /// promotedInst1(...(promotedInstN(ext(load)))).
891
892 /// Return true if the target can combine store(extractelement VectorTy,
893 /// Idx).
894 /// \p Cost[out] gives the cost of that transformation when this is true.
895 virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
896 unsigned &Cost) const {
897 return false;
898 }
899
900 /// Return true if the target shall perform extract vector element and store
901 /// given that the vector is known to be splat of constant.
902 /// \p Index[out] gives the index of the vector element to be extracted when
903 /// this is true.
905 Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const {
906 return false;
907 }
908
909 /// Return true if inserting a scalar into a variable element of an undef
910 /// vector is more efficiently handled by splatting the scalar instead.
911 virtual bool shouldSplatInsEltVarIndex(EVT) const {
912 return false;
913 }
914
915 /// Return true if target always benefits from combining into FMA for a
916 /// given value type. This must typically return false on targets where FMA
917 /// takes more cycles to execute than FADD.
918 virtual bool enableAggressiveFMAFusion(EVT VT) const { return false; }
919
920 /// Return true if target always benefits from combining into FMA for a
921 /// given value type. This must typically return false on targets where FMA
922 /// takes more cycles to execute than FADD.
923 virtual bool enableAggressiveFMAFusion(LLT Ty) const { return false; }
924
925 /// Return the ValueType of the result of SETCC operations.
926 virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
927 EVT VT) const;
928
929 /// Return the ValueType for comparison libcalls. Comparison libcalls include
930 /// floating point comparison calls, and Ordered/Unordered check calls on
931 /// floating point numbers.
932 virtual
934
935 /// For targets without i1 registers, this gives the nature of the high-bits
936 /// of boolean values held in types wider than i1.
937 ///
938 /// "Boolean values" are special true/false values produced by nodes like
939 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
940 /// Not to be confused with general values promoted from i1. Some cpus
941 /// distinguish between vectors of boolean and scalars; the isVec parameter
942 /// selects between the two kinds. For example on X86 a scalar boolean should
943 /// be zero extended from i1, while the elements of a vector of booleans
944 /// should be sign extended from i1.
945 ///
946 /// Some cpus also treat floating point types the same way as they treat
947 /// vectors instead of the way they treat scalars.
948 BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
949 if (isVec)
950 return BooleanVectorContents;
951 return isFloat ? BooleanFloatContents : BooleanContents;
952 }
953
955 return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
956 }
957
958 /// Promote the given target boolean to a target boolean of the given type.
959 /// A target boolean is an integer value, not necessarily of type i1, the bits
960 /// of which conform to getBooleanContents.
961 ///
962 /// ValVT is the type of values that produced the boolean.
964 EVT ValVT) const {
965 SDLoc dl(Bool);
966 EVT BoolVT =
967 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ValVT);
969 return DAG.getNode(ExtendCode, dl, BoolVT, Bool);
970 }
971
972 /// Return target scheduling preference.
974 return SchedPreferenceInfo;
975 }
976
977 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
978 /// for different nodes. This function returns the preference (or none) for
979 /// the given node.
981 return Sched::None;
982 }
983
984 /// Return the register class that should be used for the specified value
985 /// type.
986 virtual const TargetRegisterClass *getRegClassFor(MVT VT, bool isDivergent = false) const {
987 (void)isDivergent;
988 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
989 assert(RC && "This value type is not natively supported!");
990 return RC;
991 }
992
993 /// Allows target to decide about the register class of the
994 /// specific value that is live outside the defining block.
995 /// Returns true if the value needs uniform register class.
997 const Value *) const {
998 return false;
999 }
1000
1001 /// Return the 'representative' register class for the specified value
1002 /// type.
1003 ///
1004 /// The 'representative' register class is the largest legal super-reg
1005 /// register class for the register class of the value type. For example, on
1006 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
1007 /// register class is GR64 on x86_64.
1008 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
1009 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
1010 return RC;
1011 }
1012
1013 /// Return the cost of the 'representative' register class for the specified
1014 /// value type.
1015 virtual uint8_t getRepRegClassCostFor(MVT VT) const {
1016 return RepRegClassCostForVT[VT.SimpleTy];
1017 }
1018
1019 /// Return the preferred strategy to legalize tihs SHIFT instruction, with
1020 /// \p ExpansionFactor being the recursion depth - how many expansion needed.
1025 };
1028 unsigned ExpansionFactor) const {
1029 if (ExpansionFactor == 1)
1032 }
1033
1034 /// Return true if the target has native support for the specified value type.
1035 /// This means that it has a register that directly holds it without
1036 /// promotions or expansions.
1037 bool isTypeLegal(EVT VT) const {
1038 assert(!VT.isSimple() ||
1039 (unsigned)VT.getSimpleVT().SimpleTy < std::size(RegClassForVT));
1040 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
1041 }
1042
1044 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
1045 /// that indicates how instruction selection should deal with the type.
1046 LegalizeTypeAction ValueTypeActions[MVT::VALUETYPE_SIZE];
1047
1048 public:
1050 std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
1051 TypeLegal);
1052 }
1053
1055 return ValueTypeActions[VT.SimpleTy];
1056 }
1057
1059 ValueTypeActions[VT.SimpleTy] = Action;
1060 }
1061 };
1062
1064 return ValueTypeActions;
1065 }
1066
1067 /// Return pair that represents the legalization kind (first) that needs to
1068 /// happen to EVT (second) in order to type-legalize it.
1069 ///
1070 /// First: how we should legalize values of this type, either it is already
1071 /// legal (return 'Legal') or we need to promote it to a larger type (return
1072 /// 'Promote'), or we need to expand it into multiple registers of smaller
1073 /// integer type (return 'Expand'). 'Custom' is not an option.
1074 ///
1075 /// Second: for types supported by the target, this is an identity function.
1076 /// For types that must be promoted to larger types, this returns the larger
1077 /// type to promote to. For integer types that are larger than the largest
1078 /// integer register, this contains one step in the expansion to get to the
1079 /// smaller register. For illegal floating point types, this returns the
1080 /// integer type to transform to.
1081 LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
1082
1083 /// Return how we should legalize values of this type, either it is already
1084 /// legal (return 'Legal') or we need to promote it to a larger type (return
1085 /// 'Promote'), or we need to expand it into multiple registers of smaller
1086 /// integer type (return 'Expand'). 'Custom' is not an option.
1088 return getTypeConversion(Context, VT).first;
1089 }
1091 return ValueTypeActions.getTypeAction(VT);
1092 }
1093
1094 /// For types supported by the target, this is an identity function. For
1095 /// types that must be promoted to larger types, this returns the larger type
1096 /// to promote to. For integer types that are larger than the largest integer
1097 /// register, this contains one step in the expansion to get to the smaller
1098 /// register. For illegal floating point types, this returns the integer type
1099 /// to transform to.
1100 virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
1101 return getTypeConversion(Context, VT).second;
1102 }
1103
1104 /// For types supported by the target, this is an identity function. For
1105 /// types that must be expanded (i.e. integer types that are larger than the
1106 /// largest integer register or illegal floating point types), this returns
1107 /// the largest legal type it will be expanded to.
1108 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
1109 assert(!VT.isVector());
1110 while (true) {
1111 switch (getTypeAction(Context, VT)) {
1112 case TypeLegal:
1113 return VT;
1114 case TypeExpandInteger:
1115 VT = getTypeToTransformTo(Context, VT);
1116 break;
1117 default:
1118 llvm_unreachable("Type is not legal nor is it to be expanded!");
1119 }
1120 }
1121 }
1122
1123 /// Vector types are broken down into some number of legal first class types.
1124 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
1125 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
1126 /// turns into 4 EVT::i32 values with both PPC and X86.
1127 ///
1128 /// This method returns the number of registers needed, and the VT for each
1129 /// register. It also returns the VT and quantity of the intermediate values
1130 /// before they are promoted/expanded.
1131 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
1132 EVT &IntermediateVT,
1133 unsigned &NumIntermediates,
1134 MVT &RegisterVT) const;
1135
1136 /// Certain targets such as MIPS require that some types such as vectors are
1137 /// always broken down into scalars in some contexts. This occurs even if the
1138 /// vector type is legal.
1140 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
1141 unsigned &NumIntermediates, MVT &RegisterVT) const {
1142 return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
1143 RegisterVT);
1144 }
1145
1147 unsigned opc = 0; // target opcode
1148 EVT memVT; // memory VT
1149
1150 // value representing memory location
1152
1153 // Fallback address space for use if ptrVal is nullptr. std::nullopt means
1154 // unknown address space.
1155 std::optional<unsigned> fallbackAddressSpace;
1156
1157 int offset = 0; // offset off of ptrVal
1158 uint64_t size = 0; // the size of the memory location
1159 // (taken from memVT if zero)
1160 MaybeAlign align = Align(1); // alignment
1161
1163 IntrinsicInfo() = default;
1164 };
1165
1166 /// Given an intrinsic, checks if on the target the intrinsic will need to map
1167 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
1168 /// true and store the intrinsic information into the IntrinsicInfo that was
1169 /// passed to the function.
1172 unsigned /*Intrinsic*/) const {
1173 return false;
1174 }
1175
1176 /// Returns true if the target can instruction select the specified FP
1177 /// immediate natively. If false, the legalizer will materialize the FP
1178 /// immediate as a load from a constant pool.
1179 virtual bool isFPImmLegal(const APFloat & /*Imm*/, EVT /*VT*/,
1180 bool ForCodeSize = false) const {
1181 return false;
1182 }
1183
1184 /// Targets can use this to indicate that they only support *some*
1185 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
1186 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
1187 /// legal.
1188 virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
1189 return true;
1190 }
1191
1192 /// Returns true if the operation can trap for the value type.
1193 ///
1194 /// VT must be a legal type. By default, we optimistically assume most
1195 /// operations don't trap except for integer divide and remainder.
1196 virtual bool canOpTrap(unsigned Op, EVT VT) const;
1197
1198 /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
1199 /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
1200 /// constant pool entry.
1202 EVT /*VT*/) const {
1203 return false;
1204 }
1205
1206 /// How to legalize this custom operation?
1208 return Legal;
1209 }
1210
1211 /// Return how this operation should be treated: either it is legal, needs to
1212 /// be promoted to a larger size, needs to be expanded to some other code
1213 /// sequence, or the target has a custom expander for it.
1215 if (VT.isExtended()) return Expand;
1216 // If a target-specific SDNode requires legalization, require the target
1217 // to provide custom legalization for it.
1218 if (Op >= std::size(OpActions[0]))
1219 return Custom;
1220 return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
1221 }
1222
1223 /// Custom method defined by each target to indicate if an operation which
1224 /// may require a scale is supported natively by the target.
1225 /// If not, the operation is illegal.
1226 virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT,
1227 unsigned Scale) const {
1228 return false;
1229 }
1230
1231 /// Some fixed point operations may be natively supported by the target but
1232 /// only for specific scales. This method allows for checking
1233 /// if the width is supported by the target for a given operation that may
1234 /// depend on scale.
1236 unsigned Scale) const {
1237 auto Action = getOperationAction(Op, VT);
1238 if (Action != Legal)
1239 return Action;
1240
1241 // This operation is supported in this type but may only work on specific
1242 // scales.
1243 bool Supported;
1244 switch (Op) {
1245 default:
1246 llvm_unreachable("Unexpected fixed point operation.");
1247 case ISD::SMULFIX:
1248 case ISD::SMULFIXSAT:
1249 case ISD::UMULFIX:
1250 case ISD::UMULFIXSAT:
1251 case ISD::SDIVFIX:
1252 case ISD::SDIVFIXSAT:
1253 case ISD::UDIVFIX:
1254 case ISD::UDIVFIXSAT:
1255 Supported = isSupportedFixedPointOperation(Op, VT, Scale);
1256 break;
1257 }
1258
1259 return Supported ? Action : Expand;
1260 }
1261
1262 // If Op is a strict floating-point operation, return the result
1263 // of getOperationAction for the equivalent non-strict operation.
1265 unsigned EqOpc;
1266 switch (Op) {
1267 default: llvm_unreachable("Unexpected FP pseudo-opcode");
1268#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1269 case ISD::STRICT_##DAGN: EqOpc = ISD::DAGN; break;
1270#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1271 case ISD::STRICT_##DAGN: EqOpc = ISD::SETCC; break;
1272#include "llvm/IR/ConstrainedOps.def"
1273 }
1274
1275 return getOperationAction(EqOpc, VT);
1276 }
1277
1278 /// Return true if the specified operation is legal on this target or can be
1279 /// made legal with custom lowering. This is used to help guide high-level
1280 /// lowering decisions. LegalOnly is an optional convenience for code paths
1281 /// traversed pre and post legalisation.
1283 bool LegalOnly = false) const {
1284 if (LegalOnly)
1285 return isOperationLegal(Op, VT);
1286
1287 return (VT == MVT::Other || isTypeLegal(VT)) &&
1288 (getOperationAction(Op, VT) == Legal ||
1289 getOperationAction(Op, VT) == Custom);
1290 }
1291
1292 /// Return true if the specified operation is legal on this target or can be
1293 /// made legal using promotion. This is used to help guide high-level lowering
1294 /// decisions. LegalOnly is an optional convenience for code paths traversed
1295 /// pre and post legalisation.
1297 bool LegalOnly = false) const {
1298 if (LegalOnly)
1299 return isOperationLegal(Op, VT);
1300
1301 return (VT == MVT::Other || isTypeLegal(VT)) &&
1302 (getOperationAction(Op, VT) == Legal ||
1303 getOperationAction(Op, VT) == Promote);
1304 }
1305
1306 /// Return true if the specified operation is legal on this target or can be
1307 /// made legal with custom lowering or using promotion. This is used to help
1308 /// guide high-level lowering decisions. LegalOnly is an optional convenience
1309 /// for code paths traversed pre and post legalisation.
1311 bool LegalOnly = false) const {
1312 if (LegalOnly)
1313 return isOperationLegal(Op, VT);
1314
1315 return (VT == MVT::Other || isTypeLegal(VT)) &&
1316 (getOperationAction(Op, VT) == Legal ||
1317 getOperationAction(Op, VT) == Custom ||
1318 getOperationAction(Op, VT) == Promote);
1319 }
1320
1321 /// Return true if the operation uses custom lowering, regardless of whether
1322 /// the type is legal or not.
1323 bool isOperationCustom(unsigned Op, EVT VT) const {
1324 return getOperationAction(Op, VT) == Custom;
1325 }
1326
1327 /// Return true if lowering to a jump table is allowed.
1328 virtual bool areJTsAllowed(const Function *Fn) const {
1329 if (Fn->getFnAttribute("no-jump-tables").getValueAsBool())
1330 return false;
1331
1332 return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1334 }
1335
1336 /// Check whether the range [Low,High] fits in a machine word.
1337 bool rangeFitsInWord(const APInt &Low, const APInt &High,
1338 const DataLayout &DL) const {
1339 // FIXME: Using the pointer type doesn't seem ideal.
1340 uint64_t BW = DL.getIndexSizeInBits(0u);
1341 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
1342 return Range <= BW;
1343 }
1344
1345 /// Return true if lowering to a jump table is suitable for a set of case
1346 /// clusters which may contain \p NumCases cases, \p Range range of values.
1347 virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
1348 uint64_t Range, ProfileSummaryInfo *PSI,
1349 BlockFrequencyInfo *BFI) const;
1350
1351 /// Returns preferred type for switch condition.
1353 EVT ConditionVT) const;
1354
1355 /// Return true if lowering to a bit test is suitable for a set of case
1356 /// clusters which contains \p NumDests unique destinations, \p Low and
1357 /// \p High as its lowest and highest case values, and expects \p NumCmps
1358 /// case value comparisons. Check if the number of destinations, comparison
1359 /// metric, and range are all suitable.
1360 bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
1361 const APInt &Low, const APInt &High,
1362 const DataLayout &DL) const {
1363 // FIXME: I don't think NumCmps is the correct metric: a single case and a
1364 // range of cases both require only one branch to lower. Just looking at the
1365 // number of clusters and destinations should be enough to decide whether to
1366 // build bit tests.
1367
1368 // To lower a range with bit tests, the range must fit the bitwidth of a
1369 // machine word.
1370 if (!rangeFitsInWord(Low, High, DL))
1371 return false;
1372
1373 // Decide whether it's profitable to lower this range with bit tests. Each
1374 // destination requires a bit test and branch, and there is an overall range
1375 // check branch. For a small number of clusters, separate comparisons might
1376 // be cheaper, and for many destinations, splitting the range might be
1377 // better.
1378 return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
1379 (NumDests == 3 && NumCmps >= 6);
1380 }
1381
1382 /// Return true if the specified operation is illegal on this target or
1383 /// unlikely to be made legal with custom lowering. This is used to help guide
1384 /// high-level lowering decisions.
1385 bool isOperationExpand(unsigned Op, EVT VT) const {
1386 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
1387 }
1388
1389 /// Return true if the specified operation is legal on this target.
1390 bool isOperationLegal(unsigned Op, EVT VT) const {
1391 return (VT == MVT::Other || isTypeLegal(VT)) &&
1392 getOperationAction(Op, VT) == Legal;
1393 }
1394
1395 /// Return how this load with extension should be treated: either it is legal,
1396 /// needs to be promoted to a larger size, needs to be expanded to some other
1397 /// code sequence, or the target has a custom expander for it.
1398 LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
1399 EVT MemVT) const {
1400 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1401 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1402 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1404 MemI < MVT::VALUETYPE_SIZE && "Table isn't big enough!");
1405 unsigned Shift = 4 * ExtType;
1406 return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
1407 }
1408
1409 /// Return true if the specified load with extension is legal on this target.
1410 bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1411 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
1412 }
1413
1414 /// Return true if the specified load with extension is legal or custom
1415 /// on this target.
1416 bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1417 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
1418 getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
1419 }
1420
1421 /// Return how this store with truncation should be treated: either it is
1422 /// legal, needs to be promoted to a larger size, needs to be expanded to some
1423 /// other code sequence, or the target has a custom expander for it.
1425 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1426 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1427 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1429 "Table isn't big enough!");
1430 return TruncStoreActions[ValI][MemI];
1431 }
1432
1433 /// Return true if the specified store with truncation is legal on this
1434 /// target.
1435 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
1436 return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
1437 }
1438
1439 /// Return true if the specified store with truncation has solution on this
1440 /// target.
1441 bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
1442 return isTypeLegal(ValVT) &&
1443 (getTruncStoreAction(ValVT, MemVT) == Legal ||
1444 getTruncStoreAction(ValVT, MemVT) == Custom);
1445 }
1446
1447 virtual bool canCombineTruncStore(EVT ValVT, EVT MemVT,
1448 bool LegalOnly) const {
1449 if (LegalOnly)
1450 return isTruncStoreLegal(ValVT, MemVT);
1451
1452 return isTruncStoreLegalOrCustom(ValVT, MemVT);
1453 }
1454
1455 /// Return how the indexed load should be treated: either it is legal, needs
1456 /// to be promoted to a larger size, needs to be expanded to some other code
1457 /// sequence, or the target has a custom expander for it.
1458 LegalizeAction getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
1459 return getIndexedModeAction(IdxMode, VT, IMAB_Load);
1460 }
1461
1462 /// Return true if the specified indexed load is legal on this target.
1463 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
1464 return VT.isSimple() &&
1465 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1466 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1467 }
1468
1469 /// Return how the indexed store should be treated: either it is legal, needs
1470 /// to be promoted to a larger size, needs to be expanded to some other code
1471 /// sequence, or the target has a custom expander for it.
1472 LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
1473 return getIndexedModeAction(IdxMode, VT, IMAB_Store);
1474 }
1475
1476 /// Return true if the specified indexed load is legal on this target.
1477 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
1478 return VT.isSimple() &&
1479 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1480 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1481 }
1482
1483 /// Return how the indexed load should be treated: either it is legal, needs
1484 /// to be promoted to a larger size, needs to be expanded to some other code
1485 /// sequence, or the target has a custom expander for it.
1486 LegalizeAction getIndexedMaskedLoadAction(unsigned IdxMode, MVT VT) const {
1487 return getIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad);
1488 }
1489
1490 /// Return true if the specified indexed load is legal on this target.
1491 bool isIndexedMaskedLoadLegal(unsigned IdxMode, EVT VT) const {
1492 return VT.isSimple() &&
1493 (getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1495 }
1496
1497 /// Return how the indexed store should be treated: either it is legal, needs
1498 /// to be promoted to a larger size, needs to be expanded to some other code
1499 /// sequence, or the target has a custom expander for it.
1500 LegalizeAction getIndexedMaskedStoreAction(unsigned IdxMode, MVT VT) const {
1501 return getIndexedModeAction(IdxMode, VT, IMAB_MaskedStore);
1502 }
1503
1504 /// Return true if the specified indexed load is legal on this target.
1505 bool isIndexedMaskedStoreLegal(unsigned IdxMode, EVT VT) const {
1506 return VT.isSimple() &&
1507 (getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1509 }
1510
1511 /// Returns true if the index type for a masked gather/scatter requires
1512 /// extending
1513 virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const { return false; }
1514
1515 // Returns true if Extend can be folded into the index of a masked gathers/scatters
1516 // on this target.
1517 virtual bool shouldRemoveExtendFromGSIndex(SDValue Extend, EVT DataVT) const {
1518 return false;
1519 }
1520
1521 // Return true if the target supports a scatter/gather instruction with
1522 // indices which are scaled by the particular value. Note that all targets
1523 // must by definition support scale of 1.
1525 uint64_t ElemSize) const {
1526 // MGATHER/MSCATTER are only required to support scaling by one or by the
1527 // element size.
1528 if (Scale != ElemSize && Scale != 1)
1529 return false;
1530 return true;
1531 }
1532
1533 /// Return how the condition code should be treated: either it is legal, needs
1534 /// to be expanded to some other code sequence, or the target has a custom
1535 /// expander for it.
1538 assert((unsigned)CC < std::size(CondCodeActions) &&
1539 ((unsigned)VT.SimpleTy >> 3) < std::size(CondCodeActions[0]) &&
1540 "Table isn't big enough!");
1541 // See setCondCodeAction for how this is encoded.
1542 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1543 uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
1544 LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
1545 assert(Action != Promote && "Can't promote condition code!");
1546 return Action;
1547 }
1548
1549 /// Return true if the specified condition code is legal on this target.
1551 return getCondCodeAction(CC, VT) == Legal;
1552 }
1553
1554 /// Return true if the specified condition code is legal or custom on this
1555 /// target.
1557 return getCondCodeAction(CC, VT) == Legal ||
1558 getCondCodeAction(CC, VT) == Custom;
1559 }
1560
1561 /// If the action for this operation is to promote, this method returns the
1562 /// ValueType to promote to.
1563 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
1565 "This operation isn't promoted!");
1566
1567 // See if this has an explicit type specified.
1568 std::map<std::pair<unsigned, MVT::SimpleValueType>,
1570 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1571 if (PTTI != PromoteToType.end()) return PTTI->second;
1572
1573 assert((VT.isInteger() || VT.isFloatingPoint()) &&
1574 "Cannot autopromote this type, add it with AddPromotedToType.");
1575
1576 uint64_t VTBits = VT.getScalarSizeInBits();
1577 MVT NVT = VT;
1578 do {
1579 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1580 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
1581 "Didn't find type to promote to!");
1582 } while (VTBits >= NVT.getScalarSizeInBits() || !isTypeLegal(NVT) ||
1583 getOperationAction(Op, NVT) == Promote);
1584 return NVT;
1585 }
1586
1588 bool AllowUnknown = false) const {
1589 return getValueType(DL, Ty, AllowUnknown);
1590 }
1591
1592 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1593 /// operations except for the pointer size. If AllowUnknown is true, this
1594 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1595 /// otherwise it will assert.
1597 bool AllowUnknown = false) const {
1598 // Lower scalar pointers to native pointer types.
1599 if (auto *PTy = dyn_cast<PointerType>(Ty))
1600 return getPointerTy(DL, PTy->getAddressSpace());
1601
1602 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1603 Type *EltTy = VTy->getElementType();
1604 // Lower vectors of pointers to native pointer types.
1605 if (auto *PTy = dyn_cast<PointerType>(EltTy)) {
1606 EVT PointerTy(getPointerTy(DL, PTy->getAddressSpace()));
1607 EltTy = PointerTy.getTypeForEVT(Ty->getContext());
1608 }
1609 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(EltTy, false),
1610 VTy->getElementCount());
1611 }
1612
1613 return EVT::getEVT(Ty, AllowUnknown);
1614 }
1615
1617 bool AllowUnknown = false) const {
1618 // Lower scalar pointers to native pointer types.
1619 if (auto *PTy = dyn_cast<PointerType>(Ty))
1620 return getPointerMemTy(DL, PTy->getAddressSpace());
1621
1622 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1623 Type *EltTy = VTy->getElementType();
1624 if (auto *PTy = dyn_cast<PointerType>(EltTy)) {
1625 EVT PointerTy(getPointerMemTy(DL, PTy->getAddressSpace()));
1626 EltTy = PointerTy.getTypeForEVT(Ty->getContext());
1627 }
1628 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(EltTy, false),
1629 VTy->getElementCount());
1630 }
1631
1632 return getValueType(DL, Ty, AllowUnknown);
1633 }
1634
1635
1636 /// Return the MVT corresponding to this LLVM type. See getValueType.
1638 bool AllowUnknown = false) const {
1639 return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1640 }
1641
1642 /// Return the desired alignment for ByVal or InAlloca aggregate function
1643 /// arguments in the caller parameter area. This is the actual alignment, not
1644 /// its logarithm.
1645 virtual uint64_t getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1646
1647 /// Return the type of registers that this ValueType will eventually require.
1649 assert((unsigned)VT.SimpleTy < std::size(RegisterTypeForVT));
1650 return RegisterTypeForVT[VT.SimpleTy];
1651 }
1652
1653 /// Return the type of registers that this ValueType will eventually require.
1654 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1655 if (VT.isSimple())
1656 return getRegisterType(VT.getSimpleVT());
1657 if (VT.isVector()) {
1658 EVT VT1;
1659 MVT RegisterVT;
1660 unsigned NumIntermediates;
1661 (void)getVectorTypeBreakdown(Context, VT, VT1,
1662 NumIntermediates, RegisterVT);
1663 return RegisterVT;
1664 }
1665 if (VT.isInteger()) {
1667 }
1668 llvm_unreachable("Unsupported extended type!");
1669 }
1670
1671 /// Return the number of registers that this ValueType will eventually
1672 /// require.
1673 ///
1674 /// This is one for any types promoted to live in larger registers, but may be
1675 /// more than one for types (like i64) that are split into pieces. For types
1676 /// like i140, which are first promoted then expanded, it is the number of
1677 /// registers needed to hold all the bits of the original type. For an i140
1678 /// on a 32 bit machine this means 5 registers.
1679 ///
1680 /// RegisterVT may be passed as a way to override the default settings, for
1681 /// instance with i128 inline assembly operands on SystemZ.
1682 virtual unsigned
1684 std::optional<MVT> RegisterVT = std::nullopt) const {
1685 if (VT.isSimple()) {
1686 assert((unsigned)VT.getSimpleVT().SimpleTy <
1687 std::size(NumRegistersForVT));
1688 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1689 }
1690 if (VT.isVector()) {
1691 EVT VT1;
1692 MVT VT2;
1693 unsigned NumIntermediates;
1694 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1695 }
1696 if (VT.isInteger()) {
1697 unsigned BitWidth = VT.getSizeInBits();
1698 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1699 return (BitWidth + RegWidth - 1) / RegWidth;
1700 }
1701 llvm_unreachable("Unsupported extended type!");
1702 }
1703
1704 /// Certain combinations of ABIs, Targets and features require that types
1705 /// are legal for some operations and not for other operations.
1706 /// For MIPS all vector types must be passed through the integer register set.
1708 CallingConv::ID CC, EVT VT) const {
1709 return getRegisterType(Context, VT);
1710 }
1711
1712 /// Certain targets require unusual breakdowns of certain types. For MIPS,
1713 /// this occurs when a vector type is used, as vector are passed through the
1714 /// integer register set.
1717 EVT VT) const {
1718 return getNumRegisters(Context, VT);
1719 }
1720
1721 /// Certain targets have context sensitive alignment requirements, where one
1722 /// type has the alignment requirement of another type.
1724 const DataLayout &DL) const {
1725 return DL.getABITypeAlign(ArgTy);
1726 }
1727
1728 /// If true, then instruction selection should seek to shrink the FP constant
1729 /// of the specified type to a smaller type in order to save space and / or
1730 /// reduce runtime.
1731 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1732
1733 /// Return true if it is profitable to reduce a load to a smaller type.
1734 /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
1736 EVT NewVT) const {
1737 // By default, assume that it is cheaper to extract a subvector from a wide
1738 // vector load rather than creating multiple narrow vector loads.
1739 if (NewVT.isVector() && !Load->hasOneUse())
1740 return false;
1741
1742 return true;
1743 }
1744
1745 /// Return true (the default) if it is profitable to remove a sext_inreg(x)
1746 /// where the sext is redundant, and use x directly.
1747 virtual bool shouldRemoveRedundantExtend(SDValue Op) const { return true; }
1748
1749 /// When splitting a value of the specified type into parts, does the Lo
1750 /// or Hi part come first? This usually follows the endianness, except
1751 /// for ppcf128, where the Hi part always comes first.
1753 return DL.isBigEndian() || VT == MVT::ppcf128;
1754 }
1755
1756 /// If true, the target has custom DAG combine transformations that it can
1757 /// perform for the specified node.
1759 assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
1760 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1761 }
1762
1765 }
1766
1767 /// Returns the size of the platform's va_list object.
1768 virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1769 return getPointerTy(DL).getSizeInBits();
1770 }
1771
1772 /// Get maximum # of store operations permitted for llvm.memset
1773 ///
1774 /// This function returns the maximum number of store operations permitted
1775 /// to replace a call to llvm.memset. The value is set by the target at the
1776 /// performance threshold for such a replacement. If OptSize is true,
1777 /// return the limit for functions that have OptSize attribute.
1778 unsigned getMaxStoresPerMemset(bool OptSize) const {
1780 }
1781
1782 /// Get maximum # of store operations permitted for llvm.memcpy
1783 ///
1784 /// This function returns the maximum number of store operations permitted
1785 /// to replace a call to llvm.memcpy. The value is set by the target at the
1786 /// performance threshold for such a replacement. If OptSize is true,
1787 /// return the limit for functions that have OptSize attribute.
1788 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1790 }
1791
1792 /// \brief Get maximum # of store operations to be glued together
1793 ///
1794 /// This function returns the maximum number of store operations permitted
1795 /// to glue together during lowering of llvm.memcpy. The value is set by
1796 // the target at the performance threshold for such a replacement.
1797 virtual unsigned getMaxGluedStoresPerMemcpy() const {
1799 }
1800
1801 /// Get maximum # of load operations permitted for memcmp
1802 ///
1803 /// This function returns the maximum number of load operations permitted
1804 /// to replace a call to memcmp. The value is set by the target at the
1805 /// performance threshold for such a replacement. If OptSize is true,
1806 /// return the limit for functions that have OptSize attribute.
1807 unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
1809 }
1810
1811 /// Get maximum # of store operations permitted for llvm.memmove
1812 ///
1813 /// This function returns the maximum number of store operations permitted
1814 /// to replace a call to llvm.memmove. The value is set by the target at the
1815 /// performance threshold for such a replacement. If OptSize is true,
1816 /// return the limit for functions that have OptSize attribute.
1817 unsigned getMaxStoresPerMemmove(bool OptSize) const {
1819 }
1820
1821 /// Determine if the target supports unaligned memory accesses.
1822 ///
1823 /// This function returns true if the target allows unaligned memory accesses
1824 /// of the specified type in the given address space. If true, it also returns
1825 /// a relative speed of the unaligned memory access in the last argument by
1826 /// reference. The higher the speed number the faster the operation comparing
1827 /// to a number returned by another such call. This is used, for example, in
1828 /// situations where an array copy/move/set is converted to a sequence of
1829 /// store operations. Its use helps to ensure that such replacements don't
1830 /// generate code that causes an alignment error (trap) on the target machine.
1832 EVT, unsigned AddrSpace = 0, Align Alignment = Align(1),
1834 unsigned * /*Fast*/ = nullptr) const {
1835 return false;
1836 }
1837
1838 /// LLT handling variant.
1840 LLT, unsigned AddrSpace = 0, Align Alignment = Align(1),
1842 unsigned * /*Fast*/ = nullptr) const {
1843 return false;
1844 }
1845
1846 /// This function returns true if the memory access is aligned or if the
1847 /// target allows this specific unaligned memory access. If the access is
1848 /// allowed, the optional final parameter returns a relative speed of the
1849 /// access (as defined by the target).
1851 LLVMContext &Context, const DataLayout &DL, EVT VT,
1852 unsigned AddrSpace = 0, Align Alignment = Align(1),
1854 unsigned *Fast = nullptr) const;
1855
1856 /// Return true if the memory access of this type is aligned or if the target
1857 /// allows this specific unaligned access for the given MachineMemOperand.
1858 /// If the access is allowed, the optional final parameter returns a relative
1859 /// speed of the access (as defined by the target).
1861 const DataLayout &DL, EVT VT,
1862 const MachineMemOperand &MMO,
1863 unsigned *Fast = nullptr) const;
1864
1865 /// Return true if the target supports a memory access of this type for the
1866 /// given address space and alignment. If the access is allowed, the optional
1867 /// final parameter returns the relative speed of the access (as defined by
1868 /// the target).
1869 virtual bool
1870 allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1871 unsigned AddrSpace = 0, Align Alignment = Align(1),
1873 unsigned *Fast = nullptr) const;
1874
1875 /// Return true if the target supports a memory access of this type for the
1876 /// given MachineMemOperand. If the access is allowed, the optional
1877 /// final parameter returns the relative access speed (as defined by the
1878 /// target).
1879 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1880 const MachineMemOperand &MMO,
1881 unsigned *Fast = nullptr) const;
1882
1883 /// LLT handling variant.
1884 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, LLT Ty,
1885 const MachineMemOperand &MMO,
1886 unsigned *Fast = nullptr) const;
1887
1888 /// Returns the target specific optimal type for load and store operations as
1889 /// a result of memset, memcpy, and memmove lowering.
1890 /// It returns EVT::Other if the type should be determined using generic
1891 /// target-independent logic.
1892 virtual EVT
1894 const AttributeList & /*FuncAttributes*/) const {
1895 return MVT::Other;
1896 }
1897
1898 /// LLT returning variant.
1899 virtual LLT
1901 const AttributeList & /*FuncAttributes*/) const {
1902 return LLT();
1903 }
1904
1905 /// Returns true if it's safe to use load / store of the specified type to
1906 /// expand memcpy / memset inline.
1907 ///
1908 /// This is mostly true for all types except for some special cases. For
1909 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1910 /// fstpl which also does type conversion. Note the specified type doesn't
1911 /// have to be legal as the hook is used before type legalization.
1912 virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1913
1914 /// Return lower limit for number of blocks in a jump table.
1915 virtual unsigned getMinimumJumpTableEntries() const;
1916
1917 /// Return lower limit of the density in a jump table.
1918 unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1919
1920 /// Return upper limit for number of entries in a jump table.
1921 /// Zero if no limit.
1922 unsigned getMaximumJumpTableSize() const;
1923
1924 virtual bool isJumpTableRelative() const;
1925
1926 /// If a physical register, this specifies the register that
1927 /// llvm.savestack/llvm.restorestack should save and restore.
1929 return StackPointerRegisterToSaveRestore;
1930 }
1931
1932 /// If a physical register, this returns the register that receives the
1933 /// exception address on entry to an EH pad.
1934 virtual Register
1935 getExceptionPointerRegister(const Constant *PersonalityFn) const {
1936 return Register();
1937 }
1938
1939 /// If a physical register, this returns the register that receives the
1940 /// exception typeid on entry to a landing pad.
1941 virtual Register
1942 getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1943 return Register();
1944 }
1945
1946 virtual bool needsFixedCatchObjects() const {
1947 report_fatal_error("Funclet EH is not implemented for this target");
1948 }
1949
1950 /// Return the minimum stack alignment of an argument.
1952 return MinStackArgumentAlignment;
1953 }
1954
1955 /// Return the minimum function alignment.
1956 Align getMinFunctionAlignment() const { return MinFunctionAlignment; }
1957
1958 /// Return the preferred function alignment.
1959 Align getPrefFunctionAlignment() const { return PrefFunctionAlignment; }
1960
1961 /// Return the preferred loop alignment.
1962 virtual Align getPrefLoopAlignment(MachineLoop *ML = nullptr) const;
1963
1964 /// Return the maximum amount of bytes allowed to be emitted when padding for
1965 /// alignment
1966 virtual unsigned
1968
1969 /// Should loops be aligned even when the function is marked OptSize (but not
1970 /// MinSize).
1971 virtual bool alignLoopsWithOptSize() const { return false; }
1972
1973 /// If the target has a standard location for the stack protector guard,
1974 /// returns the address of that location. Otherwise, returns nullptr.
1975 /// DEPRECATED: please override useLoadStackGuardNode and customize
1976 /// LOAD_STACK_GUARD, or customize \@llvm.stackguard().
1977 virtual Value *getIRStackGuard(IRBuilderBase &IRB) const;
1978
1979 /// Inserts necessary declarations for SSP (stack protection) purpose.
1980 /// Should be used only when getIRStackGuard returns nullptr.
1981 virtual void insertSSPDeclarations(Module &M) const;
1982
1983 /// Return the variable that's previously inserted by insertSSPDeclarations,
1984 /// if any, otherwise return nullptr. Should be used only when
1985 /// getIRStackGuard returns nullptr.
1986 virtual Value *getSDagStackGuard(const Module &M) const;
1987
1988 /// If this function returns true, stack protection checks should XOR the
1989 /// frame pointer (or whichever pointer is used to address locals) into the
1990 /// stack guard value before checking it. getIRStackGuard must return nullptr
1991 /// if this returns true.
1992 virtual bool useStackGuardXorFP() const { return false; }
1993
1994 /// If the target has a standard stack protection check function that
1995 /// performs validation and error handling, returns the function. Otherwise,
1996 /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1997 /// Should be used only when getIRStackGuard returns nullptr.
1998 virtual Function *getSSPStackGuardCheck(const Module &M) const;
1999
2000protected:
2002 bool UseTLS) const;
2003
2004public:
2005 /// Returns the target-specific address of the unsafe stack pointer.
2006 virtual Value *getSafeStackPointerLocation(IRBuilderBase &IRB) const;
2007
2008 /// Returns the name of the symbol used to emit stack probes or the empty
2009 /// string if not applicable.
2010 virtual bool hasStackProbeSymbol(const MachineFunction &MF) const { return false; }
2011
2012 virtual bool hasInlineStackProbe(const MachineFunction &MF) const { return false; }
2013
2015 return "";
2016 }
2017
2018 /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
2019 /// are happy to sink it into basic blocks. A cast may be free, but not
2020 /// necessarily a no-op. e.g. a free truncate from a 64-bit to 32-bit pointer.
2021 virtual bool isFreeAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const;
2022
2023 /// Return true if the pointer arguments to CI should be aligned by aligning
2024 /// the object whose address is being passed. If so then MinSize is set to the
2025 /// minimum size the object must be to be aligned and PrefAlign is set to the
2026 /// preferred alignment.
2027 virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
2028 Align & /*PrefAlign*/) const {
2029 return false;
2030 }
2031
2032 //===--------------------------------------------------------------------===//
2033 /// \name Helpers for TargetTransformInfo implementations
2034 /// @{
2035
2036 /// Get the ISD node that corresponds to the Instruction class opcode.
2037 int InstructionOpcodeToISD(unsigned Opcode) const;
2038
2039 /// @}
2040
2041 //===--------------------------------------------------------------------===//
2042 /// \name Helpers for atomic expansion.
2043 /// @{
2044
2045 /// Returns the maximum atomic operation size (in bits) supported by
2046 /// the backend. Atomic operations greater than this size (as well
2047 /// as ones that are not naturally aligned), will be expanded by
2048 /// AtomicExpandPass into an __atomic_* library call.
2050 return MaxAtomicSizeInBitsSupported;
2051 }
2052
2053 /// Returns the size in bits of the maximum div/rem the backend supports.
2054 /// Larger operations will be expanded by ExpandLargeDivRem.
2056 return MaxDivRemBitWidthSupported;
2057 }
2058
2059 /// Returns the size in bits of the maximum larget fp convert the backend
2060 /// supports. Larger operations will be expanded by ExpandLargeFPConvert.
2062 return MaxLargeFPConvertBitWidthSupported;
2063 }
2064
2065 /// Returns the size of the smallest cmpxchg or ll/sc instruction
2066 /// the backend supports. Any smaller operations are widened in
2067 /// AtomicExpandPass.
2068 ///
2069 /// Note that *unlike* operations above the maximum size, atomic ops
2070 /// are still natively supported below the minimum; they just
2071 /// require a more complex expansion.
2072 unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
2073
2074 /// Whether the target supports unaligned atomic operations.
2075 bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics; }
2076
2077 /// Whether AtomicExpandPass should automatically insert fences and reduce
2078 /// ordering for this atomic. This should be true for most architectures with
2079 /// weak memory ordering. Defaults to false.
2080 virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
2081 return false;
2082 }
2083
2084 /// Whether AtomicExpandPass should automatically insert a trailing fence
2085 /// without reducing the ordering for this atomic. Defaults to false.
2086 virtual bool
2088 return false;
2089 }
2090
2091 /// Perform a load-linked operation on Addr, returning a "Value *" with the
2092 /// corresponding pointee type. This may entail some non-trivial operations to
2093 /// truncate or reconstruct types that will be illegal in the backend. See
2094 /// ARMISelLowering for an example implementation.
2095 virtual Value *emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy,
2096 Value *Addr, AtomicOrdering Ord) const {
2097 llvm_unreachable("Load linked unimplemented on this target");
2098 }
2099
2100 /// Perform a store-conditional operation to Addr. Return the status of the
2101 /// store. This should be 0 if the store succeeded, non-zero otherwise.
2103 Value *Addr, AtomicOrdering Ord) const {
2104 llvm_unreachable("Store conditional unimplemented on this target");
2105 }
2106
2107 /// Perform a masked atomicrmw using a target-specific intrinsic. This
2108 /// represents the core LL/SC loop which will be lowered at a late stage by
2109 /// the backend. The target-specific intrinsic returns the loaded value and
2110 /// is not responsible for masking and shifting the result.
2112 AtomicRMWInst *AI,
2113 Value *AlignedAddr, Value *Incr,
2114 Value *Mask, Value *ShiftAmt,
2115 AtomicOrdering Ord) const {
2116 llvm_unreachable("Masked atomicrmw expansion unimplemented on this target");
2117 }
2118
2119 /// Perform a atomicrmw expansion using a target-specific way. This is
2120 /// expected to be called when masked atomicrmw and bit test atomicrmw don't
2121 /// work, and the target supports another way to lower atomicrmw.
2122 virtual void emitExpandAtomicRMW(AtomicRMWInst *AI) const {
2124 "Generic atomicrmw expansion unimplemented on this target");
2125 }
2126
2127 /// Perform a bit test atomicrmw using a target-specific intrinsic. This
2128 /// represents the combined bit test intrinsic which will be lowered at a late
2129 /// stage by the backend.
2132 "Bit test atomicrmw expansion unimplemented on this target");
2133 }
2134
2135 /// Perform a atomicrmw which the result is only used by comparison, using a
2136 /// target-specific intrinsic. This represents the combined atomic and compare
2137 /// intrinsic which will be lowered at a late stage by the backend.
2140 "Compare arith atomicrmw expansion unimplemented on this target");
2141 }
2142
2143 /// Perform a masked cmpxchg using a target-specific intrinsic. This
2144 /// represents the core LL/SC loop which will be lowered at a late stage by
2145 /// the backend. The target-specific intrinsic returns the loaded value and
2146 /// is not responsible for masking and shifting the result.
2148 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
2149 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
2150 llvm_unreachable("Masked cmpxchg expansion unimplemented on this target");
2151 }
2152
2153 //===--------------------------------------------------------------------===//
2154 /// \name KCFI check lowering.
2155 /// @{
2156
2159 const TargetInstrInfo *TII) const {
2160 llvm_unreachable("KCFI is not supported on this target");
2161 }
2162
2163 /// @}
2164
2165 /// Inserts in the IR a target-specific intrinsic specifying a fence.
2166 /// It is called by AtomicExpandPass before expanding an
2167 /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
2168 /// if shouldInsertFencesForAtomic returns true.
2169 ///
2170 /// Inst is the original atomic instruction, prior to other expansions that
2171 /// may be performed.
2172 ///
2173 /// This function should either return a nullptr, or a pointer to an IR-level
2174 /// Instruction*. Even complex fence sequences can be represented by a
2175 /// single Instruction* through an intrinsic to be lowered later.
2176 ///
2177 /// The default implementation emits an IR fence before any release (or
2178 /// stronger) operation that stores, and after any acquire (or stronger)
2179 /// operation. This is generally a correct implementation, but backends may
2180 /// override if they wish to use alternative schemes (e.g. the PowerPC
2181 /// standard ABI uses a fence before a seq_cst load instead of after a
2182 /// seq_cst store).
2183 /// @{
2184 virtual Instruction *emitLeadingFence(IRBuilderBase &Builder,
2185 Instruction *Inst,
2186 AtomicOrdering Ord) const;
2187
2189 Instruction *Inst,
2190 AtomicOrdering Ord) const;
2191 /// @}
2192
2193 // Emits code that executes when the comparison result in the ll/sc
2194 // expansion of a cmpxchg instruction is such that the store-conditional will
2195 // not execute. This makes it possible to balance out the load-linked with
2196 // a dedicated instruction, if desired.
2197 // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
2198 // be unnecessarily held, except if clrex, inserted by this hook, is executed.
2199 virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilderBase &Builder) const {}
2200
2201 /// Returns true if arguments should be sign-extended in lib calls.
2202 virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
2203 return IsSigned;
2204 }
2205
2206 /// Returns true if arguments should be extended in lib calls.
2207 virtual bool shouldExtendTypeInLibCall(EVT Type) const {
2208 return true;
2209 }
2210
2211 /// Returns how the given (atomic) load should be expanded by the
2212 /// IR-level AtomicExpand pass.
2215 }
2216
2217 /// Returns how the given (atomic) load should be cast by the IR-level
2218 /// AtomicExpand pass.
2220 if (LI->getType()->isFloatingPointTy())
2223 }
2224
2225 /// Returns how the given (atomic) store should be expanded by the IR-level
2226 /// AtomicExpand pass into. For instance AtomicExpansionKind::Expand will try
2227 /// to use an atomicrmw xchg.
2230 }
2231
2232 /// Returns how the given (atomic) store should be cast by the IR-level
2233 /// AtomicExpand pass into. For instance AtomicExpansionKind::CastToInteger
2234 /// will try to cast the operands to integer values.
2236 if (SI->getValueOperand()->getType()->isFloatingPointTy())
2239 }
2240
2241 /// Returns how the given atomic cmpxchg should be expanded by the IR-level
2242 /// AtomicExpand pass.
2243 virtual AtomicExpansionKind
2246 }
2247
2248 /// Returns how the IR-level AtomicExpand pass should expand the given
2249 /// AtomicRMW, if at all. Default is to never expand.
2251 return RMW->isFloatingPointOperation() ?
2253 }
2254
2255 /// Returns how the given atomic atomicrmw should be cast by the IR-level
2256 /// AtomicExpand pass.
2257 virtual AtomicExpansionKind
2259 if (RMWI->getOperation() == AtomicRMWInst::Xchg &&
2260 (RMWI->getValOperand()->getType()->isFloatingPointTy() ||
2261 RMWI->getValOperand()->getType()->isPointerTy()))
2263
2265 }
2266
2267 /// On some platforms, an AtomicRMW that never actually modifies the value
2268 /// (such as fetch_add of 0) can be turned into a fence followed by an
2269 /// atomic load. This may sound useless, but it makes it possible for the
2270 /// processor to keep the cacheline shared, dramatically improving
2271 /// performance. And such idempotent RMWs are useful for implementing some
2272 /// kinds of locks, see for example (justification + benchmarks):
2273 /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
2274 /// This method tries doing that transformation, returning the atomic load if
2275 /// it succeeds, and nullptr otherwise.
2276 /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
2277 /// another round of expansion.
2278 virtual LoadInst *
2280 return nullptr;
2281 }
2282
2283 /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
2284 /// SIGN_EXTEND, or ANY_EXTEND).
2286 return ISD::ZERO_EXTEND;
2287 }
2288
2289 /// Returns how the platform's atomic compare and swap expects its comparison
2290 /// value to be extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND). This is
2291 /// separate from getExtendForAtomicOps, which is concerned with the
2292 /// sign-extension of the instruction's output, whereas here we are concerned
2293 /// with the sign-extension of the input. For targets with compare-and-swap
2294 /// instructions (or sub-word comparisons in their LL/SC loop expansions),
2295 /// the input can be ANY_EXTEND, but the output will still have a specific
2296 /// extension.
2298 return ISD::ANY_EXTEND;
2299 }
2300
2301 /// @}
2302
2303 /// Returns true if we should normalize
2304 /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
2305 /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
2306 /// that it saves us from materializing N0 and N1 in an integer register.
2307 /// Targets that are able to perform and/or on flags should return false here.
2309 EVT VT) const {
2310 // If a target has multiple condition registers, then it likely has logical
2311 // operations on those registers.
2313 return false;
2314 // Only do the transform if the value won't be split into multiple
2315 // registers.
2317 return Action != TypeExpandInteger && Action != TypeExpandFloat &&
2318 Action != TypeSplitVector;
2319 }
2320
2321 virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const { return true; }
2322
2323 /// Return true if a select of constants (select Cond, C1, C2) should be
2324 /// transformed into simple math ops with the condition value. For example:
2325 /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
2326 virtual bool convertSelectOfConstantsToMath(EVT VT) const {
2327 return false;
2328 }
2329
2330 /// Return true if it is profitable to transform an integer
2331 /// multiplication-by-constant into simpler operations like shifts and adds.
2332 /// This may be true if the target does not directly support the
2333 /// multiplication operation for the specified type or the sequence of simpler
2334 /// ops is faster than the multiply.
2336 EVT VT, SDValue C) const {
2337 return false;
2338 }
2339
2340 /// Return true if it may be profitable to transform
2341 /// (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
2342 /// This may not be true if c1 and c2 can be represented as immediates but
2343 /// c1*c2 cannot, for example.
2344 /// The target should check if c1, c2 and c1*c2 can be represented as
2345 /// immediates, or have to be materialized into registers. If it is not sure
2346 /// about some cases, a default true can be returned to let the DAGCombiner
2347 /// decide.
2348 /// AddNode is (add x, c1), and ConstNode is c2.
2350 SDValue ConstNode) const {
2351 return true;
2352 }
2353
2354 /// Return true if it is more correct/profitable to use strict FP_TO_INT
2355 /// conversion operations - canonicalizing the FP source value instead of
2356 /// converting all cases and then selecting based on value.
2357 /// This may be true if the target throws exceptions for out of bounds
2358 /// conversions or has fast FP CMOV.
2359 virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
2360 bool IsSigned) const {
2361 return false;
2362 }
2363
2364 /// Return true if it is beneficial to expand an @llvm.powi.* intrinsic.
2365 /// If not optimizing for size, expanding @llvm.powi.* intrinsics is always
2366 /// considered beneficial.
2367 /// If optimizing for size, expansion is only considered beneficial for upto
2368 /// 5 multiplies and a divide (if the exponent is negative).
2369 bool isBeneficialToExpandPowI(int64_t Exponent, bool OptForSize) const {
2370 if (Exponent < 0)
2371 Exponent = -Exponent;
2372 uint64_t E = static_cast<uint64_t>(Exponent);
2373 return !OptForSize || (llvm::popcount(E) + Log2_64(E) < 7);
2374 }
2375
2376 //===--------------------------------------------------------------------===//
2377 // TargetLowering Configuration Methods - These methods should be invoked by
2378 // the derived class constructor to configure this object for the target.
2379 //
2380protected:
2381 /// Specify how the target extends the result of integer and floating point
2382 /// boolean values from i1 to a wider type. See getBooleanContents.
2384 BooleanContents = Ty;
2385 BooleanFloatContents = Ty;
2386 }
2387
2388 /// Specify how the target extends the result of integer and floating point
2389 /// boolean values from i1 to a wider type. See getBooleanContents.
2391 BooleanContents = IntTy;
2392 BooleanFloatContents = FloatTy;
2393 }
2394
2395 /// Specify how the target extends the result of a vector boolean value from a
2396 /// vector of i1 to a wider type. See getBooleanContents.
2398 BooleanVectorContents = Ty;
2399 }
2400
2401 /// Specify the target scheduling preference.
2403 SchedPreferenceInfo = Pref;
2404 }
2405
2406 /// Indicate the minimum number of blocks to generate jump tables.
2407 void setMinimumJumpTableEntries(unsigned Val);
2408
2409 /// Indicate the maximum number of entries in jump tables.
2410 /// Set to zero to generate unlimited jump tables.
2411 void setMaximumJumpTableSize(unsigned);
2412
2413 /// If set to a physical register, this specifies the register that
2414 /// llvm.savestack/llvm.restorestack should save and restore.
2416 StackPointerRegisterToSaveRestore = R;
2417 }
2418
2419 /// Tells the code generator that the target has multiple (allocatable)
2420 /// condition registers that can be used to store the results of comparisons
2421 /// for use by selects and conditional branches. With multiple condition
2422 /// registers, the code generator will not aggressively sink comparisons into
2423 /// the blocks of their users.
2424 void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
2425 HasMultipleConditionRegisters = hasManyRegs;
2426 }
2427
2428 /// Tells the code generator that the target has BitExtract instructions.
2429 /// The code generator will aggressively sink "shift"s into the blocks of
2430 /// their users if the users will generate "and" instructions which can be
2431 /// combined with "shift" to BitExtract instructions.
2432 void setHasExtractBitsInsn(bool hasExtractInsn = true) {
2433 HasExtractBitsInsn = hasExtractInsn;
2434 }
2435
2436 /// Tells the code generator not to expand logic operations on comparison
2437 /// predicates into separate sequences that increase the amount of flow
2438 /// control.
2439 void setJumpIsExpensive(bool isExpensive = true);
2440
2441 /// Tells the code generator which bitwidths to bypass.
2442 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
2443 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
2444 }
2445
2446 /// Add the specified register class as an available regclass for the
2447 /// specified value type. This indicates the selector can handle values of
2448 /// that class natively.
2450 assert((unsigned)VT.SimpleTy < std::size(RegClassForVT));
2451 RegClassForVT[VT.SimpleTy] = RC;
2452 }
2453
2454 /// Return the largest legal super-reg register class of the register class
2455 /// for the specified type and its associated "cost".
2456 virtual std::pair<const TargetRegisterClass *, uint8_t>
2458
2459 /// Once all of the register classes are added, this allows us to compute
2460 /// derived properties we expose.
2462
2463 /// Indicate that the specified operation does not work with the specified
2464 /// type and indicate what to do about it. Note that VT may refer to either
2465 /// the type of a result or that of an operand of Op.
2466 void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action) {
2467 assert(Op < std::size(OpActions[0]) && "Table isn't big enough!");
2468 OpActions[(unsigned)VT.SimpleTy][Op] = Action;
2469 }
2471 LegalizeAction Action) {
2472 for (auto Op : Ops)
2473 setOperationAction(Op, VT, Action);
2474 }
2476 LegalizeAction Action) {
2477 for (auto VT : VTs)
2478 setOperationAction(Ops, VT, Action);
2479 }
2480
2481 /// Indicate that the specified load with extension does not work with the
2482 /// specified type and indicate what to do about it.
2483 void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
2484 LegalizeAction Action) {
2485 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
2486 MemVT.isValid() && "Table isn't big enough!");
2487 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2488 unsigned Shift = 4 * ExtType;
2489 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
2490 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
2491 }
2492 void setLoadExtAction(ArrayRef<unsigned> ExtTypes, MVT ValVT, MVT MemVT,
2493 LegalizeAction Action) {
2494 for (auto ExtType : ExtTypes)
2495 setLoadExtAction(ExtType, ValVT, MemVT, Action);
2496 }
2498 ArrayRef<MVT> MemVTs, LegalizeAction Action) {
2499 for (auto MemVT : MemVTs)
2500 setLoadExtAction(ExtTypes, ValVT, MemVT, Action);
2501 }
2502
2503 /// Indicate that the specified truncating store does not work with the
2504 /// specified type and indicate what to do about it.
2505 void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action) {
2506 assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
2507 TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
2508 }
2509
2510 /// Indicate that the specified indexed load does or does not work with the
2511 /// specified type and indicate what to do abort it.
2512 ///
2513 /// NOTE: All indexed mode loads are initialized to Expand in
2514 /// TargetLowering.cpp
2516 LegalizeAction Action) {
2517 for (auto IdxMode : IdxModes)
2518 setIndexedModeAction(IdxMode, VT, IMAB_Load, Action);
2519 }
2520
2522 LegalizeAction Action) {
2523 for (auto VT : VTs)
2524 setIndexedLoadAction(IdxModes, VT, Action);
2525 }
2526
2527 /// Indicate that the specified indexed store does or does not work with the
2528 /// specified type and indicate what to do about it.
2529 ///
2530 /// NOTE: All indexed mode stores are initialized to Expand in
2531 /// TargetLowering.cpp
2533 LegalizeAction Action) {
2534 for (auto IdxMode : IdxModes)
2535 setIndexedModeAction(IdxMode, VT, IMAB_Store, Action);
2536 }
2537
2539 LegalizeAction Action) {
2540 for (auto VT : VTs)
2541 setIndexedStoreAction(IdxModes, VT, Action);
2542 }
2543
2544 /// Indicate that the specified indexed masked load does or does not work with
2545 /// the specified type and indicate what to do about it.
2546 ///
2547 /// NOTE: All indexed mode masked loads are initialized to Expand in
2548 /// TargetLowering.cpp
2549 void setIndexedMaskedLoadAction(unsigned IdxMode, MVT VT,
2550 LegalizeAction Action) {
2551 setIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad, Action);
2552 }
2553
2554 /// Indicate that the specified indexed masked store does or does not work
2555 /// with the specified type and indicate what to do about it.
2556 ///
2557 /// NOTE: All indexed mode masked stores are initialized to Expand in
2558 /// TargetLowering.cpp
2559 void setIndexedMaskedStoreAction(unsigned IdxMode, MVT VT,
2560 LegalizeAction Action) {
2561 setIndexedModeAction(IdxMode, VT, IMAB_MaskedStore, Action);
2562 }
2563
2564 /// Indicate that the specified condition code is or isn't supported on the
2565 /// target and indicate what to do about it.
2567 LegalizeAction Action) {
2568 for (auto CC : CCs) {
2569 assert(VT.isValid() && (unsigned)CC < std::size(CondCodeActions) &&
2570 "Table isn't big enough!");
2571 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2572 /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the
2573 /// 32-bit value and the upper 29 bits index into the second dimension of
2574 /// the array to select what 32-bit value to use.
2575 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
2576 CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
2577 CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
2578 }
2579 }
2581 LegalizeAction Action) {
2582 for (auto VT : VTs)
2583 setCondCodeAction(CCs, VT, Action);
2584 }
2585
2586 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
2587 /// to trying a larger integer/fp until it can find one that works. If that
2588 /// default is insufficient, this method can be used by the target to override
2589 /// the default.
2590 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2591 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
2592 }
2593
2594 /// Convenience method to set an operation to Promote and specify the type
2595 /// in a single call.
2596 void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2597 setOperationAction(Opc, OrigVT, Promote);
2598 AddPromotedToType(Opc, OrigVT, DestVT);
2599 }
2601 MVT DestVT) {
2602 for (auto Op : Ops) {
2603 setOperationAction(Op, OrigVT, Promote);
2604 AddPromotedToType(Op, OrigVT, DestVT);
2605 }
2606 }
2607
2608 /// Targets should invoke this method for each target independent node that
2609 /// they want to provide a custom DAG combiner for by implementing the
2610 /// PerformDAGCombine virtual method.
2612 for (auto NT : NTs) {
2613 assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
2614 TargetDAGCombineArray[NT >> 3] |= 1 << (NT & 7);
2615 }
2616 }
2617
2618 /// Set the target's minimum function alignment.
2620 MinFunctionAlignment = Alignment;
2621 }
2622
2623 /// Set the target's preferred function alignment. This should be set if
2624 /// there is a performance benefit to higher-than-minimum alignment
2626 PrefFunctionAlignment = Alignment;
2627 }
2628
2629 /// Set the target's preferred loop alignment. Default alignment is one, it
2630 /// means the target does not care about loop alignment. The target may also
2631 /// override getPrefLoopAlignment to provide per-loop values.
2632 void setPrefLoopAlignment(Align Alignment) { PrefLoopAlignment = Alignment; }
2633 void setMaxBytesForAlignment(unsigned MaxBytes) {
2634 MaxBytesForAlignment = MaxBytes;
2635 }
2636
2637 /// Set the minimum stack alignment of an argument.
2639 MinStackArgumentAlignment = Alignment;
2640 }
2641
2642 /// Set the maximum atomic operation size supported by the
2643 /// backend. Atomic operations greater than this size (as well as
2644 /// ones that are not naturally aligned), will be expanded by
2645 /// AtomicExpandPass into an __atomic_* library call.
2646 void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
2647 MaxAtomicSizeInBitsSupported = SizeInBits;
2648 }
2649
2650 /// Set the size in bits of the maximum div/rem the backend supports.
2651 /// Larger operations will be expanded by ExpandLargeDivRem.
2652 void setMaxDivRemBitWidthSupported(unsigned SizeInBits) {
2653 MaxDivRemBitWidthSupported = SizeInBits;
2654 }
2655
2656 /// Set the size in bits of the maximum fp convert the backend supports.
2657 /// Larger operations will be expanded by ExpandLargeFPConvert.
2658 void setMaxLargeFPConvertBitWidthSupported(unsigned SizeInBits) {
2659 MaxLargeFPConvertBitWidthSupported = SizeInBits;
2660 }
2661
2662 /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
2663 void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
2664 MinCmpXchgSizeInBits = SizeInBits;
2665 }
2666
2667 /// Sets whether unaligned atomic operations are supported.
2668 void setSupportsUnalignedAtomics(bool UnalignedSupported) {
2669 SupportsUnalignedAtomics = UnalignedSupported;
2670 }
2671
2672public:
2673 //===--------------------------------------------------------------------===//
2674 // Addressing mode description hooks (used by LSR etc).
2675 //
2676
2677 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
2678 /// instructions reading the address. This allows as much computation as
2679 /// possible to be done in the address mode for that operand. This hook lets
2680 /// targets also pass back when this should be done on intrinsics which
2681 /// load/store.
2683 SmallVectorImpl<Value*> &/*Ops*/,
2684 Type *&/*AccessTy*/) const {
2685 return false;
2686 }
2687
2688 /// This represents an addressing mode of:
2689 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
2690 /// If BaseGV is null, there is no BaseGV.
2691 /// If BaseOffs is zero, there is no base offset.
2692 /// If HasBaseReg is false, there is no base register.
2693 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
2694 /// no scale.
2695 struct AddrMode {
2697 int64_t BaseOffs = 0;
2698 bool HasBaseReg = false;
2699 int64_t Scale = 0;
2700 AddrMode() = default;
2701 };
2702
2703 /// Return true if the addressing mode represented by AM is legal for this
2704 /// target, for a load/store of the specified type.
2705 ///
2706 /// The type may be VoidTy, in which case only return true if the addressing
2707 /// mode is legal for a load/store of any legal type. TODO: Handle
2708 /// pre/postinc as well.
2709 ///
2710 /// If the address space cannot be determined, it will be -1.
2711 ///
2712 /// TODO: Remove default argument
2713 virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
2714 Type *Ty, unsigned AddrSpace,
2715 Instruction *I = nullptr) const;
2716
2717 /// Return the prefered common base offset.
2718 virtual int64_t getPreferredLargeGEPBaseOffset(int64_t MinOffset,
2719 int64_t MaxOffset) const {
2720 return 0;
2721 }
2722
2723 /// Return true if the specified immediate is legal icmp immediate, that is
2724 /// the target has icmp instructions which can compare a register against the
2725 /// immediate without having to materialize the immediate into a register.
2726 virtual bool isLegalICmpImmediate(int64_t) const {
2727 return true;
2728 }
2729
2730 /// Return true if the specified immediate is legal add immediate, that is the
2731 /// target has add instructions which can add a register with the immediate
2732 /// without having to materialize the immediate into a register.
2733 virtual bool isLegalAddImmediate(int64_t) const {
2734 return true;
2735 }
2736
2737 /// Return true if the specified immediate is legal for the value input of a
2738 /// store instruction.
2739 virtual bool isLegalStoreImmediate(int64_t Value) const {
2740 // Default implementation assumes that at least 0 works since it is likely
2741 // that a zero register exists or a zero immediate is allowed.
2742 return Value == 0;
2743 }
2744
2745 /// Return true if it's significantly cheaper to shift a vector by a uniform
2746 /// scalar than by an amount which will vary across each lane. On x86 before
2747 /// AVX2 for example, there is a "psllw" instruction for the former case, but
2748 /// no simple instruction for a general "a << b" operation on vectors.
2749 /// This should also apply to lowering for vector funnel shifts (rotates).
2750 virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
2751 return false;
2752 }
2753
2754 /// Given a shuffle vector SVI representing a vector splat, return a new
2755 /// scalar type of size equal to SVI's scalar type if the new type is more
2756 /// profitable. Returns nullptr otherwise. For example under MVE float splats
2757 /// are converted to integer to prevent the need to move from SPR to GPR
2758 /// registers.
2760 return nullptr;
2761 }
2762
2763 /// Given a set in interconnected phis of type 'From' that are loaded/stored
2764 /// or bitcast to type 'To', return true if the set should be converted to
2765 /// 'To'.
2766 virtual bool shouldConvertPhiType(Type *From, Type *To) const {
2767 return (From->isIntegerTy() || From->isFloatingPointTy()) &&
2768 (To->isIntegerTy() || To->isFloatingPointTy());
2769 }
2770
2771 /// Returns true if the opcode is a commutative binary operation.
2772 virtual bool isCommutativeBinOp(unsigned Opcode) const {
2773 // FIXME: This should get its info from the td file.
2774 switch (Opcode) {
2775 case ISD::ADD:
2776 case ISD::SMIN:
2777 case ISD::SMAX:
2778 case ISD::UMIN:
2779 case ISD::UMAX:
2780 case ISD::MUL:
2781 case ISD::MULHU:
2782 case ISD::MULHS:
2783 case ISD::SMUL_LOHI:
2784 case ISD::UMUL_LOHI:
2785 case ISD::FADD:
2786 case ISD::FMUL:
2787 case ISD::AND:
2788 case ISD::OR:
2789 case ISD::XOR:
2790 case ISD::SADDO:
2791 case ISD::UADDO:
2792 case ISD::ADDC:
2793 case ISD::ADDE:
2794 case ISD::SADDSAT:
2795 case ISD::UADDSAT:
2796 case ISD::FMINNUM:
2797 case ISD::FMAXNUM:
2798 case ISD::FMINNUM_IEEE:
2799 case ISD::FMAXNUM_IEEE:
2800 case ISD::FMINIMUM:
2801 case ISD::FMAXIMUM:
2802 case ISD::AVGFLOORS:
2803 case ISD::AVGFLOORU:
2804 case ISD::AVGCEILS:
2805 case ISD::AVGCEILU:
2806 case ISD::ABDS:
2807 case ISD::ABDU:
2808 return true;
2809 default: return false;
2810 }
2811 }
2812
2813 /// Return true if the node is a math/logic binary operator.
2814 virtual bool isBinOp(unsigned Opcode) const {
2815 // A commutative binop must be a binop.
2816 if (isCommutativeBinOp(Opcode))
2817 return true;
2818 // These are non-commutative binops.
2819 switch (Opcode) {
2820 case ISD::SUB:
2821 case ISD::SHL:
2822 case ISD::SRL:
2823 case ISD::SRA:
2824 case ISD::ROTL:
2825 case ISD::ROTR:
2826 case ISD::SDIV:
2827 case ISD::UDIV:
2828 case ISD::SREM:
2829 case ISD::UREM:
2830 case ISD::SSUBSAT:
2831 case ISD::USUBSAT:
2832 case ISD::FSUB:
2833 case ISD::FDIV:
2834 case ISD::FREM:
2835 return true;
2836 default:
2837 return false;
2838 }
2839 }
2840
2841 /// Return true if it's free to truncate a value of type FromTy to type
2842 /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
2843 /// by referencing its sub-register AX.
2844 /// Targets must return false when FromTy <= ToTy.
2845 virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
2846 return false;
2847 }
2848
2849 /// Return true if a truncation from FromTy to ToTy is permitted when deciding
2850 /// whether a call is in tail position. Typically this means that both results
2851 /// would be assigned to the same register or stack slot, but it could mean
2852 /// the target performs adequate checks of its own before proceeding with the
2853 /// tail call. Targets must return false when FromTy <= ToTy.
2854 virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
2855 return false;
2856 }
2857
2858 virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const { return false; }
2859 virtual bool isTruncateFree(LLT FromTy, LLT ToTy, const DataLayout &DL,
2860 LLVMContext &Ctx) const {
2861 return isTruncateFree(getApproximateEVTForLLT(FromTy, DL, Ctx),
2862 getApproximateEVTForLLT(ToTy, DL, Ctx));
2863 }
2864
2865 /// Return true if truncating the specific node Val to type VT2 is free.
2866 virtual bool isTruncateFree(SDValue Val, EVT VT2) const {
2867 // Fallback to type matching.
2868 return isTruncateFree(Val.getValueType(), VT2);
2869 }
2870
2871 virtual bool isProfitableToHoist(Instruction *I) const { return true; }
2872
2873 /// Return true if the extension represented by \p I is free.
2874 /// Unlikely the is[Z|FP]ExtFree family which is based on types,
2875 /// this method can use the context provided by \p I to decide
2876 /// whether or not \p I is free.
2877 /// This method extends the behavior of the is[Z|FP]ExtFree family.
2878 /// In other words, if is[Z|FP]Free returns true, then this method
2879 /// returns true as well. The converse is not true.
2880 /// The target can perform the adequate checks by overriding isExtFreeImpl.
2881 /// \pre \p I must be a sign, zero, or fp extension.
2882 bool isExtFree(const Instruction *I) const {
2883 switch (I->getOpcode()) {
2884 case Instruction::FPExt:
2885 if (isFPExtFree(EVT::getEVT(I->getType()),
2886 EVT::getEVT(I->getOperand(0)->getType())))
2887 return true;
2888 break;
2889 case Instruction::ZExt:
2890 if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
2891 return true;
2892 break;
2893 case Instruction::SExt:
2894 break;
2895 default:
2896 llvm_unreachable("Instruction is not an extension");
2897 }
2898 return isExtFreeImpl(I);
2899 }
2900
2901 /// Return true if \p Load and \p Ext can form an ExtLoad.
2902 /// For example, in AArch64
2903 /// %L = load i8, i8* %ptr
2904 /// %E = zext i8 %L to i32
2905 /// can be lowered into one load instruction
2906 /// ldrb w0, [x0]
2907 bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
2908 const DataLayout &DL) const {
2909 EVT VT = getValueType(DL, Ext->getType());
2910 EVT LoadVT = getValueType(DL, Load->getType());
2911
2912 // If the load has other users and the truncate is not free, the ext
2913 // probably isn't free.
2914 if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
2915 !isTruncateFree(Ext->getType(), Load->getType()))
2916 return false;
2917
2918 // Check whether the target supports casts folded into loads.
2919 unsigned LType;
2920 if (isa<ZExtInst>(Ext))
2921 LType = ISD::ZEXTLOAD;
2922 else {
2923 assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
2924 LType = ISD::SEXTLOAD;
2925 }
2926
2927 return isLoadExtLegal(LType, VT, LoadVT);
2928 }
2929
2930 /// Return true if any actual instruction that defines a value of type FromTy
2931 /// implicitly zero-extends the value to ToTy in the result register.
2932 ///
2933 /// The function should return true when it is likely that the truncate can
2934 /// be freely folded with an instruction defining a value of FromTy. If
2935 /// the defining instruction is unknown (because you're looking at a
2936 /// function argument, PHI, etc.) then the target may require an
2937 /// explicit truncate, which is not necessarily free, but this function
2938 /// does not deal with those cases.
2939 /// Targets must return false when FromTy >= ToTy.
2940 virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
2941 return false;
2942 }
2943
2944 virtual bool isZExtFree(EVT FromTy, EVT ToTy) const { return false; }
2945 virtual bool isZExtFree(LLT FromTy, LLT ToTy, const DataLayout &DL,
2946 LLVMContext &Ctx) const {
2947 return isZExtFree(getApproximateEVTForLLT(FromTy, DL, Ctx),
2948 getApproximateEVTForLLT(ToTy, DL, Ctx));
2949 }
2950
2951 /// Return true if zero-extending the specific node Val to type VT2 is free
2952 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2953 /// because it's folded such as X86 zero-extending loads).
2954 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
2955 return isZExtFree(Val.getValueType(), VT2);
2956 }
2957
2958 /// Return true if sign-extension from FromTy to ToTy is cheaper than
2959 /// zero-extension.
2960 virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const {
2961 return false;
2962 }
2963
2964 /// Return true if this constant should be sign extended when promoting to
2965 /// a larger type.
2966 virtual bool signExtendConstant(const ConstantInt *C) const { return false; }
2967
2968 /// Return true if sinking I's operands to the same basic block as I is
2969 /// profitable, e.g. because the operands can be folded into a target
2970 /// instruction during instruction selection. After calling the function
2971 /// \p Ops contains the Uses to sink ordered by dominance (dominating users
2972 /// come first).
2974 SmallVectorImpl<Use *> &Ops) const {
2975 return false;
2976 }
2977
2978 /// Try to optimize extending or truncating conversion instructions (like
2979 /// zext, trunc, fptoui, uitofp) for the target.
2980 virtual bool
2982 const TargetTransformInfo &TTI) const {
2983 return false;
2984 }
2985
2986 /// Return true if the target supplies and combines to a paired load
2987 /// two loaded values of type LoadedType next to each other in memory.
2988 /// RequiredAlignment gives the minimal alignment constraints that must be met
2989 /// to be able to select this paired load.
2990 ///
2991 /// This information is *not* used to generate actual paired loads, but it is
2992 /// used to generate a sequence of loads that is easier to combine into a
2993 /// paired load.
2994 /// For instance, something like this:
2995 /// a = load i64* addr
2996 /// b = trunc i64 a to i32
2997 /// c = lshr i64 a, 32
2998 /// d = trunc i64 c to i32
2999 /// will be optimized into:
3000 /// b = load i32* addr1
3001 /// d = load i32* addr2
3002 /// Where addr1 = addr2 +/- sizeof(i32).
3003 ///
3004 /// In other words, unless the target performs a post-isel load combining,
3005 /// this information should not be provided because it will generate more
3006 /// loads.
3007 virtual bool hasPairedLoad(EVT /*LoadedType*/,
3008 Align & /*RequiredAlignment*/) const {
3009 return false;
3010 }
3011
3012 /// Return true if the target has a vector blend instruction.
3013 virtual bool hasVectorBlend() const { return false; }
3014
3015 /// Get the maximum supported factor for interleaved memory accesses.
3016 /// Default to be the minimum interleave factor: 2.
3017 virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
3018
3019 /// Lower an interleaved load to target specific intrinsics. Return
3020 /// true on success.
3021 ///
3022 /// \p LI is the vector load instruction.
3023 /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
3024 /// \p Indices is the corresponding indices for each shufflevector.
3025 /// \p Factor is the interleave factor.
3028 ArrayRef<unsigned> Indices,
3029 unsigned Factor) const {
3030 return false;
3031 }
3032
3033 /// Lower an interleaved store to target specific intrinsics. Return
3034 /// true on success.
3035 ///
3036 /// \p SI is the vector store instruction.
3037 /// \p SVI is the shufflevector to RE-interleave the stored vector.
3038 /// \p Factor is the interleave factor.
3040 unsigned Factor) const {
3041 return false;
3042 }
3043
3044 /// Lower a deinterleave intrinsic to a target specific load intrinsic.
3045 /// Return true on success. Currently only supports
3046 /// llvm.experimental.vector.deinterleave2
3047 ///
3048 /// \p DI is the deinterleave intrinsic.
3049 /// \p LI is the accompanying load instruction
3051 LoadInst *LI) const {
3052 return false;
3053 }
3054
3055 /// Lower an interleave intrinsic to a target specific store intrinsic.
3056 /// Return true on success. Currently only supports
3057 /// llvm.experimental.vector.interleave2
3058 ///
3059 /// \p II is the interleave intrinsic.
3060 /// \p SI is the accompanying store instruction
3062 StoreInst *SI) const {
3063 return false;
3064 }
3065
3066 /// Return true if an fpext operation is free (for instance, because
3067 /// single-precision floating-point numbers are implicitly extended to
3068 /// double-precision).
3069 virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
3070 assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&
3071 "invalid fpext types");
3072 return false;
3073 }
3074
3075 /// Return true if an fpext operation input to an \p Opcode operation is free
3076 /// (for instance, because half-precision floating-point numbers are
3077 /// implicitly extended to float-precision) for an FMA instruction.
3078 virtual bool isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
3079 LLT DestTy, LLT SrcTy) const {
3080 return false;
3081 }
3082
3083 /// Return true if an fpext operation input to an \p Opcode operation is free
3084 /// (for instance, because half-precision floating-point numbers are
3085 /// implicitly extended to float-precision) for an FMA instruction.
3086 virtual bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
3087 EVT DestVT, EVT SrcVT) const {
3088 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
3089 "invalid fpext types");
3090 return isFPExtFree(DestVT, SrcVT);
3091 }
3092
3093 /// Return true if folding a vector load into ExtVal (a sign, zero, or any
3094 /// extend node) is profitable.
3095 virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
3096
3097 /// Return true if an fneg operation is free to the point where it is never
3098 /// worthwhile to replace it with a bitwise operation.
3099 virtual bool isFNegFree(EVT VT) const {
3100 assert(VT.isFloatingPoint());
3101 return false;
3102 }
3103
3104 /// Return true if an fabs operation is free to the point where it is never
3105 /// worthwhile to replace it with a bitwise operation.
3106 virtual bool isFAbsFree(EVT VT) const {
3107 assert(VT.isFloatingPoint());
3108 return false;
3109 }
3110
3111 /// Return true if an FMA operation is faster than a pair of fmul and fadd
3112 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
3113 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
3114 ///
3115 /// NOTE: This may be called before legalization on types for which FMAs are
3116 /// not legal, but should return true if those types will eventually legalize
3117 /// to types that support FMAs. After legalization, it will only be called on
3118 /// types that support FMAs (via Legal or Custom actions)
3120 EVT) const {
3121 return false;
3122 }
3123
3124 /// Return true if an FMA operation is faster than a pair of fmul and fadd
3125 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
3126 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
3127 ///
3128 /// NOTE: This may be called before legalization on types for which FMAs are
3129 /// not legal, but should return true if those types will eventually legalize
3130 /// to types that support FMAs. After legalization, it will only be called on
3131 /// types that support FMAs (via Legal or Custom actions)
3133 LLT) const {
3134 return false;
3135 }
3136
3137 /// IR version
3138 virtual bool isFMAFasterThanFMulAndFAdd(const Function &F, Type *) const {
3139 return false;
3140 }
3141
3142 /// Returns true if \p MI can be combined with another instruction to
3143 /// form TargetOpcode::G_FMAD. \p N may be an TargetOpcode::G_FADD,
3144 /// TargetOpcode::G_FSUB, or an TargetOpcode::G_FMUL which will be
3145 /// distributed into an fadd/fsub.
3146 virtual bool isFMADLegal(const MachineInstr &MI, LLT Ty) const {
3147 assert((MI.getOpcode() == TargetOpcode::G_FADD ||
3148 MI.getOpcode() == TargetOpcode::G_FSUB ||
3149 MI.getOpcode() == TargetOpcode::G_FMUL) &&
3150 "unexpected node in FMAD forming combine");
3151 switch (Ty.getScalarSizeInBits()) {
3152 case 16:
3153 return isOperationLegal(TargetOpcode::G_FMAD, MVT::f16);
3154 case 32:
3155 return isOperationLegal(TargetOpcode::G_FMAD, MVT::f32);
3156 case 64:
3157 return isOperationLegal(TargetOpcode::G_FMAD, MVT::f64);
3158 default:
3159 break;
3160 }
3161
3162 return false;
3163 }
3164
3165 /// Returns true if be combined with to form an ISD::FMAD. \p N may be an
3166 /// ISD::FADD, ISD::FSUB, or an ISD::FMUL which will be distributed into an
3167 /// fadd/fsub.
3168 virtual bool isFMADLegal(const SelectionDAG &DAG, const SDNode *N) const {
3169 assert((N->getOpcode() == ISD::FADD || N->getOpcode() == ISD::FSUB ||
3170 N->getOpcode() == ISD::FMUL) &&
3171 "unexpected node in FMAD forming combine");
3172 return isOperationLegal(ISD::FMAD, N->getValueType(0));
3173 }
3174
3175 // Return true when the decision to generate FMA's (or FMS, FMLA etc) rather
3176 // than FMUL and ADD is delegated to the machine combiner.
3178 CodeGenOptLevel OptLevel) const {
3179 return false;
3180 }
3181
3182 /// Return true if it's profitable to narrow operations of type SrcVT to
3183 /// DestVT. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
3184 /// i32 to i16.
3185 virtual bool isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
3186 return false;
3187 }
3188
3189 /// Return true if pulling a binary operation into a select with an identity
3190 /// constant is profitable. This is the inverse of an IR transform.
3191 /// Example: X + (Cond ? Y : 0) --> Cond ? (X + Y) : X
3192 virtual bool shouldFoldSelectWithIdentityConstant(unsigned BinOpcode,
3193 EVT VT) const {
3194 return false;
3195 }
3196
3197 /// Return true if it is beneficial to convert a load of a constant to
3198 /// just the constant itself.
3199 /// On some targets it might be more efficient to use a combination of
3200 /// arithmetic instructions to materialize the constant instead of loading it
3201 /// from a constant pool.
3203 Type *Ty) const {
3204 return false;
3205 }
3206
3207 /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
3208 /// from this source type with this index. This is needed because
3209 /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
3210 /// the first element, and only the target knows which lowering is cheap.
3211 virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
3212 unsigned Index) const {
3213 return false;
3214 }
3215
3216 /// Try to convert an extract element of a vector binary operation into an
3217 /// extract element followed by a scalar operation.
3218 virtual bool shouldScalarizeBinop(SDValue VecOp) const {
3219 return false;
3220 }
3221
3222 /// Return true if extraction of a scalar element from the given vector type
3223 /// at the given index is cheap. For example, if scalar operations occur on
3224 /// the same register file as vector operations, then an extract element may
3225 /// be a sub-register rename rather than an actual instruction.
3226 virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const {
3227 return false;
3228 }
3229
3230 /// Try to convert math with an overflow comparison into the corresponding DAG
3231 /// node operation. Targets may want to override this independently of whether
3232 /// the operation is legal/custom for the given type because it may obscure
3233 /// matching of other patterns.
3234 virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT,
3235 bool MathUsed) const {
3236 // TODO: The default logic is inherited from code in CodeGenPrepare.
3237 // The opcode should not make a difference by default?
3238 if (Opcode != ISD::UADDO)
3239 return false;
3240
3241 // Allow the transform as long as we have an integer type that is not
3242 // obviously illegal and unsupported and if the math result is used
3243 // besides the overflow check. On some targets (e.g. SPARC), it is
3244 // not profitable to form on overflow op if the math result has no
3245 // concrete users.
3246 if (VT.isVector())
3247 return false;
3248 return MathUsed && (VT.isSimple() || !isOperationExpand(Opcode, VT));
3249 }
3250
3251 // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
3252 // even if the vector itself has multiple uses.
3253 virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
3254 return false;
3255 }
3256
3257 // Return true if CodeGenPrepare should consider splitting large offset of a
3258 // GEP to make the GEP fit into the addressing mode and can be sunk into the
3259 // same blocks of its users.
3260 virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
3261
3262 /// Return true if creating a shift of the type by the given
3263 /// amount is not profitable.
3264 virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const {
3265 return false;
3266 }
3267
3268 // Should we fold (select_cc seteq (and x, y), 0, 0, A) -> (and (sra (shl x))
3269 // A) where y has a single bit set?
3271 const APInt &AndMask) const {
3272 unsigned ShCt = AndMask.getBitWidth() - 1;
3273 return !shouldAvoidTransformToShift(VT, ShCt);
3274 }
3275
3276 /// Does this target require the clearing of high-order bits in a register
3277 /// passed to the fp16 to fp conversion library function.
3278 virtual bool shouldKeepZExtForFP16Conv() const { return false; }
3279
3280 /// Should we generate fp_to_si_sat and fp_to_ui_sat from type FPVT to type VT
3281 /// from min(max(fptoi)) saturation patterns.
3282 virtual bool shouldConvertFpToSat(unsigned Op, EVT FPVT, EVT VT) const {
3283 return isOperationLegalOrCustom(Op, VT);
3284 }
3285
3286 /// Does this target support complex deinterleaving
3287 virtual bool isComplexDeinterleavingSupported() const { return false; }
3288
3289 /// Does this target support complex deinterleaving with the given operation
3290 /// and type
3293 return false;
3294 }
3295
3296 /// Create the IR node for the given complex deinterleaving operation.
3297 /// If one cannot be created using all the given inputs, nullptr should be
3298 /// returned.
3301 ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB,
3302 Value *Accumulator = nullptr) const {
3303 return nullptr;
3304 }
3305
3306 //===--------------------------------------------------------------------===//
3307 // Runtime Library hooks
3308 //
3309
3310 /// Rename the default libcall routine name for the specified libcall.
3311 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
3312 LibcallRoutineNames[Call] = Name;
3313 }
3315 for (auto Call : Calls)
3316 setLibcallName(Call, Name);
3317 }
3318
3319 /// Get the libcall routine name for the specified libcall.
3320 const char *getLibcallName(RTLIB::Libcall Call) const {
3321 return LibcallRoutineNames[Call];
3322 }
3323
3324 /// Override the default CondCode to be used to test the result of the
3325 /// comparison libcall against zero.
3327 CmpLibcallCCs[Call] = CC;
3328 }
3329
3330 /// Get the CondCode that's to be used to test the result of the comparison
3331 /// libcall against zero.
3333 return CmpLibcallCCs[Call];
3334 }
3335
3336 /// Set the CallingConv that should be used for the specified libcall.
3338 LibcallCallingConvs[Call] = CC;
3339 }
3340
3341 /// Get the CallingConv that should be used for the specified libcall.
3343 return LibcallCallingConvs[Call];
3344 }
3345
3346 /// Execute target specific actions to finalize target lowering.
3347 /// This is used to set extra flags in MachineFrameInformation and freezing
3348 /// the set of reserved registers.
3349 /// The default implementation just freezes the set of reserved registers.
3350 virtual void finalizeLowering(MachineFunction &MF) const;
3351
3352 //===----------------------------------------------------------------------===//
3353 // GlobalISel Hooks
3354 //===----------------------------------------------------------------------===//
3355 /// Check whether or not \p MI needs to be moved close to its uses.
3356 virtual bool shouldLocalize(const MachineInstr &MI, const TargetTransformInfo *TTI) const;
3357
3358
3359private:
3360 const TargetMachine &TM;
3361
3362 /// Tells the code generator that the target has multiple (allocatable)
3363 /// condition registers that can be used to store the results of comparisons
3364 /// for use by selects and conditional branches. With multiple condition
3365 /// registers, the code generator will not aggressively sink comparisons into
3366 /// the blocks of their users.
3367 bool HasMultipleConditionRegisters;
3368
3369 /// Tells the code generator that the target has BitExtract instructions.
3370 /// The code generator will aggressively sink "shift"s into the blocks of
3371 /// their users if the users will generate "and" instructions which can be
3372 /// combined with "shift" to BitExtract instructions.
3373 bool HasExtractBitsInsn;
3374
3375 /// Tells the code generator to bypass slow divide or remainder
3376 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
3377 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
3378 /// div/rem when the operands are positive and less than 256.
3379 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
3380
3381 /// Tells the code generator that it shouldn't generate extra flow control
3382 /// instructions and should attempt to combine flow control instructions via
3383 /// predication.
3384 bool JumpIsExpensive;
3385
3386 /// Information about the contents of the high-bits in boolean values held in
3387 /// a type wider than i1. See getBooleanContents.
3388 BooleanContent BooleanContents;
3389
3390 /// Information about the contents of the high-bits in boolean values held in
3391 /// a type wider than i1. See getBooleanContents.
3392 BooleanContent BooleanFloatContents;
3393
3394 /// Information about the contents of the high-bits in boolean vector values
3395 /// when the element type is wider than i1. See getBooleanContents.
3396 BooleanContent BooleanVectorContents;
3397
3398 /// The target scheduling preference: shortest possible total cycles or lowest
3399 /// register usage.
3400 Sched::Preference SchedPreferenceInfo;
3401
3402 /// The minimum alignment that any argument on the stack needs to have.
3403 Align MinStackArgumentAlignment;
3404
3405 /// The minimum function alignment (used when optimizing for size, and to
3406 /// prevent explicitly provided alignment from leading to incorrect code).
3407 Align MinFunctionAlignment;
3408
3409 /// The preferred function alignment (used when alignment unspecified and
3410 /// optimizing for speed).
3411 Align PrefFunctionAlignment;
3412
3413 /// The preferred loop alignment (in log2 bot in bytes).
3414 Align PrefLoopAlignment;
3415 /// The maximum amount of bytes permitted to be emitted for alignment.
3416 unsigned MaxBytesForAlignment;
3417
3418 /// Size in bits of the maximum atomics size the backend supports.
3419 /// Accesses larger than this will be expanded by AtomicExpandPass.
3420 unsigned MaxAtomicSizeInBitsSupported;
3421
3422 /// Size in bits of the maximum div/rem size the backend supports.
3423 /// Larger operations will be expanded by ExpandLargeDivRem.
3424 unsigned MaxDivRemBitWidthSupported;
3425
3426 /// Size in bits of the maximum larget fp convert size the backend
3427 /// supports. Larger operations will be expanded by ExpandLargeFPConvert.
3428 unsigned MaxLargeFPConvertBitWidthSupported;
3429
3430 /// Size in bits of the minimum cmpxchg or ll/sc operation the
3431 /// backend supports.
3432 unsigned MinCmpXchgSizeInBits;
3433
3434 /// This indicates if the target supports unaligned atomic operations.
3435 bool SupportsUnalignedAtomics;
3436
3437 /// If set to a physical register, this specifies the register that
3438 /// llvm.savestack/llvm.restorestack should save and restore.
3439 Register StackPointerRegisterToSaveRestore;
3440
3441 /// This indicates the default register class to use for each ValueType the
3442 /// target supports natively.
3443 const TargetRegisterClass *RegClassForVT[MVT::VALUETYPE_SIZE];
3444 uint16_t NumRegistersForVT[MVT::VALUETYPE_SIZE];
3445 MVT RegisterTypeForVT[MVT::VALUETYPE_SIZE];
3446
3447 /// This indicates the "representative" register class to use for each
3448 /// ValueType the target supports natively. This information is used by the
3449 /// scheduler to track register pressure. By default, the representative
3450 /// register class is the largest legal super-reg register class of the
3451 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
3452 /// representative class would be GR32.
3453 const TargetRegisterClass *RepRegClassForVT[MVT::VALUETYPE_SIZE] = {0};
3454
3455 /// This indicates the "cost" of the "representative" register class for each
3456 /// ValueType. The cost is used by the scheduler to approximate register
3457 /// pressure.
3458 uint8_t RepRegClassCostForVT[MVT::VALUETYPE_SIZE];
3459
3460 /// For any value types we are promoting or expanding, this contains the value
3461 /// type that we are changing to. For Expanded types, this contains one step
3462 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
3463 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
3464 /// the same type (e.g. i32 -> i32).
3465 MVT TransformToType[MVT::VALUETYPE_SIZE];
3466
3467 /// For each operation and each value type, keep a LegalizeAction that
3468 /// indicates how instruction selection should deal with the operation. Most
3469 /// operations are Legal (aka, supported natively by the target), but
3470 /// operations that are not should be described. Note that operations on
3471 /// non-legal value types are not described here.
3473
3474 /// For each load extension type and each value type, keep a LegalizeAction
3475 /// that indicates how instruction selection should deal with a load of a
3476 /// specific value type and extension type. Uses 4-bits to store the action
3477 /// for each of the 4 load ext types.
3479
3480 /// For each value type pair keep a LegalizeAction that indicates whether a
3481 /// truncating store of a specific value type and truncating type is legal.
3483
3484 /// For each indexed mode and each value type, keep a quad of LegalizeAction
3485 /// that indicates how instruction selection should deal with the load /
3486 /// store / maskedload / maskedstore.
3487 ///
3488 /// The first dimension is the value_type for the reference. The second
3489 /// dimension represents the various modes for load store.
3491
3492 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
3493 /// indicates how instruction selection should deal with the condition code.
3494 ///
3495 /// Because each CC action takes up 4 bits, we need to have the array size be
3496 /// large enough to fit all of the value types. This can be done by rounding
3497 /// up the MVT::VALUETYPE_SIZE value to the next multiple of 8.
3498 uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::VALUETYPE_SIZE + 7) / 8];
3499
3500 ValueTypeActionImpl ValueTypeActions;
3501
3502private:
3503 /// Targets can specify ISD nodes that they would like PerformDAGCombine
3504 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
3505 /// array.
3506 unsigned char
3507 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
3508
3509 /// For operations that must be promoted to a specific type, this holds the
3510 /// destination type. This map should be sparse, so don't hold it as an
3511 /// array.
3512 ///
3513 /// Targets add entries to this map with AddPromotedToType(..), clients access
3514 /// this with getTypeToPromoteTo(..).
3515 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
3516 PromoteToType;
3517
3518 /// Stores the name each libcall.
3519 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL + 1];
3520
3521 /// The ISD::CondCode that should be used to test the result of each of the
3522 /// comparison libcall against zero.
3523 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
3524
3525 /// Stores the CallingConv that should be used for each libcall.
3526 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
3527
3528 /// Set default libcall names and calling conventions.
3529 void InitLibcalls(const Triple &TT);
3530
3531 /// The bits of IndexedModeActions used to store the legalisation actions
3532 /// We store the data as | ML | MS | L | S | each taking 4 bits.
3533 enum IndexedModeActionsBits {
3534 IMAB_Store = 0,
3535 IMAB_Load = 4,
3536 IMAB_MaskedStore = 8,
3537 IMAB_MaskedLoad = 12
3538 };
3539
3540 void setIndexedModeAction(unsigned IdxMode, MVT VT, unsigned Shift,
3541 LegalizeAction Action) {
3542 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
3543 (unsigned)Action < 0xf && "Table isn't big enough!");
3544 unsigned Ty = (unsigned)VT.SimpleTy;
3545 IndexedModeActions[Ty][IdxMode] &= ~(0xf << Shift);
3546 IndexedModeActions[Ty][IdxMode] |= ((uint16_t)Action) << Shift;
3547 }
3548
3549 LegalizeAction getIndexedModeAction(unsigned IdxMode, MVT VT,
3550 unsigned Shift) const {
3551 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
3552 "Table isn't big enough!");
3553 unsigned Ty = (unsigned)VT.SimpleTy;
3554 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] >> Shift) & 0xf);
3555 }
3556
3557protected:
3558 /// Return true if the extension represented by \p I is free.
3559 /// \pre \p I is a sign, zero, or fp extension and
3560 /// is[Z|FP]ExtFree of the related types is not true.
3561 virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
3562
3563 /// Depth that GatherAllAliases should continue looking for chain
3564 /// dependencies when trying to find a more preferable chain. As an
3565 /// approximation, this should be more than the number of consecutive stores
3566 /// expected to be merged.
3568
3569 /// \brief Specify maximum number of store instructions per memset call.
3570 ///
3571 /// When lowering \@llvm.memset this field specifies the maximum number of
3572 /// store operations that may be substituted for the call to memset. Targets
3573 /// must set this value based on the cost threshold for that target. Targets
3574 /// should assume that the memset will be done using as many of the largest
3575 /// store operations first, followed by smaller ones, if necessary, per
3576 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
3577 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
3578 /// store. This only applies to setting a constant array of a constant size.
3580 /// Likewise for functions with the OptSize attribute.
3582
3583 /// \brief Specify maximum number of store instructions per memcpy call.
3584 ///
3585 /// When lowering \@llvm.memcpy this field specifies the maximum number of
3586 /// store operations that may be substituted for a call to memcpy. Targets
3587 /// must set this value based on the cost threshold for that target. Targets
3588 /// should assume that the memcpy will be done using as many of the largest
3589 /// store operations first, followed by smaller ones, if necessary, per
3590 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
3591 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
3592 /// and one 1-byte store. This only applies to copying a constant array of
3593 /// constant size.
3595 /// Likewise for functions with the OptSize attribute.
3597 /// \brief Specify max number of store instructions to glue in inlined memcpy.
3598 ///
3599 /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
3600 /// of store instructions to keep together. This helps in pairing and
3601 // vectorization later on.
3603
3604 /// \brief Specify maximum number of load instructions per memcmp call.
3605 ///
3606 /// When lowering \@llvm.memcmp this field specifies the maximum number of
3607 /// pairs of load operations that may be substituted for a call to memcmp.
3608 /// Targets must set this value based on the cost threshold for that target.
3609 /// Targets should assume that the memcmp will be done using as many of the
3610 /// largest load operations first, followed by smaller ones, if necessary, per
3611 /// alignment restrictions. For example, loading 7 bytes on a 32-bit machine
3612 /// with 32-bit alignment would result in one 4-byte load, a one 2-byte load
3613 /// and one 1-byte load. This only applies to copying a constant array of
3614 /// constant size.
3616 /// Likewise for functions with the OptSize attribute.
3618
3619 /// \brief Specify maximum number of store instructions per memmove call.
3620 ///
3621 /// When lowering \@llvm.memmove this field specifies the maximum number of
3622 /// store instructions that may be substituted for a call to memmove. Targets
3623 /// must set this value based on the cost threshold for that target. Targets
3624 /// should assume that the memmove will be done using as many of the largest
3625 /// store operations first, followed by smaller ones, if necessary, per
3626 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
3627 /// with 8-bit alignment would result in nine 1-byte stores. This only
3628 /// applies to copying a constant array of constant size.
3630 /// Likewise for functions with the OptSize attribute.
3632
3633 /// Tells the code generator that select is more expensive than a branch if
3634 /// the branch is usually predicted right.
3636
3637 /// \see enableExtLdPromotion.
3639
3640 /// Return true if the value types that can be represented by the specified
3641 /// register class are all legal.
3642 bool isLegalRC(const TargetRegisterInfo &TRI,
3643 const TargetRegisterClass &RC) const;
3644
3645 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
3646 /// sequence of memory operands that is recognized by PrologEpilogInserter.
3648 MachineBasicBlock *MBB) const;
3649
3651};
3652
3653/// This class defines information used to lower LLVM code to legal SelectionDAG
3654/// operators that the target instruction selector can accept natively.
3655///
3656/// This class also defines callbacks that targets must implement to lower
3657/// target-specific constructs to SelectionDAG operators.
3659public:
3660 struct DAGCombinerInfo;
3661 struct MakeLibCallOptions;
3662
3665
3666 explicit TargetLowering(const TargetMachine &TM);
3667
3668 bool isPositionIndependent() const;
3669
3672 UniformityInfo *UA) const {
3673 return false;
3674 }
3675
3676 // Lets target to control the following reassociation of operands: (op (op x,
3677 // c1), y) -> (op (op x, y), c1) where N0 is (op x, c1) and N1 is y. By
3678 // default consider profitable any case where N0 has single use. This
3679 // behavior reflects the condition replaced by this target hook call in the
3680 // DAGCombiner. Any particular target can implement its own heuristic to
3681 // restrict common combiner.
3683 SDValue N1) const {
3684 return N0.hasOneUse();
3685 }
3686
3687 // Lets target to control the following reassociation of operands: (op (op x,
3688 // c1), y) -> (op (op x, y), c1) where N0 is (op x, c1) and N1 is y. By
3689 // default consider profitable any case where N0 has single use. This
3690 // behavior reflects the condition replaced by this target hook call in the
3691 // combiner. Any particular target can implement its own heuristic to
3692 // restrict common combiner.
3694 Register N1) const {
3695 return MRI.hasOneNonDBGUse(N0);
3696 }
3697
3698 virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
3699 return false;
3700 }
3701
3702 /// Returns true by value, base pointer and offset pointer and addressing mode
3703 /// by reference if the node's address can be legally represented as
3704 /// pre-indexed load / store address.
3705 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
3706 SDValue &/*Offset*/,
3707 ISD::MemIndexedMode &/*AM*/,
3708 SelectionDAG &/*DAG*/) const {
3709 return false;
3710 }
3711
3712 /// Returns true by value, base pointer and offset pointer and addressing mode
3713 /// by reference if this node can be combined with a load / store to form a
3714 /// post-indexed load / store.
3715 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
3716 SDValue &/*Base*/,
3717 SDValue &/*Offset*/,
3718 ISD::MemIndexedMode &/*AM*/,
3719 SelectionDAG &/*DAG*/) const {
3720 return false;
3721 }
3722
3723 /// Returns true if the specified base+offset is a legal indexed addressing
3724 /// mode for this target. \p MI is the load or store instruction that is being
3725 /// considered for transformation.
3727 bool IsPre, MachineRegisterInfo &MRI) const {
3728 return false;
3729 }
3730
3731 /// Return the entry encoding for a jump table in the current function. The
3732 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
3733 virtual unsigned getJumpTableEncoding() const;
3734
3735 virtual const MCExpr *
3737 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
3738 MCContext &/*Ctx*/) const {
3739 llvm_unreachable("Need to implement this hook if target has custom JTIs");
3740 }
3741
3742 /// Returns relocation base for the given PIC jumptable.
3744 SelectionDAG &DAG) const;
3745
3746 /// This returns the relocation base for the given PIC jumptable, the same as
3747 /// getPICJumpTableRelocBase, but as an MCExpr.
3748 virtual const MCExpr *
3750 unsigned JTI, MCContext &Ctx) const;
3751
3752 /// Return true if folding a constant offset with the given GlobalAddress is
3753 /// legal. It is frequently not legal in PIC relocation models.
3754 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
3755
3756 /// On x86, return true if the operand with index OpNo is a CALL or JUMP
3757 /// instruction, which can use either a memory constraint or an address
3758 /// constraint. -fasm-blocks "__asm call foo" lowers to
3759 /// call void asm sideeffect inteldialect "call ${0:P}", "*m..."
3760 ///
3761 /// This function is used by a hack to choose the address constraint,
3762 /// lowering to a direct call.
3763 virtual bool
3765 unsigned OpNo) const {
3766 return false;
3767 }
3768
3770 SDValue &Chain) const;
3771
3772 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
3773 SDValue &NewRHS, ISD::CondCode &CCCode,
3774 const SDLoc &DL, const SDValue OldLHS,
3775 const SDValue OldRHS) const;
3776
3777 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
3778 SDValue &NewRHS, ISD::CondCode &CCCode,
3779 const SDLoc &DL, const SDValue OldLHS,
3780 const SDValue OldRHS, SDValue &Chain,
3781 bool IsSignaling = false) const;
3782
3783 /// Returns a pair of (return value, chain).
3784 /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
3785 std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
3786 EVT RetVT, ArrayRef<SDValue> Ops,
3787 MakeLibCallOptions CallOptions,
3788 const SDLoc &dl,
3789 SDValue Chain = SDValue()) const;
3790
3791 /// Check whether parameters to a call that are passed in callee saved
3792 /// registers are the same as from the calling function. This needs to be
3793 /// checked for tail call eligibility.
3795 const uint32_t *CallerPreservedMask,
3796 const SmallVectorImpl<CCValAssign> &ArgLocs,
3797 const SmallVectorImpl<SDValue> &OutVals) const;
3798
3799 //===--------------------------------------------------------------------===//
3800 // TargetLowering Optimization Methods
3801 //
3802
3803 /// A convenience struct that encapsulates a DAG, and two SDValues for
3804 /// returning information from TargetLowering to its clients that want to
3805 /// combine.
3812
3814 bool LT, bool LO) :
3815 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
3816
3817 bool LegalTypes() const { return LegalTys; }
3818 bool LegalOperations() const { return LegalOps; }
3819
3821 Old = O;
3822 New = N;
3823 return true;
3824 }
3825 };
3826
3827 /// Determines the optimal series of memory ops to replace the memset / memcpy.
3828 /// Return true if the number of memory ops is below the threshold (Limit).
3829 /// Note that this is always the case when Limit is ~0.
3830 /// It returns the types of the sequence of memory ops to perform
3831 /// memset / memcpy by reference.
3832 virtual bool
3833 findOptimalMemOpLowering(std::vector<EVT> &MemOps, unsigned Limit,
3834 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
3835 const AttributeList &FuncAttributes) const;
3836
3837 /// Check to see if the specified operand of the specified instruction is a
3838 /// constant integer. If so, check to see if there are any bits set in the
3839 /// constant that are not demanded. If so, shrink the constant and return
3840 /// true.
3842 const APInt &DemandedElts,
3843 TargetLoweringOpt &TLO) const;
3844
3845 /// Helper wrapper around ShrinkDemandedConstant, demanding all elements.
3847 TargetLoweringOpt &TLO) const;
3848
3849 // Target hook to do target-specific const optimization, which is called by
3850 // ShrinkDemandedConstant. This function should return true if the target
3851 // doesn't want ShrinkDemandedConstant to further optimize the constant.
3853 const APInt &DemandedBits,
3854 const APInt &DemandedElts,
3855 TargetLoweringOpt &TLO) const {
3856 return false;
3857 }
3858
3859 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
3860 /// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast,
3861 /// but it could be generalized for targets with other types of implicit
3862 /// widening casts.
3863 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
3864 const APInt &DemandedBits,
3865 TargetLoweringOpt &TLO) const;
3866
3867 /// Look at Op. At this point, we know that only the DemandedBits bits of the
3868 /// result of Op are ever used downstream. If we can use this information to
3869 /// simplify Op, create a new simplified DAG node and return true, returning
3870 /// the original and new nodes in Old and New. Otherwise, analyze the
3871 /// expression and return a mask of KnownOne and KnownZero bits for the
3872 /// expression (used to simplify the caller). The KnownZero/One bits may only
3873 /// be accurate for those bits in the Demanded masks.
3874 /// \p AssumeSingleUse When this parameter is true, this function will
3875 /// attempt to simplify \p Op even if there are multiple uses.
3876 /// Callers are responsible for correctly updating the DAG based on the
3877 /// results of this function, because simply replacing TLO.Old
3878 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
3879 /// has multiple uses.
3881 const APInt &DemandedElts, KnownBits &Known,
3882 TargetLoweringOpt &TLO, unsigned Depth = 0,
3883 bool AssumeSingleUse = false) const;
3884
3885 /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
3886 /// Adds Op back to the worklist upon success.
3888 KnownBits &Known, TargetLoweringOpt &TLO,
3889 unsigned Depth = 0,
3890 bool AssumeSingleUse = false) const;
3891
3892 /// Helper wrapper around SimplifyDemandedBits.
3893 /// Adds Op back to the worklist upon success.
3895 DAGCombinerInfo &DCI) const;
3896
3897 /// Helper wrapper around SimplifyDemandedBits.
3898 /// Adds Op back to the worklist upon success.
3900 const APInt &DemandedElts,
3901 DAGCombinerInfo &DCI) const;
3902
3903 /// More limited version of SimplifyDemandedBits that can be used to "look
3904 /// through" ops that don't contribute to the DemandedBits/DemandedElts -
3905 /// bitwise ops etc.
3907 const APInt &DemandedElts,
3908 SelectionDAG &DAG,
3909 unsigned Depth = 0) const;
3910
3911 /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
3912 /// elements.
3914 SelectionDAG &DAG,
3915 unsigned Depth = 0) const;
3916
3917 /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
3918 /// bits from only some vector elements.
3920 const APInt &DemandedElts,
3921 SelectionDAG &DAG,
3922 unsigned Depth = 0) const;
3923
3924 /// Look at Vector Op. At this point, we know that only the DemandedElts
3925 /// elements of the result of Op are ever used downstream. If we can use
3926 /// this information to simplify Op, create a new simplified DAG node and
3927 /// return true, storing the original and new nodes in TLO.
3928 /// Otherwise, analyze the expression and return a mask of KnownUndef and
3929 /// KnownZero elements for the expression (used to simplify the caller).
3930 /// The KnownUndef/Zero elements may only be accurate for those bits
3931 /// in the DemandedMask.
3932 /// \p AssumeSingleUse When this parameter is true, this function will
3933 /// attempt to simplify \p Op even if there are multiple uses.
3934 /// Callers are responsible for correctly updating the DAG based on the
3935 /// results of this function, because simply replacing TLO.Old
3936 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
3937 /// has multiple uses.
3938 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask,
3939 APInt &KnownUndef, APInt &KnownZero,
3940 TargetLoweringOpt &TLO, unsigned Depth = 0,
3941 bool AssumeSingleUse = false) const;
3942
3943 /// Helper wrapper around SimplifyDemandedVectorElts.
3944 /// Adds Op back to the worklist upon success.
3945 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
3946 DAGCombinerInfo &DCI) const;
3947
3948 /// Return true if the target supports simplifying demanded vector elements by
3949 /// converting them to undefs.
3950 virtual bool
3952 const TargetLoweringOpt &TLO) const {
3953 return true;
3954 }
3955
3956 /// Determine which of the bits specified in Mask are known to be either zero
3957 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3958 /// argument allows us to only collect the known bits that are shared by the
3959 /// requested vector elements.
3960 virtual void computeKnownBitsForTargetNode(const SDValue Op,
3961 KnownBits &Known,
3962 const APInt &DemandedElts,
3963 const SelectionDAG &DAG,
3964 unsigned Depth = 0) const;
3965
3966 /// Determine which of the bits specified in Mask are known to be either zero
3967 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3968 /// argument allows us to only collect the known bits that are shared by the
3969 /// requested vector elements. This is for GISel.
3971 Register R, KnownBits &Known,
3972 const APInt &DemandedElts,
3973 const MachineRegisterInfo &MRI,
3974 unsigned Depth = 0) const;
3975
3976 /// Determine the known alignment for the pointer value \p R. This is can
3977 /// typically be inferred from the number of low known 0 bits. However, for a
3978 /// pointer with a non-integral address space, the alignment value may be
3979 /// independent from the known low bits.
3981 Register R,
3982 const MachineRegisterInfo &MRI,
3983 unsigned Depth = 0) const;
3984
3985 /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
3986 /// Default implementation computes low bits based on alignment
3987 /// information. This should preserve known bits passed into it.
3988 virtual void computeKnownBitsForFrameIndex(int FIOp,
3989 KnownBits &Known,
3990 const MachineFunction &MF) const;
3991
3992 /// This method can be implemented by targets that want to expose additional
3993 /// information about sign bits to the DAG Combiner. The DemandedElts
3994 /// argument allows us to only collect the minimum sign bits that are shared
3995 /// by the requested vector elements.
3997 const APInt &DemandedElts,
3998 const SelectionDAG &DAG,
3999 unsigned Depth = 0) const;
4000
4001 /// This method can be implemented by targets that want to expose additional
4002 /// information about sign bits to GlobalISel combiners. The DemandedElts
4003 /// argument allows us to only collect the minimum sign bits that are shared
4004 /// by the requested vector elements.
4006 Register R,
4007 const APInt &DemandedElts,
4008 const MachineRegisterInfo &MRI,
4009 unsigned Depth = 0) const;
4010
4011 /// Attempt to simplify any target nodes based on the demanded vector
4012 /// elements, returning true on success. Otherwise, analyze the expression and
4013 /// return a mask of KnownUndef and KnownZero elements for the expression
4014 /// (used to simplify the caller). The KnownUndef/Zero elements may only be
4015 /// accurate for those bits in the DemandedMask.
4017 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef,
4018 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth = 0) const;
4019
4020 /// Attempt to simplify any target nodes based on the demanded bits/elts,
4021 /// returning true on success. Otherwise, analyze the
4022 /// expression and return a mask of KnownOne and KnownZero bits for the
4023 /// expression (used to simplify the caller). The KnownZero/One bits may only
4024 /// be accurate for those bits in the Demanded masks.
4026 const APInt &DemandedBits,
4027 const APInt &DemandedElts,
4028 KnownBits &Known,
4029 TargetLoweringOpt &TLO,
4030 unsigned Depth = 0) const;
4031
4032 /// More limited version of SimplifyDemandedBits that can be used to "look
4033 /// through" ops that don't contribute to the DemandedBits/DemandedElts -
4034 /// bitwise ops etc.
4036 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4037 SelectionDAG &DAG, unsigned Depth) const;
4038
4039 /// Return true if this function can prove that \p Op is never poison
4040 /// and, if \p PoisonOnly is false, does not have undef bits. The DemandedElts
4041 /// argument limits the check to the requested vector elements.
4043 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4044 bool PoisonOnly, unsigned Depth) const;
4045
4046 /// Return true if Op can create undef or poison from non-undef & non-poison
4047 /// operands. The DemandedElts argument limits the check to the requested
4048 /// vector elements.
4049 virtual bool
4051 const SelectionDAG &DAG, bool PoisonOnly,
4052 bool ConsiderFlags, unsigned Depth) const;
4053
4054 /// Tries to build a legal vector shuffle using the provided parameters
4055 /// or equivalent variations. The Mask argument maybe be modified as the
4056 /// function tries different variations.
4057 /// Returns an empty SDValue if the operation fails.
4060 SelectionDAG &DAG) const;
4061
4062 /// This method returns the constant pool value that will be loaded by LD.
4063 /// NOTE: You must check for implicit extensions of the constant by LD.
4064 virtual const Constant *getTargetConstantFromLoad(LoadSDNode *LD) const;
4065
4066 /// If \p SNaN is false, \returns true if \p Op is known to never be any
4067 /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
4068 /// NaN.
4070 const SelectionDAG &DAG,
4071 bool SNaN = false,
4072 unsigned Depth = 0) const;
4073
4074 /// Return true if vector \p Op has the same value across all \p DemandedElts,
4075 /// indicating any elements which may be undef in the output \p UndefElts.
4076 virtual bool isSplatValueForTargetNode(SDValue Op, const APInt &DemandedElts,
4077 APInt &UndefElts,
4078 const SelectionDAG &DAG,
4079 unsigned Depth = 0) const;
4080
4081 /// Returns true if the given Opc is considered a canonical constant for the
4082 /// target, which should not be transformed back into a BUILD_VECTOR.
4084 return Op.getOpcode() == ISD::SPLAT_VECTOR ||
4085 Op.getOpcode() == ISD::SPLAT_VECTOR_PARTS;
4086 }
4087
4089 void *DC; // The DAG Combiner object.
4092
4093 public:
4095
4096 DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
4097 : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
4098
4099 bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
4100 bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
4101 bool isAfterLegalizeDAG() const { return Level >= AfterLegalizeDAG; }
4104
4105 void AddToWorklist(SDNode *N);
4106 SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
4107 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
4108 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
4109
4111
4113 };
4114
4115 /// Return if the N is a constant or constant vector equal to the true value
4116 /// from getBooleanContents().
4117 bool isConstTrueVal(SDValue N) const;
4118
4119 /// Return if the N is a constant or constant vector equal to the false value
4120 /// from getBooleanContents().
4121 bool isConstFalseVal(SDValue N) const;
4122
4123 /// Return if \p N is a True value when extended to \p VT.
4124 bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const;
4125
4126 /// Try to simplify a setcc built with the specified operands and cc. If it is
4127 /// unable to simplify it, return a null SDValue.
4129 bool foldBooleans, DAGCombinerInfo &DCI,
4130 const SDLoc &dl) const;
4131
4132 // For targets which wrap address, unwrap for analysis.
4133 virtual SDValue unwrapAddress(SDValue N) const { return N; }
4134
4135 /// Returns true (and the GlobalValue and the offset) if the node is a
4136 /// GlobalAddress + offset.
4137 virtual bool
4138 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
4139
4140 /// This method will be invoked for all target nodes and for any
4141 /// target-independent nodes that the target has registered with invoke it
4142 /// for.
4143 ///
4144 /// The semantics are as follows:
4145 /// Return Value:
4146 /// SDValue.Val == 0 - No change was made
4147 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
4148 /// otherwise - N should be replaced by the returned Operand.
4149 ///
4150 /// In addition, methods provided by DAGCombinerInfo may be used to perform
4151 /// more complex transformations.
4152 ///
4153 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
4154
4155 /// Return true if it is profitable to move this shift by a constant amount
4156 /// through its operand, adjusting any immediate operands as necessary to
4157 /// preserve semantics. This transformation may not be desirable if it
4158 /// disrupts a particularly auspicious target-specific tree (e.g. bitfield
4159 /// extraction in AArch64). By default, it returns true.
4160 ///
4161 /// @param N the shift node
4162 /// @param Level the current DAGCombine legalization level.
4164 CombineLevel Level) const {
4165 return true;
4166 }
4167
4168 /// GlobalISel - return true if it is profitable to move this shift by a
4169 /// constant amount through its operand, adjusting any immediate operands as
4170 /// necessary to preserve semantics. This transformation may not be desirable
4171 /// if it disrupts a particularly auspicious target-specific tree (e.g.
4172 /// bitfield extraction in AArch64). By default, it returns true.
4173 ///
4174 /// @param MI the shift instruction
4175 /// @param IsAfterLegal true if running after legalization.
4177 bool IsAfterLegal) const {
4178 return true;
4179 }
4180
4181 /// GlobalISel - return true if it's profitable to perform the combine:
4182 /// shl ([sza]ext x), y => zext (shl x, y)
4183 virtual bool isDesirableToPullExtFromShl(const MachineInstr &MI) const {
4184 return true;
4185 }
4186
4187 // Return AndOrSETCCFoldKind::{AddAnd, ABS} if its desirable to try and
4188 // optimize LogicOp(SETCC0, SETCC1). An example (what is implemented as of
4189 // writing this) is:
4190 // With C as a power of 2 and C != 0 and C != INT_MIN:
4191 // AddAnd:
4192 // (icmp eq A, C) | (icmp eq A, -C)
4193 // -> (icmp eq and(add(A, C), ~(C + C)), 0)
4194 // (icmp ne A, C) & (icmp ne A, -C)w
4195 // -> (icmp ne and(add(A, C), ~(C + C)), 0)
4196 // ABS:
4197 // (icmp eq A, C) | (icmp eq A, -C)
4198 // -> (icmp eq Abs(A), C)
4199 // (icmp ne A, C) & (icmp ne A, -C)w
4200 // -> (icmp ne Abs(A), C)
4201 //
4202 // @param LogicOp the logic op
4203 // @param SETCC0 the first of the SETCC nodes
4204 // @param SETCC0 the second of the SETCC nodes
4206 const SDNode *LogicOp, const SDNode *SETCC0, const SDNode *SETCC1) const {
4208 }
4209
4210 /// Return true if it is profitable to combine an XOR of a logical shift
4211 /// to create a logical shift of NOT. This transformation may not be desirable
4212 /// if it disrupts a particularly auspicious target-specific tree (e.g.
4213 /// BIC on ARM/AArch64). By default, it returns true.
4214 virtual bool isDesirableToCommuteXorWithShift(const SDNode *N) const {
4215 return true;
4216 }
4217
4218 /// Return true if the target has native support for the specified value type
4219 /// and it is 'desirable' to use the type for the given node type. e.g. On x86
4220 /// i16 is legal, but undesirable since i16 instruction encodings are longer
4221 /// and some i16 instructions are slow.
4222 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
4223 // By default, assume all legal types are desirable.
4224 return isTypeLegal(VT);
4225 }
4226
4227 /// Return true if it is profitable for dag combiner to transform a floating
4228 /// point op of specified opcode to a equivalent op of an integer
4229 /// type. e.g. f32 load -> i32 load can be profitable on ARM.
4230 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
4231 EVT /*VT*/) const {
4232 return false;
4233 }
4234
4235 /// This method query the target whether it is beneficial for dag combiner to
4236 /// promote the specified node. If true, it should return the desired
4237 /// promotion type by reference.
4238 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
4239 return false;
4240 }
4241
4242 /// Return true if the target supports swifterror attribute. It optimizes
4243 /// loads and stores to reading and writing a specific register.
4244 virtual bool supportSwiftError() const {
4245 return false;
4246 }
4247
4248 /// Return true if the target supports that a subset of CSRs for the given
4249 /// machine function is handled explicitly via copies.
4250 virtual bool supportSplitCSR(MachineFunction *MF) const {
4251 return false;
4252 }
4253
4254 /// Return true if the target supports kcfi operand bundles.
4255 virtual bool supportKCFIBundles() const { return false; }
4256
4257 /// Perform necessary initialization to handle a subset of CSRs explicitly
4258 /// via copies. This function is called at the beginning of instruction
4259 /// selection.
4260 virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
4261 llvm_unreachable("Not Implemented");
4262 }
4263
4264 /// Insert explicit copies in entry and exit blocks. We copy a subset of
4265 /// CSRs to virtual registers in the entry block, and copy them back to
4266 /// physical registers in the exit blocks. This function is called at the end
4267 /// of instruction selection.
4269 MachineBasicBlock *Entry,
4270 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
4271 llvm_unreachable("Not Implemented");
4272 }
4273
4274 /// Return the newly negated expression if the cost is not expensive and
4275 /// set the cost in \p Cost to indicate that if it is cheaper or neutral to
4276 /// do the negation.
4278 bool LegalOps, bool OptForSize,
4280 unsigned Depth = 0) const;
4281
4283 SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize,
4285 unsigned Depth = 0) const {
4287 SDValue Neg =
4288 getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
4289 if (!Neg)
4290 return SDValue();
4291
4292 if (Cost <= CostThreshold)
4293 return Neg;
4294
4295 // Remove the new created node to avoid the side effect to the DAG.
4296 if (Neg->use_empty())
4297 DAG.RemoveDeadNode(Neg.getNode());
4298 return SDValue();
4299 }
4300
4301 /// This is the helper function to return the newly negated expression only
4302 /// when the cost is cheaper.
4304 bool LegalOps, bool OptForSize,
4305 unsigned Depth = 0) const {
4306 return getCheaperOrNeutralNegatedExpression(Op, DAG, LegalOps, OptForSize,
4308 }
4309
4310 /// This is the helper function to return the newly negated expression if
4311 /// the cost is not expensive.
4313 bool OptForSize, unsigned Depth = 0) const {
4315 return getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
4316 }
4317
4318 //===--------------------------------------------------------------------===//
4319 // Lowering methods - These methods must be implemented by targets so that
4320 // the SelectionDAGBuilder code knows how to lower these.
4321 //
4322
4323 /// Target-specific splitting of values into parts that fit a register
4324 /// storing a legal type
4326 SelectionDAG & DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4327 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4328 return false;
4329 }
4330
4331 /// Allows the target to handle physreg-carried dependency
4332 /// in target-specific way. Used from the ScheduleDAGSDNodes to decide whether
4333 /// to add the edge to the dependency graph.
4334 /// Def - input: Selection DAG node defininfg physical register
4335 /// User - input: Selection DAG node using physical register
4336 /// Op - input: Number of User operand
4337 /// PhysReg - inout: set to the physical register if the edge is
4338 /// necessary, unchanged otherwise
4339 /// Cost - inout: physical register copy cost.
4340 /// Returns 'true' is the edge is necessary, 'false' otherwise
4341 virtual bool checkForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
4342 const TargetRegisterInfo *TRI,
4343 const TargetInstrInfo *TII,
4344 unsigned &PhysReg, int &Cost) const {
4345 return false;
4346 }
4347
4348 /// Target-specific combining of register parts into its original value
4349 virtual SDValue
4351 const SDValue *Parts, unsigned NumParts,
4352 MVT PartVT, EVT ValueVT,
4353 std::optional<CallingConv::ID> CC) const {
4354 return SDValue();
4355 }
4356
4357 /// This hook must be implemented to lower the incoming (formal) arguments,
4358 /// described by the Ins array, into the specified DAG. The implementation
4359 /// should fill in the InVals array with legal-type argument values, and
4360 /// return the resulting token chain value.
4362 SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
4363 const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
4364 SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
4365 llvm_unreachable("Not Implemented");
4366 }
4367
4368 /// This structure contains all information that is necessary for lowering
4369 /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
4370 /// needs to lower a call, and targets will see this struct in their LowerCall
4371 /// implementation.
4374 Type *RetTy = nullptr;
4375 bool RetSExt : 1;
4376 bool RetZExt : 1;
4377 bool IsVarArg : 1;
4378 bool IsInReg : 1;
4384 bool NoMerge : 1;
4385
4386 // IsTailCall should be modified by implementations of
4387 // TargetLowering::LowerCall that perform tail call conversions.
4388 bool IsTailCall = false;
4389
4390 // Is Call lowering done post SelectionDAG type legalization.
4392
4393 unsigned NumFixedArgs = -1;