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