Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/include/llvm/CodeGen/TargetLowering.h
Line
Count
Source (jump to first uncovered line)
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"
28
#include "llvm/ADT/STLExtras.h"
29
#include "llvm/ADT/SmallVector.h"
30
#include "llvm/ADT/StringRef.h"
31
#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
32
#include "llvm/CodeGen/DAGCombine.h"
33
#include "llvm/CodeGen/ISDOpcodes.h"
34
#include "llvm/CodeGen/RuntimeLibcalls.h"
35
#include "llvm/CodeGen/SelectionDAG.h"
36
#include "llvm/CodeGen/SelectionDAGNodes.h"
37
#include "llvm/CodeGen/TargetCallingConv.h"
38
#include "llvm/CodeGen/ValueTypes.h"
39
#include "llvm/IR/Attributes.h"
40
#include "llvm/IR/CallSite.h"
41
#include "llvm/IR/CallingConv.h"
42
#include "llvm/IR/DataLayout.h"
43
#include "llvm/IR/DerivedTypes.h"
44
#include "llvm/IR/Function.h"
45
#include "llvm/IR/IRBuilder.h"
46
#include "llvm/IR/InlineAsm.h"
47
#include "llvm/IR/Instruction.h"
48
#include "llvm/IR/Instructions.h"
49
#include "llvm/IR/Type.h"
50
#include "llvm/MC/MCRegisterInfo.h"
51
#include "llvm/Support/AtomicOrdering.h"
52
#include "llvm/Support/Casting.h"
53
#include "llvm/Support/ErrorHandling.h"
54
#include "llvm/Support/MachineValueType.h"
55
#include "llvm/Target/TargetMachine.h"
56
#include <algorithm>
57
#include <cassert>
58
#include <climits>
59
#include <cstdint>
60
#include <iterator>
61
#include <map>
62
#include <string>
63
#include <utility>
64
#include <vector>
65
66
namespace llvm {
67
68
class BranchProbability;
69
class CCState;
70
class CCValAssign;
71
class Constant;
72
class FastISel;
73
class FunctionLoweringInfo;
74
class GlobalValue;
75
class IntrinsicInst;
76
struct KnownBits;
77
class LLVMContext;
78
class MachineBasicBlock;
79
class MachineFunction;
80
class MachineInstr;
81
class MachineJumpTableInfo;
82
class MachineLoop;
83
class MachineRegisterInfo;
84
class MCContext;
85
class MCExpr;
86
class Module;
87
class TargetRegisterClass;
88
class TargetLibraryInfo;
89
class TargetRegisterInfo;
90
class Value;
91
92
namespace Sched {
93
94
  enum Preference {
95
    None,             // No preference
96
    Source,           // Follow source order.
97
    RegPressure,      // Scheduling for lowest register pressure.
98
    Hybrid,           // Scheduling for both latency and register pressure.
99
    ILP,              // Scheduling for ILP in low register pressure mode.
100
    VLIW              // Scheduling for VLIW targets.
101
  };
102
103
} // end namespace Sched
104
105
/// This base class for TargetLowering contains the SelectionDAG-independent
106
/// parts that can be used from the rest of CodeGen.
107
class TargetLoweringBase {
108
public:
109
  /// This enum indicates whether operations are valid for a target, and if not,
110
  /// what action should be used to make them valid.
111
  enum LegalizeAction : uint8_t {
112
    Legal,      // The target natively supports this operation.
113
    Promote,    // This operation should be executed in a larger type.
114
    Expand,     // Try to expand this to other ops, otherwise use a libcall.
115
    LibCall,    // Don't try to expand this to other ops, always use a libcall.
116
    Custom      // Use the LowerOperation hook to implement custom lowering.
117
  };
118
119
  /// This enum indicates whether a types are legal for a target, and if not,
120
  /// what action should be used to make them valid.
121
  enum LegalizeTypeAction : uint8_t {
122
    TypeLegal,           // The target natively supports this type.
123
    TypePromoteInteger,  // Replace this integer with a larger one.
124
    TypeExpandInteger,   // Split this integer into two of half the size.
125
    TypeSoftenFloat,     // Convert this float to a same size integer type,
126
                         // if an operation is not supported in target HW.
127
    TypeExpandFloat,     // Split this float into two of half the size.
128
    TypeScalarizeVector, // Replace this one-element vector with its element.
129
    TypeSplitVector,     // Split this vector into two of half the size.
130
    TypeWidenVector,     // This vector should be widened into a larger vector.
131
    TypePromoteFloat     // Replace this float with a larger one.
132
  };
133
134
  /// LegalizeKind holds the legalization kind that needs to happen to EVT
135
  /// in order to type-legalize it.
136
  using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
137
138
  /// Enum that describes how the target represents true/false values.
139
  enum BooleanContent {
140
    UndefinedBooleanContent,    // Only bit 0 counts, the rest can hold garbage.
141
    ZeroOrOneBooleanContent,        // All bits zero except for bit 0.
142
    ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
143
  };
144
145
  /// Enum that describes what type of support for selects the target has.
146
  enum SelectSupportKind {
147
    ScalarValSelect,      // The target supports scalar selects (ex: cmov).
148
    ScalarCondVectorVal,  // The target supports selects with a scalar condition
149
                          // and vector values (ex: cmov).
150
    VectorMaskSelect      // The target supports vector selects with a vector
151
                          // mask (ex: x86 blends).
152
  };
153
154
  /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
155
  /// to, if at all. Exists because different targets have different levels of
156
  /// support for these atomic instructions, and also have different options
157
  /// w.r.t. what they should expand to.
158
  enum class AtomicExpansionKind {
159
    None,    // Don't expand the instruction.
160
    LLSC,    // Expand the instruction into loadlinked/storeconditional; used
161
             // by ARM/AArch64.
162
    LLOnly,  // Expand the (load) instruction into just a load-linked, which has
163
             // greater atomic guarantees than a normal load.
164
    CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
165
    MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
166
  };
167
168
  /// Enum that specifies when a multiplication should be expanded.
169
  enum class MulExpansionKind {
170
    Always,            // Always expand the instruction.
171
    OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
172
                       // or custom.
173
  };
174
175
  class ArgListEntry {
176
  public:
177
    Value *Val = nullptr;
178
    SDValue Node = SDValue();
179
    Type *Ty = nullptr;
180
    bool IsSExt : 1;
181
    bool IsZExt : 1;
182
    bool IsInReg : 1;
183
    bool IsSRet : 1;
184
    bool IsNest : 1;
185
    bool IsByVal : 1;
186
    bool IsInAlloca : 1;
187
    bool IsReturned : 1;
188
    bool IsSwiftSelf : 1;
189
    bool IsSwiftError : 1;
190
    uint16_t Alignment = 0;
191
    Type *ByValType = nullptr;
192
193
    ArgListEntry()
194
        : IsSExt(false), IsZExt(false), IsInReg(false), IsSRet(false),
195
          IsNest(false), IsByVal(false), IsInAlloca(false), IsReturned(false),
196
1.02M
          IsSwiftSelf(false), IsSwiftError(false) {}
197
198
    void setAttributes(const CallBase *Call, unsigned ArgIdx);
199
200
1.00M
    void setAttributes(ImmutableCallSite *CS, unsigned ArgIdx) {
201
1.00M
      return setAttributes(cast<CallBase>(CS->getInstruction()), ArgIdx);
202
1.00M
    }
203
  };
204
  using ArgListTy = std::vector<ArgListEntry>;
205
206
  virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
207
15.8k
                                     ArgListTy &Args) const {};
208
209
254k
  static ISD::NodeType getExtendForContent(BooleanContent Content) {
210
254k
    switch (Content) {
211
254k
    case UndefinedBooleanContent:
212
107
      // Extend by adding rubbish bits.
213
107
      return ISD::ANY_EXTEND;
214
254k
    case ZeroOrOneBooleanContent:
215
252k
      // Extend by adding zero bits.
216
252k
      return ISD::ZERO_EXTEND;
217
254k
    case ZeroOrNegativeOneBooleanContent:
218
2.41k
      // Extend by copying the sign bit.
219
2.41k
      return ISD::SIGN_EXTEND;
220
0
    }
221
0
    llvm_unreachable("Invalid content kind");
222
0
  }
223
224
  /// NOTE: The TargetMachine owns TLOF.
225
  explicit TargetLoweringBase(const TargetMachine &TM);
226
  TargetLoweringBase(const TargetLoweringBase &) = delete;
227
  TargetLoweringBase &operator=(const TargetLoweringBase &) = delete;
228
40.4k
  virtual ~TargetLoweringBase() = default;
229
230
protected:
231
  /// Initialize all of the actions to default values.
232
  void initActions();
233
234
public:
235
12.8M
  const TargetMachine &getTargetMachine() const { return TM; }
236
237
3.19M
  virtual bool useSoftFloat() const { return false; }
238
239
  /// Return the pointer type for the given address space, defaults to
240
  /// the pointer type from the data layout.
241
  /// FIXME: The default needs to be removed once all the code is updated.
242
26.8M
  virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
243
26.8M
    return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
244
26.8M
  }
245
246
  /// Return the in-memory pointer type for the given address space, defaults to
247
  /// the pointer type from the data layout.  FIXME: The default needs to be
248
  /// removed once all the code is updated.
249
1.62M
  MVT getPointerMemTy(const DataLayout &DL, uint32_t AS = 0) const {
250
1.62M
    return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
251
1.62M
  }
252
253
  /// Return the type for frame index, which is determined by
254
  /// the alloca address space specified through the data layout.
255
262k
  MVT getFrameIndexTy(const DataLayout &DL) const {
256
262k
    return getPointerTy(DL, DL.getAllocaAddrSpace());
257
262k
  }
258
259
  /// Return the type for operands of fence.
260
  /// TODO: Let fence operands be of i32 type and remove this.
261
8.02k
  virtual MVT getFenceOperandTy(const DataLayout &DL) const {
262
8.02k
    return getPointerTy(DL);
263
8.02k
  }
264
265
  /// EVT is not used in-tree, but is used by out-of-tree target.
266
  /// A documentation for this function would be nice...
267
  virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
268
269
  EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
270
                       bool LegalTypes = true) const;
271
272
  /// Returns the type to be used for the index operand of:
273
  /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
274
  /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
275
339k
  virtual MVT getVectorIdxTy(const DataLayout &DL) const {
276
339k
    return getPointerTy(DL);
277
339k
  }
278
279
257k
  virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
280
257k
    return true;
281
257k
  }
282
283
  /// Return true if it is profitable to convert a select of FP constants into
284
  /// a constant pool load whose address depends on the select condition. The
285
  /// parameter may be used to differentiate a select with FP compare from
286
  /// integer compare.
287
92.4k
  virtual bool reduceSelectOfFPConstantLoads(bool IsFPSetCC) const {
288
92.4k
    return true;
289
92.4k
  }
290
291
  /// Return true if multiple condition registers are available.
292
3.68M
  bool hasMultipleConditionRegisters() const {
293
3.68M
    return HasMultipleConditionRegisters;
294
3.68M
  }
295
296
  /// Return true if the target has BitExtract instructions.
297
193k
  bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
298
299
  /// Return the preferred vector type legalization action.
300
  virtual TargetLoweringBase::LegalizeTypeAction
301
4.93M
  getPreferredVectorAction(MVT VT) const {
302
4.93M
    // The default action for one element vectors is to scalarize
303
4.93M
    if (VT.getVectorNumElements() == 1)
304
685k
      return TypeScalarizeVector;
305
4.24M
    // The default action for an odd-width vector is to widen.
306
4.24M
    if (!VT.isPow2VectorType())
307
181k
      return TypeWidenVector;
308
4.06M
    // The default action for other vectors is to promote
309
4.06M
    return TypePromoteInteger;
310
4.06M
  }
311
312
  // There are two general methods for expanding a BUILD_VECTOR node:
313
  //  1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
314
  //     them together.
315
  //  2. Build the vector on the stack and then load it.
316
  // If this function returns true, then method (1) will be used, subject to
317
  // the constraint that all of the necessary shuffles are legal (as determined
318
  // by isShuffleMaskLegal). If this function returns false, then method (2) is
319
  // always used. The vector type, and the number of defined values, are
320
  // provided.
321
  virtual bool
322
  shouldExpandBuildVectorWithShuffles(EVT /* VT */,
323
2.44k
                                      unsigned DefinedValues) const {
324
2.44k
    return DefinedValues < 3;
325
2.44k
  }
326
327
  /// Return true if integer divide is usually cheaper than a sequence of
328
  /// several shifts, adds, and multiplies for this target.
329
  /// The definition of "cheaper" may depend on whether we're optimizing
330
  /// for speed or for size.
331
1.30k
  virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
332
333
  /// Return true if the target can handle a standalone remainder operation.
334
0
  virtual bool hasStandaloneRem(EVT VT) const {
335
0
    return true;
336
0
  }
337
338
  /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
339
182
  virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
340
182
    // Default behavior is to replace SQRT(X) with X*RSQRT(X).
341
182
    return false;
342
182
  }
343
344
  /// Reciprocal estimate status values used by the functions below.
345
  enum ReciprocalEstimate : int {
346
    Unspecified = -1,
347
    Disabled = 0,
348
    Enabled = 1
349
  };
350
351
  /// Return a ReciprocalEstimate enum value for a square root of the given type
352
  /// based on the function's attributes. If the operation is not overridden by
353
  /// the function's attributes, "Unspecified" is returned and target defaults
354
  /// are expected to be used for instruction selection.
355
  int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const;
356
357
  /// Return a ReciprocalEstimate enum value for a division of the given type
358
  /// based on the function's attributes. If the operation is not overridden by
359
  /// the function's attributes, "Unspecified" is returned and target defaults
360
  /// are expected to be used for instruction selection.
361
  int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const;
362
363
  /// Return the refinement step count for a square root of the given type based
364
  /// on the function's attributes. If the operation is not overridden by
365
  /// the function's attributes, "Unspecified" is returned and target defaults
366
  /// are expected to be used for instruction selection.
367
  int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
368
369
  /// Return the refinement step count for a division of the given type based
370
  /// on the function's attributes. If the operation is not overridden by
371
  /// the function's attributes, "Unspecified" is returned and target defaults
372
  /// are expected to be used for instruction selection.
373
  int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
374
375
  /// Returns true if target has indicated at least one type should be bypassed.
376
486k
  bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
377
378
  /// Returns map of slow types for division or remainder with corresponding
379
  /// fast types
380
11.6k
  const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
381
11.6k
    return BypassSlowDivWidths;
382
11.6k
  }
383
384
  /// Return true if Flow Control is an expensive operation that should be
385
  /// avoided.
386
48.6k
  bool isJumpExpensive() const { return JumpIsExpensive; }
387
388
  /// Return true if selects are only cheaper than branches if the branch is
389
  /// unlikely to be predicted right.
390
268k
  bool isPredictableSelectExpensive() const {
391
268k
    return PredictableSelectIsExpensive;
392
268k
  }
393
394
  /// If a branch or a select condition is skewed in one direction by more than
395
  /// this factor, it is very likely to be predicted correctly.
396
  virtual BranchProbability getPredictableBranchThreshold() const;
397
398
  /// Return true if the following transform is beneficial:
399
  /// fold (conv (load x)) -> (load (conv*)x)
400
  /// On architectures that don't natively support some vector loads
401
  /// efficiently, casting the load to a smaller vector of larger types and
402
  /// loading is more efficient, however, this can be undone by optimizations in
403
  /// dag combiner.
404
  virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
405
                                       const SelectionDAG &DAG,
406
6.45k
                                       const MachineMemOperand &MMO) const {
407
6.45k
    // Don't do if we could do an indexed load on the original type, but not on
408
6.45k
    // the new one.
409
6.45k
    if (!LoadVT.isSimple() || 
!BitcastVT.isSimple()6.38k
)
410
86
      return true;
411
6.36k
412
6.36k
    MVT LoadMVT = LoadVT.getSimpleVT();
413
6.36k
414
6.36k
    // Don't bother doing this if it's just going to be promoted again later, as
415
6.36k
    // doing so might interfere with other combines.
416
6.36k
    if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
417
6.36k
        
getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT()374
)
418
248
      return false;
419
6.11k
420
6.11k
    bool Fast = false;
421
6.11k
    return allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), BitcastVT,
422
6.11k
                              MMO, &Fast) && 
Fast6.01k
;
423
6.11k
  }
424
425
  /// Return true if the following transform is beneficial:
426
  /// (store (y (conv x)), y*)) -> (store x, (x*))
427
  virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT,
428
                                        const SelectionDAG &DAG,
429
19.0k
                                        const MachineMemOperand &MMO) const {
430
19.0k
    // Default to the same logic as loads.
431
19.0k
    return isLoadBitCastBeneficial(StoreVT, BitcastVT, DAG, MMO);
432
19.0k
  }
433
434
  /// Return true if it is expected to be cheaper to do a store of a non-zero
435
  /// vector constant with the given size and type for the address space than to
436
  /// store the individual scalar element constants.
437
  virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
438
                                            unsigned NumElem,
439
79.1k
                                            unsigned AddrSpace) const {
440
79.1k
    return false;
441
79.1k
  }
442
443
  /// Allow store merging for the specified type after legalization in addition
444
  /// to before legalization. This may transform stores that do not exist
445
  /// earlier (for example, stores created from intrinsics).
446
1.00M
  virtual bool mergeStoresAfterLegalization(EVT MemVT) const {
447
1.00M
    return true;
448
1.00M
  }
449
450
  /// Returns if it's reasonable to merge stores to MemVT size.
451
  virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
452
7.71k
                                const SelectionDAG &DAG) const {
453
7.71k
    return true;
454
7.71k
  }
455
456
  /// Return true if it is cheap to speculate a call to intrinsic cttz.
457
20
  virtual bool isCheapToSpeculateCttz() const {
458
20
    return false;
459
20
  }
460
461
  /// Return true if it is cheap to speculate a call to intrinsic ctlz.
462
2
  virtual bool isCheapToSpeculateCtlz() const {
463
2
    return false;
464
2
  }
465
466
  /// Return true if ctlz instruction is fast.
467
0
  virtual bool isCtlzFast() const {
468
0
    return false;
469
0
  }
470
471
  /// Return true if it is safe to transform an integer-domain bitwise operation
472
  /// into the equivalent floating-point operation. This should be set to true
473
  /// if the target has IEEE-754-compliant fabs/fneg operations for the input
474
  /// type.
475
24.6k
  virtual bool hasBitPreservingFPLogic(EVT VT) const {
476
24.6k
    return false;
477
24.6k
  }
478
479
  /// Return true if it is cheaper to split the store of a merged int val
480
  /// from a pair of smaller values into multiple stores.
481
430
  virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
482
430
    return false;
483
430
  }
484
485
  /// Return if the target supports combining a
486
  /// chain like:
487
  /// \code
488
  ///   %andResult = and %val1, #mask
489
  ///   %icmpResult = icmp %andResult, 0
490
  /// \endcode
491
  /// into a single machine instruction of a form like:
492
  /// \code
493
  ///   cc = test %register, #mask
494
  /// \endcode
495
79
  virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
496
79
    return false;
497
79
  }
498
499
  /// Use bitwise logic to make pairs of compares more efficient. For example:
500
  /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
501
  /// This should be true when it takes more than one instruction to lower
502
  /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
503
  /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
504
2.44k
  virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
505
2.44k
    return false;
506
2.44k
  }
507
508
  /// Return the preferred operand type if the target has a quick way to compare
509
  /// integer values of the given size. Assume that any legal integer type can
510
  /// be compared efficiently. Targets may override this to allow illegal wide
511
  /// types to return a vector type if there is support to compare that type.
512
0
  virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
513
0
    MVT VT = MVT::getIntegerVT(NumBits);
514
0
    return isTypeLegal(VT) ? VT : MVT::INVALID_SIMPLE_VALUE_TYPE;
515
0
  }
516
517
  /// Return true if the target should transform:
518
  /// (X & Y) == Y ---> (~X & Y) == 0
519
  /// (X & Y) != Y ---> (~X & Y) != 0
520
  ///
521
  /// This may be profitable if the target has a bitwise and-not operation that
522
  /// sets comparison flags. A target may want to limit the transformation based
523
  /// on the type of Y or if Y is a constant.
524
  ///
525
  /// Note that the transform will not occur if Y is known to be a power-of-2
526
  /// because a mask and compare of a single bit can be handled by inverting the
527
  /// predicate, for example:
528
  /// (X & 8) == 8 ---> (X & 8) != 0
529
689
  virtual bool hasAndNotCompare(SDValue Y) const {
530
689
    return false;
531
689
  }
532
533
  /// Return true if the target has a bitwise and-not operation:
534
  /// X = ~A & B
535
  /// This can be used to simplify select or other instructions.
536
804
  virtual bool hasAndNot(SDValue X) const {
537
804
    // If the target has the more complex version of this operation, assume that
538
804
    // it has this operation too.
539
804
    return hasAndNotCompare(X);
540
804
  }
541
542
  /// There are two ways to clear extreme bits (either low or high):
543
  /// Mask:    x &  (-1 << y)  (the instcombine canonical form)
544
  /// Shifts:  x >> y << y
545
  /// Return true if the variant with 2 variable shifts is preferred.
546
  /// Return false if there is no preference.
547
241k
  virtual bool shouldFoldMaskToVariableShiftPair(SDValue X) const {
548
241k
    // By default, let's assume that no one prefers shifts.
549
241k
    return false;
550
241k
  }
551
552
  /// Return true if it is profitable to fold a pair of shifts into a mask.
553
  /// This is usually true on most targets. But some targets, like Thumb1,
554
  /// have immediate shift instructions, but no immediate "and" instruction;
555
  /// this makes the fold unprofitable.
556
  virtual bool shouldFoldConstantShiftPairToMask(const SDNode *N,
557
4.67k
                                                 CombineLevel Level) const {
558
4.67k
    return true;
559
4.67k
  }
560
561
  /// Should we tranform the IR-optimal check for whether given truncation
562
  /// down into KeptBits would be truncating or not:
563
  ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
564
  /// Into it's more traditional form:
565
  ///   ((%x << C) a>> C) dstcond %x
566
  /// Return true if we should transform.
567
  /// Return false if there is no preference.
568
  virtual bool shouldTransformSignedTruncationCheck(EVT XVT,
569
36
                                                    unsigned KeptBits) const {
570
36
    // By default, let's assume that no one prefers shifts.
571
36
    return false;
572
36
  }
573
574
  /// These two forms are equivalent:
575
  ///   sub %y, (xor %x, -1)
576
  ///   add (add %x, 1), %y
577
  /// The variant with two add's is IR-canonical.
578
  /// Some targets may prefer one to the other.
579
2.54M
  virtual bool preferIncOfAddToSubOfNot(EVT VT) const {
580
2.54M
    // By default, let's assume that everyone prefers the form with two add's.
581
2.54M
    return true;
582
2.54M
  }
583
584
  /// Return true if the target wants to use the optimization that
585
  /// turns ext(promotableInst1(...(promotableInstN(load)))) into
586
  /// promotedInst1(...(promotedInstN(ext(load)))).
587
531k
  bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
588
589
  /// Return true if the target can combine store(extractelement VectorTy,
590
  /// Idx).
591
  /// \p Cost[out] gives the cost of that transformation when this is true.
592
  virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
593
67.0k
                                         unsigned &Cost) const {
594
67.0k
    return false;
595
67.0k
  }
596
597
  /// Return true if inserting a scalar into a variable element of an undef
598
  /// vector is more efficiently handled by splatting the scalar instead.
599
77
  virtual bool shouldSplatInsEltVarIndex(EVT) const {
600
77
    return false;
601
77
  }
602
603
  /// Return true if target always beneficiates from combining into FMA for a
604
  /// given value type. This must typically return false on targets where FMA
605
  /// takes more cycles to execute than FADD.
606
4.79k
  virtual bool enableAggressiveFMAFusion(EVT VT) const {
607
4.79k
    return false;
608
4.79k
  }
609
610
  /// Return the ValueType of the result of SETCC operations.
611
  virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
612
                                 EVT VT) const;
613
614
  /// Return the ValueType for comparison libcalls. Comparions libcalls include
615
  /// floating point comparion calls, and Ordered/Unordered check calls on
616
  /// floating point numbers.
617
  virtual
618
  MVT::SimpleValueType getCmpLibcallReturnType() const;
619
620
  /// For targets without i1 registers, this gives the nature of the high-bits
621
  /// of boolean values held in types wider than i1.
622
  ///
623
  /// "Boolean values" are special true/false values produced by nodes like
624
  /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
625
  /// Not to be confused with general values promoted from i1.  Some cpus
626
  /// distinguish between vectors of boolean and scalars; the isVec parameter
627
  /// selects between the two kinds.  For example on X86 a scalar boolean should
628
  /// be zero extended from i1, while the elements of a vector of booleans
629
  /// should be sign extended from i1.
630
  ///
631
  /// Some cpus also treat floating point types the same way as they treat
632
  /// vectors instead of the way they treat scalars.
633
1.76M
  BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
634
1.76M
    if (isVec)
635
500k
      return BooleanVectorContents;
636
1.26M
    return isFloat ? 
BooleanFloatContents36.5k
:
BooleanContents1.23M
;
637
1.26M
  }
638
639
1.74M
  BooleanContent getBooleanContents(EVT Type) const {
640
1.74M
    return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
641
1.74M
  }
642
643
  /// Return target scheduling preference.
644
314k
  Sched::Preference getSchedulingPreference() const {
645
314k
    return SchedPreferenceInfo;
646
314k
  }
647
648
  /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
649
  /// for different nodes. This function returns the preference (or none) for
650
  /// the given node.
651
10.0M
  virtual Sched::Preference getSchedulingPreference(SDNode *) const {
652
10.0M
    return Sched::None;
653
10.0M
  }
654
655
  /// Return the register class that should be used for the specified value
656
  /// type.
657
15.3M
  virtual const TargetRegisterClass *getRegClassFor(MVT VT, bool isDivergent = false) const {
658
15.3M
    (void)isDivergent;
659
15.3M
    const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
660
15.3M
    assert(RC && "This value type is not natively supported!");
661
15.3M
    return RC;
662
15.3M
  }
663
664
  /// Allows target to decide about the register class of the
665
  /// specific value that is live outside the defining block.
666
  /// Returns true if the value needs uniform register class.
667
  virtual bool requiresUniformRegister(MachineFunction &MF,
668
12.2k
                                       const Value *) const {
669
12.2k
    return false;
670
12.2k
  }
671
672
  /// Return the 'representative' register class for the specified value
673
  /// type.
674
  ///
675
  /// The 'representative' register class is the largest legal super-reg
676
  /// register class for the register class of the value type.  For example, on
677
  /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
678
  /// register class is GR64 on x86_64.
679
1.97M
  virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
680
1.97M
    const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
681
1.97M
    return RC;
682
1.97M
  }
683
684
  /// Return the cost of the 'representative' register class for the specified
685
  /// value type.
686
1.47M
  virtual uint8_t getRepRegClassCostFor(MVT VT) const {
687
1.47M
    return RepRegClassCostForVT[VT.SimpleTy];
688
1.47M
  }
689
690
  /// Return true if SHIFT instructions should be expanded to SHIFT_PARTS
691
  /// instructions, and false if a library call is preferred (e.g for code-size
692
  /// reasons).
693
255
  virtual bool shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
694
255
    return true;
695
255
  }
696
697
  /// Return true if the target has native support for the specified value type.
698
  /// This means that it has a register that directly holds it without
699
  /// promotions or expansions.
700
510M
  bool isTypeLegal(EVT VT) const {
701
510M
    assert(!VT.isSimple() ||
702
510M
           (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
703
510M
    return VT.isSimple() && 
RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr510M
;
704
510M
  }
705
706
  class ValueTypeActionImpl {
707
    /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
708
    /// that indicates how instruction selection should deal with the type.
709
    LegalizeTypeAction ValueTypeActions[MVT::LAST_VALUETYPE];
710
711
  public:
712
53.2k
    ValueTypeActionImpl() {
713
53.2k
      std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
714
53.2k
                TypeLegal);
715
53.2k
    }
716
717
86.3M
    LegalizeTypeAction getTypeAction(MVT VT) const {
718
86.3M
      return ValueTypeActions[VT.SimpleTy];
719
86.3M
    }
720
721
5.87M
    void setTypeAction(MVT VT, LegalizeTypeAction Action) {
722
5.87M
      ValueTypeActions[VT.SimpleTy] = Action;
723
5.87M
    }
724
  };
725
726
1.28M
  const ValueTypeActionImpl &getValueTypeActions() const {
727
1.28M
    return ValueTypeActions;
728
1.28M
  }
729
730
  /// Return how we should legalize values of this type, either it is already
731
  /// legal (return 'Legal') or we need to promote it to a larger type (return
732
  /// 'Promote'), or we need to expand it into multiple registers of smaller
733
  /// integer type (return 'Expand').  'Custom' is not an option.
734
78.6M
  LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
735
78.6M
    return getTypeConversion(Context, VT).first;
736
78.6M
  }
737
35.1k
  LegalizeTypeAction getTypeAction(MVT VT) const {
738
35.1k
    return ValueTypeActions.getTypeAction(VT);
739
35.1k
  }
740
741
  /// For types supported by the target, this is an identity function.  For
742
  /// types that must be promoted to larger types, this returns the larger type
743
  /// to promote to.  For integer types that are larger than the largest integer
744
  /// register, this contains one step in the expansion to get to the smaller
745
  /// register. For illegal floating point types, this returns the integer type
746
  /// to transform to.
747
1.32M
  EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
748
1.32M
    return getTypeConversion(Context, VT).second;
749
1.32M
  }
750
751
  /// For types supported by the target, this is an identity function.  For
752
  /// types that must be expanded (i.e. integer types that are larger than the
753
  /// largest integer register or illegal floating point types), this returns
754
  /// the largest legal type it will be expanded to.
755
14.2k
  EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
756
14.2k
    assert(!VT.isVector());
757
16.1k
    while (true) {
758
16.1k
      switch (getTypeAction(Context, VT)) {
759
16.1k
      case TypeLegal:
760
14.2k
        return VT;
761
16.1k
      case TypeExpandInteger:
762
1.83k
        VT = getTypeToTransformTo(Context, VT);
763
1.83k
        break;
764
16.1k
      default:
765
0
        llvm_unreachable("Type is not legal nor is it to be expanded!");
766
16.1k
      }
767
16.1k
    }
768
14.2k
  }
769
770
  /// Vector types are broken down into some number of legal first class types.
771
  /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
772
  /// promoted EVT::f64 values with the X86 FP stack.  Similarly, EVT::v2i64
773
  /// turns into 4 EVT::i32 values with both PPC and X86.
774
  ///
775
  /// This method returns the number of registers needed, and the VT for each
776
  /// register.  It also returns the VT and quantity of the intermediate values
777
  /// before they are promoted/expanded.
778
  unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
779
                                  EVT &IntermediateVT,
780
                                  unsigned &NumIntermediates,
781
                                  MVT &RegisterVT) const;
782
783
  /// Certain targets such as MIPS require that some types such as vectors are
784
  /// always broken down into scalars in some contexts. This occurs even if the
785
  /// vector type is legal.
786
  virtual unsigned getVectorTypeBreakdownForCallingConv(
787
      LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
788
18.9k
      unsigned &NumIntermediates, MVT &RegisterVT) const {
789
18.9k
    return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
790
18.9k
                                  RegisterVT);
791
18.9k
  }
792
793
  struct IntrinsicInfo {
794
    unsigned     opc = 0;          // target opcode
795
    EVT          memVT;            // memory VT
796
797
    // value representing memory location
798
    PointerUnion<const Value *, const PseudoSourceValue *> ptrVal;
799
800
    int          offset = 0;       // offset off of ptrVal
801
    unsigned     size = 0;         // the size of the memory location
802
                                   // (taken from memVT if zero)
803
    unsigned     align = 1;        // alignment
804
805
    MachineMemOperand::Flags flags = MachineMemOperand::MONone;
806
203k
    IntrinsicInfo() = default;
807
  };
808
809
  /// Given an intrinsic, checks if on the target the intrinsic will need to map
810
  /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
811
  /// true and store the intrinsic information into the IntrinsicInfo that was
812
  /// passed to the function.
813
  virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
814
                                  MachineFunction &,
815
5.18k
                                  unsigned /*Intrinsic*/) const {
816
5.18k
    return false;
817
5.18k
  }
818
819
  /// Returns true if the target can instruction select the specified FP
820
  /// immediate natively. If false, the legalizer will materialize the FP
821
  /// immediate as a load from a constant pool.
822
  virtual bool isFPImmLegal(const APFloat & /*Imm*/, EVT /*VT*/,
823
166
                            bool ForCodeSize = false) const {
824
166
    return false;
825
166
  }
826
827
  /// Targets can use this to indicate that they only support *some*
828
  /// VECTOR_SHUFFLE operations, those with specific masks.  By default, if a
829
  /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
830
  /// legal.
831
1.59k
  virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
832
1.59k
    return true;
833
1.59k
  }
834
835
  /// Returns true if the operation can trap for the value type.
836
  ///
837
  /// VT must be a legal type. By default, we optimistically assume most
838
  /// operations don't trap except for integer divide and remainder.
839
  virtual bool canOpTrap(unsigned Op, EVT VT) const;
840
841
  /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
842
  /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
843
  /// constant pool entry.
844
  virtual bool isVectorClearMaskLegal(ArrayRef<int> /*Mask*/,
845
12.1k
                                      EVT /*VT*/) const {
846
12.1k
    return false;
847
12.1k
  }
848
849
  /// Return how this operation should be treated: either it is legal, needs to
850
  /// be promoted to a larger size, needs to be expanded to some other code
851
  /// sequence, or the target has a custom expander for it.
852
109M
  LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
853
109M
    if (VT.isExtended()) 
return Expand196k
;
854
109M
    // If a target-specific SDNode requires legalization, require the target
855
109M
    // to provide custom legalization for it.
856
109M
    if (Op >= array_lengthof(OpActions[0])) 
return Custom4.76k
;
857
109M
    return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
858
109M
  }
859
860
  /// Custom method defined by each target to indicate if an operation which
861
  /// may require a scale is supported natively by the target.
862
  /// If not, the operation is illegal.
863
  virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT,
864
0
                                              unsigned Scale) const {
865
0
    return false;
866
0
  }
867
868
  /// Some fixed point operations may be natively supported by the target but
869
  /// only for specific scales. This method allows for checking
870
  /// if the width is supported by the target for a given operation that may
871
  /// depend on scale.
872
  LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT,
873
80
                                              unsigned Scale) const {
874
80
    auto Action = getOperationAction(Op, VT);
875
80
    if (Action != Legal)
876
80
      return Action;
877
0
878
0
    // This operation is supported in this type but may only work on specific
879
0
    // scales.
880
0
    bool Supported;
881
0
    switch (Op) {
882
0
    default:
883
0
      llvm_unreachable("Unexpected fixed point operation.");
884
0
    case ISD::SMULFIX:
885
0
    case ISD::SMULFIXSAT:
886
0
    case ISD::UMULFIX:
887
0
      Supported = isSupportedFixedPointOperation(Op, VT, Scale);
888
0
      break;
889
0
    }
890
0
891
0
    return Supported ? Action : Expand;
892
0
  }
893
894
4.15k
  LegalizeAction getStrictFPOperationAction(unsigned Op, EVT VT) const {
895
4.15k
    unsigned EqOpc;
896
4.15k
    switch (Op) {
897
4.15k
      
default: 0
llvm_unreachable0
("Unexpected FP pseudo-opcode");
898
4.15k
      
case ISD::STRICT_FADD: EqOpc = ISD::FADD; break316
;
899
4.15k
      
case ISD::STRICT_FSUB: EqOpc = ISD::FSUB; break316
;
900
4.15k
      
case ISD::STRICT_FMUL: EqOpc = ISD::FMUL; break414
;
901
4.15k
      
case ISD::STRICT_FDIV: EqOpc = ISD::FDIV; break308
;
902
4.15k
      
case ISD::STRICT_FREM: EqOpc = ISD::FREM; break99
;
903
4.15k
      
case ISD::STRICT_FSQRT: EqOpc = ISD::FSQRT; break244
;
904
4.15k
      
case ISD::STRICT_FPOW: EqOpc = ISD::FPOW; break99
;
905
4.15k
      
case ISD::STRICT_FPOWI: EqOpc = ISD::FPOWI; break99
;
906
4.15k
      
case ISD::STRICT_FMA: EqOpc = ISD::FMA; break204
;
907
4.15k
      
case ISD::STRICT_FSIN: EqOpc = ISD::FSIN; break99
;
908
4.15k
      
case ISD::STRICT_FCOS: EqOpc = ISD::FCOS; break99
;
909
4.15k
      
case ISD::STRICT_FEXP: EqOpc = ISD::FEXP; break99
;
910
4.15k
      
case ISD::STRICT_FEXP2: EqOpc = ISD::FEXP2; break99
;
911
4.15k
      
case ISD::STRICT_FLOG: EqOpc = ISD::FLOG; break99
;
912
4.15k
      
case ISD::STRICT_FLOG10: EqOpc = ISD::FLOG10; break99
;
913
4.15k
      
case ISD::STRICT_FLOG2: EqOpc = ISD::FLOG2; break99
;
914
4.15k
      
case ISD::STRICT_FRINT: EqOpc = ISD::FRINT; break164
;
915
4.15k
      
case ISD::STRICT_FNEARBYINT: EqOpc = ISD::FNEARBYINT; break156
;
916
4.15k
      
case ISD::STRICT_FMAXNUM: EqOpc = ISD::FMAXNUM; break119
;
917
4.15k
      
case ISD::STRICT_FMINNUM: EqOpc = ISD::FMINNUM; break119
;
918
4.15k
      
case ISD::STRICT_FCEIL: EqOpc = ISD::FCEIL; break125
;
919
4.15k
      
case ISD::STRICT_FFLOOR: EqOpc = ISD::FFLOOR; break125
;
920
4.15k
      
case ISD::STRICT_FROUND: EqOpc = ISD::FROUND; break118
;
921
4.15k
      
case ISD::STRICT_FTRUNC: EqOpc = ISD::FTRUNC; break125
;
922
4.15k
      
case ISD::STRICT_FP_ROUND: EqOpc = ISD::FP_ROUND; break148
;
923
4.15k
      
case ISD::STRICT_FP_EXTEND: EqOpc = ISD::FP_EXTEND; break164
;
924
4.15k
    }
925
4.15k
926
4.15k
    auto Action = getOperationAction(EqOpc, VT);
927
4.15k
928
4.15k
    // We don't currently handle Custom or Promote for strict FP pseudo-ops.
929
4.15k
    // For now, we just expand for those cases.
930
4.15k
    if (Action != Legal)
931
1.39k
      Action = Expand;
932
4.15k
933
4.15k
    return Action;
934
4.15k
  }
935
936
  /// Return true if the specified operation is legal on this target or can be
937
  /// made legal with custom lowering. This is used to help guide high-level
938
  /// lowering decisions.
939
23.4M
  bool isOperationLegalOrCustom(unsigned Op, EVT VT) const {
940
23.4M
    return (VT == MVT::Other || 
isTypeLegal(VT)23.3M
) &&
941
23.4M
      
(18.3M
getOperationAction(Op, VT) == Legal18.3M
||
942
18.3M
       
getOperationAction(Op, VT) == Custom9.70M
);
943
23.4M
  }
944
945
  /// Return true if the specified operation is legal on this target or can be
946
  /// made legal using promotion. This is used to help guide high-level lowering
947
  /// decisions.
948
607k
  bool isOperationLegalOrPromote(unsigned Op, EVT VT) const {
949
607k
    return (VT == MVT::Other || isTypeLegal(VT)) &&
950
607k
      
(607k
getOperationAction(Op, VT) == Legal607k
||
951
607k
       
getOperationAction(Op, VT) == Promote74.2k
);
952
607k
  }
953
954
  /// Return true if the specified operation is legal on this target or can be
955
  /// made legal with custom lowering or using promotion. This is used to help
956
  /// guide high-level lowering decisions.
957
611k
  bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT) const {
958
611k
    return (VT == MVT::Other || isTypeLegal(VT)) &&
959
611k
      
(597k
getOperationAction(Op, VT) == Legal597k
||
960
597k
       
getOperationAction(Op, VT) == Custom43.6k
||
961
597k
       
getOperationAction(Op, VT) == Promote21.5k
);
962
611k
  }
963
964
  /// Return true if the operation uses custom lowering, regardless of whether
965
  /// the type is legal or not.
966
1.32k
  bool isOperationCustom(unsigned Op, EVT VT) const {
967
1.32k
    return getOperationAction(Op, VT) == Custom;
968
1.32k
  }
969
970
  /// Return true if lowering to a jump table is allowed.
971
54.1k
  virtual bool areJTsAllowed(const Function *Fn) const {
972
54.1k
    if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")
973
2
      return false;
974
54.1k
975
54.1k
    return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
976
54.1k
           
isOperationLegalOrCustom(ISD::BRIND, MVT::Other)7.42k
;
977
54.1k
  }
978
979
  /// Check whether the range [Low,High] fits in a machine word.
980
  bool rangeFitsInWord(const APInt &Low, const APInt &High,
981
50.4k
                       const DataLayout &DL) const {
982
50.4k
    // FIXME: Using the pointer type doesn't seem ideal.
983
50.4k
    uint64_t BW = DL.getIndexSizeInBits(0u);
984
50.4k
    uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
985
50.4k
    return Range <= BW;
986
50.4k
  }
987
988
  /// Return true if lowering to a jump table is suitable for a set of case
989
  /// clusters which may contain \p NumCases cases, \p Range range of values.
990
  virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
991
39.7k
                                      uint64_t Range) const {
992
39.7k
    // FIXME: This function check the maximum table size and density, but the
993
39.7k
    // minimum size is not checked. It would be nice if the minimum size is
994
39.7k
    // also combined within this function. Currently, the minimum size check is
995
39.7k
    // performed in findJumpTable() in SelectionDAGBuiler and
996
39.7k
    // getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
997
39.7k
    const bool OptForSize = SI->getParent()->getParent()->hasOptSize();
998
39.7k
    const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize);
999
39.7k
    const unsigned MaxJumpTableSize = getMaximumJumpTableSize();
1000
39.7k
    
1001
39.7k
    // Check whether the number of cases is small enough and
1002
39.7k
    // the range is dense enough for a jump table.
1003
39.7k
    if ((OptForSize || 
Range <= MaxJumpTableSize39.6k
) &&
1004
39.7k
        
(NumCases * 100 >= Range * MinDensity)39.2k
) {
1005
26.4k
      return true;
1006
26.4k
    }
1007
13.3k
    return false;
1008
13.3k
  }
1009
1010
  /// Return true if lowering to a bit test is suitable for a set of case
1011
  /// clusters which contains \p NumDests unique destinations, \p Low and
1012
  /// \p High as its lowest and highest case values, and expects \p NumCmps
1013
  /// case value comparisons. Check if the number of destinations, comparison
1014
  /// metric, and range are all suitable.
1015
  bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
1016
                             const APInt &Low, const APInt &High,
1017
40.7k
                             const DataLayout &DL) const {
1018
40.7k
    // FIXME: I don't think NumCmps is the correct metric: a single case and a
1019
40.7k
    // range of cases both require only one branch to lower. Just looking at the
1020
40.7k
    // number of clusters and destinations should be enough to decide whether to
1021
40.7k
    // build bit tests.
1022
40.7k
1023
40.7k
    // To lower a range with bit tests, the range must fit the bitwidth of a
1024
40.7k
    // machine word.
1025
40.7k
    if (!rangeFitsInWord(Low, High, DL))
1026
6.88k
      return false;
1027
33.8k
1028
33.8k
    // Decide whether it's profitable to lower this range with bit tests. Each
1029
33.8k
    // destination requires a bit test and branch, and there is an overall range
1030
33.8k
    // check branch. For a small number of clusters, separate comparisons might
1031
33.8k
    // be cheaper, and for many destinations, splitting the range might be
1032
33.8k
    // better.
1033
33.8k
    return (NumDests == 1 && 
NumCmps >= 36.42k
) ||
(30.7k
NumDests == 230.7k
&&
NumCmps >= 515.3k
) ||
1034
33.8k
           
(29.9k
NumDests == 329.9k
&&
NumCmps >= 62.63k
);
1035
33.8k
  }
1036
1037
  /// Return true if the specified operation is illegal on this target or
1038
  /// unlikely to be made legal with custom lowering. This is used to help guide
1039
  /// high-level lowering decisions.
1040
279k
  bool isOperationExpand(unsigned Op, EVT VT) const {
1041
279k
    return (!isTypeLegal(VT) || 
getOperationAction(Op, VT) == Expand279k
);
1042
279k
  }
1043
1044
  /// Return true if the specified operation is legal on this target.
1045
3.20M
  bool isOperationLegal(unsigned Op, EVT VT) const {
1046
3.20M
    return (VT == MVT::Other || isTypeLegal(VT)) &&
1047
3.20M
           
getOperationAction(Op, VT) == Legal3.01M
;
1048
3.20M
  }
1049
1050
  /// Return how this load with extension should be treated: either it is legal,
1051
  /// needs to be promoted to a larger size, needs to be expanded to some other
1052
  /// code sequence, or the target has a custom expander for it.
1053
  LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
1054
1.20M
                                  EVT MemVT) const {
1055
1.20M
    if (ValVT.isExtended() || 
MemVT.isExtended()1.20M
)
return Expand5.66k
;
1056
1.19M
    unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1057
1.19M
    unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1058
1.19M
    assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE &&
1059
1.19M
           MemI < MVT::LAST_VALUETYPE && "Table isn't big enough!");
1060
1.19M
    unsigned Shift = 4 * ExtType;
1061
1.19M
    return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
1062
1.19M
  }
1063
1064
  /// Return true if the specified load with extension is legal on this target.
1065
816k
  bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1066
816k
    return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
1067
816k
  }
1068
1069
  /// Return true if the specified load with extension is legal or custom
1070
  /// on this target.
1071
3.79k
  bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1072
3.79k
    return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
1073
3.79k
           
getLoadExtAction(ExtType, ValVT, MemVT) == Custom3.30k
;
1074
3.79k
  }
1075
1076
  /// Return how this store with truncation should be treated: either it is
1077
  /// legal, needs to be promoted to a larger size, needs to be expanded to some
1078
  /// other code sequence, or the target has a custom expander for it.
1079
379k
  LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
1080
379k
    if (ValVT.isExtended() || MemVT.isExtended()) 
return Expand125k
;
1081
253k
    unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1082
253k
    unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1083
253k
    assert(ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&
1084
253k
           "Table isn't big enough!");
1085
253k
    return TruncStoreActions[ValI][MemI];
1086
253k
  }
1087
1088
  /// Return true if the specified store with truncation is legal on this
1089
  /// target.
1090
220k
  bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
1091
220k
    return isTypeLegal(ValVT) && 
getTruncStoreAction(ValVT, MemVT) == Legal162k
;
1092
220k
  }
1093
1094
  /// Return true if the specified store with truncation has solution on this
1095
  /// target.
1096
2.95k
  bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
1097
2.95k
    return isTypeLegal(ValVT) &&
1098
2.95k
      
(2.87k
getTruncStoreAction(ValVT, MemVT) == Legal2.87k
||
1099
2.87k
       
getTruncStoreAction(ValVT, MemVT) == Custom1.20k
);
1100
2.95k
  }
1101
1102
  /// Return how the indexed load should be treated: either it is legal, needs
1103
  /// to be promoted to a larger size, needs to be expanded to some other code
1104
  /// sequence, or the target has a custom expander for it.
1105
  LegalizeAction
1106
13.2M
  getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
1107
13.2M
    assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
1108
13.2M
           "Table isn't big enough!");
1109
13.2M
    unsigned Ty = (unsigned)VT.SimpleTy;
1110
13.2M
    return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4);
1111
13.2M
  }
1112
1113
  /// Return true if the specified indexed load is legal on this target.
1114
10.6M
  bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
1115
10.6M
    return VT.isSimple() &&
1116
10.6M
      (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1117
10.6M
       
getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom2.62M
);
1118
10.6M
  }
1119
1120
  /// Return how the indexed store should be treated: either it is legal, needs
1121
  /// to be promoted to a larger size, needs to be expanded to some other code
1122
  /// sequence, or the target has a custom expander for it.
1123
  LegalizeAction
1124
7.16M
  getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
1125
7.16M
    assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
1126
7.16M
           "Table isn't big enough!");
1127
7.16M
    unsigned Ty = (unsigned)VT.SimpleTy;
1128
7.16M
    return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f);
1129
7.16M
  }
1130
1131
  /// Return true if the specified indexed load is legal on this target.
1132
4.03M
  bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
1133
4.03M
    return VT.isSimple() &&
1134
4.03M
      (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1135
4.03M
       
getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom3.13M
);
1136
4.03M
  }
1137
1138
  /// Return how the condition code should be treated: either it is legal, needs
1139
  /// to be expanded to some other code sequence, or the target has a custom
1140
  /// expander for it.
1141
  LegalizeAction
1142
573k
  getCondCodeAction(ISD::CondCode CC, MVT VT) const {
1143
573k
    assert((unsigned)CC < array_lengthof(CondCodeActions) &&
1144
573k
           ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) &&
1145
573k
           "Table isn't big enough!");
1146
573k
    // See setCondCodeAction for how this is encoded.
1147
573k
    uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1148
573k
    uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
1149
573k
    LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
1150
573k
    assert(Action != Promote && "Can't promote condition code!");
1151
573k
    return Action;
1152
573k
  }
1153
1154
  /// Return true if the specified condition code is legal on this target.
1155
33.2k
  bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
1156
33.2k
    return getCondCodeAction(CC, VT) == Legal;
1157
33.2k
  }
1158
1159
  /// Return true if the specified condition code is legal or custom on this
1160
  /// target.
1161
4.47k
  bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const {
1162
4.47k
    return getCondCodeAction(CC, VT) == Legal ||
1163
4.47k
           
getCondCodeAction(CC, VT) == Custom1.78k
;
1164
4.47k
  }
1165
1166
  /// If the action for this operation is to promote, this method returns the
1167
  /// ValueType to promote to.
1168
205k
  MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
1169
205k
    assert(getOperationAction(Op, VT) == Promote &&
1170
205k
           "This operation isn't promoted!");
1171
205k
1172
205k
    // See if this has an explicit type specified.
1173
205k
    std::map<std::pair<unsigned, MVT::SimpleValueType>,
1174
205k
             MVT::SimpleValueType>::const_iterator PTTI =
1175
205k
      PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1176
205k
    if (PTTI != PromoteToType.end()) 
return PTTI->second203k
;
1177
1.77k
1178
1.77k
    assert((VT.isInteger() || VT.isFloatingPoint()) &&
1179
1.77k
           "Cannot autopromote this type, add it with AddPromotedToType.");
1180
1.77k
1181
1.77k
    MVT NVT = VT;
1182
2.14k
    do {
1183
2.14k
      NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1184
2.14k
      assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
1185
2.14k
             "Didn't find type to promote to!");
1186
2.14k
    } while (!isTypeLegal(NVT) ||
1187
2.14k
              
getOperationAction(Op, NVT) == Promote1.88k
);
1188
1.77k
    return NVT;
1189
1.77k
  }
1190
1191
  /// Return the EVT corresponding to this LLVM type.  This is fixed by the LLVM
1192
  /// operations except for the pointer size.  If AllowUnknown is true, this
1193
  /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1194
  /// otherwise it will assert.
1195
  EVT getValueType(const DataLayout &DL, Type *Ty,
1196
68.2M
                   bool AllowUnknown = false) const {
1197
68.2M
    // Lower scalar pointers to native pointer types.
1198
68.2M
    if (auto *PTy = dyn_cast<PointerType>(Ty))
1199
19.9M
      return getPointerTy(DL, PTy->getAddressSpace());
1200
48.2M
1201
48.2M
    if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1202
6.69M
      Type *EltTy = VTy->getElementType();
1203
6.69M
      // Lower vectors of pointers to native pointer types.
1204
6.69M
      if (auto *PTy = dyn_cast<PointerType>(EltTy)) {
1205
345k
        EVT PointerTy(getPointerTy(DL, PTy->getAddressSpace()));
1206
345k
        EltTy = PointerTy.getTypeForEVT(Ty->getContext());
1207
345k
      }
1208
6.69M
      return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(EltTy, false),
1209
6.69M
                              VTy->getNumElements());
1210
6.69M
    }
1211
41.5M
1212
41.5M
    return EVT::getEVT(Ty, AllowUnknown);
1213
41.5M
  }
1214
1215
  EVT getMemValueType(const DataLayout &DL, Type *Ty,
1216
2.45M
                      bool AllowUnknown = false) const {
1217
2.45M
    // Lower scalar pointers to native pointer types.
1218
2.45M
    if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1219
399k
      return getPointerMemTy(DL, PTy->getAddressSpace());
1220
2.05M
    else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1221
291k
      Type *Elm = VTy->getElementType();
1222
291k
      if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
1223
1.93k
        EVT PointerTy(getPointerMemTy(DL, PT->getAddressSpace()));
1224
1.93k
        Elm = PointerTy.getTypeForEVT(Ty->getContext());
1225
1.93k
      }
1226
291k
      return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
1227
291k
                       VTy->getNumElements());
1228
291k
    }
1229
1.76M
1230
1.76M
    return getValueType(DL, Ty, AllowUnknown);
1231
1.76M
  }
1232
1233
1234
  /// Return the MVT corresponding to this LLVM type. See getValueType.
1235
  MVT getSimpleValueType(const DataLayout &DL, Type *Ty,
1236
23.4k
                         bool AllowUnknown = false) const {
1237
23.4k
    return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1238
23.4k
  }
1239
1240
  /// Return the desired alignment for ByVal or InAlloca aggregate function
1241
  /// arguments in the caller parameter area.  This is the actual alignment, not
1242
  /// its logarithm.
1243
  virtual unsigned getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1244
1245
  /// Return the type of registers that this ValueType will eventually require.
1246
5.13M
  MVT getRegisterType(MVT VT) const {
1247
5.13M
    assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
1248
5.13M
    return RegisterTypeForVT[VT.SimpleTy];
1249
5.13M
  }
1250
1251
  /// Return the type of registers that this ValueType will eventually require.
1252
7.36M
  MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1253
7.36M
    if (VT.isSimple()) {
1254
7.35M
      assert((unsigned)VT.getSimpleVT().SimpleTy <
1255
7.35M
                array_lengthof(RegisterTypeForVT));
1256
7.35M
      return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
1257
7.35M
    }
1258
16.6k
    if (VT.isVector()) {
1259
4.44k
      EVT VT1;
1260
4.44k
      MVT RegisterVT;
1261
4.44k
      unsigned NumIntermediates;
1262
4.44k
      (void)getVectorTypeBreakdown(Context, VT, VT1,
1263
4.44k
                                   NumIntermediates, RegisterVT);
1264
4.44k
      return RegisterVT;
1265
4.44k
    }
1266
12.2k
    
if (12.2k
VT.isInteger()12.2k
) {
1267
12.2k
      return getRegisterType(Context, getTypeToTransformTo(Context, VT));
1268
12.2k
    }
1269
18.4E
    llvm_unreachable("Unsupported extended type!");
1270
18.4E
  }
1271
1272
  /// Return the number of registers that this ValueType will eventually
1273
  /// require.
1274
  ///
1275
  /// This is one for any types promoted to live in larger registers, but may be
1276
  /// more than one for types (like i64) that are split into pieces.  For types
1277
  /// like i140, which are first promoted then expanded, it is the number of
1278
  /// registers needed to hold all the bits of the original type.  For an i140
1279
  /// on a 32 bit machine this means 5 registers.
1280
8.16M
  unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
1281
8.16M
    if (VT.isSimple()) {
1282
8.15M
      assert((unsigned)VT.getSimpleVT().SimpleTy <
1283
8.15M
                array_lengthof(NumRegistersForVT));
1284
8.15M
      return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1285
8.15M
    }
1286
9.50k
    if (VT.isVector()) {
1287
4.72k
      EVT VT1;
1288
4.72k
      MVT VT2;
1289
4.72k
      unsigned NumIntermediates;
1290
4.72k
      return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1291
4.72k
    }
1292
4.79k
    
if (4.78k
VT.isInteger()4.78k
) {
1293
4.79k
      unsigned BitWidth = VT.getSizeInBits();
1294
4.79k
      unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1295
4.79k
      return (BitWidth + RegWidth - 1) / RegWidth;
1296
4.79k
    }
1297
18.4E
    llvm_unreachable("Unsupported extended type!");
1298
18.4E
  }
1299
1300
  /// Certain combinations of ABIs, Targets and features require that types
1301
  /// are legal for some operations and not for other operations.
1302
  /// For MIPS all vector types must be passed through the integer register set.
1303
  virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context,
1304
3.44M
                                            CallingConv::ID CC, EVT VT) const {
1305
3.44M
    return getRegisterType(Context, VT);
1306
3.44M
  }
1307
1308
  /// Certain targets require unusual breakdowns of certain types. For MIPS,
1309
  /// this occurs when a vector type is used, as vector are passed through the
1310
  /// integer register set.
1311
  virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context,
1312
                                                 CallingConv::ID CC,
1313
3.44M
                                                 EVT VT) const {
1314
3.44M
    return getNumRegisters(Context, VT);
1315
3.44M
  }
1316
1317
  /// Certain targets have context senstive alignment requirements, where one
1318
  /// type has the alignment requirement of another type.
1319
  virtual unsigned getABIAlignmentForCallingConv(Type *ArgTy,
1320
1.36M
                                                 DataLayout DL) const {
1321
1.36M
    return DL.getABITypeAlignment(ArgTy);
1322
1.36M
  }
1323
1324
  /// If true, then instruction selection should seek to shrink the FP constant
1325
  /// of the specified type to a smaller type in order to save space and / or
1326
  /// reduce runtime.
1327
540
  virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1328
1329
  /// Return true if it is profitable to reduce a load to a smaller type.
1330
  /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
1331
  virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy,
1332
20.4k
                                     EVT NewVT) const {
1333
20.4k
    // By default, assume that it is cheaper to extract a subvector from a wide
1334
20.4k
    // vector load rather than creating multiple narrow vector loads.
1335
20.4k
    if (NewVT.isVector() && 
!Load->hasOneUse()9.93k
)
1336
9.76k
      return false;
1337
10.7k
1338
10.7k
    return true;
1339
10.7k
  }
1340
1341
  /// When splitting a value of the specified type into parts, does the Lo
1342
  /// or Hi part come first?  This usually follows the endianness, except
1343
  /// for ppcf128, where the Hi part always comes first.
1344
145k
  bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
1345
145k
    return DL.isBigEndian() || 
VT == MVT::ppcf128139k
;
1346
145k
  }
1347
1348
  /// If true, the target has custom DAG combine transformations that it can
1349
  /// perform for the specified node.
1350
62.4M
  bool hasTargetDAGCombine(ISD::NodeType NT) const {
1351
62.4M
    assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1352
62.4M
    return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1353
62.4M
  }
1354
1355
9.52M
  unsigned getGatherAllAliasesMaxDepth() const {
1356
9.52M
    return GatherAllAliasesMaxDepth;
1357
9.52M
  }
1358
1359
  /// Returns the size of the platform's va_list object.
1360
0
  virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1361
0
    return getPointerTy(DL).getSizeInBits();
1362
0
  }
1363
1364
  /// Get maximum # of store operations permitted for llvm.memset
1365
  ///
1366
  /// This function returns the maximum number of store operations permitted
1367
  /// to replace a call to llvm.memset. The value is set by the target at the
1368
  /// performance threshold for such a replacement. If OptSize is true,
1369
  /// return the limit for functions that have OptSize attribute.
1370
4.57k
  unsigned getMaxStoresPerMemset(bool OptSize) const {
1371
4.57k
    return OptSize ? 
MaxStoresPerMemsetOptSize21
:
MaxStoresPerMemset4.55k
;
1372
4.57k
  }
1373
1374
  /// Get maximum # of store operations permitted for llvm.memcpy
1375
  ///
1376
  /// This function returns the maximum number of store operations permitted
1377
  /// to replace a call to llvm.memcpy. The value is set by the target at the
1378
  /// performance threshold for such a replacement. If OptSize is true,
1379
  /// return the limit for functions that have OptSize attribute.
1380
6.54k
  unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1381
6.54k
    return OptSize ? 
MaxStoresPerMemcpyOptSize48
:
MaxStoresPerMemcpy6.49k
;
1382
6.54k
  }
1383
1384
  /// \brief Get maximum # of store operations to be glued together
1385
  ///
1386
  /// This function returns the maximum number of store operations permitted
1387
  /// to glue together during lowering of llvm.memcpy. The value is set by
1388
  //  the target at the performance threshold for such a replacement.
1389
5.98k
  virtual unsigned getMaxGluedStoresPerMemcpy() const {
1390
5.98k
    return MaxGluedStoresPerMemcpy;
1391
5.98k
  }
1392
1393
  /// Get maximum # of load operations permitted for memcmp
1394
  ///
1395
  /// This function returns the maximum number of load operations permitted
1396
  /// to replace a call to memcmp. The value is set by the target at the
1397
  /// performance threshold for such a replacement. If OptSize is true,
1398
  /// return the limit for functions that have OptSize attribute.
1399
146k
  unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
1400
146k
    return OptSize ? 
MaxLoadsPerMemcmpOptSize2.05k
:
MaxLoadsPerMemcmp144k
;
1401
146k
  }
1402
1403
  /// Get maximum # of store operations permitted for llvm.memmove
1404
  ///
1405
  /// This function returns the maximum number of store operations permitted
1406
  /// to replace a call to llvm.memmove. The value is set by the target at the
1407
  /// performance threshold for such a replacement. If OptSize is true,
1408
  /// return the limit for functions that have OptSize attribute.
1409
1.64k
  unsigned getMaxStoresPerMemmove(bool OptSize) const {
1410
1.64k
    return OptSize ? 
MaxStoresPerMemmoveOptSize0
: MaxStoresPerMemmove;
1411
1.64k
  }
1412
1413
  /// Determine if the target supports unaligned memory accesses.
1414
  ///
1415
  /// This function returns true if the target allows unaligned memory accesses
1416
  /// of the specified type in the given address space. If true, it also returns
1417
  /// whether the unaligned memory access is "fast" in the last argument by
1418
  /// reference. This is used, for example, in situations where an array
1419
  /// copy/move/set is converted to a sequence of store operations. Its use
1420
  /// helps to ensure that such replacements don't generate code that causes an
1421
  /// alignment error (trap) on the target machine.
1422
  virtual bool allowsMisalignedMemoryAccesses(
1423
      EVT, unsigned AddrSpace = 0, unsigned Align = 1,
1424
      MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
1425
1.07k
      bool * /*Fast*/ = nullptr) const {
1426
1.07k
    return false;
1427
1.07k
  }
1428
1429
  /// Return true if the target supports a memory access of this type for the
1430
  /// given address space and alignment. If the access is allowed, the optional
1431
  /// final parameter returns if the access is also fast (as defined by the
1432
  /// target).
1433
  bool
1434
  allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1435
                     unsigned AddrSpace = 0, unsigned Alignment = 1,
1436
                     MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
1437
                     bool *Fast = nullptr) const;
1438
1439
  /// Return true if the target supports a memory access of this type for the
1440
  /// given MachineMemOperand. If the access is allowed, the optional
1441
  /// final parameter returns if the access is also fast (as defined by the
1442
  /// target).
1443
  bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1444
                          const MachineMemOperand &MMO,
1445
                          bool *Fast = nullptr) const;
1446
1447
  /// Returns the target specific optimal type for load and store operations as
1448
  /// a result of memset, memcpy, and memmove lowering.
1449
  ///
1450
  /// If DstAlign is zero that means it's safe to destination alignment can
1451
  /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
1452
  /// a need to check it against alignment requirement, probably because the
1453
  /// source does not need to be loaded. If 'IsMemset' is true, that means it's
1454
  /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
1455
  /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
1456
  /// does not need to be loaded.  It returns EVT::Other if the type should be
1457
  /// determined using generic target-independent logic.
1458
  virtual EVT
1459
  getOptimalMemOpType(uint64_t /*Size*/, unsigned /*DstAlign*/,
1460
                      unsigned /*SrcAlign*/, bool /*IsMemset*/,
1461
                      bool /*ZeroMemset*/, bool /*MemcpyStrSrc*/,
1462
180
                      const AttributeList & /*FuncAttributes*/) const {
1463
180
    return MVT::Other;
1464
180
  }
1465
1466
  /// Returns true if it's safe to use load / store of the specified type to
1467
  /// expand memcpy / memset inline.
1468
  ///
1469
  /// This is mostly true for all types except for some special cases. For
1470
  /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1471
  /// fstpl which also does type conversion. Note the specified type doesn't
1472
  /// have to be legal as the hook is used before type legalization.
1473
3.52k
  virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1474
1475
  /// Determine if we should use _setjmp or setjmp to implement llvm.setjmp.
1476
0
  bool usesUnderscoreSetJmp() const {
1477
0
    return UseUnderscoreSetJmp;
1478
0
  }
1479
1480
  /// Determine if we should use _longjmp or longjmp to implement llvm.longjmp.
1481
0
  bool usesUnderscoreLongJmp() const {
1482
0
    return UseUnderscoreLongJmp;
1483
0
  }
1484
1485
  /// Return lower limit for number of blocks in a jump table.
1486
  virtual unsigned getMinimumJumpTableEntries() const;
1487
1488
  /// Return lower limit of the density in a jump table.
1489
  unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1490
1491
  /// Return upper limit for number of entries in a jump table.
1492
  /// Zero if no limit.
1493
  unsigned getMaximumJumpTableSize() const;
1494
1495
345
  virtual bool isJumpTableRelative() const {
1496
345
    return TM.isPositionIndependent();
1497
345
  }
1498
1499
  /// If a physical register, this specifies the register that
1500
  /// llvm.savestack/llvm.restorestack should save and restore.
1501
20.4M
  unsigned getStackPointerRegisterToSaveRestore() const {
1502
20.4M
    return StackPointerRegisterToSaveRestore;
1503
20.4M
  }
1504
1505
  /// If a physical register, this returns the register that receives the
1506
  /// exception address on entry to an EH pad.
1507
  virtual unsigned
1508
0
  getExceptionPointerRegister(const Constant *PersonalityFn) const {
1509
0
    // 0 is guaranteed to be the NoRegister value on all targets
1510
0
    return 0;
1511
0
  }
1512
1513
  /// If a physical register, this returns the register that receives the
1514
  /// exception typeid on entry to a landing pad.
1515
  virtual unsigned
1516
0
  getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1517
0
    // 0 is guaranteed to be the NoRegister value on all targets
1518
0
    return 0;
1519
0
  }
1520
1521
0
  virtual bool needsFixedCatchObjects() const {
1522
0
    report_fatal_error("Funclet EH is not implemented for this target");
1523
0
  }
1524
1525
  /// Returns the target's jmp_buf size in bytes (if never set, the default is
1526
  /// 200)
1527
0
  unsigned getJumpBufSize() const {
1528
0
    return JumpBufSize;
1529
0
  }
1530
1531
  /// Returns the target's jmp_buf alignment in bytes (if never set, the default
1532
  /// is 0)
1533
0
  unsigned getJumpBufAlignment() const {
1534
0
    return JumpBufAlignment;
1535
0
  }
1536
1537
  /// Return the minimum stack alignment of an argument.
1538
263
  unsigned getMinStackArgumentAlignment() const {
1539
263
    return MinStackArgumentAlignment;
1540
263
  }
1541
1542
  /// Return the minimum function alignment.
1543
527k
  unsigned getMinFunctionAlignment() const {
1544
527k
    return MinFunctionAlignment;
1545
527k
  }
1546
1547
  /// Return the preferred function alignment.
1548
524k
  unsigned getPrefFunctionAlignment() const {
1549
524k
    return PrefFunctionAlignment;
1550
524k
  }
1551
1552
  /// Return the preferred loop alignment.
1553
638k
  virtual unsigned getPrefLoopAlignment(MachineLoop *ML = nullptr) const {
1554
638k
    return PrefLoopAlignment;
1555
638k
  }
1556
1557
  /// Should loops be aligned even when the function is marked OptSize (but not
1558
  /// MinSize).
1559
152
  virtual bool alignLoopsWithOptSize() const {
1560
152
    return false;
1561
152
  }
1562
1563
  /// If the target has a standard location for the stack protector guard,
1564
  /// returns the address of that location. Otherwise, returns nullptr.
1565
  /// DEPRECATED: please override useLoadStackGuardNode and customize
1566
  ///             LOAD_STACK_GUARD, or customize \@llvm.stackguard().
1567
  virtual Value *getIRStackGuard(IRBuilder<> &IRB) const;
1568
1569
  /// Inserts necessary declarations for SSP (stack protection) purpose.
1570
  /// Should be used only when getIRStackGuard returns nullptr.
1571
  virtual void insertSSPDeclarations(Module &M) const;
1572
1573
  /// Return the variable that's previously inserted by insertSSPDeclarations,
1574
  /// if any, otherwise return nullptr. Should be used only when
1575
  /// getIRStackGuard returns nullptr.
1576
  virtual Value *getSDagStackGuard(const Module &M) const;
1577
1578
  /// If this function returns true, stack protection checks should XOR the
1579
  /// frame pointer (or whichever pointer is used to address locals) into the
1580
  /// stack guard value before checking it. getIRStackGuard must return nullptr
1581
  /// if this returns true.
1582
3.13k
  virtual bool useStackGuardXorFP() const { return false; }
1583
1584
  /// If the target has a standard stack protection check function that
1585
  /// performs validation and error handling, returns the function. Otherwise,
1586
  /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1587
  /// Should be used only when getIRStackGuard returns nullptr.
1588
  virtual Function *getSSPStackGuardCheck(const Module &M) const;
1589
1590
protected:
1591
  Value *getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1592
                                            bool UseTLS) const;
1593
1594
public:
1595
  /// Returns the target-specific address of the unsafe stack pointer.
1596
  virtual Value *getSafeStackPointerLocation(IRBuilder<> &IRB) const;
1597
1598
  /// Returns the name of the symbol used to emit stack probes or the empty
1599
  /// string if not applicable.
1600
0
  virtual StringRef getStackProbeSymbolName(MachineFunction &MF) const {
1601
0
    return "";
1602
0
  }
1603
1604
  /// Returns true if a cast between SrcAS and DestAS is a noop.
1605
474
  virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1606
474
    return false;
1607
474
  }
1608
1609
  /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1610
  /// are happy to sink it into basic blocks. A cast may be free, but not
1611
  /// necessarily a no-op. e.g. a free truncate from a 64-bit to 32-bit pointer.
1612
205
  virtual bool isFreeAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
1613
205
    return isNoopAddrSpaceCast(SrcAS, DestAS);
1614
205
  }
1615
1616
  /// Return true if the pointer arguments to CI should be aligned by aligning
1617
  /// the object whose address is being passed. If so then MinSize is set to the
1618
  /// minimum size the object must be to be aligned and PrefAlign is set to the
1619
  /// preferred alignment.
1620
  virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
1621
3.87M
                                      unsigned & /*PrefAlign*/) const {
1622
3.87M
    return false;
1623
3.87M
  }
1624
1625
  //===--------------------------------------------------------------------===//
1626
  /// \name Helpers for TargetTransformInfo implementations
1627
  /// @{
1628
1629
  /// Get the ISD node that corresponds to the Instruction class opcode.
1630
  int InstructionOpcodeToISD(unsigned Opcode) const;
1631
1632
  /// Estimate the cost of type-legalization and the legalized type.
1633
  std::pair<int, MVT> getTypeLegalizationCost(const DataLayout &DL,
1634
                                              Type *Ty) const;
1635
1636
  /// @}
1637
1638
  //===--------------------------------------------------------------------===//
1639
  /// \name Helpers for atomic expansion.
1640
  /// @{
1641
1642
  /// Returns the maximum atomic operation size (in bits) supported by
1643
  /// the backend. Atomic operations greater than this size (as well
1644
  /// as ones that are not naturally aligned), will be expanded by
1645
  /// AtomicExpandPass into an __atomic_* library call.
1646
43.6k
  unsigned getMaxAtomicSizeInBitsSupported() const {
1647
43.6k
    return MaxAtomicSizeInBitsSupported;
1648
43.6k
  }
1649
1650
  /// Returns the size of the smallest cmpxchg or ll/sc instruction
1651
  /// the backend supports.  Any smaller operations are widened in
1652
  /// AtomicExpandPass.
1653
  ///
1654
  /// Note that *unlike* operations above the maximum size, atomic ops
1655
  /// are still natively supported below the minimum; they just
1656
  /// require a more complex expansion.
1657
55.8k
  unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
1658
1659
  /// Whether the target supports unaligned atomic operations.
1660
1.66k
  bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics; }
1661
1662
  /// Whether AtomicExpandPass should automatically insert fences and reduce
1663
  /// ordering for this atomic. This should be true for most architectures with
1664
  /// weak memory ordering. Defaults to false.
1665
44.2k
  virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
1666
44.2k
    return false;
1667
44.2k
  }
1668
1669
  /// Perform a load-linked operation on Addr, returning a "Value *" with the
1670
  /// corresponding pointee type. This may entail some non-trivial operations to
1671
  /// truncate or reconstruct types that will be illegal in the backend. See
1672
  /// ARMISelLowering for an example implementation.
1673
  virtual Value *emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
1674
0
                                AtomicOrdering Ord) const {
1675
0
    llvm_unreachable("Load linked unimplemented on this target");
1676
0
  }
1677
1678
  /// Perform a store-conditional operation to Addr. Return the status of the
1679
  /// store. This should be 0 if the store succeeded, non-zero otherwise.
1680
  virtual Value *emitStoreConditional(IRBuilder<> &Builder, Value *Val,
1681
0
                                      Value *Addr, AtomicOrdering Ord) const {
1682
0
    llvm_unreachable("Store conditional unimplemented on this target");
1683
0
  }
1684
1685
  /// Perform a masked atomicrmw using a target-specific intrinsic. This
1686
  /// represents the core LL/SC loop which will be lowered at a late stage by
1687
  /// the backend.
1688
  virtual Value *emitMaskedAtomicRMWIntrinsic(IRBuilder<> &Builder,
1689
                                              AtomicRMWInst *AI,
1690
                                              Value *AlignedAddr, Value *Incr,
1691
                                              Value *Mask, Value *ShiftAmt,
1692
0
                                              AtomicOrdering Ord) const {
1693
0
    llvm_unreachable("Masked atomicrmw expansion unimplemented on this target");
1694
0
  }
1695
1696
  /// Perform a masked cmpxchg using a target-specific intrinsic. This
1697
  /// represents the core LL/SC loop which will be lowered at a late stage by
1698
  /// the backend.
1699
  virtual Value *emitMaskedAtomicCmpXchgIntrinsic(
1700
      IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
1701
0
      Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
1702
0
    llvm_unreachable("Masked cmpxchg expansion unimplemented on this target");
1703
0
  }
1704
1705
  /// Inserts in the IR a target-specific intrinsic specifying a fence.
1706
  /// It is called by AtomicExpandPass before expanding an
1707
  ///   AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
1708
  ///   if shouldInsertFencesForAtomic returns true.
1709
  ///
1710
  /// Inst is the original atomic instruction, prior to other expansions that
1711
  /// may be performed.
1712
  ///
1713
  /// This function should either return a nullptr, or a pointer to an IR-level
1714
  ///   Instruction*. Even complex fence sequences can be represented by a
1715
  ///   single Instruction* through an intrinsic to be lowered later.
1716
  /// Backends should override this method to produce target-specific intrinsic
1717
  ///   for their fences.
1718
  /// FIXME: Please note that the default implementation here in terms of
1719
  ///   IR-level fences exists for historical/compatibility reasons and is
1720
  ///   *unsound* ! Fences cannot, in general, be used to restore sequential
1721
  ///   consistency. For example, consider the following example:
1722
  /// atomic<int> x = y = 0;
1723
  /// int r1, r2, r3, r4;
1724
  /// Thread 0:
1725
  ///   x.store(1);
1726
  /// Thread 1:
1727
  ///   y.store(1);
1728
  /// Thread 2:
1729
  ///   r1 = x.load();
1730
  ///   r2 = y.load();
1731
  /// Thread 3:
1732
  ///   r3 = y.load();
1733
  ///   r4 = x.load();
1734
  ///  r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
1735
  ///  seq_cst. But if they are lowered to monotonic accesses, no amount of
1736
  ///  IR-level fences can prevent it.
1737
  /// @{
1738
  virtual Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst,
1739
129
                                        AtomicOrdering Ord) const {
1740
129
    if (isReleaseOrStronger(Ord) && 
Inst->hasAtomicStore()99
)
1741
96
      return Builder.CreateFence(Ord);
1742
33
    else
1743
33
      return nullptr;
1744
129
  }
1745
1746
  virtual Instruction *emitTrailingFence(IRBuilder<> &Builder,
1747
                                         Instruction *Inst,
1748
129
                                         AtomicOrdering Ord) const {
1749
129
    if (isAcquireOrStronger(Ord))
1750
106
      return Builder.CreateFence(Ord);
1751
23
    else
1752
23
      return nullptr;
1753
129
  }
1754
  /// @}
1755
1756
  // Emits code that executes when the comparison result in the ll/sc
1757
  // expansion of a cmpxchg instruction is such that the store-conditional will
1758
  // not execute.  This makes it possible to balance out the load-linked with
1759
  // a dedicated instruction, if desired.
1760
  // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
1761
  // be unnecessarily held, except if clrex, inserted by this hook, is executed.
1762
3
  virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> &Builder) const {}
1763
1764
  /// Returns true if the given (atomic) store should be expanded by the
1765
  /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
1766
435
  virtual bool shouldExpandAtomicStoreInIR(StoreInst *SI) const {
1767
435
    return false;
1768
435
  }
1769
1770
  /// Returns true if arguments should be sign-extended in lib calls.
1771
42.9k
  virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
1772
42.9k
    return IsSigned;
1773
42.9k
  }
1774
1775
  /// Returns how the given (atomic) load should be expanded by the
1776
  /// IR-level AtomicExpand pass.
1777
453
  virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const {
1778
453
    return AtomicExpansionKind::None;
1779
453
  }
1780
1781
  /// Returns how the given atomic cmpxchg should be expanded by the IR-level
1782
  /// AtomicExpand pass.
1783
  virtual AtomicExpansionKind
1784
1.83k
  shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
1785
1.83k
    return AtomicExpansionKind::None;
1786
1.83k
  }
1787
1788
  /// Returns how the IR-level AtomicExpand pass should expand the given
1789
  /// AtomicRMW, if at all. Default is to never expand.
1790
788
  virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
1791
788
    return RMW->isFloatingPointOperation() ?
1792
786
      
AtomicExpansionKind::CmpXChg2
: AtomicExpansionKind::None;
1793
788
  }
1794
1795
  /// On some platforms, an AtomicRMW that never actually modifies the value
1796
  /// (such as fetch_add of 0) can be turned into a fence followed by an
1797
  /// atomic load. This may sound useless, but it makes it possible for the
1798
  /// processor to keep the cacheline shared, dramatically improving
1799
  /// performance. And such idempotent RMWs are useful for implementing some
1800
  /// kinds of locks, see for example (justification + benchmarks):
1801
  /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
1802
  /// This method tries doing that transformation, returning the atomic load if
1803
  /// it succeeds, and nullptr otherwise.
1804
  /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
1805
  /// another round of expansion.
1806
  virtual LoadInst *
1807
0
  lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const {
1808
0
    return nullptr;
1809
0
  }
1810
1811
  /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
1812
  /// SIGN_EXTEND, or ANY_EXTEND).
1813
1.08k
  virtual ISD::NodeType getExtendForAtomicOps() const {
1814
1.08k
    return ISD::ZERO_EXTEND;
1815
1.08k
  }
1816
1817
  /// @}
1818
1819
  /// Returns true if we should normalize
1820
  /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
1821
  /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
1822
  /// that it saves us from materializing N0 and N1 in an integer register.
1823
  /// Targets that are able to perform and/or on flags should return false here.
1824
  virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context,
1825
39.1k
                                               EVT VT) const {
1826
39.1k
    // If a target has multiple condition registers, then it likely has logical
1827
39.1k
    // operations on those registers.
1828
39.1k
    if (hasMultipleConditionRegisters())
1829
15.8k
      return false;
1830
23.2k
    // Only do the transform if the value won't be split into multiple
1831
23.2k
    // registers.
1832
23.2k
    LegalizeTypeAction Action = getTypeAction(Context, VT);
1833
23.2k
    return Action != TypeExpandInteger && 
Action != TypeExpandFloat22.7k
&&
1834
23.2k
      
Action != TypeSplitVector22.7k
;
1835
23.2k
  }
1836
1837
445
  virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const { return true; }
1838
1839
  /// Return true if a select of constants (select Cond, C1, C2) should be
1840
  /// transformed into simple math ops with the condition value. For example:
1841
  /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
1842
5.88k
  virtual bool convertSelectOfConstantsToMath(EVT VT) const {
1843
5.88k
    return false;
1844
5.88k
  }
1845
1846
  /// Return true if it is profitable to transform an integer
1847
  /// multiplication-by-constant into simpler operations like shifts and adds.
1848
  /// This may be true if the target does not directly support the
1849
  /// multiplication operation for the specified type or the sequence of simpler
1850
  /// ops is faster than the multiply.
1851
35.8k
  virtual bool decomposeMulByConstant(EVT VT, SDValue C) const {
1852
35.8k
    return false;
1853
35.8k
  }
1854
1855
  /// Return true if it is more correct/profitable to use strict FP_TO_INT
1856
  /// conversion operations - canonicalizing the FP source value instead of
1857
  /// converting all cases and then selecting based on value.
1858
  /// This may be true if the target throws exceptions for out of bounds
1859
  /// conversions or has fast FP CMOV.
1860
  virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
1861
49
                                        bool IsSigned) const {
1862
49
    return false;
1863
49
  }
1864
1865
  //===--------------------------------------------------------------------===//
1866
  // TargetLowering Configuration Methods - These methods should be invoked by
1867
  // the derived class constructor to configure this object for the target.
1868
  //
1869
protected:
1870
  /// Specify how the target extends the result of integer and floating point
1871
  /// boolean values from i1 to a wider type.  See getBooleanContents.
1872
53.2k
  void setBooleanContents(BooleanContent Ty) {
1873
53.2k
    BooleanContents = Ty;
1874
53.2k
    BooleanFloatContents = Ty;
1875
53.2k
  }
1876
1877
  /// Specify how the target extends the result of integer and floating point
1878
  /// boolean values from i1 to a wider type.  See getBooleanContents.
1879
1.45k
  void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy) {
1880
1.45k
    BooleanContents = IntTy;
1881
1.45k
    BooleanFloatContents = FloatTy;
1882
1.45k
  }
1883
1884
  /// Specify how the target extends the result of a vector boolean value from a
1885
  /// vector of i1 to a wider type.  See getBooleanContents.
1886
52.0k
  void setBooleanVectorContents(BooleanContent Ty) {
1887
52.0k
    BooleanVectorContents = Ty;
1888
52.0k
  }
1889
1890
  /// Specify the target scheduling preference.
1891
44.7k
  void setSchedulingPreference(Sched::Preference Pref) {
1892
44.7k
    SchedPreferenceInfo = Pref;
1893
44.7k
  }
1894
1895
  /// Indicate whether this target prefers to use _setjmp to implement
1896
  /// llvm.setjmp or the version without _.  Defaults to false.
1897
17.1k
  void setUseUnderscoreSetJmp(bool Val) {
1898
17.1k
    UseUnderscoreSetJmp = Val;
1899
17.1k
  }
1900
1901
  /// Indicate whether this target prefers to use _longjmp to implement
1902
  /// llvm.longjmp or the version without _.  Defaults to false.
1903
17.1k
  void setUseUnderscoreLongJmp(bool Val) {
1904
17.1k
    UseUnderscoreLongJmp = Val;
1905
17.1k
  }
1906
1907
  /// Indicate the minimum number of blocks to generate jump tables.
1908
  void setMinimumJumpTableEntries(unsigned Val);
1909
1910
  /// Indicate the maximum number of entries in jump tables.
1911
  /// Set to zero to generate unlimited jump tables.
1912
  void setMaximumJumpTableSize(unsigned);
1913
1914
  /// If set to a physical register, this specifies the register that
1915
  /// llvm.savestack/llvm.restorestack should save and restore.
1916
48.8k
  void setStackPointerRegisterToSaveRestore(unsigned R) {
1917
48.8k
    StackPointerRegisterToSaveRestore = R;
1918
48.8k
  }
1919
1920
  /// Tells the code generator that the target has multiple (allocatable)
1921
  /// condition registers that can be used to store the results of comparisons
1922
  /// for use by selects and conditional branches. With multiple condition
1923
  /// registers, the code generator will not aggressively sink comparisons into
1924
  /// the blocks of their users.
1925
5.55k
  void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
1926
5.55k
    HasMultipleConditionRegisters = hasManyRegs;
1927
5.55k
  }
1928
1929
  /// Tells the code generator that the target has BitExtract instructions.
1930
  /// The code generator will aggressively sink "shift"s into the blocks of
1931
  /// their users if the users will generate "and" instructions which can be
1932
  /// combined with "shift" to BitExtract instructions.
1933
13.0k
  void setHasExtractBitsInsn(bool hasExtractInsn = true) {
1934
13.0k
    HasExtractBitsInsn = hasExtractInsn;
1935
13.0k
  }
1936
1937
  /// Tells the code generator not to expand logic operations on comparison
1938
  /// predicates into separate sequences that increase the amount of flow
1939
  /// control.
1940
  void setJumpIsExpensive(bool isExpensive = true);
1941
1942
  /// Tells the code generator which bitwidths to bypass.
1943
1.71k
  void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
1944
1.71k
    BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
1945
1.71k
  }
1946
1947
  /// Add the specified register class as an available regclass for the
1948
  /// specified value type. This indicates the selector can handle values of
1949
  /// that class natively.
1950
673k
  void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
1951
673k
    assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
1952
673k
    RegClassForVT[VT.SimpleTy] = RC;
1953
673k
  }
1954
1955
  /// Return the largest legal super-reg register class of the register class
1956
  /// for the specified type and its associated "cost".
1957
  virtual std::pair<const TargetRegisterClass *, uint8_t>
1958
  findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
1959
1960
  /// Once all of the register classes are added, this allows us to compute
1961
  /// derived properties we expose.
1962
  void computeRegisterProperties(const TargetRegisterInfo *TRI);
1963
1964
  /// Indicate that the specified operation does not work with the specified
1965
  /// type and indicate what to do about it. Note that VT may refer to either
1966
  /// the type of a result or that of an operand of Op.
1967
  void setOperationAction(unsigned Op, MVT VT,
1968
747M
                          LegalizeAction Action) {
1969
747M
    assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
1970
747M
    OpActions[(unsigned)VT.SimpleTy][Op] = Action;
1971
747M
  }
1972
1973
  /// Indicate that the specified load with extension does not work with the
1974
  /// specified type and indicate what to do about it.
1975
  void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
1976
1.21G
                        LegalizeAction Action) {
1977
1.21G
    assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
1978
1.21G
           MemVT.isValid() && "Table isn't big enough!");
1979
1.21G
    assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
1980
1.21G
    unsigned Shift = 4 * ExtType;
1981
1.21G
    LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
1982
1.21G
    LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
1983
1.21G
  }
1984
1985
  /// Indicate that the specified truncating store does not work with the
1986
  /// specified type and indicate what to do about it.
1987
  void setTruncStoreAction(MVT ValVT, MVT MemVT,
1988
443M
                           LegalizeAction Action) {
1989
443M
    assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
1990
443M
    TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
1991
443M
  }
1992
1993
  /// Indicate that the specified indexed load does or does not work with the
1994
  /// specified type and indicate what to do abort it.
1995
  ///
1996
  /// NOTE: All indexed mode loads are initialized to Expand in
1997
  /// TargetLowering.cpp
1998
  void setIndexedLoadAction(unsigned IdxMode, MVT VT,
1999
28.3M
                            LegalizeAction Action) {
2000
28.3M
    assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
2001
28.3M
           (unsigned)Action < 0xf && "Table isn't big enough!");
2002
28.3M
    // Load action are kept in the upper half.
2003
28.3M
    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0;
2004
28.3M
    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4;
2005
28.3M
  }
2006
2007
  /// Indicate that the specified indexed store does or does not work with the
2008
  /// specified type and indicate what to do about it.
2009
  ///
2010
  /// NOTE: All indexed mode stores are initialized to Expand in
2011
  /// TargetLowering.cpp
2012
  void setIndexedStoreAction(unsigned IdxMode, MVT VT,
2013
28.3M
                             LegalizeAction Action) {
2014
28.3M
    assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
2015
28.3M
           (unsigned)Action < 0xf && "Table isn't big enough!");
2016
28.3M
    // Store action are kept in the lower half.
2017
28.3M
    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f;
2018
28.3M
    IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action);
2019
28.3M
  }
2020
2021
  /// Indicate that the specified condition code is or isn't supported on the
2022
  /// target and indicate what to do about it.
2023
  void setCondCodeAction(ISD::CondCode CC, MVT VT,
2024
360k
                         LegalizeAction Action) {
2025
360k
    assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&
2026
360k
           "Table isn't big enough!");
2027
360k
    assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2028
360k
    /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the 32-bit
2029
360k
    /// value and the upper 29 bits index into the second dimension of the array
2030
360k
    /// to select what 32-bit value to use.
2031
360k
    uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
2032
360k
    CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
2033
360k
    CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
2034
360k
  }
2035
2036
  /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
2037
  /// to trying a larger integer/fp until it can find one that works. If that
2038
  /// default is insufficient, this method can be used by the target to override
2039
  /// the default.
2040
2.08M
  void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2041
2.08M
    PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
2042
2.08M
  }
2043
2044
  /// Convenience method to set an operation to Promote and specify the type
2045
  /// in a single call.
2046
242k
  void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2047
242k
    setOperationAction(Opc, OrigVT, Promote);
2048
242k
    AddPromotedToType(Opc, OrigVT, DestVT);
2049
242k
  }
2050
2051
  /// Targets should invoke this method for each target independent node that
2052
  /// they want to provide a custom DAG combiner for by implementing the
2053
  /// PerformDAGCombine virtual method.
2054
1.38M
  void setTargetDAGCombine(ISD::NodeType NT) {
2055
1.38M
    assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
2056
1.38M
    TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
2057
1.38M
  }
2058
2059
  /// Set the target's required jmp_buf buffer size (in bytes); default is 200
2060
0
  void setJumpBufSize(unsigned Size) {
2061
0
    JumpBufSize = Size;
2062
0
  }
2063
2064
  /// Set the target's required jmp_buf buffer alignment (in bytes); default is
2065
  /// 0
2066
0
  void setJumpBufAlignment(unsigned Align) {
2067
0
    JumpBufAlignment = Align;
2068
0
  }
2069
2070
  /// Set the target's minimum function alignment (in log2(bytes))
2071
33.0k
  void setMinFunctionAlignment(unsigned Align) {
2072
33.0k
    MinFunctionAlignment = Align;
2073
33.0k
  }
2074
2075
  /// Set the target's preferred function alignment.  This should be set if
2076
  /// there is a performance benefit to higher-than-minimum alignment (in
2077
  /// log2(bytes))
2078
28.5k
  void setPrefFunctionAlignment(unsigned Align) {
2079
28.5k
    PrefFunctionAlignment = Align;
2080
28.5k
  }
2081
2082
  /// Set the target's preferred loop alignment. Default alignment is zero, it
2083
  /// means the target does not care about loop alignment.  The alignment is
2084
  /// specified in log2(bytes). The target may also override
2085
  /// getPrefLoopAlignment to provide per-loop values.
2086
34.0k
  void setPrefLoopAlignment(unsigned Align) {
2087
34.0k
    PrefLoopAlignment = Align;
2088
34.0k
  }
2089
2090
  /// Set the minimum stack alignment of an argument (in log2(bytes)).
2091
20.6k
  void setMinStackArgumentAlignment(unsigned Align) {
2092
20.6k
    MinStackArgumentAlignment = Align;
2093
20.6k
  }
2094
2095
  /// Set the maximum atomic operation size supported by the
2096
  /// backend. Atomic operations greater than this size (as well as
2097
  /// ones that are not naturally aligned), will be expanded by
2098
  /// AtomicExpandPass into an __atomic_* library call.
2099
2.40k
  void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
2100
2.40k
    MaxAtomicSizeInBitsSupported = SizeInBits;
2101
2.40k
  }
2102
2103
  /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
2104
5.37k
  void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
2105
5.37k
    MinCmpXchgSizeInBits = SizeInBits;
2106
5.37k
  }
2107
2108
  /// Sets whether unaligned atomic operations are supported.
2109
3.93k
  void setSupportsUnalignedAtomics(bool UnalignedSupported) {
2110
3.93k
    SupportsUnalignedAtomics = UnalignedSupported;
2111
3.93k
  }
2112
2113
public:
2114
  //===--------------------------------------------------------------------===//
2115
  // Addressing mode description hooks (used by LSR etc).
2116
  //
2117
2118
  /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
2119
  /// instructions reading the address. This allows as much computation as
2120
  /// possible to be done in the address mode for that operand. This hook lets
2121
  /// targets also pass back when this should be done on intrinsics which
2122
  /// load/store.
2123
  virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
2124
                                    SmallVectorImpl<Value*> &/*Ops*/,
2125
844k
                                    Type *&/*AccessTy*/) const {
2126
844k
    return false;
2127
844k
  }
2128
2129
  /// This represents an addressing mode of:
2130
  ///    BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
2131
  /// If BaseGV is null,  there is no BaseGV.
2132
  /// If BaseOffs is zero, there is no base offset.
2133
  /// If HasBaseReg is false, there is no base register.
2134
  /// If Scale is zero, there is no ScaleReg.  Scale of 1 indicates a reg with
2135
  /// no scale.
2136
  struct AddrMode {
2137
    GlobalValue *BaseGV = nullptr;
2138
    int64_t      BaseOffs = 0;
2139
    bool         HasBaseReg = false;
2140
    int64_t      Scale = 0;
2141
74.1M
    AddrMode() = default;
2142
  };
2143
2144
  /// Return true if the addressing mode represented by AM is legal for this
2145
  /// target, for a load/store of the specified type.
2146
  ///
2147
  /// The type may be VoidTy, in which case only return true if the addressing
2148
  /// mode is legal for a load/store of any legal type.  TODO: Handle
2149
  /// pre/postinc as well.
2150
  ///
2151
  /// If the address space cannot be determined, it will be -1.
2152
  ///
2153
  /// TODO: Remove default argument
2154
  virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
2155
                                     Type *Ty, unsigned AddrSpace,
2156
                                     Instruction *I = nullptr) const;
2157
2158
  /// Return the cost of the scaling factor used in the addressing mode
2159
  /// represented by AM for this target, for a load/store of the specified type.
2160
  ///
2161
  /// If the AM is supported, the return value must be >= 0.
2162
  /// If the AM is not supported, it returns a negative value.
2163
  /// TODO: Handle pre/postinc as well.
2164
  /// TODO: Remove default argument
2165
  virtual int getScalingFactorCost(const DataLayout &DL, const AddrMode &AM,
2166
13.0k
                                   Type *Ty, unsigned AS = 0) const {
2167
13.0k
    // Default: assume that any scaling factor used in a legal AM is free.
2168
13.0k
    if (isLegalAddressingMode(DL, AM, Ty, AS))
2169
13.0k
      return 0;
2170
0
    return -1;
2171
0
  }
2172
2173
  /// Return true if the specified immediate is legal icmp immediate, that is
2174
  /// the target has icmp instructions which can compare a register against the
2175
  /// immediate without having to materialize the immediate into a register.
2176
20.5k
  virtual bool isLegalICmpImmediate(int64_t) const {
2177
20.5k
    return true;
2178
20.5k
  }
2179
2180
  /// Return true if the specified immediate is legal add immediate, that is the
2181
  /// target has add instructions which can add a register with the immediate
2182
  /// without having to materialize the immediate into a register.
2183
1.88k
  virtual bool isLegalAddImmediate(int64_t) const {
2184
1.88k
    return true;
2185
1.88k
  }
2186
2187
  /// Return true if the specified immediate is legal for the value input of a
2188
  /// store instruction.
2189
1.64k
  virtual bool isLegalStoreImmediate(int64_t Value) const {
2190
1.64k
    // Default implementation assumes that at least 0 works since it is likely
2191
1.64k
    // that a zero register exists or a zero immediate is allowed.
2192
1.64k
    return Value == 0;
2193
1.64k
  }
2194
2195
  /// Return true if it's significantly cheaper to shift a vector by a uniform
2196
  /// scalar than by an amount which will vary across each lane. On x86, for
2197
  /// example, there is a "psllw" instruction for the former case, but no simple
2198
  /// instruction for a general "a << b" operation on vectors.
2199
190k
  virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
2200
190k
    return false;
2201
190k
  }
2202
2203
  /// Returns true if the opcode is a commutative binary operation.
2204
84.6M
  virtual bool isCommutativeBinOp(unsigned Opcode) const {
2205
84.6M
    // FIXME: This should get its info from the td file.
2206
84.6M
    switch (Opcode) {
2207
84.6M
    case ISD::ADD:
2208
13.4M
    case ISD::SMIN:
2209
13.4M
    case ISD::SMAX:
2210
13.4M
    case ISD::UMIN:
2211
13.4M
    case ISD::UMAX:
2212
13.4M
    case ISD::MUL:
2213
13.4M
    case ISD::MULHU:
2214
13.4M
    case ISD::MULHS:
2215
13.4M
    case ISD::SMUL_LOHI:
2216
13.4M
    case ISD::UMUL_LOHI:
2217
13.4M
    case ISD::FADD:
2218
13.4M
    case ISD::FMUL:
2219
13.4M
    case ISD::AND:
2220
13.4M
    case ISD::OR:
2221
13.4M
    case ISD::XOR:
2222
13.4M
    case ISD::SADDO:
2223
13.4M
    case ISD::UADDO:
2224
13.4M
    case ISD::ADDC:
2225
13.4M
    case ISD::ADDE:
2226
13.4M
    case ISD::SADDSAT:
2227
13.4M
    case ISD::UADDSAT:
2228
13.4M
    case ISD::FMINNUM:
2229
13.4M
    case ISD::FMAXNUM:
2230
13.4M
    case ISD::FMINNUM_IEEE:
2231
13.4M
    case ISD::FMAXNUM_IEEE:
2232
13.4M
    case ISD::FMINIMUM:
2233
13.4M
    case ISD::FMAXIMUM:
2234
13.4M
      return true;
2235
71.1M
    default: return false;
2236
84.6M
    }
2237
84.6M
  }
2238
2239
  /// Return true if the node is a math/logic binary operator.
2240
854k
  virtual bool isBinOp(unsigned Opcode) const {
2241
854k
    // A commutative binop must be a binop.
2242
854k
    if (isCommutativeBinOp(Opcode))
2243
80.0k
      return true;
2244
774k
    // These are non-commutative binops.
2245
774k
    switch (Opcode) {
2246
774k
    case ISD::SUB:
2247
9.87k
    case ISD::SHL:
2248
9.87k
    case ISD::SRL:
2249
9.87k
    case ISD::SRA:
2250
9.87k
    case ISD::SDIV:
2251
9.87k
    case ISD::UDIV:
2252
9.87k
    case ISD::SREM:
2253
9.87k
    case ISD::UREM:
2254
9.87k
    case ISD::FSUB:
2255
9.87k
    case ISD::FDIV:
2256
9.87k
    case ISD::FREM:
2257
9.87k
      return true;
2258
764k
    default:
2259
764k
      return false;
2260
774k
    }
2261
774k
  }
2262
2263
  /// Return true if it's free to truncate a value of type FromTy to type
2264
  /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
2265
  /// by referencing its sub-register AX.
2266
  /// Targets must return false when FromTy <= ToTy.
2267
235
  virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
2268
235
    return false;
2269
235
  }
2270
2271
  /// Return true if a truncation from FromTy to ToTy is permitted when deciding
2272
  /// whether a call is in tail position. Typically this means that both results
2273
  /// would be assigned to the same register or stack slot, but it could mean
2274
  /// the target performs adequate checks of its own before proceeding with the
2275
  /// tail call.  Targets must return false when FromTy <= ToTy.
2276
5
  virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
2277
5
    return false;
2278
5
  }
2279
2280
20.2k
  virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const {
2281
20.2k
    return false;
2282
20.2k
  }
2283
2284
42.4k
  virtual bool isProfitableToHoist(Instruction *I) const { return true; }
2285
2286
  /// Return true if the extension represented by \p I is free.
2287
  /// Unlikely the is[Z|FP]ExtFree family which is based on types,
2288
  /// this method can use the context provided by \p I to decide
2289
  /// whether or not \p I is free.
2290
  /// This method extends the behavior of the is[Z|FP]ExtFree family.
2291
  /// In other words, if is[Z|FP]Free returns true, then this method
2292
  /// returns true as well. The converse is not true.
2293
  /// The target can perform the adequate checks by overriding isExtFreeImpl.
2294
  /// \pre \p I must be a sign, zero, or fp extension.
2295
1.88M
  bool isExtFree(const Instruction *I) const {
2296
1.88M
    switch (I->getOpcode()) {
2297
1.88M
    case Instruction::FPExt:
2298
73.0k
      if (isFPExtFree(EVT::getEVT(I->getType()),
2299
73.0k
                      EVT::getEVT(I->getOperand(0)->getType())))
2300
6
        return true;
2301
73.0k
      break;
2302
798k
    case Instruction::ZExt:
2303
798k
      if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
2304
351k
        return true;
2305
447k
      break;
2306
1.01M
    case Instruction::SExt:
2307
1.01M
      break;
2308
447k
    default:
2309
0
      llvm_unreachable("Instruction is not an extension");
2310
1.53M
    }
2311
1.53M
    return isExtFreeImpl(I);
2312
1.53M
  }
2313
2314
  /// Return true if \p Load and \p Ext can form an ExtLoad.
2315
  /// For example, in AArch64
2316
  ///   %L = load i8, i8* %ptr
2317
  ///   %E = zext i8 %L to i32
2318
  /// can be lowered into one load instruction
2319
  ///   ldrb w0, [x0]
2320
  bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
2321
625k
                 const DataLayout &DL) const {
2322
625k
    EVT VT = getValueType(DL, Ext->getType());
2323
625k
    EVT LoadVT = getValueType(DL, Load->getType());
2324
625k
2325
625k
    // If the load has other users and the truncate is not free, the ext
2326
625k
    // probably isn't free.
2327
625k
    if (!Load->hasOneUse() && 
(256k
isTypeLegal(LoadVT)256k
||
!isTypeLegal(VT)133k
) &&
2328
625k
        
!isTruncateFree(Ext->getType(), Load->getType())123k
)
2329
369
      return false;
2330
624k
2331
624k
    // Check whether the target supports casts folded into loads.
2332
624k
    unsigned LType;
2333
624k
    if (isa<ZExtInst>(Ext))
2334
262k
      LType = ISD::ZEXTLOAD;
2335
362k
    else {
2336
362k
      assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
2337
362k
      LType = ISD::SEXTLOAD;
2338
362k
    }
2339
624k
2340
624k
    return isLoadExtLegal(LType, VT, LoadVT);
2341
624k
  }
2342
2343
  /// Return true if any actual instruction that defines a value of type FromTy
2344
  /// implicitly zero-extends the value to ToTy in the result register.
2345
  ///
2346
  /// The function should return true when it is likely that the truncate can
2347
  /// be freely folded with an instruction defining a value of FromTy. If
2348
  /// the defining instruction is unknown (because you're looking at a
2349
  /// function argument, PHI, etc.) then the target may require an
2350
  /// explicit truncate, which is not necessarily free, but this function
2351
  /// does not deal with those cases.
2352
  /// Targets must return false when FromTy >= ToTy.
2353
30.2k
  virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
2354
30.2k
    return false;
2355
30.2k
  }
2356
2357
29.5k
  virtual bool isZExtFree(EVT FromTy, EVT ToTy) const {
2358
29.5k
    return false;
2359
29.5k
  }
2360
2361
  /// Return true if sign-extension from FromTy to ToTy is cheaper than
2362
  /// zero-extension.
2363
175k
  virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const {
2364
175k
    return false;
2365
175k
  }
2366
2367
  /// Return true if sinking I's operands to the same basic block as I is
2368
  /// profitable, e.g. because the operands can be folded into a target
2369
  /// instruction during instruction selection. After calling the function
2370
  /// \p Ops contains the Uses to sink ordered by dominance (dominating users
2371
  /// come first).
2372
  virtual bool shouldSinkOperands(Instruction *I,
2373
2.23M
                                  SmallVectorImpl<Use *> &Ops) const {
2374
2.23M
    return false;
2375
2.23M
  }
2376
2377
  /// Return true if the target supplies and combines to a paired load
2378
  /// two loaded values of type LoadedType next to each other in memory.
2379
  /// RequiredAlignment gives the minimal alignment constraints that must be met
2380
  /// to be able to select this paired load.
2381
  ///
2382
  /// This information is *not* used to generate actual paired loads, but it is
2383
  /// used to generate a sequence of loads that is easier to combine into a
2384
  /// paired load.
2385
  /// For instance, something like this:
2386
  /// a = load i64* addr
2387
  /// b = trunc i64 a to i32
2388
  /// c = lshr i64 a, 32
2389
  /// d = trunc i64 c to i32
2390
  /// will be optimized into:
2391
  /// b = load i32* addr1
2392
  /// d = load i32* addr2
2393
  /// Where addr1 = addr2 +/- sizeof(i32).
2394
  ///
2395
  /// In other words, unless the target performs a post-isel load combining,
2396
  /// this information should not be provided because it will generate more
2397
  /// loads.
2398
  virtual bool hasPairedLoad(EVT /*LoadedType*/,
2399
13.7k
                             unsigned & /*RequiredAlignment*/) const {
2400
13.7k
    return false;
2401
13.7k
  }
2402
2403
  /// Return true if the target has a vector blend instruction.
2404
37.2k
  virtual bool hasVectorBlend() const { return false; }
2405
2406
  /// Get the maximum supported factor for interleaved memory accesses.
2407
  /// Default to be the minimum interleave factor: 2.
2408
0
  virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
2409
2410
  /// Lower an interleaved load to target specific intrinsics. Return
2411
  /// true on success.
2412
  ///
2413
  /// \p LI is the vector load instruction.
2414
  /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
2415
  /// \p Indices is the corresponding indices for each shufflevector.
2416
  /// \p Factor is the interleave factor.
2417
  virtual bool lowerInterleavedLoad(LoadInst *LI,
2418
                                    ArrayRef<ShuffleVectorInst *> Shuffles,
2419
                                    ArrayRef<unsigned> Indices,
2420
0
                                    unsigned Factor) const {
2421
0
    return false;
2422
0
  }
2423
2424
  /// Lower an interleaved store to target specific intrinsics. Return
2425
  /// true on success.
2426
  ///
2427
  /// \p SI is the vector store instruction.
2428
  /// \p SVI is the shufflevector to RE-interleave the stored vector.
2429
  /// \p Factor is the interleave factor.
2430
  virtual bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI,
2431
0
                                     unsigned Factor) const {
2432
0
    return false;
2433
0
  }
2434
2435
  /// Return true if zero-extending the specific node Val to type VT2 is free
2436
  /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2437
  /// because it's folded such as X86 zero-extending loads).
2438
11.6k
  virtual bool isZExtFree(SDValue Val, EVT VT2) const {
2439
11.6k
    return isZExtFree(Val.getValueType(), VT2);
2440
11.6k
  }
2441
2442
  /// Return true if an fpext operation is free (for instance, because
2443
  /// single-precision floating-point numbers are implicitly extended to
2444
  /// double-precision).
2445
73.6k
  virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
2446
73.6k
    assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&
2447
73.6k
           "invalid fpext types");
2448
73.6k
    return false;
2449
73.6k
  }
2450
2451
  /// Return true if an fpext operation input to an \p Opcode operation is free
2452
  /// (for instance, because half-precision floating-point numbers are
2453
  /// implicitly extended to float-precision) for an FMA instruction.
2454
44
  virtual bool isFPExtFoldable(unsigned Opcode, EVT DestVT, EVT SrcVT) const {
2455
44
    assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
2456
44
           "invalid fpext types");
2457
44
    return isFPExtFree(DestVT, SrcVT);
2458
44
  }
2459
2460
  /// Return true if folding a vector load into ExtVal (a sign, zero, or any
2461
  /// extend node) is profitable.
2462
7.05k
  virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
2463
2464
  /// Return true if an fneg operation is free to the point where it is never
2465
  /// worthwhile to replace it with a bitwise operation.
2466
3.50k
  virtual bool isFNegFree(EVT VT) const {
2467
3.50k
    assert(VT.isFloatingPoint());
2468
3.50k
    return false;
2469
3.50k
  }
2470
2471
  /// Return true if an fabs operation is free to the point where it is never
2472
  /// worthwhile to replace it with a bitwise operation.
2473
4.95k
  virtual bool isFAbsFree(EVT VT) const {
2474
4.95k
    assert(VT.isFloatingPoint());
2475
4.95k
    return false;
2476
4.95k
  }
2477
2478
  /// Return true if an FMA operation is faster than a pair of fmul and fadd
2479
  /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2480
  /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2481
  ///
2482
  /// NOTE: This may be called before legalization on types for which FMAs are
2483
  /// not legal, but should return true if those types will eventually legalize
2484
  /// to types that support FMAs. After legalization, it will only be called on
2485
  /// types that support FMAs (via Legal or Custom actions)
2486
5.24k
  virtual bool isFMAFasterThanFMulAndFAdd(EVT) const {
2487
5.24k
    return false;
2488
5.24k
  }
2489
2490
  /// Return true if it's profitable to narrow operations of type VT1 to
2491
  /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
2492
  /// i32 to i16.
2493
4.74k
  virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
2494
4.74k
    return false;
2495
4.74k
  }
2496
2497
  /// Return true if it is beneficial to convert a load of a constant to
2498
  /// just the constant itself.
2499
  /// On some targets it might be more efficient to use a combination of
2500
  /// arithmetic instructions to materialize the constant instead of loading it
2501
  /// from a constant pool.
2502
  virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
2503
10
                                                 Type *Ty) const {
2504
10
    return false;
2505
10
  }
2506
2507
  /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
2508
  /// from this source type with this index. This is needed because
2509
  /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
2510
  /// the first element, and only the target knows which lowering is cheap.
2511
  virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
2512
92
                                       unsigned Index) const {
2513
92
    return false;
2514
92
  }
2515
2516
  /// Try to convert an extract element of a vector binary operation into an
2517
  /// extract element followed by a scalar operation.
2518
516
  virtual bool shouldScalarizeBinop(SDValue VecOp) const {
2519
516
    return false;
2520
516
  }
2521
2522
  /// Return true if extraction of a scalar element from the given vector type
2523
  /// at the given index is cheap. For example, if scalar operations occur on
2524
  /// the same register file as vector operations, then an extract element may
2525
  /// be a sub-register rename rather than an actual instruction.
2526
12.4k
  virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const {
2527
12.4k
    return false;
2528
12.4k
  }
2529
2530
  /// Try to convert math with an overflow comparison into the corresponding DAG
2531
  /// node operation. Targets may want to override this independently of whether
2532
  /// the operation is legal/custom for the given type because it may obscure
2533
  /// matching of other patterns.
2534
17.0k
  virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT) const {
2535
17.0k
    // TODO: The default logic is inherited from code in CodeGenPrepare.
2536
17.0k
    // The opcode should not make a difference by default?
2537
17.0k
    if (Opcode != ISD::UADDO)
2538
14.7k
      return false;
2539
2.39k
2540
2.39k
    // Allow the transform as long as we have an integer type that is not
2541
2.39k
    // obviously illegal and unsupported.
2542
2.39k
    if (VT.isVector())
2543
16
      return false;
2544
2.37k
    return VT.isSimple() || 
!isOperationExpand(Opcode, VT)0
;
2545
2.37k
  }
2546
2547
  // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
2548
  // even if the vector itself has multiple uses.
2549
849
  virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
2550
849
    return false;
2551
849
  }
2552
2553
  // Return true if CodeGenPrepare should consider splitting large offset of a
2554
  // GEP to make the GEP fit into the addressing mode and can be sunk into the
2555
  // same blocks of its users.
2556
3.73k
  virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
2557
2558
  //===--------------------------------------------------------------------===//
2559
  // Runtime Library hooks
2560
  //
2561
2562
  /// Rename the default libcall routine name for the specified libcall.
2563
28.8M
  void setLibcallName(RTLIB::Libcall Call, const char *Name) {
2564
28.8M
    LibcallRoutineNames[Call] = Name;
2565
28.8M
  }
2566
2567
  /// Get the libcall routine name for the specified libcall.
2568
126k
  const char *getLibcallName(RTLIB::Libcall Call) const {
2569
126k
    return LibcallRoutineNames[Call];
2570
126k
  }
2571
2572
  /// Override the default CondCode to be used to test the result of the
2573
  /// comparison libcall against zero.
2574
81.7k
  void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
2575
81.7k
    CmpLibcallCCs[Call] = CC;
2576
81.7k
  }
2577
2578
  /// Get the CondCode that's to be used to test the result of the comparison
2579
  /// libcall against zero.
2580
1.21k
  ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
2581
1.21k
    return CmpLibcallCCs[Call];
2582
1.21k
  }
2583
2584
  /// Set the CallingConv that should be used for the specified libcall.
2585
29.1M
  void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
2586
29.1M
    LibcallCallingConvs[Call] = CC;
2587
29.1M
  }
2588
2589
  /// Get the CallingConv that should be used for the specified libcall.
2590
51.5k
  CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
2591
51.5k
    return LibcallCallingConvs[Call];
2592
51.5k
  }
2593
2594
  /// Execute target specific actions to finalize target lowering.
2595
  /// This is used to set extra flags in MachineFrameInformation and freezing
2596
  /// the set of reserved registers.
2597
  /// The default implementation just freezes the set of reserved registers.
2598
  virtual void finalizeLowering(MachineFunction &MF) const;
2599
2600
private:
2601
  const TargetMachine &TM;
2602
2603
  /// Tells the code generator that the target has multiple (allocatable)
2604
  /// condition registers that can be used to store the results of comparisons
2605
  /// for use by selects and conditional branches. With multiple condition
2606
  /// registers, the code generator will not aggressively sink comparisons into
2607
  /// the blocks of their users.
2608
  bool HasMultipleConditionRegisters;
2609
2610
  /// Tells the code generator that the target has BitExtract instructions.
2611
  /// The code generator will aggressively sink "shift"s into the blocks of
2612
  /// their users if the users will generate "and" instructions which can be
2613
  /// combined with "shift" to BitExtract instructions.
2614
  bool HasExtractBitsInsn;
2615
2616
  /// Tells the code generator to bypass slow divide or remainder
2617
  /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
2618
  /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
2619
  /// div/rem when the operands are positive and less than 256.
2620
  DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
2621
2622
  /// Tells the code generator that it shouldn't generate extra flow control
2623
  /// instructions and should attempt to combine flow control instructions via
2624
  /// predication.
2625
  bool JumpIsExpensive;
2626
2627
  /// This target prefers to use _setjmp to implement llvm.setjmp.
2628
  ///
2629
  /// Defaults to false.
2630
  bool UseUnderscoreSetJmp;
2631
2632
  /// This target prefers to use _longjmp to implement llvm.longjmp.
2633
  ///
2634
  /// Defaults to false.
2635
  bool UseUnderscoreLongJmp;
2636
2637
  /// Information about the contents of the high-bits in boolean values held in
2638
  /// a type wider than i1. See getBooleanContents.
2639
  BooleanContent BooleanContents;
2640
2641
  /// Information about the contents of the high-bits in boolean values held in
2642
  /// a type wider than i1. See getBooleanContents.
2643
  BooleanContent BooleanFloatContents;
2644
2645
  /// Information about the contents of the high-bits in boolean vector values
2646
  /// when the element type is wider than i1. See getBooleanContents.
2647
  BooleanContent BooleanVectorContents;
2648
2649
  /// The target scheduling preference: shortest possible total cycles or lowest
2650
  /// register usage.
2651
  Sched::Preference SchedPreferenceInfo;
2652
2653
  /// The size, in bytes, of the target's jmp_buf buffers
2654
  unsigned JumpBufSize;
2655
2656
  /// The alignment, in bytes, of the target's jmp_buf buffers
2657
  unsigned JumpBufAlignment;
2658
2659
  /// The minimum alignment that any argument on the stack needs to have.
2660
  unsigned MinStackArgumentAlignment;
2661
2662
  /// The minimum function alignment (used when optimizing for size, and to
2663
  /// prevent explicitly provided alignment from leading to incorrect code).
2664
  unsigned MinFunctionAlignment;
2665
2666
  /// The preferred function alignment (used when alignment unspecified and
2667
  /// optimizing for speed).
2668
  unsigned PrefFunctionAlignment;
2669
2670
  /// The preferred loop alignment.
2671
  unsigned PrefLoopAlignment;
2672
2673
  /// Size in bits of the maximum atomics size the backend supports.
2674
  /// Accesses larger than this will be expanded by AtomicExpandPass.
2675
  unsigned MaxAtomicSizeInBitsSupported;
2676
2677
  /// Size in bits of the minimum cmpxchg or ll/sc operation the
2678
  /// backend supports.
2679
  unsigned MinCmpXchgSizeInBits;
2680
2681
  /// This indicates if the target supports unaligned atomic operations.
2682
  bool SupportsUnalignedAtomics;
2683
2684
  /// If set to a physical register, this specifies the register that
2685
  /// llvm.savestack/llvm.restorestack should save and restore.
2686
  unsigned StackPointerRegisterToSaveRestore;
2687
2688
  /// This indicates the default register class to use for each ValueType the
2689
  /// target supports natively.
2690
  const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
2691
  unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
2692
  MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
2693
2694
  /// This indicates the "representative" register class to use for each
2695
  /// ValueType the target supports natively. This information is used by the
2696
  /// scheduler to track register pressure. By default, the representative
2697
  /// register class is the largest legal super-reg register class of the
2698
  /// register class of the specified type. e.g. On x86, i8, i16, and i32's
2699
  /// representative class would be GR32.
2700
  const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
2701
2702
  /// This indicates the "cost" of the "representative" register class for each
2703
  /// ValueType. The cost is used by the scheduler to approximate register
2704
  /// pressure.
2705
  uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
2706
2707
  /// For any value types we are promoting or expanding, this contains the value
2708
  /// type that we are changing to.  For Expanded types, this contains one step
2709
  /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
2710
  /// (e.g. i64 -> i16).  For types natively supported by the system, this holds
2711
  /// the same type (e.g. i32 -> i32).
2712
  MVT TransformToType[MVT::LAST_VALUETYPE];
2713
2714
  /// For each operation and each value type, keep a LegalizeAction that
2715
  /// indicates how instruction selection should deal with the operation.  Most
2716
  /// operations are Legal (aka, supported natively by the target), but
2717
  /// operations that are not should be described.  Note that operations on
2718
  /// non-legal value types are not described here.
2719
  LegalizeAction OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
2720
2721
  /// For each load extension type and each value type, keep a LegalizeAction
2722
  /// that indicates how instruction selection should deal with a load of a
2723
  /// specific value type and extension type. Uses 4-bits to store the action
2724
  /// for each of the 4 load ext types.
2725
  uint16_t LoadExtActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2726
2727
  /// For each value type pair keep a LegalizeAction that indicates whether a
2728
  /// truncating store of a specific value type and truncating type is legal.
2729
  LegalizeAction TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2730
2731
  /// For each indexed mode and each value type, keep a pair of LegalizeAction
2732
  /// that indicates how instruction selection should deal with the load /
2733
  /// store.
2734
  ///
2735
  /// The first dimension is the value_type for the reference. The second
2736
  /// dimension represents the various modes for load store.
2737
  uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
2738
2739
  /// For each condition code (ISD::CondCode) keep a LegalizeAction that
2740
  /// indicates how instruction selection should deal with the condition code.
2741
  ///
2742
  /// Because each CC action takes up 4 bits, we need to have the array size be
2743
  /// large enough to fit all of the value types. This can be done by rounding
2744
  /// up the MVT::LAST_VALUETYPE value to the next multiple of 8.
2745
  uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 7) / 8];
2746
2747
protected:
2748
  ValueTypeActionImpl ValueTypeActions;
2749
2750
private:
2751
  LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
2752
2753
  /// Targets can specify ISD nodes that they would like PerformDAGCombine
2754
  /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
2755
  /// array.
2756
  unsigned char
2757
  TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
2758
2759
  /// For operations that must be promoted to a specific type, this holds the
2760
  /// destination type.  This map should be sparse, so don't hold it as an
2761
  /// array.
2762
  ///
2763
  /// Targets add entries to this map with AddPromotedToType(..), clients access
2764
  /// this with getTypeToPromoteTo(..).
2765
  std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
2766
    PromoteToType;
2767
2768
  /// Stores the name each libcall.
2769
  const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL + 1];
2770
2771
  /// The ISD::CondCode that should be used to test the result of each of the
2772
  /// comparison libcall against zero.
2773
  ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
2774
2775
  /// Stores the CallingConv that should be used for each libcall.
2776
  CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
2777
2778
  /// Set default libcall names and calling conventions.
2779
  void InitLibcalls(const Triple &TT);
2780
2781
protected:
2782
  /// Return true if the extension represented by \p I is free.
2783
  /// \pre \p I is a sign, zero, or fp extension and
2784
  ///      is[Z|FP]ExtFree of the related types is not true.
2785
167k
  virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
2786
2787
  /// Depth that GatherAllAliases should should continue looking for chain
2788
  /// dependencies when trying to find a more preferable chain. As an
2789
  /// approximation, this should be more than the number of consecutive stores
2790
  /// expected to be merged.
2791
  unsigned GatherAllAliasesMaxDepth;
2792
2793
  /// Specify maximum number of store instructions per memset call.
2794
  ///
2795
  /// When lowering \@llvm.memset this field specifies the maximum number of
2796
  /// store operations that may be substituted for the call to memset. Targets
2797
  /// must set this value based on the cost threshold for that target. Targets
2798
  /// should assume that the memset will be done using as many of the largest
2799
  /// store operations first, followed by smaller ones, if necessary, per
2800
  /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
2801
  /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
2802
  /// store.  This only applies to setting a constant array of a constant size.
2803
  unsigned MaxStoresPerMemset;
2804
2805
  /// Maximum number of stores operations that may be substituted for the call
2806
  /// to memset, used for functions with OptSize attribute.
2807
  unsigned MaxStoresPerMemsetOptSize;
2808
2809
  /// Specify maximum bytes of store instructions per memcpy call.
2810
  ///
2811
  /// When lowering \@llvm.memcpy this field specifies the maximum number of
2812
  /// store operations that may be substituted for a call to memcpy. Targets
2813
  /// must set this value based on the cost threshold for that target. Targets
2814
  /// should assume that the memcpy will be done using as many of the largest
2815
  /// store operations first, followed by smaller ones, if necessary, per
2816
  /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
2817
  /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
2818
  /// and one 1-byte store. This only applies to copying a constant array of
2819
  /// constant size.
2820
  unsigned MaxStoresPerMemcpy;
2821
2822
2823
  /// \brief Specify max number of store instructions to glue in inlined memcpy.
2824
  ///
2825
  /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
2826
  /// of store instructions to keep together. This helps in pairing and
2827
  //  vectorization later on.
2828
  unsigned MaxGluedStoresPerMemcpy = 0;
2829
2830
  /// Maximum number of store operations that may be substituted for a call to
2831
  /// memcpy, used for functions with OptSize attribute.
2832
  unsigned MaxStoresPerMemcpyOptSize;
2833
  unsigned MaxLoadsPerMemcmp;
2834
  unsigned MaxLoadsPerMemcmpOptSize;
2835
2836
  /// Specify maximum bytes of store instructions per memmove call.
2837
  ///
2838
  /// When lowering \@llvm.memmove this field specifies the maximum number of
2839
  /// store instructions that may be substituted for a call to memmove. Targets
2840
  /// must set this value based on the cost threshold for that target. Targets
2841
  /// should assume that the memmove will be done using as many of the largest
2842
  /// store operations first, followed by smaller ones, if necessary, per
2843
  /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
2844
  /// with 8-bit alignment would result in nine 1-byte stores.  This only
2845
  /// applies to copying a constant array of constant size.
2846
  unsigned MaxStoresPerMemmove;
2847
2848
  /// Maximum number of store instructions that may be substituted for a call to
2849
  /// memmove, used for functions with OptSize attribute.
2850
  unsigned MaxStoresPerMemmoveOptSize;
2851
2852
  /// Tells the code generator that select is more expensive than a branch if
2853
  /// the branch is usually predicted right.
2854
  bool PredictableSelectIsExpensive;
2855
2856
  /// \see enableExtLdPromotion.
2857
  bool EnableExtLdPromotion;
2858
2859
  /// Return true if the value types that can be represented by the specified
2860
  /// register class are all legal.
2861
  bool isLegalRC(const TargetRegisterInfo &TRI,
2862
                 const TargetRegisterClass &RC) const;
2863
2864
  /// Replace/modify any TargetFrameIndex operands with a targte-dependent
2865
  /// sequence of memory operands that is recognized by PrologEpilogInserter.
2866
  MachineBasicBlock *emitPatchPoint(MachineInstr &MI,
2867
                                    MachineBasicBlock *MBB) const;
2868
2869
  /// Replace/modify the XRay custom event operands with target-dependent
2870
  /// details.
2871
  MachineBasicBlock *emitXRayCustomEvent(MachineInstr &MI,
2872
                                         MachineBasicBlock *MBB) const;
2873
2874
  /// Replace/modify the XRay typed event operands with target-dependent
2875
  /// details.
2876
  MachineBasicBlock *emitXRayTypedEvent(MachineInstr &MI,
2877
                                        MachineBasicBlock *MBB) const;
2878
};
2879
2880
/// This class defines information used to lower LLVM code to legal SelectionDAG
2881
/// operators that the target instruction selector can accept natively.
2882
///
2883
/// This class also defines callbacks that targets must implement to lower
2884
/// target-specific constructs to SelectionDAG operators.
2885
class TargetLowering : public TargetLoweringBase {
2886
public:
2887
  struct DAGCombinerInfo;
2888
2889
  TargetLowering(const TargetLowering &) = delete;
2890
  TargetLowering &operator=(const TargetLowering &) = delete;
2891
2892
  /// NOTE: The TargetMachine owns TLOF.
2893
  explicit TargetLowering(const TargetMachine &TM);
2894
2895
  bool isPositionIndependent() const;
2896
2897
  virtual bool isSDNodeSourceOfDivergence(const SDNode *N,
2898
                                          FunctionLoweringInfo *FLI,
2899
36.3M
                                          LegacyDivergenceAnalysis *DA) const {
2900
36.3M
    return false;
2901
36.3M
  }
2902
2903
30.5M
  virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
2904
30.5M
    return false;
2905
30.5M
  }
2906
2907
  /// Returns true by value, base pointer and offset pointer and addressing mode
2908
  /// by reference if the node's address can be legally represented as
2909
  /// pre-indexed load / store address.
2910
  virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
2911
                                         SDValue &/*Offset*/,
2912
                                         ISD::MemIndexedMode &/*AM*/,
2913
0
                                         SelectionDAG &/*DAG*/) const {
2914
0
    return false;
2915
0
  }
2916
2917
  /// Returns true by value, base pointer and offset pointer and addressing mode
2918
  /// by reference if this node can be combined with a load / store to form a
2919
  /// post-indexed load / store.
2920
  virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
2921
                                          SDValue &/*Base*/,
2922
                                          SDValue &/*Offset*/,
2923
                                          ISD::MemIndexedMode &/*AM*/,
2924
0
                                          SelectionDAG &/*DAG*/) const {
2925
0
    return false;
2926
0
  }
2927
2928
  /// Return the entry encoding for a jump table in the current function.  The
2929
  /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
2930
  virtual unsigned getJumpTableEncoding() const;
2931
2932
  virtual const MCExpr *
2933
  LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
2934
                            const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
2935
0
                            MCContext &/*Ctx*/) const {
2936
0
    llvm_unreachable("Need to implement this hook if target has custom JTIs");
2937
0
  }
2938
2939
  /// Returns relocation base for the given PIC jumptable.
2940
  virtual SDValue getPICJumpTableRelocBase(SDValue Table,
2941
                                           SelectionDAG &DAG) const;
2942
2943
  /// This returns the relocation base for the given PIC jumptable, the same as
2944
  /// getPICJumpTableRelocBase, but as an MCExpr.
2945
  virtual const MCExpr *
2946
  getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2947
                               unsigned JTI, MCContext &Ctx) const;
2948
2949
  /// Return true if folding a constant offset with the given GlobalAddress is
2950
  /// legal.  It is frequently not legal in PIC relocation models.
2951
  virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
2952
2953
  bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
2954
                            SDValue &Chain) const;
2955
2956
  void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
2957
                           SDValue &NewRHS, ISD::CondCode &CCCode,
2958
                           const SDLoc &DL) const;
2959
2960
  /// Returns a pair of (return value, chain).
2961
  /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
2962
  std::pair<SDValue, SDValue> makeLibCall(
2963
      SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, ArrayRef<SDValue> Ops,
2964
      bool isSigned, const SDLoc &dl, bool doesNotReturn = false,
2965
      bool isReturnValueUsed = true, bool isPostTypeLegalization = false) const;
2966
2967
  /// Check whether parameters to a call that are passed in callee saved
2968
  /// registers are the same as from the calling function.  This needs to be
2969
  /// checked for tail call eligibility.
2970
  bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
2971
      const uint32_t *CallerPreservedMask,
2972
      const SmallVectorImpl<CCValAssign> &ArgLocs,
2973
      const SmallVectorImpl<SDValue> &OutVals) const;
2974
2975
  //===--------------------------------------------------------------------===//
2976
  // TargetLowering Optimization Methods
2977
  //
2978
2979
  /// A convenience struct that encapsulates a DAG, and two SDValues for
2980
  /// returning information from TargetLowering to its clients that want to
2981
  /// combine.
2982
  struct TargetLoweringOpt {
2983
    SelectionDAG &DAG;
2984
    bool LegalTys;
2985
    bool LegalOps;
2986
    SDValue Old;
2987
    SDValue New;
2988
2989
    explicit TargetLoweringOpt(SelectionDAG &InDAG,
2990
                               bool LT, bool LO) :
2991
6.96M
      DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
2992
2993
81.7k
    bool LegalTypes() const { return LegalTys; }
2994
235k
    bool LegalOperations() const { return LegalOps; }
2995
2996
358k
    bool CombineTo(SDValue O, SDValue N) {
2997
358k
      Old = O;
2998
358k
      New = N;
2999
358k
      return true;
3000
358k
    }
3001
  };
3002
3003
  /// Determines the optimal series of memory ops to replace the memset / memcpy.
3004
  /// Return true if the number of memory ops is below the threshold (Limit).
3005
  /// It returns the types of the sequence of memory ops to perform
3006
  /// memset / memcpy by reference.
3007
  bool findOptimalMemOpLowering(std::vector<EVT> &MemOps,
3008
                                unsigned Limit, uint64_t Size,
3009
                                unsigned DstAlign, unsigned SrcAlign,
3010
                                bool IsMemset,
3011
                                bool ZeroMemset,
3012
                                bool MemcpyStrSrc,
3013
                                bool AllowOverlap,
3014
                                unsigned DstAS, unsigned SrcAS,
3015
                                const AttributeList &FuncAttributes) const;
3016
3017
  /// Check to see if the specified operand of the specified instruction is a
3018
  /// constant integer.  If so, check to see if there are any bits set in the
3019
  /// constant that are not demanded.  If so, shrink the constant and return
3020
  /// true.
3021
  bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
3022
                              TargetLoweringOpt &TLO) const;
3023
3024
  // Target hook to do target-specific const optimization, which is called by
3025
  // ShrinkDemandedConstant. This function should return true if the target
3026
  // doesn't want ShrinkDemandedConstant to further optimize the constant.
3027
  virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
3028
396k
                                            TargetLoweringOpt &TLO) const {
3029
396k
    return false;
3030
396k
  }
3031
3032
  /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.  This
3033
  /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
3034
  /// generalized for targets with other types of implicit widening casts.
3035
  bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
3036
                        TargetLoweringOpt &TLO) const;
3037
3038
  /// Look at Op.  At this point, we know that only the DemandedBits bits of the
3039
  /// result of Op are ever used downstream.  If we can use this information to
3040
  /// simplify Op, create a new simplified DAG node and return true, returning
3041
  /// the original and new nodes in Old and New.  Otherwise, analyze the
3042
  /// expression and return a mask of KnownOne and KnownZero bits for the
3043
  /// expression (used to simplify the caller).  The KnownZero/One bits may only
3044
  /// be accurate for those bits in the Demanded masks.
3045
  /// \p AssumeSingleUse When this parameter is true, this function will
3046
  ///    attempt to simplify \p Op even if there are multiple uses.
3047
  ///    Callers are responsible for correctly updating the DAG based on the
3048
  ///    results of this function, because simply replacing replacing TLO.Old
3049
  ///    with TLO.New will be incorrect when this parameter is true and TLO.Old
3050
  ///    has multiple uses.
3051
  bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
3052
                            const APInt &DemandedElts, KnownBits &Known,
3053
                            TargetLoweringOpt &TLO, unsigned Depth = 0,
3054
                            bool AssumeSingleUse = false) const;
3055
3056
  /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
3057
  /// Adds Op back to the worklist upon success.
3058
  bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
3059
                            KnownBits &Known, TargetLoweringOpt &TLO,
3060
                            unsigned Depth = 0,
3061
                            bool AssumeSingleUse = false) const;
3062
3063
  /// Helper wrapper around SimplifyDemandedBits.
3064
  /// Adds Op back to the worklist upon success.
3065
  bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
3066
                            DAGCombinerInfo &DCI) const;
3067
3068
  /// More limited version of SimplifyDemandedBits that can be used to "look
3069
  /// through" ops that don't contribute to the DemandedBits/DemandedElts -
3070
  /// bitwise ops etc.
3071
  SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits,
3072
                                          const APInt &DemandedElts,
3073
                                          SelectionDAG &DAG,
3074
                                          unsigned Depth) const;
3075
3076
  /// Look at Vector Op. At this point, we know that only the DemandedElts
3077
  /// elements of the result of Op are ever used downstream.  If we can use
3078
  /// this information to simplify Op, create a new simplified DAG node and
3079
  /// return true, storing the original and new nodes in TLO.
3080
  /// Otherwise, analyze the expression and return a mask of KnownUndef and
3081
  /// KnownZero elements for the expression (used to simplify the caller).
3082
  /// The KnownUndef/Zero elements may only be accurate for those bits
3083
  /// in the DemandedMask.
3084
  /// \p AssumeSingleUse When this parameter is true, this function will
3085
  ///    attempt to simplify \p Op even if there are multiple uses.
3086
  ///    Callers are responsible for correctly updating the DAG based on the
3087
  ///    results of this function, because simply replacing replacing TLO.Old
3088
  ///    with TLO.New will be incorrect when this parameter is true and TLO.Old
3089
  ///    has multiple uses.
3090
  bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask,
3091
                                  APInt &KnownUndef, APInt &KnownZero,
3092
                                  TargetLoweringOpt &TLO, unsigned Depth = 0,
3093
                                  bool AssumeSingleUse = false) const;
3094
3095
  /// Helper wrapper around SimplifyDemandedVectorElts.
3096
  /// Adds Op back to the worklist upon success.
3097
  bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
3098
                                  APInt &KnownUndef, APInt &KnownZero,
3099
                                  DAGCombinerInfo &DCI) const;
3100
3101
  /// Determine which of the bits specified in Mask are known to be either zero
3102
  /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3103
  /// argument allows us to only collect the known bits that are shared by the
3104
  /// requested vector elements.
3105
  virtual void computeKnownBitsForTargetNode(const SDValue Op,
3106
                                             KnownBits &Known,
3107
                                             const APInt &DemandedElts,
3108
                                             const SelectionDAG &DAG,
3109
                                             unsigned Depth = 0) const;
3110
3111
  /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
3112
  /// Default implementation computes low bits based on alignment
3113
  /// information. This should preserve known bits passed into it.
3114
  virtual void computeKnownBitsForFrameIndex(const SDValue FIOp,
3115
                                             KnownBits &Known,
3116
                                             const APInt &DemandedElts,
3117
                                             const SelectionDAG &DAG,
3118
                                             unsigned Depth = 0) const;
3119
3120
  /// This method can be implemented by targets that want to expose additional
3121
  /// information about sign bits to the DAG Combiner. The DemandedElts
3122
  /// argument allows us to only collect the minimum sign bits that are shared
3123
  /// by the requested vector elements.
3124
  virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
3125
                                                   const APInt &DemandedElts,
3126
                                                   const SelectionDAG &DAG,
3127
                                                   unsigned Depth = 0) const;
3128
3129
  /// Attempt to simplify any target nodes based on the demanded vector
3130
  /// elements, returning true on success. Otherwise, analyze the expression and
3131
  /// return a mask of KnownUndef and KnownZero elements for the expression
3132
  /// (used to simplify the caller). The KnownUndef/Zero elements may only be
3133
  /// accurate for those bits in the DemandedMask.
3134
  virtual bool SimplifyDemandedVectorEltsForTargetNode(
3135
      SDValue Op, const APInt &DemandedElts, APInt &KnownUndef,
3136
      APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth = 0) const;
3137
3138
  /// Attempt to simplify any target nodes based on the demanded bits/elts,
3139
  /// returning true on success. Otherwise, analyze the
3140
  /// expression and return a mask of KnownOne and KnownZero bits for the
3141
  /// expression (used to simplify the caller).  The KnownZero/One bits may only
3142
  /// be accurate for those bits in the Demanded masks.
3143
  virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op,
3144
                                                 const APInt &DemandedBits,
3145
                                                 const APInt &DemandedElts,
3146
                                                 KnownBits &Known,
3147
                                                 TargetLoweringOpt &TLO,
3148
                                                 unsigned Depth = 0) const;
3149
3150
  /// More limited version of SimplifyDemandedBits that can be used to "look
3151
  /// through" ops that don't contribute to the DemandedBits/DemandedElts -
3152
  /// bitwise ops etc.
3153
  virtual SDValue SimplifyMultipleUseDemandedBitsForTargetNode(
3154
      SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3155
      SelectionDAG &DAG, unsigned Depth) const;
3156
3157
  /// This method returns the constant pool value that will be loaded by LD.
3158
  /// NOTE: You must check for implicit extensions of the constant by LD.
3159
  virtual const Constant *getTargetConstantFromLoad(LoadSDNode *LD) const;
3160
3161
  /// If \p SNaN is false, \returns true if \p Op is known to never be any
3162
  /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
3163
  /// NaN.
3164
  virtual bool isKnownNeverNaNForTargetNode(SDValue Op,
3165
                                            const SelectionDAG &DAG,
3166
                                            bool SNaN = false,
3167
                                            unsigned Depth = 0) const;
3168
  struct DAGCombinerInfo {
3169
    void *DC;  // The DAG Combiner object.
3170
    CombineLevel Level;
3171
    bool CalledByLegalizer;
3172
3173
  public:
3174
    SelectionDAG &DAG;
3175
3176
    DAGCombinerInfo(SelectionDAG &dag, CombineLevel level,  bool cl, void *dc)
3177
17.3M
      : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
3178
3179
5.15M
    bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
3180
4.71M
    bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
3181
292k
    bool isAfterLegalizeDAG() const {
3182
292k
      return Level == AfterLegalizeDAG;
3183
292k
    }
3184
179k
    CombineLevel getDAGCombineLevel() { return Level; }
3185
55.5k
    bool isCalledByLegalizer() const { return CalledByLegalizer; }
3186
3187
    void AddToWorklist(SDNode *N);
3188
    SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
3189
    SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
3190
    SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
3191
3192
    void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
3193
  };
3194
3195
  /// Return if the N is a constant or constant vector equal to the true value
3196
  /// from getBooleanContents().
3197
  bool isConstTrueVal(const SDNode *N) const;
3198
3199
  /// Return if the N is a constant or constant vector equal to the false value
3200
  /// from getBooleanContents().
3201
  bool isConstFalseVal(const SDNode *N) const;
3202
3203
  /// Return if \p N is a True value when extended to \p VT.
3204
  bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const;
3205
3206
  /// Try to simplify a setcc built with the specified operands and cc. If it is
3207
  /// unable to simplify it, return a null SDValue.
3208
  SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
3209
                        bool foldBooleans, DAGCombinerInfo &DCI,
3210
                        const SDLoc &dl) const;
3211
3212
  // For targets which wrap address, unwrap for analysis.
3213
99.2M
  virtual SDValue unwrapAddress(SDValue N) const { return N; }
3214
3215
  /// Returns true (and the GlobalValue and the offset) if the node is a
3216
  /// GlobalAddress + offset.
3217
  virtual bool
3218
  isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
3219
3220
  /// This method will be invoked for all target nodes and for any
3221
  /// target-independent nodes that the target has registered with invoke it
3222
  /// for.
3223
  ///
3224
  /// The semantics are as follows:
3225
  /// Return Value:
3226
  ///   SDValue.Val == 0   - No change was made
3227
  ///   SDValue.Val == N   - N was replaced, is dead, and is already handled.
3228
  ///   otherwise          - N should be replaced by the returned Operand.
3229
  ///
3230
  /// In addition, methods provided by DAGCombinerInfo may be used to perform
3231
  /// more complex transformations.
3232
  ///
3233
  virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
3234
3235
  /// Return true if it is profitable to move this shift by a constant amount
3236
  /// though its operand, adjusting any immediate operands as necessary to
3237
  /// preserve semantics. This transformation may not be desirable if it
3238
  /// disrupts a particularly auspicious target-specific tree (e.g. bitfield
3239
  /// extraction in AArch64). By default, it returns true.
3240
  ///
3241
  /// @param N the shift node
3242
  /// @param Level the current DAGCombine legalization level.
3243
  virtual bool isDesirableToCommuteWithShift(const SDNode *N,
3244
2.26k
                                             CombineLevel Level) const {
3245
2.26k
    return true;
3246
2.26k
  }
3247
3248
  // Return true if it is profitable to combine a BUILD_VECTOR with a stride-pattern
3249
  // to a shuffle and a truncate.
3250
  // Example of such a combine:
3251
  // v4i32 build_vector((extract_elt V, 1),
3252
  //                    (extract_elt V, 3),
3253
  //                    (extract_elt V, 5),
3254
  //                    (extract_elt V, 7))
3255
  //  -->
3256
  // v4i32 truncate (bitcast (shuffle<1,u,3,u,5,u,7,u> V, u) to v4i64)
3257
  virtual bool isDesirableToCombineBuildVectorToShuffleTruncate(
3258
0
      ArrayRef<int> ShuffleMask, EVT SrcVT, EVT TruncVT) const {
3259
0
    return false;
3260
0
  }
3261
3262
  /// Return true if the target has native support for the specified value type
3263
  /// and it is 'desirable' to use the type for the given node type. e.g. On x86
3264
  /// i16 is legal, but undesirable since i16 instruction encodings are longer
3265
  /// and some i16 instructions are slow.
3266
2.23M
  virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
3267
2.23M
    // By default, assume all legal types are desirable.
3268
2.23M
    return isTypeLegal(VT);
3269
2.23M
  }
3270
3271
  /// Return true if it is profitable for dag combiner to transform a floating
3272
  /// point op of specified opcode to a equivalent op of an integer
3273
  /// type. e.g. f32 load -> i32 load can be profitable on ARM.
3274
  virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
3275
2.03k
                                                 EVT /*VT*/) const {
3276
2.03k
    return false;
3277
2.03k
  }
3278
3279
  /// This method query the target whether it is beneficial for dag combiner to
3280
  /// promote the specified node. If true, it should return the desired
3281
  /// promotion type by reference.
3282
4.90k
  virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
3283
4.90k
    return false;
3284
4.90k
  }
3285
3286
  /// Return true if the target supports swifterror attribute. It optimizes
3287
  /// loads and stores to reading and writing a specific register.
3288
524k
  virtual bool supportSwiftError() const {
3289
524k
    return false;
3290
524k
  }
3291
3292
  /// Return true if the target supports that a subset of CSRs for the given
3293
  /// machine function is handled explicitly via copies.
3294
36.4k
  virtual bool supportSplitCSR(MachineFunction *MF) const {
3295
36.4k
    return false;
3296
36.4k
  }
3297
3298
  /// Perform necessary initialization to handle a subset of CSRs explicitly
3299
  /// via copies. This function is called at the beginning of instruction
3300
  /// selection.
3301
0
  virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
3302
0
    llvm_unreachable("Not Implemented");
3303
0
  }
3304
3305
  /// Insert explicit copies in entry and exit blocks. We copy a subset of
3306
  /// CSRs to virtual registers in the entry block, and copy them back to
3307
  /// physical registers in the exit blocks. This function is called at the end
3308
  /// of instruction selection.
3309
  virtual void insertCopiesSplitCSR(
3310
      MachineBasicBlock *Entry,
3311
0
      const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
3312
0
    llvm_unreachable("Not Implemented");
3313
0
  }
3314
3315
  //===--------------------------------------------------------------------===//
3316
  // Lowering methods - These methods must be implemented by targets so that
3317
  // the SelectionDAGBuilder code knows how to lower these.
3318
  //
3319
3320
  /// This hook must be implemented to lower the incoming (formal) arguments,
3321
  /// described by the Ins array, into the specified DAG. The implementation
3322
  /// should fill in the InVals array with legal-type argument values, and
3323
  /// return the resulting token chain value.
3324
  virtual SDValue LowerFormalArguments(
3325
      SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
3326
      const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
3327
0
      SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
3328
0
    llvm_unreachable("Not Implemented");
3329
0
  }
3330
3331
  /// This structure contains all information that is necessary for lowering
3332
  /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
3333
  /// needs to lower a call, and targets will see this struct in their LowerCall
3334
  /// implementation.
3335
  struct CallLoweringInfo {
3336
    SDValue Chain;
3337
    Type *RetTy = nullptr;
3338
    bool RetSExt           : 1;
3339
    bool RetZExt           : 1;
3340
    bool IsVarArg          : 1;
3341
    bool IsInReg           : 1;
3342
    bool DoesNotReturn     : 1;
3343
    bool IsReturnValueUsed : 1;
3344
    bool IsConvergent      : 1;
3345
    bool IsPatchPoint      : 1;
3346
3347
    // IsTailCall should be modified by implementations of
3348
    // TargetLowering::LowerCall that perform tail call conversions.
3349
    bool IsTailCall = false;
3350
3351
    // Is Call lowering done post SelectionDAG type legalization.
3352
    bool IsPostTypeLegalization = false;
3353
3354
    unsigned NumFixedArgs = -1;
3355
    CallingConv::ID CallConv = CallingConv::C;
3356
    SDValue Callee;
3357
    ArgListTy Args;
3358
    SelectionDAG &DAG;
3359
    SDLoc DL;
3360
    ImmutableCallSite CS;
3361
    SmallVector<ISD::OutputArg, 32> Outs;
3362
    SmallVector<SDValue, 32> OutVals;
3363
    SmallVector<ISD::InputArg, 32> Ins;
3364
    SmallVector<SDValue, 4> InVals;
3365
3366
    CallLoweringInfo(SelectionDAG &DAG)
3367
        : RetSExt(false), RetZExt(false), IsVarArg(false), IsInReg(false),
3368
          DoesNotReturn(false), IsReturnValueUsed(true), IsConvergent(false),
3369
459k
          IsPatchPoint(false), DAG(DAG) {}
3370
3371
459k
    CallLoweringInfo &setDebugLoc(const SDLoc &dl) {
3372
459k
      DL = dl;
3373
459k
      return *this;
3374
459k
    }
3375
3376
466k
    CallLoweringInfo &setChain(SDValue InChain) {
3377
466k
      Chain = InChain;
3378
466k
      return *this;
3379
466k
    }
3380
3381
    // setCallee with target/module-specific attributes
3382
    CallLoweringInfo &setLibCallee(CallingConv::ID CC, Type *ResultType,
3383
18.4k
                                   SDValue Target, ArgListTy &&ArgsList) {
3384
18.4k
      RetTy = ResultType;
3385
18.4k
      Callee = Target;
3386
18.4k
      CallConv = CC;
3387
18.4k
      NumFixedArgs = ArgsList.size();
3388
18.4k
      Args = std::move(ArgsList);
3389
18.4k
3390
18.4k
      DAG.getTargetLoweringInfo().markLibCallAttributes(
3391
18.4k
          &(DAG.getMachineFunction()), CC, Args);
3392
18.4k
      return *this;
3393
18.4k
    }
3394
3395
    CallLoweringInfo &setCallee(CallingConv::ID CC, Type *ResultType,
3396
638
                                SDValue Target, ArgListTy &&ArgsList) {
3397
638
      RetTy = ResultType;
3398
638
      Callee = Target;
3399
638
      CallConv = CC;
3400
638
      NumFixedArgs = ArgsList.size();
3401
638
      Args = std::move(ArgsList);
3402
638
      return *this;
3403
638
    }
3404
3405
    CallLoweringInfo &setCallee(Type *ResultType, FunctionType *FTy,
3406
                                SDValue Target, ArgListTy &&ArgsList,
3407
440k
                                ImmutableCallSite Call) {
3408
440k
      RetTy = ResultType;
3409
440k
3410
440k
      IsInReg = Call.hasRetAttr(Attribute::InReg);
3411
440k
      DoesNotReturn =
3412
440k
          Call.doesNotReturn() ||
3413
440k
          
(417k
!Call.isInvoke()417k
&&
3414
417k
           
isa<UnreachableInst>(Call.getInstruction()->getNextNode())411k
);
3415
440k
      IsVarArg = FTy->isVarArg();
3416
440k
      IsReturnValueUsed = !Call.getInstruction()->use_empty();
3417
440k
      RetSExt = Call.hasRetAttr(Attribute::SExt);
3418
440k
      RetZExt = Call.hasRetAttr(Attribute::ZExt);
3419
440k
3420
440k
      Callee = Target;
3421
440k
3422
440k
      CallConv = Call.getCallingConv();
3423
440k
      NumFixedArgs = FTy->getNumParams();
3424
440k
      Args = std::move(ArgsList);
3425
440k
3426
440k
      CS = Call;
3427
440k
3428
440k
      return *this;
3429
440k
    }
3430
3431
208
    CallLoweringInfo &setInRegister(bool Value = true) {
3432
208
      IsInReg = Value;
3433
208
      return *this;
3434
208
    }
3435
3436
5.99k
    CallLoweringInfo &setNoReturn(bool Value = true) {
3437
5.99k
      DoesNotReturn = Value;
3438
5.99k
      return *this;
3439
5.99k
    }
3440
3441
0
    CallLoweringInfo &setVarArg(bool Value = true) {
3442
0
      IsVarArg = Value;
3443
0
      return *this;
3444
0
    }
3445
3446
447k
    CallLoweringInfo &setTailCall(bool Value = true) {
3447
447k
      IsTailCall = Value;
3448
447k
      return *this;
3449
447k
    }
3450
3451
12.4k
    CallLoweringInfo &setDiscardResult(bool Value = true) {
3452
12.4k
      IsReturnValueUsed = !Value;
3453
12.4k
      return *this;
3454
12.4k
    }
3455
3456
440k
    CallLoweringInfo &setConvergent(bool Value = true) {
3457
440k
      IsConvergent = Value;
3458
440k
      return *this;
3459
440k
    }
3460
3461
12.0k
    CallLoweringInfo &setSExtResult(bool Value = true) {
3462
12.0k
      RetSExt = Value;
3463
12.0k
      return *this;
3464
12.0k
    }
3465
3466
12.0k
    CallLoweringInfo &setZExtResult(bool Value = true) {
3467
12.0k
      RetZExt = Value;
3468
12.0k
      return *this;
3469
12.0k
    }
3470
3471
234
    CallLoweringInfo &setIsPatchPoint(bool Value = true) {
3472
234
      IsPatchPoint = Value;
3473
234
      return *this;
3474
234
    }
3475
3476
11.6k
    CallLoweringInfo &setIsPostTypeLegalization(bool Value=true) {
3477
11.6k
      IsPostTypeLegalization = Value;
3478
11.6k
      return *this;
3479
11.6k
    }
3480
3481
1.01M
    ArgListTy &getArgs() {
3482
1.01M
      return Args;
3483
1.01M
    }
3484
  };
3485
3486
  /// This function lowers an abstract call to a function into an actual call.
3487
  /// This returns a pair of operands.  The first element is the return value
3488
  /// for the function (if RetTy is not VoidTy).  The second element is the
3489
  /// outgoing token chain. It calls LowerCall to do the actual lowering.
3490
  std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
3491
3492
  /// This hook must be implemented to lower calls into the specified
3493
  /// DAG. The outgoing arguments to the call are described by the Outs array,
3494
  /// and the values to be returned by the call are described by the Ins
3495
  /// array. The implementation should fill in the InVals array with legal-type
3496
  /// return values from the call, and return the resulting token chain value.
3497
  virtual SDValue
3498
    LowerCall(CallLoweringInfo &/*CLI*/,
3499
0
              SmallVectorImpl<SDValue> &/*InVals*/) const {
3500
0
    llvm_unreachable("Not Implemented");
3501
0
  }
3502
3503
  /// Target-specific cleanup for formal ByVal parameters.
3504
1.11k
  virtual void HandleByVal(CCState *, unsigned &, unsigned) const {}
3505
3506
  /// This hook should be implemented to check whether the return values
3507
  /// described by the Outs array can fit into the return registers.  If false
3508
  /// is returned, an sret-demotion is performed.
3509
  virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
3510
                              MachineFunction &/*MF*/, bool /*isVarArg*/,
3511
               const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
3512
               LLVMContext &/*Context*/) const
3513
5.74k
  {
3514
5.74k
    // Return true by default to get preexisting behavior.
3515
5.74k
    return true;
3516
5.74k
  }
3517
3518
  /// This hook must be implemented to lower outgoing return values, described
3519
  /// by the Outs array, into the specified DAG. The implementation should
3520
  /// return the resulting token chain value.
3521
  virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
3522
                              bool /*isVarArg*/,
3523
                              const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
3524
                              const SmallVectorImpl<SDValue> & /*OutVals*/,
3525
                              const SDLoc & /*dl*/,
3526
0
                              SelectionDAG & /*DAG*/) const {
3527
0
    llvm_unreachable("Not Implemented");
3528
0
  }
3529
3530
  /// Return true if result of the specified node is used by a return node
3531
  /// only. It also compute and return the input chain for the tail call.
3532
  ///
3533
  /// This is used to determine whether it is possible to codegen a libcall as
3534
  /// tail call at legalization time.
3535
1.53k
  virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
3536
1.53k
    return false;
3537
1.53k
  }
3538
3539
  /// Return true if the target may be able emit the call instruction as a tail
3540
  /// call. This is used by optimization passes to determine if it's profitable
3541
  /// to duplicate return instructions to enable tailcall optimization.
3542
225
  virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
3543
225
    return false;
3544
225
  }
3545
3546
  /// Return the builtin name for the __builtin___clear_cache intrinsic
3547
  /// Default is to invoke the clear cache library call
3548
2
  virtual const char * getClearCacheBuiltinName() const {
3549
2
    return "__clear_cache";
3550
2
  }
3551
3552
  /// Return the register ID of the name passed in. Used by named register
3553
  /// global variables extension. There is no target-independent behaviour
3554
  /// so the default action is to bail.
3555
  virtual unsigned getRegisterByName(const char* RegName, EVT VT,
3556
0
                                     SelectionDAG &DAG) const {
3557
0
    report_fatal_error("Named registers not implemented for this target");
3558
0
  }
3559
3560
  /// Return the type that should be used to zero or sign extend a
3561
  /// zeroext/signext integer return value.  FIXME: Some C calling conventions
3562
  /// require the return type to be promoted, but this is not true all the time,
3563
  /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
3564
  /// conventions. The frontend should handle this and include all of the
3565
  /// necessary information.
3566
  virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT,
3567
3.70k
                                       ISD::NodeType /*ExtendKind*/) const {
3568
3.70k
    EVT MinVT = getRegisterType(Context, MVT::i32);
3569
3.70k
    return VT.bitsLT(MinVT) ? 
MinVT2.69k
:
VT1.00k
;
3570
3.70k
  }
3571
3572
  /// For some targets, an LLVM struct type must be broken down into multiple
3573
  /// simple types, but the calling convention specifies that the entire struct
3574
  /// must be passed in a block of consecutive registers.
3575
  virtual bool
3576
  functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv,
3577
959k
                                            bool isVarArg) const {
3578
959k
    return false;
3579
959k
  }
3580
3581
  /// For most targets, an LLVM type must be broken down into multiple
3582
  /// smaller types. Usually the halves are ordered according to the endianness
3583
  /// but for some platform that would break. So this method will default to
3584
  /// matching the endianness but can be overridden.
3585
  virtual bool
3586
16
  shouldSplitFunctionArgumentsAsLittleEndian(const DataLayout &DL) const {
3587
16
    return DL.isLittleEndian();
3588
16
  }
3589
3590
  /// Returns a 0 terminated array of registers that can be safely used as
3591
  /// scratch registers.
3592
0
  virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
3593
0
    return nullptr;
3594
0
  }
3595
3596
  /// This callback is used to prepare for a volatile or atomic load.
3597
  /// It takes a chain node as input and returns the chain for the load itself.
3598
  ///
3599
  /// Having a callback like this is necessary for targets like SystemZ,
3600
  /// which allows a CPU to reuse the result of a previous load indefinitely,
3601
  /// even if a cache-coherent store is performed by another CPU.  The default
3602
  /// implementation does nothing.
3603
  virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL,
3604
24.2k
                                              SelectionDAG &DAG) const {
3605
24.2k
    return Chain;
3606
24.2k
  }
3607
3608
  /// This callback is used to inspect load/store instructions and add
3609
  /// target-specific MachineMemOperand flags to them.  The default
3610
  /// implementation does nothing.
3611
499k
  virtual MachineMemOperand::Flags getMMOFlags(const Instruction &I) const {
3612
499k
    return MachineMemOperand::MONone;
3613
499k
  }
3614
3615
  /// This callback is invoked by the type legalizer to legalize nodes with an
3616
  /// illegal operand type but legal result types.  It replaces the
3617
  /// LowerOperation callback in the type Legalizer.  The reason we can not do
3618
  /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
3619
  /// use this callback.
3620
  ///
3621
  /// TODO: Consider merging with ReplaceNodeResults.
3622
  ///
3623
  /// The target places new result values for the node in Results (their number
3624
  /// and types must exactly match those of the original return values of
3625
  /// the node), or leaves Results empty, which indicates that the node is not
3626
  /// to be custom lowered after all.
3627
  /// The default implementation calls LowerOperation.
3628
  virtual void LowerOperationWrapper(SDNode *N,
3629
                                     SmallVectorImpl<SDValue> &Results,
3630
                                     SelectionDAG &DAG) const;
3631
3632
  /// This callback is invoked for operations that are unsupported by the
3633
  /// target, which are registered to use 'custom' lowering, and whose defined
3634
  /// values are all legal.  If the target has no operations that require custom
3635
  /// lowering, it need not implement this.  The default implementation of this
3636
  /// aborts.
3637
  virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
3638
3639
  /// This callback is invoked when a node result type is illegal for the
3640
  /// target, and the operation was registered to use 'custom' lowering for that
3641
  /// result type.  The target places new result values for the node in Results
3642
  /// (their number and types must exactly match those of the original return
3643
  /// values of the node), or leaves Results empty, which indicates that the
3644
  /// node is not to be custom lowered after all.
3645
  ///
3646
  /// If the target has no operations that require custom lowering, it need not
3647
  /// implement this.  The default implementation aborts.
3648
  virtual void ReplaceNodeResults(SDNode * /*N*/,
3649
                                  SmallVectorImpl<SDValue> &/*Results*/,
3650
0
                                  SelectionDAG &/*DAG*/) const {
3651
0
    llvm_unreachable("ReplaceNodeResults not implemented for this target!");
3652
0
  }
3653
3654
  /// This method returns the name of a target specific DAG node.
3655
  virtual const char *getTargetNodeName(unsigned Opcode) const;
3656
3657
  /// This method returns a target specific FastISel object, or null if the
3658
  /// target does not support "fast" ISel.
3659
  virtual FastISel *createFastISel(FunctionLoweringInfo &,
3660
2.68k
                                   const TargetLibraryInfo *) const {
3661
2.68k
    return nullptr;
3662
2.68k
  }
3663
3664
  bool verifyReturnAddressArgumentIsConstant(SDValue Op,
3665
                                             SelectionDAG &DAG) const;
3666
3667
  //===--------------------------------------------------------------------===//
3668
  // Inline Asm Support hooks
3669
  //
3670
3671
  /// This hook allows the target to expand an inline asm call to be explicit
3672
  /// llvm code if it wants to.  This is useful for turning simple inline asms
3673
  /// into LLVM intrinsics, which gives the compiler more information about the
3674
  /// behavior of the code.
3675
5.44k
  virtual bool ExpandInlineAsm(CallInst *) const {
3676
5.44k
    return false;
3677
5.44k
  }
3678
3679
  enum ConstraintType {
3680
    C_Register,            // Constraint represents specific register(s).
3681
    C_RegisterClass,       // Constraint represents any of register(s) in class.
3682
    C_Memory,              // Memory constraint.
3683
    C_Other,               // Something else.
3684
    C_Unknown              // Unsupported constraint.
3685
  };
3686
3687
  enum ConstraintWeight {
3688
    // Generic weights.
3689
    CW_Invalid  = -1,     // No match.
3690
    CW_Okay     = 0,      // Acceptable.
3691
    CW_Good     = 1,      // Good weight.
3692
    CW_Better   = 2,      // Better weight.
3693
    CW_Best     = 3,      // Best weight.
3694
3695
    // Well-known weights.
3696
    CW_SpecificReg  = CW_Okay,    // Specific register operands.
3697
    CW_Register     = CW_Good,    // Register operands.
3698
    CW_Memory       = CW_Better,  // Memory operands.
3699
    CW_Constant     = CW_Best,    // Constant operand.
3700
    CW_Default      = CW_Okay     // Default or don't know type.
3701
  };
3702
3703
  /// This contains information for each constraint that we are lowering.
3704
  struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3705
    /// This contains the actual string for the code, like "m".  TargetLowering
3706
    /// picks the 'best' code from ConstraintInfo::Codes that most closely
3707
    /// matches the operand.
3708
    std::string ConstraintCode;
3709
3710
    /// Information about the constraint code, e.g. Register, RegisterClass,
3711
    /// Memory, Other, Unknown.
3712
    TargetLowering::ConstraintType ConstraintType = TargetLowering::C_Unknown;
3713
3714
    /// If this is the result output operand or a clobber, this is null,
3715
    /// otherwise it is the incoming operand to the CallInst.  This gets
3716
    /// modified as the asm is processed.
3717
    Value *CallOperandVal = nullptr;
3718
3719
    /// The ValueType for the operand value.
3720
    MVT ConstraintVT = MVT::Other;
3721
3722
    /// Copy constructor for copying from a ConstraintInfo.
3723
    AsmOperandInfo(InlineAsm::ConstraintInfo Info)
3724
335k
        : InlineAsm::ConstraintInfo(std::move(Info)) {}
3725
3726
    /// Return true of this is an input operand that is a matching constraint
3727
    /// like "4".
3728
    bool isMatchingInputConstraint() const;
3729
3730
    /// If this is an input matching constraint, this method returns the output
3731
    /// operand it matches.
3732
    unsigned getMatchedOperand() const;
3733
  };
3734
3735
  using AsmOperandInfoVector = std::vector<AsmOperandInfo>;
3736
3737
  /// Split up the constraint string from the inline assembly value into the
3738
  /// specific constraints and their prefixes, and also tie in the associated
3739
  /// operand values.  If this returns an empty vector, and if the constraint
3740
  /// string itself isn't empty, there was an error parsing.
3741
  virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL,
3742
                                                const TargetRegisterInfo *TRI,
3743
                                                ImmutableCallSite CS) const;
3744
3745
  /// Examine constraint type and operand type and determine a weight value.
3746
  /// The operand object must already have been set up with the operand type.
3747
  virtual ConstraintWeight getMultipleConstraintMatchWeight(
3748
      AsmOperandInfo &info, int maIndex) const;
3749
3750
  /// Examine constraint string and operand type and determine a weight value.
3751
  /// The operand object must already have been set up with the operand type.
3752
  virtual ConstraintWeight getSingleConstraintMatchWeight(
3753
      AsmOperandInfo &info, const char *constraint) const;
3754
3755
  /// Determines the constraint code and constraint type to use for the specific
3756
  /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
3757
  /// If the actual operand being passed in is available, it can be passed in as
3758
  /// Op, otherwise an empty SDValue can be passed.
3759
  virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
3760
                                      SDValue Op,
3761
                                      SelectionDAG *DAG = nullptr) const;
3762
3763
  /// Given a constraint, return the type of constraint it is for this target.
3764
  virtual ConstraintType getConstraintType(StringRef Constraint) const;
3765
3766
  /// Given a physical register constraint (e.g.  {edx}), return the register
3767
  /// number and the register class for the register.
3768
  ///
3769
  /// Given a register class constraint, like 'r', if this corresponds directly
3770
  /// to an LLVM register class, return a register of 0 and the register class
3771
  /// pointer.
3772
  ///
3773
  /// This should only be used for C_Register constraints.  On error, this
3774
  /// returns a register number of 0 and a null register class pointer.
3775
  virtual std::pair<unsigned, const TargetRegisterClass *>
3776
  getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3777
                               StringRef Constraint, MVT VT) const;
3778
3779
434
  virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const {
3780
434
    if (ConstraintCode == "i")
3781
0
      return InlineAsm::Constraint_i;
3782
434
    else if (ConstraintCode == "m")
3783
434
      return InlineAsm::Constraint_m;
3784
0
    return InlineAsm::Constraint_Unknown;
3785
0
  }
3786
3787
  /// Try to replace an X constraint, which matches anything, with another that
3788
  /// has more specific requirements based on the type of the corresponding
3789
  /// operand.  This returns null if there is no replacement to make.
3790
  virtual const char *LowerXConstraint(EVT ConstraintVT) const;
3791
3792
  /// Lower the specified operand into the Ops vector.  If it is invalid, don't
3793
  /// add anything to Ops.
3794
  virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
3795
                                            std::vector<SDValue> &Ops,
3796
                                            SelectionDAG &DAG) const;
3797
3798
  // Lower custom output constraints. If invalid, return SDValue().
3799
  virtual SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Flag,
3800
                                              SDLoc DL,
3801
                                              const AsmOperandInfo &OpInfo,
3802
                                              SelectionDAG &DAG) const;
3803
3804
  //===--------------------------------------------------------------------===//
3805
  // Div utility functions
3806
  //
3807
  SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
3808
                    SmallVectorImpl<SDNode *> &Created) const;
3809
  SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
3810
                    SmallVectorImpl<SDNode *> &Created) const;
3811
3812
  /// Targets may override this function to provide custom SDIV lowering for
3813
  /// power-of-2 denominators.  If the target returns an empty SDValue, LLVM
3814
  /// assumes SDIV is expensive and replaces it with a series of other integer
3815
  /// operations.
3816
  virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
3817
                                SelectionDAG &DAG,
3818
                                SmallVectorImpl<SDNode *> &Created) const;
3819
3820
  /// Indicate whether this target prefers to combine FDIVs with the same
3821
  /// divisor. If the transform should never be done, return zero. If the
3822
  /// transform should be done, return the minimum number of divisor uses
3823
  /// that must exist.
3824
162
  virtual unsigned combineRepeatedFPDivisors() const {
3825
162
    return 0;
3826
162
  }
3827
3828
  /// Hooks for building estimates in place of slower divisions and square
3829
  /// roots.
3830
3831
  /// Return either a square root or its reciprocal estimate value for the input
3832
  /// operand.
3833
  /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3834
  /// 'Enabled' as set by a potential default override attribute.
3835
  /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3836
  /// refinement iterations required to generate a sufficient (though not
3837
  /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3838
  /// The boolean UseOneConstNR output is used to select a Newton-Raphson
3839
  /// algorithm implementation that uses either one or two constants.
3840
  /// The boolean Reciprocal is used to select whether the estimate is for the
3841
  /// square root of the input operand or the reciprocal of its square root.
3842
  /// A target may choose to implement its own refinement within this function.
3843
  /// If that's true, then return '0' as the number of RefinementSteps to avoid
3844
  /// any further refinement of the estimate.
3845
  /// An empty SDValue return means no estimate sequence can be created.
3846
  virtual SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
3847
                                  int Enabled, int &RefinementSteps,
3848
32
                                  bool &UseOneConstNR, bool Reciprocal) const {
3849
32
    return SDValue();
3850
32
  }
3851
3852
  /// Return a reciprocal estimate value for the input operand.
3853
  /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
3854
  /// 'Enabled' as set by a potential default override attribute.
3855
  /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
3856
  /// refinement iterations required to generate a sufficient (though not
3857
  /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
3858
  /// A target may choose to implement its own refinement within this function.
3859
  /// If that's true, then return '0' as the number of RefinementSteps to avoid
3860
  /// any further refinement of the estimate.
3861
  /// An empty SDValue return means no estimate sequence can be created.
3862
  virtual SDValue getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
3863
38
                                   int Enabled, int &RefinementSteps) const {
3864
38
    return SDValue();
3865
38
  }
3866
3867
  //===--------------------------------------------------------------------===//
3868
  // Legalization utility functions
3869
  //
3870
3871
  /// Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes,
3872
  /// respectively, each computing an n/2-bit part of the result.
3873
  /// \param Result A vector that will be filled with the parts of the result
3874
  ///        in little-endian order.
3875
  /// \param LL Low bits of the LHS of the MUL.  You can use this parameter
3876
  ///        if you want to control how low bits are extracted from the LHS.
3877
  /// \param LH High bits of the LHS of the MUL.  See LL for meaning.
3878
  /// \param RL Low bits of the RHS of the MUL.  See LL for meaning
3879
  /// \param RH High bits of the RHS of the MUL.  See LL for meaning.
3880
  /// \returns true if the node has been expanded, false if it has not
3881
  bool expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl, SDValue LHS,
3882
                      SDValue RHS, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
3883
                      SelectionDAG &DAG, MulExpansionKind Kind,
3884
                      SDValue LL = SDValue(), SDValue LH = SDValue(),
3885
                      SDValue RL = SDValue(), SDValue RH = SDValue()) const;
3886
3887
  /// Expand a MUL into two nodes.  One that computes the high bits of
3888
  /// the result and one that computes the low bits.
3889
  /// \param HiLoVT The value type to use for the Lo and Hi nodes.
3890
  /// \param LL Low bits of the LHS of the MUL.  You can use this parameter
3891
  ///        if you want to control how low bits are extracted from the LHS.
3892
  /// \param LH High bits of the LHS of the MUL.  See LL for meaning.
3893
  /// \param RL Low bits of the RHS of the MUL.  See LL for meaning
3894
  /// \param RH High bits of the RHS of the MUL.  See LL for meaning.
3895
  /// \returns true if the node has been expanded. false if it has not
3896
  bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
3897
                 SelectionDAG &DAG, MulExpansionKind Kind,
3898
                 SDValue LL = SDValue(), SDValue LH = SDValue(),
3899
                 SDValue RL = SDValue(), SDValue RH = SDValue()) const;
3900
3901
  /// Expand funnel shift.
3902
  /// \param N Node to expand
3903
  /// \param Result output after conversion
3904
  /// \returns True, if the expansion was successful, false otherwise
3905
  bool expandFunnelShift(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3906
3907
  /// Expand rotations.
3908
  /// \param N Node to expand
3909
  /// \param Result output after conversion
3910
  /// \returns True, if the expansion was successful, false otherwise
3911
  bool expandROT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3912
3913
  /// Expand float(f32) to SINT(i64) conversion
3914
  /// \param N Node to expand
3915
  /// \param Result output after conversion
3916
  /// \returns True, if the expansion was successful, false otherwise
3917
  bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3918
3919
  /// Expand float to UINT conversion
3920
  /// \param N Node to expand
3921
  /// \param Result output after conversion
3922
  /// \returns True, if the expansion was successful, false otherwise
3923
  bool expandFP_TO_UINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3924
3925
  /// Expand UINT(i64) to double(f64) conversion
3926
  /// \param N Node to expand
3927
  /// \param Result output after conversion
3928
  /// \returns True, if the expansion was successful, false otherwise
3929
  bool expandUINT_TO_FP(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3930
3931
  /// Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
3932
  SDValue expandFMINNUM_FMAXNUM(SDNode *N, SelectionDAG &DAG) const;
3933
3934
  /// Expand CTPOP nodes. Expands vector/scalar CTPOP nodes,
3935
  /// vector nodes can only succeed if all operations are legal/custom.
3936
  /// \param N Node to expand
3937
  /// \param Result output after conversion
3938
  /// \returns True, if the expansion was successful, false otherwise
3939
  bool expandCTPOP(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3940
3941
  /// Expand CTLZ/CTLZ_ZERO_UNDEF nodes. Expands vector/scalar CTLZ nodes,
3942
  /// vector nodes can only succeed if all operations are legal/custom.
3943
  /// \param N Node to expand
3944
  /// \param Result output after conversion
3945
  /// \returns True, if the expansion was successful, false otherwise
3946
  bool expandCTLZ(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3947
3948
  /// Expand CTTZ/CTTZ_ZERO_UNDEF nodes. Expands vector/scalar CTTZ nodes,
3949
  /// vector nodes can only succeed if all operations are legal/custom.
3950
  /// \param N Node to expand
3951
  /// \param Result output after conversion
3952
  /// \returns True, if the expansion was successful, false otherwise
3953
  bool expandCTTZ(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3954
3955
  /// Expand ABS nodes. Expands vector/scalar ABS nodes,
3956
  /// vector nodes can only succeed if all operations are legal/custom.
3957
  /// (ABS x) -> (XOR (ADD x, (SRA x, type_size)), (SRA x, type_size))
3958
  /// \param N Node to expand
3959
  /// \param Result output after conversion
3960
  /// \returns True, if the expansion was successful, false otherwise
3961
  bool expandABS(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
3962
3963
  /// Turn load of vector type into a load of the individual elements.
3964
  /// \param LD load to expand
3965
  /// \returns MERGE_VALUEs of the scalar loads with their chains.
3966
  SDValue scalarizeVectorLoad(LoadSDNode *LD, SelectionDAG &DAG) const;
3967
3968
  // Turn a store of a vector type into stores of the individual elements.
3969
  /// \param ST Store with a vector value type
3970
  /// \returns MERGE_VALUs of the individual store chains.
3971
  SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const;
3972
3973
  /// Expands an unaligned load to 2 half-size loads for an integer, and
3974
  /// possibly more for vectors.
3975
  std::pair<SDValue, SDValue> expandUnalignedLoad(LoadSDNode *LD,
3976
                                                  SelectionDAG &DAG) const;
3977
3978
  /// Expands an unaligned store to 2 half-size stores for integer values, and
3979
  /// possibly more for vectors.
3980
  SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const;
3981
3982
  /// Increments memory address \p Addr according to the type of the value
3983
  /// \p DataVT that should be stored. If the data is stored in compressed
3984
  /// form, the memory address should be incremented according to the number of
3985
  /// the stored elements. This number is equal to the number of '1's bits
3986
  /// in the \p Mask.
3987
  /// \p DataVT is a vector type. \p Mask is a vector value.
3988
  /// \p DataVT and \p Mask have the same number of vector elements.
3989
  SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL,
3990
                                 EVT DataVT, SelectionDAG &DAG,
3991
                                 bool IsCompressedMemory) const;
3992
3993
  /// Get a pointer to vector element \p Idx located in memory for a vector of
3994
  /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
3995
  /// bounds the returned pointer is unspecified, but will be within the vector
3996
  /// bounds.
3997
  SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT,
3998
                                  SDValue Index) const;
3999
4000
  /// Method for building the DAG expansion of ISD::[US][ADD|SUB]SAT. This
4001
  /// method accepts integers as its arguments.
4002
  SDValue expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const;
4003
4004
  /// Method for building the DAG expansion of ISD::SMULFIX. This method accepts
4005
  /// integers as its arguments.
4006
  SDValue expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const;
4007
4008
  /// Method for building the DAG expansion of ISD::U(ADD|SUB)O. Expansion
4009
  /// always suceeds and populates the Result and Overflow arguments.
4010
  void expandUADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
4011
                      SelectionDAG &DAG) const;
4012
4013
  /// Method for building the DAG expansion of ISD::S(ADD|SUB)O. Expansion
4014
  /// always suceeds and populates the Result and Overflow arguments.
4015
  void expandSADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
4016
                      SelectionDAG &DAG) const;
4017
4018
  /// Method for building the DAG expansion of ISD::[US]MULO. Returns whether
4019
  /// expansion was successful and populates the Result and Overflow arguments.
4020
  bool expandMULO(SDNode *Node, SDValue &Result, SDValue &Overflow,
4021
                  SelectionDAG &DAG) const;
4022
4023
  /// Expand a VECREDUCE_* into an explicit calculation. If Count is specified,
4024
  /// only the first Count elements of the vector are used.
4025
  SDValue expandVecReduce(SDNode *Node, SelectionDAG &DAG) const;
4026
4027
  //===--------------------------------------------------------------------===//
4028
  // Instruction Emitting Hooks
4029
  //
4030
4031
  /// This method should be implemented by targets that mark instructions with
4032
  /// the 'usesCustomInserter' flag.  These instructions are special in various
4033
  /// ways, which require special support to insert.  The specified MachineInstr
4034
  /// is created but not inserted into any basic blocks, and this method is
4035
  /// called to expand it into a sequence of instructions, potentially also
4036
  /// creating new basic blocks and control flow.
4037
  /// As long as the returned basic block is different (i.e., we created a new
4038
  /// one), the custom inserter is free to modify the rest of \p MBB.
4039
  virtual MachineBasicBlock *
4040
  EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const;
4041
4042
  /// This method should be implemented by targets that mark instructions with
4043
  /// the 'hasPostISelHook' flag. These instructions must be adjusted after
4044
  /// instruction selection by target hooks.  e.g. To fill in optional defs for
4045
  /// ARM 's' setting instructions.
4046
  virtual void AdjustInstrPostInstrSelection(MachineInstr &MI,
4047
                                             SDNode *Node) const;
4048
4049
  /// If this function returns true, SelectionDAGBuilder emits a
4050
  /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
4051
27
  virtual bool useLoadStackGuardNode() const {
4052
27
    return false;
4053
27
  }
4054
4055
  virtual SDValue emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
4056
0
                                      const SDLoc &DL) const {
4057
0
    llvm_unreachable("not implemented for this target");
4058
0
  }
4059
4060
  /// Lower TLS global address SDNode for target independent emulated TLS model.
4061
  virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
4062
                                          SelectionDAG &DAG) const;
4063
4064
  /// Expands target specific indirect branch for the case of JumpTable
4065
  /// expanasion.
4066
  virtual SDValue expandIndirectJTBranch(const SDLoc& dl, SDValue Value, SDValue Addr,
4067
371
                                         SelectionDAG &DAG) const {
4068
371
    return DAG.getNode(ISD::BRIND, dl, MVT::Other, Value, Addr);
4069
371
  }
4070
4071
  // seteq(x, 0) -> truncate(srl(ctlz(zext(x)), log2(#bits)))
4072
  // If we're comparing for equality to zero and isCtlzFast is true, expose the
4073
  // fact that this can be implemented as a ctlz/srl pair, so that the dag
4074
  // combiner can fold the new nodes.
4075
  SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const;
4076
4077
private:
4078
  SDValue foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
4079
                           const SDLoc &DL, DAGCombinerInfo &DCI) const;
4080
  SDValue foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
4081
                             const SDLoc &DL, DAGCombinerInfo &DCI) const;
4082
4083
  SDValue optimizeSetCCOfSignedTruncationCheck(EVT SCCVT, SDValue N0,
4084
                                               SDValue N1, ISD::CondCode Cond,
4085
                                               DAGCombinerInfo &DCI,
4086
                                               const SDLoc &DL) const;
4087
4088
  SDValue prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
4089
                            SDValue CompTargetNode, ISD::CondCode Cond,
4090
                            DAGCombinerInfo &DCI, const SDLoc &DL,
4091
                            SmallVectorImpl<SDNode *> &Created) const;
4092
  SDValue buildUREMEqFold(EVT SETCCVT, SDValue REMNode, SDValue CompTargetNode,
4093
                          ISD::CondCode Cond, DAGCombinerInfo &DCI,
4094
                          const SDLoc &DL) const;
4095
};
4096
4097
/// Given an LLVM IR type and return type attributes, compute the return value
4098
/// EVTs and flags, and optionally also the offsets, if the return value is
4099
/// being lowered to memory.
4100
void GetReturnInfo(CallingConv::ID CC, Type *ReturnType, AttributeList attr,
4101
                   SmallVectorImpl<ISD::OutputArg> &Outs,
4102
                   const TargetLowering &TLI, const DataLayout &DL);
4103
4104
} // end namespace llvm
4105
4106
#endif // LLVM_CODEGEN_TARGETLOWERING_H