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