xref: /llvm-project/llvm/lib/CodeGen/TargetLoweringBase.cpp (revision 8aceb7a53d82f9566a7cf4775effa4089b22a75b)
1 //===- TargetLoweringBase.cpp - Implement the TargetLoweringBase class ----===//
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 // This implements the TargetLoweringBase class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/BitVector.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Analysis/Loads.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/ISDOpcodes.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/RuntimeLibcalls.h"
32 #include "llvm/CodeGen/StackMaps.h"
33 #include "llvm/CodeGen/TargetLowering.h"
34 #include "llvm/CodeGen/TargetOpcodes.h"
35 #include "llvm/CodeGen/TargetRegisterInfo.h"
36 #include "llvm/CodeGen/ValueTypes.h"
37 #include "llvm/CodeGenTypes/MachineValueType.h"
38 #include "llvm/IR/Attributes.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalValue.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/IRBuilder.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "llvm/TargetParser/Triple.h"
56 #include "llvm/Transforms/Utils/SizeOpts.h"
57 #include <algorithm>
58 #include <cassert>
59 #include <cstdint>
60 #include <cstring>
61 #include <iterator>
62 #include <string>
63 #include <tuple>
64 #include <utility>
65 
66 using namespace llvm;
67 
68 static cl::opt<bool> JumpIsExpensiveOverride(
69     "jump-is-expensive", cl::init(false),
70     cl::desc("Do not create extra branches to split comparison logic."),
71     cl::Hidden);
72 
73 static cl::opt<unsigned> MinimumJumpTableEntries
74   ("min-jump-table-entries", cl::init(4), cl::Hidden,
75    cl::desc("Set minimum number of entries to use a jump table."));
76 
77 static cl::opt<unsigned> MaximumJumpTableSize
78   ("max-jump-table-size", cl::init(UINT_MAX), cl::Hidden,
79    cl::desc("Set maximum size of jump tables."));
80 
81 /// Minimum jump table density for normal functions.
82 static cl::opt<unsigned>
83     JumpTableDensity("jump-table-density", cl::init(10), cl::Hidden,
84                      cl::desc("Minimum density for building a jump table in "
85                               "a normal function"));
86 
87 /// Minimum jump table density for -Os or -Oz functions.
88 static cl::opt<unsigned> OptsizeJumpTableDensity(
89     "optsize-jump-table-density", cl::init(40), cl::Hidden,
90     cl::desc("Minimum density for building a jump table in "
91              "an optsize function"));
92 
93 // FIXME: This option is only to test if the strict fp operation processed
94 // correctly by preventing mutating strict fp operation to normal fp operation
95 // during development. When the backend supports strict float operation, this
96 // option will be meaningless.
97 static cl::opt<bool> DisableStrictNodeMutation("disable-strictnode-mutation",
98        cl::desc("Don't mutate strict-float node to a legalize node"),
99        cl::init(false), cl::Hidden);
100 
101 static bool darwinHasSinCos(const Triple &TT) {
102   assert(TT.isOSDarwin() && "should be called with darwin triple");
103   // Don't bother with 32 bit x86.
104   if (TT.getArch() == Triple::x86)
105     return false;
106   // Macos < 10.9 has no sincos_stret.
107   if (TT.isMacOSX())
108     return !TT.isMacOSXVersionLT(10, 9) && TT.isArch64Bit();
109   // iOS < 7.0 has no sincos_stret.
110   if (TT.isiOS())
111     return !TT.isOSVersionLT(7, 0);
112   // Any other darwin such as WatchOS/TvOS is new enough.
113   return true;
114 }
115 
116 void TargetLoweringBase::InitLibcalls(const Triple &TT) {
117 #define HANDLE_LIBCALL(code, name) \
118   setLibcallName(RTLIB::code, name);
119 #include "llvm/IR/RuntimeLibcalls.def"
120 #undef HANDLE_LIBCALL
121   // Initialize calling conventions to their default.
122   for (int LC = 0; LC < RTLIB::UNKNOWN_LIBCALL; ++LC)
123     setLibcallCallingConv((RTLIB::Libcall)LC, CallingConv::C);
124 
125   // Use the f128 variants of math functions on x86_64
126   if (TT.getArch() == Triple::ArchType::x86_64 && TT.isGNUEnvironment()) {
127     setLibcallName(RTLIB::REM_F128, "fmodf128");
128     setLibcallName(RTLIB::FMA_F128, "fmaf128");
129     setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
130     setLibcallName(RTLIB::CBRT_F128, "cbrtf128");
131     setLibcallName(RTLIB::LOG_F128, "logf128");
132     setLibcallName(RTLIB::LOG_FINITE_F128, "__logf128_finite");
133     setLibcallName(RTLIB::LOG2_F128, "log2f128");
134     setLibcallName(RTLIB::LOG2_FINITE_F128, "__log2f128_finite");
135     setLibcallName(RTLIB::LOG10_F128, "log10f128");
136     setLibcallName(RTLIB::LOG10_FINITE_F128, "__log10f128_finite");
137     setLibcallName(RTLIB::EXP_F128, "expf128");
138     setLibcallName(RTLIB::EXP_FINITE_F128, "__expf128_finite");
139     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
140     setLibcallName(RTLIB::EXP2_FINITE_F128, "__exp2f128_finite");
141     setLibcallName(RTLIB::EXP10_F128, "exp10f128");
142     setLibcallName(RTLIB::SIN_F128, "sinf128");
143     setLibcallName(RTLIB::COS_F128, "cosf128");
144     setLibcallName(RTLIB::SINCOS_F128, "sincosf128");
145     setLibcallName(RTLIB::POW_F128, "powf128");
146     setLibcallName(RTLIB::POW_FINITE_F128, "__powf128_finite");
147     setLibcallName(RTLIB::CEIL_F128, "ceilf128");
148     setLibcallName(RTLIB::TRUNC_F128, "truncf128");
149     setLibcallName(RTLIB::RINT_F128, "rintf128");
150     setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
151     setLibcallName(RTLIB::ROUND_F128, "roundf128");
152     setLibcallName(RTLIB::ROUNDEVEN_F128, "roundevenf128");
153     setLibcallName(RTLIB::FLOOR_F128, "floorf128");
154     setLibcallName(RTLIB::COPYSIGN_F128, "copysignf128");
155     setLibcallName(RTLIB::FMIN_F128, "fminf128");
156     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
157     setLibcallName(RTLIB::LROUND_F128, "lroundf128");
158     setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
159     setLibcallName(RTLIB::LRINT_F128, "lrintf128");
160     setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
161     setLibcallName(RTLIB::LDEXP_F128, "ldexpf128");
162     setLibcallName(RTLIB::FREXP_F128, "frexpf128");
163   }
164 
165   // For IEEE quad-precision libcall names, PPC uses "kf" instead of "tf".
166   if (TT.isPPC()) {
167     setLibcallName(RTLIB::ADD_F128, "__addkf3");
168     setLibcallName(RTLIB::SUB_F128, "__subkf3");
169     setLibcallName(RTLIB::MUL_F128, "__mulkf3");
170     setLibcallName(RTLIB::DIV_F128, "__divkf3");
171     setLibcallName(RTLIB::POWI_F128, "__powikf2");
172     setLibcallName(RTLIB::FPEXT_F32_F128, "__extendsfkf2");
173     setLibcallName(RTLIB::FPEXT_F64_F128, "__extenddfkf2");
174     setLibcallName(RTLIB::FPROUND_F128_F32, "__trunckfsf2");
175     setLibcallName(RTLIB::FPROUND_F128_F64, "__trunckfdf2");
176     setLibcallName(RTLIB::FPTOSINT_F128_I32, "__fixkfsi");
177     setLibcallName(RTLIB::FPTOSINT_F128_I64, "__fixkfdi");
178     setLibcallName(RTLIB::FPTOSINT_F128_I128, "__fixkfti");
179     setLibcallName(RTLIB::FPTOUINT_F128_I32, "__fixunskfsi");
180     setLibcallName(RTLIB::FPTOUINT_F128_I64, "__fixunskfdi");
181     setLibcallName(RTLIB::FPTOUINT_F128_I128, "__fixunskfti");
182     setLibcallName(RTLIB::SINTTOFP_I32_F128, "__floatsikf");
183     setLibcallName(RTLIB::SINTTOFP_I64_F128, "__floatdikf");
184     setLibcallName(RTLIB::SINTTOFP_I128_F128, "__floattikf");
185     setLibcallName(RTLIB::UINTTOFP_I32_F128, "__floatunsikf");
186     setLibcallName(RTLIB::UINTTOFP_I64_F128, "__floatundikf");
187     setLibcallName(RTLIB::UINTTOFP_I128_F128, "__floatuntikf");
188     setLibcallName(RTLIB::OEQ_F128, "__eqkf2");
189     setLibcallName(RTLIB::UNE_F128, "__nekf2");
190     setLibcallName(RTLIB::OGE_F128, "__gekf2");
191     setLibcallName(RTLIB::OLT_F128, "__ltkf2");
192     setLibcallName(RTLIB::OLE_F128, "__lekf2");
193     setLibcallName(RTLIB::OGT_F128, "__gtkf2");
194     setLibcallName(RTLIB::UO_F128, "__unordkf2");
195   }
196 
197   // A few names are different on particular architectures or environments.
198   if (TT.isOSDarwin()) {
199     // For f16/f32 conversions, Darwin uses the standard naming scheme, instead
200     // of the gnueabi-style __gnu_*_ieee.
201     // FIXME: What about other targets?
202     setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
203     setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
204 
205     // Some darwins have an optimized __bzero/bzero function.
206     switch (TT.getArch()) {
207     case Triple::x86:
208     case Triple::x86_64:
209       if (TT.isMacOSX() && !TT.isMacOSXVersionLT(10, 6))
210         setLibcallName(RTLIB::BZERO, "__bzero");
211       break;
212     case Triple::aarch64:
213     case Triple::aarch64_32:
214       setLibcallName(RTLIB::BZERO, "bzero");
215       break;
216     default:
217       break;
218     }
219 
220     if (darwinHasSinCos(TT)) {
221       setLibcallName(RTLIB::SINCOS_STRET_F32, "__sincosf_stret");
222       setLibcallName(RTLIB::SINCOS_STRET_F64, "__sincos_stret");
223       if (TT.isWatchABI()) {
224         setLibcallCallingConv(RTLIB::SINCOS_STRET_F32,
225                               CallingConv::ARM_AAPCS_VFP);
226         setLibcallCallingConv(RTLIB::SINCOS_STRET_F64,
227                               CallingConv::ARM_AAPCS_VFP);
228       }
229     }
230 
231     switch (TT.getOS()) {
232     case Triple::MacOSX:
233       if (TT.isMacOSXVersionLT(10, 9)) {
234         setLibcallName(RTLIB::EXP10_F32, nullptr);
235         setLibcallName(RTLIB::EXP10_F64, nullptr);
236       } else {
237         setLibcallName(RTLIB::EXP10_F32, "__exp10f");
238         setLibcallName(RTLIB::EXP10_F64, "__exp10");
239       }
240       break;
241     case Triple::IOS:
242     case Triple::TvOS:
243     case Triple::WatchOS:
244     case Triple::XROS:
245       if (!TT.isWatchOS() &&
246           (TT.isOSVersionLT(7, 0) || (TT.isOSVersionLT(9, 0) && TT.isX86()))) {
247         setLibcallName(RTLIB::EXP10_F32, nullptr);
248         setLibcallName(RTLIB::EXP10_F64, nullptr);
249       } else {
250         setLibcallName(RTLIB::EXP10_F32, "__exp10f");
251         setLibcallName(RTLIB::EXP10_F64, "__exp10");
252       }
253 
254       break;
255     default:
256       break;
257     }
258   } else {
259     setLibcallName(RTLIB::FPEXT_F16_F32, "__gnu_h2f_ieee");
260     setLibcallName(RTLIB::FPROUND_F32_F16, "__gnu_f2h_ieee");
261   }
262 
263   if (TT.isGNUEnvironment() || TT.isOSFuchsia() ||
264       (TT.isAndroid() && !TT.isAndroidVersionLT(9))) {
265     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
266     setLibcallName(RTLIB::SINCOS_F64, "sincos");
267     setLibcallName(RTLIB::SINCOS_F80, "sincosl");
268     setLibcallName(RTLIB::SINCOS_F128, "sincosl");
269     setLibcallName(RTLIB::SINCOS_PPCF128, "sincosl");
270   }
271 
272   if (TT.isPS()) {
273     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
274     setLibcallName(RTLIB::SINCOS_F64, "sincos");
275   }
276 
277   if (TT.isOSOpenBSD()) {
278     setLibcallName(RTLIB::STACKPROTECTOR_CHECK_FAIL, nullptr);
279   }
280 
281   if (TT.isOSWindows() && !TT.isOSCygMing()) {
282     setLibcallName(RTLIB::LDEXP_F32, nullptr);
283     setLibcallName(RTLIB::LDEXP_F80, nullptr);
284     setLibcallName(RTLIB::LDEXP_F128, nullptr);
285     setLibcallName(RTLIB::LDEXP_PPCF128, nullptr);
286 
287     setLibcallName(RTLIB::FREXP_F32, nullptr);
288     setLibcallName(RTLIB::FREXP_F80, nullptr);
289     setLibcallName(RTLIB::FREXP_F128, nullptr);
290     setLibcallName(RTLIB::FREXP_PPCF128, nullptr);
291   }
292 }
293 
294 /// GetFPLibCall - Helper to return the right libcall for the given floating
295 /// point type, or UNKNOWN_LIBCALL if there is none.
296 RTLIB::Libcall RTLIB::getFPLibCall(EVT VT,
297                                    RTLIB::Libcall Call_F32,
298                                    RTLIB::Libcall Call_F64,
299                                    RTLIB::Libcall Call_F80,
300                                    RTLIB::Libcall Call_F128,
301                                    RTLIB::Libcall Call_PPCF128) {
302   return
303     VT == MVT::f32 ? Call_F32 :
304     VT == MVT::f64 ? Call_F64 :
305     VT == MVT::f80 ? Call_F80 :
306     VT == MVT::f128 ? Call_F128 :
307     VT == MVT::ppcf128 ? Call_PPCF128 :
308     RTLIB::UNKNOWN_LIBCALL;
309 }
310 
311 /// getFPEXT - Return the FPEXT_*_* value for the given types, or
312 /// UNKNOWN_LIBCALL if there is none.
313 RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) {
314   if (OpVT == MVT::f16) {
315     if (RetVT == MVT::f32)
316       return FPEXT_F16_F32;
317     if (RetVT == MVT::f64)
318       return FPEXT_F16_F64;
319     if (RetVT == MVT::f80)
320       return FPEXT_F16_F80;
321     if (RetVT == MVT::f128)
322       return FPEXT_F16_F128;
323   } else if (OpVT == MVT::f32) {
324     if (RetVT == MVT::f64)
325       return FPEXT_F32_F64;
326     if (RetVT == MVT::f128)
327       return FPEXT_F32_F128;
328     if (RetVT == MVT::ppcf128)
329       return FPEXT_F32_PPCF128;
330   } else if (OpVT == MVT::f64) {
331     if (RetVT == MVT::f128)
332       return FPEXT_F64_F128;
333     else if (RetVT == MVT::ppcf128)
334       return FPEXT_F64_PPCF128;
335   } else if (OpVT == MVT::f80) {
336     if (RetVT == MVT::f128)
337       return FPEXT_F80_F128;
338   } else if (OpVT == MVT::bf16) {
339     if (RetVT == MVT::f32)
340       return FPEXT_BF16_F32;
341   }
342 
343   return UNKNOWN_LIBCALL;
344 }
345 
346 /// getFPROUND - Return the FPROUND_*_* value for the given types, or
347 /// UNKNOWN_LIBCALL if there is none.
348 RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) {
349   if (RetVT == MVT::f16) {
350     if (OpVT == MVT::f32)
351       return FPROUND_F32_F16;
352     if (OpVT == MVT::f64)
353       return FPROUND_F64_F16;
354     if (OpVT == MVT::f80)
355       return FPROUND_F80_F16;
356     if (OpVT == MVT::f128)
357       return FPROUND_F128_F16;
358     if (OpVT == MVT::ppcf128)
359       return FPROUND_PPCF128_F16;
360   } else if (RetVT == MVT::bf16) {
361     if (OpVT == MVT::f32)
362       return FPROUND_F32_BF16;
363     if (OpVT == MVT::f64)
364       return FPROUND_F64_BF16;
365   } else if (RetVT == MVT::f32) {
366     if (OpVT == MVT::f64)
367       return FPROUND_F64_F32;
368     if (OpVT == MVT::f80)
369       return FPROUND_F80_F32;
370     if (OpVT == MVT::f128)
371       return FPROUND_F128_F32;
372     if (OpVT == MVT::ppcf128)
373       return FPROUND_PPCF128_F32;
374   } else if (RetVT == MVT::f64) {
375     if (OpVT == MVT::f80)
376       return FPROUND_F80_F64;
377     if (OpVT == MVT::f128)
378       return FPROUND_F128_F64;
379     if (OpVT == MVT::ppcf128)
380       return FPROUND_PPCF128_F64;
381   } else if (RetVT == MVT::f80) {
382     if (OpVT == MVT::f128)
383       return FPROUND_F128_F80;
384   }
385 
386   return UNKNOWN_LIBCALL;
387 }
388 
389 /// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or
390 /// UNKNOWN_LIBCALL if there is none.
391 RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) {
392   if (OpVT == MVT::f16) {
393     if (RetVT == MVT::i32)
394       return FPTOSINT_F16_I32;
395     if (RetVT == MVT::i64)
396       return FPTOSINT_F16_I64;
397     if (RetVT == MVT::i128)
398       return FPTOSINT_F16_I128;
399   } else if (OpVT == MVT::f32) {
400     if (RetVT == MVT::i32)
401       return FPTOSINT_F32_I32;
402     if (RetVT == MVT::i64)
403       return FPTOSINT_F32_I64;
404     if (RetVT == MVT::i128)
405       return FPTOSINT_F32_I128;
406   } else if (OpVT == MVT::f64) {
407     if (RetVT == MVT::i32)
408       return FPTOSINT_F64_I32;
409     if (RetVT == MVT::i64)
410       return FPTOSINT_F64_I64;
411     if (RetVT == MVT::i128)
412       return FPTOSINT_F64_I128;
413   } else if (OpVT == MVT::f80) {
414     if (RetVT == MVT::i32)
415       return FPTOSINT_F80_I32;
416     if (RetVT == MVT::i64)
417       return FPTOSINT_F80_I64;
418     if (RetVT == MVT::i128)
419       return FPTOSINT_F80_I128;
420   } else if (OpVT == MVT::f128) {
421     if (RetVT == MVT::i32)
422       return FPTOSINT_F128_I32;
423     if (RetVT == MVT::i64)
424       return FPTOSINT_F128_I64;
425     if (RetVT == MVT::i128)
426       return FPTOSINT_F128_I128;
427   } else if (OpVT == MVT::ppcf128) {
428     if (RetVT == MVT::i32)
429       return FPTOSINT_PPCF128_I32;
430     if (RetVT == MVT::i64)
431       return FPTOSINT_PPCF128_I64;
432     if (RetVT == MVT::i128)
433       return FPTOSINT_PPCF128_I128;
434   }
435   return UNKNOWN_LIBCALL;
436 }
437 
438 /// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or
439 /// UNKNOWN_LIBCALL if there is none.
440 RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) {
441   if (OpVT == MVT::f16) {
442     if (RetVT == MVT::i32)
443       return FPTOUINT_F16_I32;
444     if (RetVT == MVT::i64)
445       return FPTOUINT_F16_I64;
446     if (RetVT == MVT::i128)
447       return FPTOUINT_F16_I128;
448   } else if (OpVT == MVT::f32) {
449     if (RetVT == MVT::i32)
450       return FPTOUINT_F32_I32;
451     if (RetVT == MVT::i64)
452       return FPTOUINT_F32_I64;
453     if (RetVT == MVT::i128)
454       return FPTOUINT_F32_I128;
455   } else if (OpVT == MVT::f64) {
456     if (RetVT == MVT::i32)
457       return FPTOUINT_F64_I32;
458     if (RetVT == MVT::i64)
459       return FPTOUINT_F64_I64;
460     if (RetVT == MVT::i128)
461       return FPTOUINT_F64_I128;
462   } else if (OpVT == MVT::f80) {
463     if (RetVT == MVT::i32)
464       return FPTOUINT_F80_I32;
465     if (RetVT == MVT::i64)
466       return FPTOUINT_F80_I64;
467     if (RetVT == MVT::i128)
468       return FPTOUINT_F80_I128;
469   } else if (OpVT == MVT::f128) {
470     if (RetVT == MVT::i32)
471       return FPTOUINT_F128_I32;
472     if (RetVT == MVT::i64)
473       return FPTOUINT_F128_I64;
474     if (RetVT == MVT::i128)
475       return FPTOUINT_F128_I128;
476   } else if (OpVT == MVT::ppcf128) {
477     if (RetVT == MVT::i32)
478       return FPTOUINT_PPCF128_I32;
479     if (RetVT == MVT::i64)
480       return FPTOUINT_PPCF128_I64;
481     if (RetVT == MVT::i128)
482       return FPTOUINT_PPCF128_I128;
483   }
484   return UNKNOWN_LIBCALL;
485 }
486 
487 /// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or
488 /// UNKNOWN_LIBCALL if there is none.
489 RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) {
490   if (OpVT == MVT::i32) {
491     if (RetVT == MVT::f16)
492       return SINTTOFP_I32_F16;
493     if (RetVT == MVT::f32)
494       return SINTTOFP_I32_F32;
495     if (RetVT == MVT::f64)
496       return SINTTOFP_I32_F64;
497     if (RetVT == MVT::f80)
498       return SINTTOFP_I32_F80;
499     if (RetVT == MVT::f128)
500       return SINTTOFP_I32_F128;
501     if (RetVT == MVT::ppcf128)
502       return SINTTOFP_I32_PPCF128;
503   } else if (OpVT == MVT::i64) {
504     if (RetVT == MVT::f16)
505       return SINTTOFP_I64_F16;
506     if (RetVT == MVT::f32)
507       return SINTTOFP_I64_F32;
508     if (RetVT == MVT::f64)
509       return SINTTOFP_I64_F64;
510     if (RetVT == MVT::f80)
511       return SINTTOFP_I64_F80;
512     if (RetVT == MVT::f128)
513       return SINTTOFP_I64_F128;
514     if (RetVT == MVT::ppcf128)
515       return SINTTOFP_I64_PPCF128;
516   } else if (OpVT == MVT::i128) {
517     if (RetVT == MVT::f16)
518       return SINTTOFP_I128_F16;
519     if (RetVT == MVT::f32)
520       return SINTTOFP_I128_F32;
521     if (RetVT == MVT::f64)
522       return SINTTOFP_I128_F64;
523     if (RetVT == MVT::f80)
524       return SINTTOFP_I128_F80;
525     if (RetVT == MVT::f128)
526       return SINTTOFP_I128_F128;
527     if (RetVT == MVT::ppcf128)
528       return SINTTOFP_I128_PPCF128;
529   }
530   return UNKNOWN_LIBCALL;
531 }
532 
533 /// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or
534 /// UNKNOWN_LIBCALL if there is none.
535 RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) {
536   if (OpVT == MVT::i32) {
537     if (RetVT == MVT::f16)
538       return UINTTOFP_I32_F16;
539     if (RetVT == MVT::f32)
540       return UINTTOFP_I32_F32;
541     if (RetVT == MVT::f64)
542       return UINTTOFP_I32_F64;
543     if (RetVT == MVT::f80)
544       return UINTTOFP_I32_F80;
545     if (RetVT == MVT::f128)
546       return UINTTOFP_I32_F128;
547     if (RetVT == MVT::ppcf128)
548       return UINTTOFP_I32_PPCF128;
549   } else if (OpVT == MVT::i64) {
550     if (RetVT == MVT::f16)
551       return UINTTOFP_I64_F16;
552     if (RetVT == MVT::f32)
553       return UINTTOFP_I64_F32;
554     if (RetVT == MVT::f64)
555       return UINTTOFP_I64_F64;
556     if (RetVT == MVT::f80)
557       return UINTTOFP_I64_F80;
558     if (RetVT == MVT::f128)
559       return UINTTOFP_I64_F128;
560     if (RetVT == MVT::ppcf128)
561       return UINTTOFP_I64_PPCF128;
562   } else if (OpVT == MVT::i128) {
563     if (RetVT == MVT::f16)
564       return UINTTOFP_I128_F16;
565     if (RetVT == MVT::f32)
566       return UINTTOFP_I128_F32;
567     if (RetVT == MVT::f64)
568       return UINTTOFP_I128_F64;
569     if (RetVT == MVT::f80)
570       return UINTTOFP_I128_F80;
571     if (RetVT == MVT::f128)
572       return UINTTOFP_I128_F128;
573     if (RetVT == MVT::ppcf128)
574       return UINTTOFP_I128_PPCF128;
575   }
576   return UNKNOWN_LIBCALL;
577 }
578 
579 RTLIB::Libcall RTLIB::getPOWI(EVT RetVT) {
580   return getFPLibCall(RetVT, POWI_F32, POWI_F64, POWI_F80, POWI_F128,
581                       POWI_PPCF128);
582 }
583 
584 RTLIB::Libcall RTLIB::getLDEXP(EVT RetVT) {
585   return getFPLibCall(RetVT, LDEXP_F32, LDEXP_F64, LDEXP_F80, LDEXP_F128,
586                       LDEXP_PPCF128);
587 }
588 
589 RTLIB::Libcall RTLIB::getFREXP(EVT RetVT) {
590   return getFPLibCall(RetVT, FREXP_F32, FREXP_F64, FREXP_F80, FREXP_F128,
591                       FREXP_PPCF128);
592 }
593 
594 RTLIB::Libcall RTLIB::getOutlineAtomicHelper(const Libcall (&LC)[5][4],
595                                              AtomicOrdering Order,
596                                              uint64_t MemSize) {
597   unsigned ModeN, ModelN;
598   switch (MemSize) {
599   case 1:
600     ModeN = 0;
601     break;
602   case 2:
603     ModeN = 1;
604     break;
605   case 4:
606     ModeN = 2;
607     break;
608   case 8:
609     ModeN = 3;
610     break;
611   case 16:
612     ModeN = 4;
613     break;
614   default:
615     return RTLIB::UNKNOWN_LIBCALL;
616   }
617 
618   switch (Order) {
619   case AtomicOrdering::Monotonic:
620     ModelN = 0;
621     break;
622   case AtomicOrdering::Acquire:
623     ModelN = 1;
624     break;
625   case AtomicOrdering::Release:
626     ModelN = 2;
627     break;
628   case AtomicOrdering::AcquireRelease:
629   case AtomicOrdering::SequentiallyConsistent:
630     ModelN = 3;
631     break;
632   default:
633     return UNKNOWN_LIBCALL;
634   }
635 
636   return LC[ModeN][ModelN];
637 }
638 
639 RTLIB::Libcall RTLIB::getOUTLINE_ATOMIC(unsigned Opc, AtomicOrdering Order,
640                                         MVT VT) {
641   if (!VT.isScalarInteger())
642     return UNKNOWN_LIBCALL;
643   uint64_t MemSize = VT.getScalarSizeInBits() / 8;
644 
645 #define LCALLS(A, B)                                                           \
646   { A##B##_RELAX, A##B##_ACQ, A##B##_REL, A##B##_ACQ_REL }
647 #define LCALL5(A)                                                              \
648   LCALLS(A, 1), LCALLS(A, 2), LCALLS(A, 4), LCALLS(A, 8), LCALLS(A, 16)
649   switch (Opc) {
650   case ISD::ATOMIC_CMP_SWAP: {
651     const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_CAS)};
652     return getOutlineAtomicHelper(LC, Order, MemSize);
653   }
654   case ISD::ATOMIC_SWAP: {
655     const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_SWP)};
656     return getOutlineAtomicHelper(LC, Order, MemSize);
657   }
658   case ISD::ATOMIC_LOAD_ADD: {
659     const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDADD)};
660     return getOutlineAtomicHelper(LC, Order, MemSize);
661   }
662   case ISD::ATOMIC_LOAD_OR: {
663     const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDSET)};
664     return getOutlineAtomicHelper(LC, Order, MemSize);
665   }
666   case ISD::ATOMIC_LOAD_CLR: {
667     const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDCLR)};
668     return getOutlineAtomicHelper(LC, Order, MemSize);
669   }
670   case ISD::ATOMIC_LOAD_XOR: {
671     const Libcall LC[5][4] = {LCALL5(OUTLINE_ATOMIC_LDEOR)};
672     return getOutlineAtomicHelper(LC, Order, MemSize);
673   }
674   default:
675     return UNKNOWN_LIBCALL;
676   }
677 #undef LCALLS
678 #undef LCALL5
679 }
680 
681 RTLIB::Libcall RTLIB::getSYNC(unsigned Opc, MVT VT) {
682 #define OP_TO_LIBCALL(Name, Enum)                                              \
683   case Name:                                                                   \
684     switch (VT.SimpleTy) {                                                     \
685     default:                                                                   \
686       return UNKNOWN_LIBCALL;                                                  \
687     case MVT::i8:                                                              \
688       return Enum##_1;                                                         \
689     case MVT::i16:                                                             \
690       return Enum##_2;                                                         \
691     case MVT::i32:                                                             \
692       return Enum##_4;                                                         \
693     case MVT::i64:                                                             \
694       return Enum##_8;                                                         \
695     case MVT::i128:                                                            \
696       return Enum##_16;                                                        \
697     }
698 
699   switch (Opc) {
700     OP_TO_LIBCALL(ISD::ATOMIC_SWAP, SYNC_LOCK_TEST_AND_SET)
701     OP_TO_LIBCALL(ISD::ATOMIC_CMP_SWAP, SYNC_VAL_COMPARE_AND_SWAP)
702     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_ADD, SYNC_FETCH_AND_ADD)
703     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_SUB, SYNC_FETCH_AND_SUB)
704     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_AND, SYNC_FETCH_AND_AND)
705     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_OR, SYNC_FETCH_AND_OR)
706     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_XOR, SYNC_FETCH_AND_XOR)
707     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_NAND, SYNC_FETCH_AND_NAND)
708     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MAX, SYNC_FETCH_AND_MAX)
709     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMAX, SYNC_FETCH_AND_UMAX)
710     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MIN, SYNC_FETCH_AND_MIN)
711     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMIN, SYNC_FETCH_AND_UMIN)
712   }
713 
714 #undef OP_TO_LIBCALL
715 
716   return UNKNOWN_LIBCALL;
717 }
718 
719 RTLIB::Libcall RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
720   switch (ElementSize) {
721   case 1:
722     return MEMCPY_ELEMENT_UNORDERED_ATOMIC_1;
723   case 2:
724     return MEMCPY_ELEMENT_UNORDERED_ATOMIC_2;
725   case 4:
726     return MEMCPY_ELEMENT_UNORDERED_ATOMIC_4;
727   case 8:
728     return MEMCPY_ELEMENT_UNORDERED_ATOMIC_8;
729   case 16:
730     return MEMCPY_ELEMENT_UNORDERED_ATOMIC_16;
731   default:
732     return UNKNOWN_LIBCALL;
733   }
734 }
735 
736 RTLIB::Libcall RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
737   switch (ElementSize) {
738   case 1:
739     return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_1;
740   case 2:
741     return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_2;
742   case 4:
743     return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_4;
744   case 8:
745     return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_8;
746   case 16:
747     return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_16;
748   default:
749     return UNKNOWN_LIBCALL;
750   }
751 }
752 
753 RTLIB::Libcall RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
754   switch (ElementSize) {
755   case 1:
756     return MEMSET_ELEMENT_UNORDERED_ATOMIC_1;
757   case 2:
758     return MEMSET_ELEMENT_UNORDERED_ATOMIC_2;
759   case 4:
760     return MEMSET_ELEMENT_UNORDERED_ATOMIC_4;
761   case 8:
762     return MEMSET_ELEMENT_UNORDERED_ATOMIC_8;
763   case 16:
764     return MEMSET_ELEMENT_UNORDERED_ATOMIC_16;
765   default:
766     return UNKNOWN_LIBCALL;
767   }
768 }
769 
770 /// InitCmpLibcallCCs - Set default comparison libcall CC.
771 static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
772   std::fill(CCs, CCs + RTLIB::UNKNOWN_LIBCALL, ISD::SETCC_INVALID);
773   CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
774   CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
775   CCs[RTLIB::OEQ_F128] = ISD::SETEQ;
776   CCs[RTLIB::OEQ_PPCF128] = ISD::SETEQ;
777   CCs[RTLIB::UNE_F32] = ISD::SETNE;
778   CCs[RTLIB::UNE_F64] = ISD::SETNE;
779   CCs[RTLIB::UNE_F128] = ISD::SETNE;
780   CCs[RTLIB::UNE_PPCF128] = ISD::SETNE;
781   CCs[RTLIB::OGE_F32] = ISD::SETGE;
782   CCs[RTLIB::OGE_F64] = ISD::SETGE;
783   CCs[RTLIB::OGE_F128] = ISD::SETGE;
784   CCs[RTLIB::OGE_PPCF128] = ISD::SETGE;
785   CCs[RTLIB::OLT_F32] = ISD::SETLT;
786   CCs[RTLIB::OLT_F64] = ISD::SETLT;
787   CCs[RTLIB::OLT_F128] = ISD::SETLT;
788   CCs[RTLIB::OLT_PPCF128] = ISD::SETLT;
789   CCs[RTLIB::OLE_F32] = ISD::SETLE;
790   CCs[RTLIB::OLE_F64] = ISD::SETLE;
791   CCs[RTLIB::OLE_F128] = ISD::SETLE;
792   CCs[RTLIB::OLE_PPCF128] = ISD::SETLE;
793   CCs[RTLIB::OGT_F32] = ISD::SETGT;
794   CCs[RTLIB::OGT_F64] = ISD::SETGT;
795   CCs[RTLIB::OGT_F128] = ISD::SETGT;
796   CCs[RTLIB::OGT_PPCF128] = ISD::SETGT;
797   CCs[RTLIB::UO_F32] = ISD::SETNE;
798   CCs[RTLIB::UO_F64] = ISD::SETNE;
799   CCs[RTLIB::UO_F128] = ISD::SETNE;
800   CCs[RTLIB::UO_PPCF128] = ISD::SETNE;
801 }
802 
803 /// NOTE: The TargetMachine owns TLOF.
804 TargetLoweringBase::TargetLoweringBase(const TargetMachine &tm) : TM(tm) {
805   initActions();
806 
807   // Perform these initializations only once.
808   MaxStoresPerMemset = MaxStoresPerMemcpy = MaxStoresPerMemmove =
809       MaxLoadsPerMemcmp = 8;
810   MaxGluedStoresPerMemcpy = 0;
811   MaxStoresPerMemsetOptSize = MaxStoresPerMemcpyOptSize =
812       MaxStoresPerMemmoveOptSize = MaxLoadsPerMemcmpOptSize = 4;
813   HasMultipleConditionRegisters = false;
814   HasExtractBitsInsn = false;
815   JumpIsExpensive = JumpIsExpensiveOverride;
816   PredictableSelectIsExpensive = false;
817   EnableExtLdPromotion = false;
818   StackPointerRegisterToSaveRestore = 0;
819   BooleanContents = UndefinedBooleanContent;
820   BooleanFloatContents = UndefinedBooleanContent;
821   BooleanVectorContents = UndefinedBooleanContent;
822   SchedPreferenceInfo = Sched::ILP;
823   GatherAllAliasesMaxDepth = 18;
824   IsStrictFPEnabled = DisableStrictNodeMutation;
825   MaxBytesForAlignment = 0;
826   MaxAtomicSizeInBitsSupported = 0;
827 
828   // Assume that even with libcalls, no target supports wider than 128 bit
829   // division.
830   MaxDivRemBitWidthSupported = 128;
831 
832   MaxLargeFPConvertBitWidthSupported = llvm::IntegerType::MAX_INT_BITS;
833 
834   MinCmpXchgSizeInBits = 0;
835   SupportsUnalignedAtomics = false;
836 
837   std::fill(std::begin(LibcallRoutineNames), std::end(LibcallRoutineNames), nullptr);
838 
839   InitLibcalls(TM.getTargetTriple());
840   InitCmpLibcallCCs(CmpLibcallCCs);
841 }
842 
843 void TargetLoweringBase::initActions() {
844   // All operations default to being supported.
845   memset(OpActions, 0, sizeof(OpActions));
846   memset(LoadExtActions, 0, sizeof(LoadExtActions));
847   memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
848   memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
849   memset(CondCodeActions, 0, sizeof(CondCodeActions));
850   std::fill(std::begin(RegClassForVT), std::end(RegClassForVT), nullptr);
851   std::fill(std::begin(TargetDAGCombineArray),
852             std::end(TargetDAGCombineArray), 0);
853 
854   // Let extending atomic loads be unsupported by default.
855   for (MVT ValVT : MVT::all_valuetypes())
856     for (MVT MemVT : MVT::all_valuetypes())
857       setAtomicLoadExtAction({ISD::SEXTLOAD, ISD::ZEXTLOAD}, ValVT, MemVT,
858                              Expand);
859 
860   // We're somewhat special casing MVT::i2 and MVT::i4. Ideally we want to
861   // remove this and targets should individually set these types if not legal.
862   for (ISD::NodeType NT : enum_seq(ISD::DELETED_NODE, ISD::BUILTIN_OP_END,
863                                    force_iteration_on_noniterable_enum)) {
864     for (MVT VT : {MVT::i2, MVT::i4})
865       OpActions[(unsigned)VT.SimpleTy][NT] = Expand;
866   }
867   for (MVT AVT : MVT::all_valuetypes()) {
868     for (MVT VT : {MVT::i2, MVT::i4, MVT::v128i2, MVT::v64i4}) {
869       setTruncStoreAction(AVT, VT, Expand);
870       setLoadExtAction(ISD::EXTLOAD, AVT, VT, Expand);
871       setLoadExtAction(ISD::ZEXTLOAD, AVT, VT, Expand);
872     }
873   }
874   for (unsigned IM = (unsigned)ISD::PRE_INC;
875        IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
876     for (MVT VT : {MVT::i2, MVT::i4}) {
877       setIndexedLoadAction(IM, VT, Expand);
878       setIndexedStoreAction(IM, VT, Expand);
879       setIndexedMaskedLoadAction(IM, VT, Expand);
880       setIndexedMaskedStoreAction(IM, VT, Expand);
881     }
882   }
883 
884   for (MVT VT : MVT::fp_valuetypes()) {
885     MVT IntVT = MVT::getIntegerVT(VT.getFixedSizeInBits());
886     if (IntVT.isValid()) {
887       setOperationAction(ISD::ATOMIC_SWAP, VT, Promote);
888       AddPromotedToType(ISD::ATOMIC_SWAP, VT, IntVT);
889     }
890   }
891 
892   // Set default actions for various operations.
893   for (MVT VT : MVT::all_valuetypes()) {
894     // Default all indexed load / store to expand.
895     for (unsigned IM = (unsigned)ISD::PRE_INC;
896          IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
897       setIndexedLoadAction(IM, VT, Expand);
898       setIndexedStoreAction(IM, VT, Expand);
899       setIndexedMaskedLoadAction(IM, VT, Expand);
900       setIndexedMaskedStoreAction(IM, VT, Expand);
901     }
902 
903     // Most backends expect to see the node which just returns the value loaded.
904     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Expand);
905 
906     // These operations default to expand.
907     setOperationAction({ISD::FGETSIGN,       ISD::CONCAT_VECTORS,
908                         ISD::FMINNUM,        ISD::FMAXNUM,
909                         ISD::FMINNUM_IEEE,   ISD::FMAXNUM_IEEE,
910                         ISD::FMINIMUM,       ISD::FMAXIMUM,
911                         ISD::FMAD,           ISD::SMIN,
912                         ISD::SMAX,           ISD::UMIN,
913                         ISD::UMAX,           ISD::ABS,
914                         ISD::FSHL,           ISD::FSHR,
915                         ISD::SADDSAT,        ISD::UADDSAT,
916                         ISD::SSUBSAT,        ISD::USUBSAT,
917                         ISD::SSHLSAT,        ISD::USHLSAT,
918                         ISD::SMULFIX,        ISD::SMULFIXSAT,
919                         ISD::UMULFIX,        ISD::UMULFIXSAT,
920                         ISD::SDIVFIX,        ISD::SDIVFIXSAT,
921                         ISD::UDIVFIX,        ISD::UDIVFIXSAT,
922                         ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT,
923                         ISD::IS_FPCLASS},
924                        VT, Expand);
925 
926     // Overflow operations default to expand
927     setOperationAction({ISD::SADDO, ISD::SSUBO, ISD::UADDO, ISD::USUBO,
928                         ISD::SMULO, ISD::UMULO},
929                        VT, Expand);
930 
931     // Carry-using overflow operations default to expand.
932     setOperationAction({ISD::UADDO_CARRY, ISD::USUBO_CARRY, ISD::SETCCCARRY,
933                         ISD::SADDO_CARRY, ISD::SSUBO_CARRY},
934                        VT, Expand);
935 
936     // ADDC/ADDE/SUBC/SUBE default to expand.
937     setOperationAction({ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}, VT,
938                        Expand);
939 
940     // Halving adds
941     setOperationAction(
942         {ISD::AVGFLOORS, ISD::AVGFLOORU, ISD::AVGCEILS, ISD::AVGCEILU}, VT,
943         Expand);
944 
945     // Absolute difference
946     setOperationAction({ISD::ABDS, ISD::ABDU}, VT, Expand);
947 
948     // These default to Expand so they will be expanded to CTLZ/CTTZ by default.
949     setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
950                        Expand);
951 
952     setOperationAction({ISD::BITREVERSE, ISD::PARITY}, VT, Expand);
953 
954     // These library functions default to expand.
955     setOperationAction({ISD::FROUND, ISD::FPOWI, ISD::FLDEXP, ISD::FFREXP}, VT,
956                        Expand);
957 
958     // These operations default to expand for vector types.
959     if (VT.isVector())
960       setOperationAction(
961           {ISD::FCOPYSIGN, ISD::SIGN_EXTEND_INREG, ISD::ANY_EXTEND_VECTOR_INREG,
962            ISD::SIGN_EXTEND_VECTOR_INREG, ISD::ZERO_EXTEND_VECTOR_INREG,
963            ISD::SPLAT_VECTOR, ISD::LRINT, ISD::LLRINT},
964           VT, Expand);
965 
966       // Constrained floating-point operations default to expand.
967 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
968     setOperationAction(ISD::STRICT_##DAGN, VT, Expand);
969 #include "llvm/IR/ConstrainedOps.def"
970 
971     // For most targets @llvm.get.dynamic.area.offset just returns 0.
972     setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand);
973 
974     // Vector reduction default to expand.
975     setOperationAction(
976         {ISD::VECREDUCE_FADD, ISD::VECREDUCE_FMUL, ISD::VECREDUCE_ADD,
977          ISD::VECREDUCE_MUL, ISD::VECREDUCE_AND, ISD::VECREDUCE_OR,
978          ISD::VECREDUCE_XOR, ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
979          ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN, ISD::VECREDUCE_FMAX,
980          ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAXIMUM, ISD::VECREDUCE_FMINIMUM,
981          ISD::VECREDUCE_SEQ_FADD, ISD::VECREDUCE_SEQ_FMUL},
982         VT, Expand);
983 
984     // Named vector shuffles default to expand.
985     setOperationAction(ISD::VECTOR_SPLICE, VT, Expand);
986 
987     // VP operations default to expand.
988 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...)                                   \
989     setOperationAction(ISD::SDOPC, VT, Expand);
990 #include "llvm/IR/VPIntrinsics.def"
991 
992     // FP environment operations default to expand.
993     setOperationAction(ISD::GET_FPENV, VT, Expand);
994     setOperationAction(ISD::SET_FPENV, VT, Expand);
995     setOperationAction(ISD::RESET_FPENV, VT, Expand);
996   }
997 
998   // Most targets ignore the @llvm.prefetch intrinsic.
999   setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
1000 
1001   // Most targets also ignore the @llvm.readcyclecounter intrinsic.
1002   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand);
1003 
1004   // Most targets also ignore the @llvm.readsteadycounter intrinsic.
1005   setOperationAction(ISD::READSTEADYCOUNTER, MVT::i64, Expand);
1006 
1007   // ConstantFP nodes default to expand.  Targets can either change this to
1008   // Legal, in which case all fp constants are legal, or use isFPImmLegal()
1009   // to optimize expansions for certain constants.
1010   setOperationAction(ISD::ConstantFP,
1011                      {MVT::bf16, MVT::f16, MVT::f32, MVT::f64, MVT::f80, MVT::f128},
1012                      Expand);
1013 
1014   // These library functions default to expand.
1015   setOperationAction({ISD::FCBRT, ISD::FLOG, ISD::FLOG2, ISD::FLOG10, ISD::FEXP,
1016                       ISD::FEXP2, ISD::FEXP10, ISD::FFLOOR, ISD::FNEARBYINT,
1017                       ISD::FCEIL, ISD::FRINT, ISD::FTRUNC, ISD::LROUND,
1018                       ISD::LLROUND, ISD::LRINT, ISD::LLRINT, ISD::FROUNDEVEN},
1019                      {MVT::f32, MVT::f64, MVT::f128}, Expand);
1020 
1021   // Default ISD::TRAP to expand (which turns it into abort).
1022   setOperationAction(ISD::TRAP, MVT::Other, Expand);
1023 
1024   // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
1025   // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
1026   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand);
1027 
1028   setOperationAction(ISD::UBSANTRAP, MVT::Other, Expand);
1029 
1030   setOperationAction(ISD::GET_FPENV_MEM, MVT::Other, Expand);
1031   setOperationAction(ISD::SET_FPENV_MEM, MVT::Other, Expand);
1032 
1033   for (MVT VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
1034     setOperationAction(ISD::GET_FPMODE, VT, Expand);
1035     setOperationAction(ISD::SET_FPMODE, VT, Expand);
1036   }
1037   setOperationAction(ISD::RESET_FPMODE, MVT::Other, Expand);
1038 }
1039 
1040 MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL,
1041                                                EVT) const {
1042   return MVT::getIntegerVT(DL.getPointerSizeInBits(0));
1043 }
1044 
1045 EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
1046                                          bool LegalTypes) const {
1047   assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
1048   if (LHSTy.isVector())
1049     return LHSTy;
1050   MVT ShiftVT =
1051       LegalTypes ? getScalarShiftAmountTy(DL, LHSTy) : getPointerTy(DL);
1052   // If any possible shift value won't fit in the prefered type, just use
1053   // something safe. Assume it will be legalized when the shift is expanded.
1054   if (ShiftVT.getSizeInBits() < Log2_32_Ceil(LHSTy.getSizeInBits()))
1055     ShiftVT = MVT::i32;
1056   assert(ShiftVT.getSizeInBits() >= Log2_32_Ceil(LHSTy.getSizeInBits()) &&
1057          "ShiftVT is still too small!");
1058   return ShiftVT;
1059 }
1060 
1061 bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const {
1062   assert(isTypeLegal(VT));
1063   switch (Op) {
1064   default:
1065     return false;
1066   case ISD::SDIV:
1067   case ISD::UDIV:
1068   case ISD::SREM:
1069   case ISD::UREM:
1070     return true;
1071   }
1072 }
1073 
1074 bool TargetLoweringBase::isFreeAddrSpaceCast(unsigned SrcAS,
1075                                              unsigned DestAS) const {
1076   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1077 }
1078 
1079 unsigned TargetLoweringBase::getBitWidthForCttzElements(
1080     Type *RetTy, ElementCount EC, bool ZeroIsPoison,
1081     const ConstantRange *VScaleRange) const {
1082   // Find the smallest "sensible" element type to use for the expansion.
1083   ConstantRange CR(APInt(64, EC.getKnownMinValue()));
1084   if (EC.isScalable())
1085     CR = CR.umul_sat(*VScaleRange);
1086 
1087   if (ZeroIsPoison)
1088     CR = CR.subtract(APInt(64, 1));
1089 
1090   unsigned EltWidth = RetTy->getScalarSizeInBits();
1091   EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits());
1092   EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8);
1093 
1094   return EltWidth;
1095 }
1096 
1097 void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) {
1098   // If the command-line option was specified, ignore this request.
1099   if (!JumpIsExpensiveOverride.getNumOccurrences())
1100     JumpIsExpensive = isExpensive;
1101 }
1102 
1103 TargetLoweringBase::LegalizeKind
1104 TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const {
1105   // If this is a simple type, use the ComputeRegisterProp mechanism.
1106   if (VT.isSimple()) {
1107     MVT SVT = VT.getSimpleVT();
1108     assert((unsigned)SVT.SimpleTy < std::size(TransformToType));
1109     MVT NVT = TransformToType[SVT.SimpleTy];
1110     LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
1111 
1112     assert((LA == TypeLegal || LA == TypeSoftenFloat ||
1113             LA == TypeSoftPromoteHalf ||
1114             (NVT.isVector() ||
1115              ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)) &&
1116            "Promote may not follow Expand or Promote");
1117 
1118     if (LA == TypeSplitVector)
1119       return LegalizeKind(LA, EVT(SVT).getHalfNumVectorElementsVT(Context));
1120     if (LA == TypeScalarizeVector)
1121       return LegalizeKind(LA, SVT.getVectorElementType());
1122     return LegalizeKind(LA, NVT);
1123   }
1124 
1125   // Handle Extended Scalar Types.
1126   if (!VT.isVector()) {
1127     assert(VT.isInteger() && "Float types must be simple");
1128     unsigned BitSize = VT.getSizeInBits();
1129     // First promote to a power-of-two size, then expand if necessary.
1130     if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1131       EVT NVT = VT.getRoundIntegerType(Context);
1132       assert(NVT != VT && "Unable to round integer VT");
1133       LegalizeKind NextStep = getTypeConversion(Context, NVT);
1134       // Avoid multi-step promotion.
1135       if (NextStep.first == TypePromoteInteger)
1136         return NextStep;
1137       // Return rounded integer type.
1138       return LegalizeKind(TypePromoteInteger, NVT);
1139     }
1140 
1141     return LegalizeKind(TypeExpandInteger,
1142                         EVT::getIntegerVT(Context, VT.getSizeInBits() / 2));
1143   }
1144 
1145   // Handle vector types.
1146   ElementCount NumElts = VT.getVectorElementCount();
1147   EVT EltVT = VT.getVectorElementType();
1148 
1149   // Vectors with only one element are always scalarized.
1150   if (NumElts.isScalar())
1151     return LegalizeKind(TypeScalarizeVector, EltVT);
1152 
1153   // Try to widen vector elements until the element type is a power of two and
1154   // promote it to a legal type later on, for example:
1155   // <3 x i8> -> <4 x i8> -> <4 x i32>
1156   if (EltVT.isInteger()) {
1157     // Vectors with a number of elements that is not a power of two are always
1158     // widened, for example <3 x i8> -> <4 x i8>.
1159     if (!VT.isPow2VectorType()) {
1160       NumElts = NumElts.coefficientNextPowerOf2();
1161       EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1162       return LegalizeKind(TypeWidenVector, NVT);
1163     }
1164 
1165     // Examine the element type.
1166     LegalizeKind LK = getTypeConversion(Context, EltVT);
1167 
1168     // If type is to be expanded, split the vector.
1169     //  <4 x i140> -> <2 x i140>
1170     if (LK.first == TypeExpandInteger) {
1171       if (VT.getVectorElementCount().isScalable())
1172         return LegalizeKind(TypeScalarizeScalableVector, EltVT);
1173       return LegalizeKind(TypeSplitVector,
1174                           VT.getHalfNumVectorElementsVT(Context));
1175     }
1176 
1177     // Promote the integer element types until a legal vector type is found
1178     // or until the element integer type is too big. If a legal type was not
1179     // found, fallback to the usual mechanism of widening/splitting the
1180     // vector.
1181     EVT OldEltVT = EltVT;
1182     while (true) {
1183       // Increase the bitwidth of the element to the next pow-of-two
1184       // (which is greater than 8 bits).
1185       EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits())
1186                   .getRoundIntegerType(Context);
1187 
1188       // Stop trying when getting a non-simple element type.
1189       // Note that vector elements may be greater than legal vector element
1190       // types. Example: X86 XMM registers hold 64bit element on 32bit
1191       // systems.
1192       if (!EltVT.isSimple())
1193         break;
1194 
1195       // Build a new vector type and check if it is legal.
1196       MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1197       // Found a legal promoted vector type.
1198       if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1199         return LegalizeKind(TypePromoteInteger,
1200                             EVT::getVectorVT(Context, EltVT, NumElts));
1201     }
1202 
1203     // Reset the type to the unexpanded type if we did not find a legal vector
1204     // type with a promoted vector element type.
1205     EltVT = OldEltVT;
1206   }
1207 
1208   // Try to widen the vector until a legal type is found.
1209   // If there is no wider legal type, split the vector.
1210   while (true) {
1211     // Round up to the next power of 2.
1212     NumElts = NumElts.coefficientNextPowerOf2();
1213 
1214     // If there is no simple vector type with this many elements then there
1215     // cannot be a larger legal vector type.  Note that this assumes that
1216     // there are no skipped intermediate vector types in the simple types.
1217     if (!EltVT.isSimple())
1218       break;
1219     MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1220     if (LargerVector == MVT())
1221       break;
1222 
1223     // If this type is legal then widen the vector.
1224     if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1225       return LegalizeKind(TypeWidenVector, LargerVector);
1226   }
1227 
1228   // Widen odd vectors to next power of two.
1229   if (!VT.isPow2VectorType()) {
1230     EVT NVT = VT.getPow2VectorType(Context);
1231     return LegalizeKind(TypeWidenVector, NVT);
1232   }
1233 
1234   if (VT.getVectorElementCount() == ElementCount::getScalable(1))
1235     return LegalizeKind(TypeScalarizeScalableVector, EltVT);
1236 
1237   // Vectors with illegal element types are expanded.
1238   EVT NVT = EVT::getVectorVT(Context, EltVT,
1239                              VT.getVectorElementCount().divideCoefficientBy(2));
1240   return LegalizeKind(TypeSplitVector, NVT);
1241 }
1242 
1243 static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
1244                                           unsigned &NumIntermediates,
1245                                           MVT &RegisterVT,
1246                                           TargetLoweringBase *TLI) {
1247   // Figure out the right, legal destination reg to copy into.
1248   ElementCount EC = VT.getVectorElementCount();
1249   MVT EltTy = VT.getVectorElementType();
1250 
1251   unsigned NumVectorRegs = 1;
1252 
1253   // Scalable vectors cannot be scalarized, so splitting or widening is
1254   // required.
1255   if (VT.isScalableVector() && !isPowerOf2_32(EC.getKnownMinValue()))
1256     llvm_unreachable(
1257         "Splitting or widening of non-power-of-2 MVTs is not implemented.");
1258 
1259   // FIXME: We don't support non-power-of-2-sized vectors for now.
1260   // Ideally we could break down into LHS/RHS like LegalizeDAG does.
1261   if (!isPowerOf2_32(EC.getKnownMinValue())) {
1262     // Split EC to unit size (scalable property is preserved).
1263     NumVectorRegs = EC.getKnownMinValue();
1264     EC = ElementCount::getFixed(1);
1265   }
1266 
1267   // Divide the input until we get to a supported size. This will
1268   // always end up with an EC that represent a scalar or a scalable
1269   // scalar.
1270   while (EC.getKnownMinValue() > 1 &&
1271          !TLI->isTypeLegal(MVT::getVectorVT(EltTy, EC))) {
1272     EC = EC.divideCoefficientBy(2);
1273     NumVectorRegs <<= 1;
1274   }
1275 
1276   NumIntermediates = NumVectorRegs;
1277 
1278   MVT NewVT = MVT::getVectorVT(EltTy, EC);
1279   if (!TLI->isTypeLegal(NewVT))
1280     NewVT = EltTy;
1281   IntermediateVT = NewVT;
1282 
1283   unsigned LaneSizeInBits = NewVT.getScalarSizeInBits();
1284 
1285   // Convert sizes such as i33 to i64.
1286   LaneSizeInBits = llvm::bit_ceil(LaneSizeInBits);
1287 
1288   MVT DestVT = TLI->getRegisterType(NewVT);
1289   RegisterVT = DestVT;
1290   if (EVT(DestVT).bitsLT(NewVT))    // Value is expanded, e.g. i64 -> i16.
1291     return NumVectorRegs * (LaneSizeInBits / DestVT.getScalarSizeInBits());
1292 
1293   // Otherwise, promotion or legal types use the same number of registers as
1294   // the vector decimated to the appropriate level.
1295   return NumVectorRegs;
1296 }
1297 
1298 /// isLegalRC - Return true if the value types that can be represented by the
1299 /// specified register class are all legal.
1300 bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI,
1301                                    const TargetRegisterClass &RC) const {
1302   for (const auto *I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I)
1303     if (isTypeLegal(*I))
1304       return true;
1305   return false;
1306 }
1307 
1308 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
1309 /// sequence of memory operands that is recognized by PrologEpilogInserter.
1310 MachineBasicBlock *
1311 TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI,
1312                                    MachineBasicBlock *MBB) const {
1313   MachineInstr *MI = &InitialMI;
1314   MachineFunction &MF = *MI->getMF();
1315   MachineFrameInfo &MFI = MF.getFrameInfo();
1316 
1317   // We're handling multiple types of operands here:
1318   // PATCHPOINT MetaArgs - live-in, read only, direct
1319   // STATEPOINT Deopt Spill - live-through, read only, indirect
1320   // STATEPOINT Deopt Alloca - live-through, read only, direct
1321   // (We're currently conservative and mark the deopt slots read/write in
1322   // practice.)
1323   // STATEPOINT GC Spill - live-through, read/write, indirect
1324   // STATEPOINT GC Alloca - live-through, read/write, direct
1325   // The live-in vs live-through is handled already (the live through ones are
1326   // all stack slots), but we need to handle the different type of stackmap
1327   // operands and memory effects here.
1328 
1329   if (llvm::none_of(MI->operands(),
1330                     [](MachineOperand &Operand) { return Operand.isFI(); }))
1331     return MBB;
1332 
1333   MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc());
1334 
1335   // Inherit previous memory operands.
1336   MIB.cloneMemRefs(*MI);
1337 
1338   for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
1339     MachineOperand &MO = MI->getOperand(i);
1340     if (!MO.isFI()) {
1341       // Index of Def operand this Use it tied to.
1342       // Since Defs are coming before Uses, if Use is tied, then
1343       // index of Def must be smaller that index of that Use.
1344       // Also, Defs preserve their position in new MI.
1345       unsigned TiedTo = i;
1346       if (MO.isReg() && MO.isTied())
1347         TiedTo = MI->findTiedOperandIdx(i);
1348       MIB.add(MO);
1349       if (TiedTo < i)
1350         MIB->tieOperands(TiedTo, MIB->getNumOperands() - 1);
1351       continue;
1352     }
1353 
1354     // foldMemoryOperand builds a new MI after replacing a single FI operand
1355     // with the canonical set of five x86 addressing-mode operands.
1356     int FI = MO.getIndex();
1357 
1358     // Add frame index operands recognized by stackmaps.cpp
1359     if (MFI.isStatepointSpillSlotObjectIndex(FI)) {
1360       // indirect-mem-ref tag, size, #FI, offset.
1361       // Used for spills inserted by StatepointLowering.  This codepath is not
1362       // used for patchpoints/stackmaps at all, for these spilling is done via
1363       // foldMemoryOperand callback only.
1364       assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity");
1365       MIB.addImm(StackMaps::IndirectMemRefOp);
1366       MIB.addImm(MFI.getObjectSize(FI));
1367       MIB.add(MO);
1368       MIB.addImm(0);
1369     } else {
1370       // direct-mem-ref tag, #FI, offset.
1371       // Used by patchpoint, and direct alloca arguments to statepoints
1372       MIB.addImm(StackMaps::DirectMemRefOp);
1373       MIB.add(MO);
1374       MIB.addImm(0);
1375     }
1376 
1377     assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!");
1378 
1379     // Add a new memory operand for this FI.
1380     assert(MFI.getObjectOffset(FI) != -1);
1381 
1382     // Note: STATEPOINT MMOs are added during SelectionDAG.  STACKMAP, and
1383     // PATCHPOINT should be updated to do the same. (TODO)
1384     if (MI->getOpcode() != TargetOpcode::STATEPOINT) {
1385       auto Flags = MachineMemOperand::MOLoad;
1386       MachineMemOperand *MMO = MF.getMachineMemOperand(
1387           MachinePointerInfo::getFixedStack(MF, FI), Flags,
1388           MF.getDataLayout().getPointerSize(), MFI.getObjectAlign(FI));
1389       MIB->addMemOperand(MF, MMO);
1390     }
1391   }
1392   MBB->insert(MachineBasicBlock::iterator(MI), MIB);
1393   MI->eraseFromParent();
1394   return MBB;
1395 }
1396 
1397 /// findRepresentativeClass - Return the largest legal super-reg register class
1398 /// of the register class for the specified type and its associated "cost".
1399 // This function is in TargetLowering because it uses RegClassForVT which would
1400 // need to be moved to TargetRegisterInfo and would necessitate moving
1401 // isTypeLegal over as well - a massive change that would just require
1402 // TargetLowering having a TargetRegisterInfo class member that it would use.
1403 std::pair<const TargetRegisterClass *, uint8_t>
1404 TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI,
1405                                             MVT VT) const {
1406   const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
1407   if (!RC)
1408     return std::make_pair(RC, 0);
1409 
1410   // Compute the set of all super-register classes.
1411   BitVector SuperRegRC(TRI->getNumRegClasses());
1412   for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
1413     SuperRegRC.setBitsInMask(RCI.getMask());
1414 
1415   // Find the first legal register class with the largest spill size.
1416   const TargetRegisterClass *BestRC = RC;
1417   for (unsigned i : SuperRegRC.set_bits()) {
1418     const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
1419     // We want the largest possible spill size.
1420     if (TRI->getSpillSize(*SuperRC) <= TRI->getSpillSize(*BestRC))
1421       continue;
1422     if (!isLegalRC(*TRI, *SuperRC))
1423       continue;
1424     BestRC = SuperRC;
1425   }
1426   return std::make_pair(BestRC, 1);
1427 }
1428 
1429 /// computeRegisterProperties - Once all of the register classes are added,
1430 /// this allows us to compute derived properties we expose.
1431 void TargetLoweringBase::computeRegisterProperties(
1432     const TargetRegisterInfo *TRI) {
1433   // Everything defaults to needing one register.
1434   for (unsigned i = 0; i != MVT::VALUETYPE_SIZE; ++i) {
1435     NumRegistersForVT[i] = 1;
1436     RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
1437   }
1438   // ...except isVoid, which doesn't need any registers.
1439   NumRegistersForVT[MVT::isVoid] = 0;
1440 
1441   // Find the largest integer register class.
1442   unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
1443   for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg)
1444     assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
1445 
1446   // Every integer value type larger than this largest register takes twice as
1447   // many registers to represent as the previous ValueType.
1448   for (unsigned ExpandedReg = LargestIntReg + 1;
1449        ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
1450     NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
1451     RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
1452     TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
1453     ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg,
1454                                    TypeExpandInteger);
1455   }
1456 
1457   // Inspect all of the ValueType's smaller than the largest integer
1458   // register to see which ones need promotion.
1459   unsigned LegalIntReg = LargestIntReg;
1460   for (unsigned IntReg = LargestIntReg - 1;
1461        IntReg >= (unsigned)MVT::i1; --IntReg) {
1462     MVT IVT = (MVT::SimpleValueType)IntReg;
1463     if (isTypeLegal(IVT)) {
1464       LegalIntReg = IntReg;
1465     } else {
1466       RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
1467         (MVT::SimpleValueType)LegalIntReg;
1468       ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
1469     }
1470   }
1471 
1472   // ppcf128 type is really two f64's.
1473   if (!isTypeLegal(MVT::ppcf128)) {
1474     if (isTypeLegal(MVT::f64)) {
1475       NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
1476       RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
1477       TransformToType[MVT::ppcf128] = MVT::f64;
1478       ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
1479     } else {
1480       NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128];
1481       RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128];
1482       TransformToType[MVT::ppcf128] = MVT::i128;
1483       ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat);
1484     }
1485   }
1486 
1487   // Decide how to handle f128. If the target does not have native f128 support,
1488   // expand it to i128 and we will be generating soft float library calls.
1489   if (!isTypeLegal(MVT::f128)) {
1490     NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128];
1491     RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128];
1492     TransformToType[MVT::f128] = MVT::i128;
1493     ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
1494   }
1495 
1496   // Decide how to handle f80. If the target does not have native f80 support,
1497   // expand it to i96 and we will be generating soft float library calls.
1498   if (!isTypeLegal(MVT::f80)) {
1499     NumRegistersForVT[MVT::f80] = 3*NumRegistersForVT[MVT::i32];
1500     RegisterTypeForVT[MVT::f80] = RegisterTypeForVT[MVT::i32];
1501     TransformToType[MVT::f80] = MVT::i32;
1502     ValueTypeActions.setTypeAction(MVT::f80, TypeSoftenFloat);
1503   }
1504 
1505   // Decide how to handle f64. If the target does not have native f64 support,
1506   // expand it to i64 and we will be generating soft float library calls.
1507   if (!isTypeLegal(MVT::f64)) {
1508     NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
1509     RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
1510     TransformToType[MVT::f64] = MVT::i64;
1511     ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
1512   }
1513 
1514   // Decide how to handle f32. If the target does not have native f32 support,
1515   // expand it to i32 and we will be generating soft float library calls.
1516   if (!isTypeLegal(MVT::f32)) {
1517     NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
1518     RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
1519     TransformToType[MVT::f32] = MVT::i32;
1520     ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
1521   }
1522 
1523   // Decide how to handle f16. If the target does not have native f16 support,
1524   // promote it to f32, because there are no f16 library calls (except for
1525   // conversions).
1526   if (!isTypeLegal(MVT::f16)) {
1527     // Allow targets to control how we legalize half.
1528     bool SoftPromoteHalfType = softPromoteHalfType();
1529     bool UseFPRegsForHalfType = !SoftPromoteHalfType || useFPRegsForHalfType();
1530 
1531     if (!UseFPRegsForHalfType) {
1532       NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::i16];
1533       RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::i16];
1534     } else {
1535       NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32];
1536       RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32];
1537     }
1538     TransformToType[MVT::f16] = MVT::f32;
1539     if (SoftPromoteHalfType) {
1540       ValueTypeActions.setTypeAction(MVT::f16, TypeSoftPromoteHalf);
1541     } else {
1542       ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat);
1543     }
1544   }
1545 
1546   // Decide how to handle bf16. If the target does not have native bf16 support,
1547   // promote it to f32, because there are no bf16 library calls (except for
1548   // converting from f32 to bf16).
1549   if (!isTypeLegal(MVT::bf16)) {
1550     NumRegistersForVT[MVT::bf16] = NumRegistersForVT[MVT::f32];
1551     RegisterTypeForVT[MVT::bf16] = RegisterTypeForVT[MVT::f32];
1552     TransformToType[MVT::bf16] = MVT::f32;
1553     ValueTypeActions.setTypeAction(MVT::bf16, TypeSoftPromoteHalf);
1554   }
1555 
1556   // Loop over all of the vector value types to see which need transformations.
1557   for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
1558        i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1559     MVT VT = (MVT::SimpleValueType) i;
1560     if (isTypeLegal(VT))
1561       continue;
1562 
1563     MVT EltVT = VT.getVectorElementType();
1564     ElementCount EC = VT.getVectorElementCount();
1565     bool IsLegalWiderType = false;
1566     bool IsScalable = VT.isScalableVector();
1567     LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT);
1568     switch (PreferredAction) {
1569     case TypePromoteInteger: {
1570       MVT::SimpleValueType EndVT = IsScalable ?
1571                                    MVT::LAST_INTEGER_SCALABLE_VECTOR_VALUETYPE :
1572                                    MVT::LAST_INTEGER_FIXEDLEN_VECTOR_VALUETYPE;
1573       // Try to promote the elements of integer vectors. If no legal
1574       // promotion was found, fall through to the widen-vector method.
1575       for (unsigned nVT = i + 1;
1576            (MVT::SimpleValueType)nVT <= EndVT; ++nVT) {
1577         MVT SVT = (MVT::SimpleValueType) nVT;
1578         // Promote vectors of integers to vectors with the same number
1579         // of elements, with a wider element type.
1580         if (SVT.getScalarSizeInBits() > EltVT.getFixedSizeInBits() &&
1581             SVT.getVectorElementCount() == EC && isTypeLegal(SVT)) {
1582           TransformToType[i] = SVT;
1583           RegisterTypeForVT[i] = SVT;
1584           NumRegistersForVT[i] = 1;
1585           ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
1586           IsLegalWiderType = true;
1587           break;
1588         }
1589       }
1590       if (IsLegalWiderType)
1591         break;
1592       [[fallthrough]];
1593     }
1594 
1595     case TypeWidenVector:
1596       if (isPowerOf2_32(EC.getKnownMinValue())) {
1597         // Try to widen the vector.
1598         for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
1599           MVT SVT = (MVT::SimpleValueType) nVT;
1600           if (SVT.getVectorElementType() == EltVT &&
1601               SVT.isScalableVector() == IsScalable &&
1602               SVT.getVectorElementCount().getKnownMinValue() >
1603                   EC.getKnownMinValue() &&
1604               isTypeLegal(SVT)) {
1605             TransformToType[i] = SVT;
1606             RegisterTypeForVT[i] = SVT;
1607             NumRegistersForVT[i] = 1;
1608             ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1609             IsLegalWiderType = true;
1610             break;
1611           }
1612         }
1613         if (IsLegalWiderType)
1614           break;
1615       } else {
1616         // Only widen to the next power of 2 to keep consistency with EVT.
1617         MVT NVT = VT.getPow2VectorType();
1618         if (isTypeLegal(NVT)) {
1619           TransformToType[i] = NVT;
1620           ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1621           RegisterTypeForVT[i] = NVT;
1622           NumRegistersForVT[i] = 1;
1623           break;
1624         }
1625       }
1626       [[fallthrough]];
1627 
1628     case TypeSplitVector:
1629     case TypeScalarizeVector: {
1630       MVT IntermediateVT;
1631       MVT RegisterVT;
1632       unsigned NumIntermediates;
1633       unsigned NumRegisters = getVectorTypeBreakdownMVT(VT, IntermediateVT,
1634           NumIntermediates, RegisterVT, this);
1635       NumRegistersForVT[i] = NumRegisters;
1636       assert(NumRegistersForVT[i] == NumRegisters &&
1637              "NumRegistersForVT size cannot represent NumRegisters!");
1638       RegisterTypeForVT[i] = RegisterVT;
1639 
1640       MVT NVT = VT.getPow2VectorType();
1641       if (NVT == VT) {
1642         // Type is already a power of 2.  The default action is to split.
1643         TransformToType[i] = MVT::Other;
1644         if (PreferredAction == TypeScalarizeVector)
1645           ValueTypeActions.setTypeAction(VT, TypeScalarizeVector);
1646         else if (PreferredAction == TypeSplitVector)
1647           ValueTypeActions.setTypeAction(VT, TypeSplitVector);
1648         else if (EC.getKnownMinValue() > 1)
1649           ValueTypeActions.setTypeAction(VT, TypeSplitVector);
1650         else
1651           ValueTypeActions.setTypeAction(VT, EC.isScalable()
1652                                                  ? TypeScalarizeScalableVector
1653                                                  : TypeScalarizeVector);
1654       } else {
1655         TransformToType[i] = NVT;
1656         ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1657       }
1658       break;
1659     }
1660     default:
1661       llvm_unreachable("Unknown vector legalization action!");
1662     }
1663   }
1664 
1665   // Determine the 'representative' register class for each value type.
1666   // An representative register class is the largest (meaning one which is
1667   // not a sub-register class / subreg register class) legal register class for
1668   // a group of value types. For example, on i386, i8, i16, and i32
1669   // representative would be GR32; while on x86_64 it's GR64.
1670   for (unsigned i = 0; i != MVT::VALUETYPE_SIZE; ++i) {
1671     const TargetRegisterClass* RRC;
1672     uint8_t Cost;
1673     std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i);
1674     RepRegClassForVT[i] = RRC;
1675     RepRegClassCostForVT[i] = Cost;
1676   }
1677 }
1678 
1679 EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1680                                            EVT VT) const {
1681   assert(!VT.isVector() && "No default SetCC type for vectors!");
1682   return getPointerTy(DL).SimpleTy;
1683 }
1684 
1685 MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const {
1686   return MVT::i32; // return the default value
1687 }
1688 
1689 /// getVectorTypeBreakdown - Vector types are broken down into some number of
1690 /// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
1691 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
1692 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
1693 ///
1694 /// This method returns the number of registers needed, and the VT for each
1695 /// register.  It also returns the VT and quantity of the intermediate values
1696 /// before they are promoted/expanded.
1697 unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context,
1698                                                     EVT VT, EVT &IntermediateVT,
1699                                                     unsigned &NumIntermediates,
1700                                                     MVT &RegisterVT) const {
1701   ElementCount EltCnt = VT.getVectorElementCount();
1702 
1703   // If there is a wider vector type with the same element type as this one,
1704   // or a promoted vector type that has the same number of elements which
1705   // are wider, then we should convert to that legal vector type.
1706   // This handles things like <2 x float> -> <4 x float> and
1707   // <4 x i1> -> <4 x i32>.
1708   LegalizeTypeAction TA = getTypeAction(Context, VT);
1709   if (!EltCnt.isScalar() &&
1710       (TA == TypeWidenVector || TA == TypePromoteInteger)) {
1711     EVT RegisterEVT = getTypeToTransformTo(Context, VT);
1712     if (isTypeLegal(RegisterEVT)) {
1713       IntermediateVT = RegisterEVT;
1714       RegisterVT = RegisterEVT.getSimpleVT();
1715       NumIntermediates = 1;
1716       return 1;
1717     }
1718   }
1719 
1720   // Figure out the right, legal destination reg to copy into.
1721   EVT EltTy = VT.getVectorElementType();
1722 
1723   unsigned NumVectorRegs = 1;
1724 
1725   // Scalable vectors cannot be scalarized, so handle the legalisation of the
1726   // types like done elsewhere in SelectionDAG.
1727   if (EltCnt.isScalable()) {
1728     LegalizeKind LK;
1729     EVT PartVT = VT;
1730     do {
1731       // Iterate until we've found a legal (part) type to hold VT.
1732       LK = getTypeConversion(Context, PartVT);
1733       PartVT = LK.second;
1734     } while (LK.first != TypeLegal);
1735 
1736     if (!PartVT.isVector()) {
1737       report_fatal_error(
1738           "Don't know how to legalize this scalable vector type");
1739     }
1740 
1741     NumIntermediates =
1742         divideCeil(VT.getVectorElementCount().getKnownMinValue(),
1743                    PartVT.getVectorElementCount().getKnownMinValue());
1744     IntermediateVT = PartVT;
1745     RegisterVT = getRegisterType(Context, IntermediateVT);
1746     return NumIntermediates;
1747   }
1748 
1749   // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally
1750   // we could break down into LHS/RHS like LegalizeDAG does.
1751   if (!isPowerOf2_32(EltCnt.getKnownMinValue())) {
1752     NumVectorRegs = EltCnt.getKnownMinValue();
1753     EltCnt = ElementCount::getFixed(1);
1754   }
1755 
1756   // Divide the input until we get to a supported size.  This will always
1757   // end with a scalar if the target doesn't support vectors.
1758   while (EltCnt.getKnownMinValue() > 1 &&
1759          !isTypeLegal(EVT::getVectorVT(Context, EltTy, EltCnt))) {
1760     EltCnt = EltCnt.divideCoefficientBy(2);
1761     NumVectorRegs <<= 1;
1762   }
1763 
1764   NumIntermediates = NumVectorRegs;
1765 
1766   EVT NewVT = EVT::getVectorVT(Context, EltTy, EltCnt);
1767   if (!isTypeLegal(NewVT))
1768     NewVT = EltTy;
1769   IntermediateVT = NewVT;
1770 
1771   MVT DestVT = getRegisterType(Context, NewVT);
1772   RegisterVT = DestVT;
1773 
1774   if (EVT(DestVT).bitsLT(NewVT)) {  // Value is expanded, e.g. i64 -> i16.
1775     TypeSize NewVTSize = NewVT.getSizeInBits();
1776     // Convert sizes such as i33 to i64.
1777     if (!llvm::has_single_bit<uint32_t>(NewVTSize.getKnownMinValue()))
1778       NewVTSize = NewVTSize.coefficientNextPowerOf2();
1779     return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
1780   }
1781 
1782   // Otherwise, promotion or legal types use the same number of registers as
1783   // the vector decimated to the appropriate level.
1784   return NumVectorRegs;
1785 }
1786 
1787 bool TargetLoweringBase::isSuitableForJumpTable(const SwitchInst *SI,
1788                                                 uint64_t NumCases,
1789                                                 uint64_t Range,
1790                                                 ProfileSummaryInfo *PSI,
1791                                                 BlockFrequencyInfo *BFI) const {
1792   // FIXME: This function check the maximum table size and density, but the
1793   // minimum size is not checked. It would be nice if the minimum size is
1794   // also combined within this function. Currently, the minimum size check is
1795   // performed in findJumpTable() in SelectionDAGBuiler and
1796   // getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
1797   const bool OptForSize =
1798       SI->getParent()->getParent()->hasOptSize() ||
1799       llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI);
1800   const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize);
1801   const unsigned MaxJumpTableSize = getMaximumJumpTableSize();
1802 
1803   // Check whether the number of cases is small enough and
1804   // the range is dense enough for a jump table.
1805   return (OptForSize || Range <= MaxJumpTableSize) &&
1806          (NumCases * 100 >= Range * MinDensity);
1807 }
1808 
1809 MVT TargetLoweringBase::getPreferredSwitchConditionType(LLVMContext &Context,
1810                                                         EVT ConditionVT) const {
1811   return getRegisterType(Context, ConditionVT);
1812 }
1813 
1814 /// Get the EVTs and ArgFlags collections that represent the legalized return
1815 /// type of the given function.  This does not require a DAG or a return value,
1816 /// and is suitable for use before any DAGs for the function are constructed.
1817 /// TODO: Move this out of TargetLowering.cpp.
1818 void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType,
1819                          AttributeList attr,
1820                          SmallVectorImpl<ISD::OutputArg> &Outs,
1821                          const TargetLowering &TLI, const DataLayout &DL) {
1822   SmallVector<EVT, 4> ValueVTs;
1823   ComputeValueVTs(TLI, DL, ReturnType, ValueVTs);
1824   unsigned NumValues = ValueVTs.size();
1825   if (NumValues == 0) return;
1826 
1827   for (unsigned j = 0, f = NumValues; j != f; ++j) {
1828     EVT VT = ValueVTs[j];
1829     ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1830 
1831     if (attr.hasRetAttr(Attribute::SExt))
1832       ExtendKind = ISD::SIGN_EXTEND;
1833     else if (attr.hasRetAttr(Attribute::ZExt))
1834       ExtendKind = ISD::ZERO_EXTEND;
1835 
1836     if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1837       VT = TLI.getTypeForExtReturn(ReturnType->getContext(), VT, ExtendKind);
1838 
1839     unsigned NumParts =
1840         TLI.getNumRegistersForCallingConv(ReturnType->getContext(), CC, VT);
1841     MVT PartVT =
1842         TLI.getRegisterTypeForCallingConv(ReturnType->getContext(), CC, VT);
1843 
1844     // 'inreg' on function refers to return value
1845     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1846     if (attr.hasRetAttr(Attribute::InReg))
1847       Flags.setInReg();
1848 
1849     // Propagate extension type if any
1850     if (attr.hasRetAttr(Attribute::SExt))
1851       Flags.setSExt();
1852     else if (attr.hasRetAttr(Attribute::ZExt))
1853       Flags.setZExt();
1854 
1855     for (unsigned i = 0; i < NumParts; ++i) {
1856       ISD::ArgFlagsTy OutFlags = Flags;
1857       if (NumParts > 1 && i == 0)
1858         OutFlags.setSplit();
1859       else if (i == NumParts - 1 && i != 0)
1860         OutFlags.setSplitEnd();
1861 
1862       Outs.push_back(
1863           ISD::OutputArg(OutFlags, PartVT, VT, /*isfixed=*/true, 0, 0));
1864     }
1865   }
1866 }
1867 
1868 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1869 /// function arguments in the caller parameter area.  This is the actual
1870 /// alignment, not its logarithm.
1871 uint64_t TargetLoweringBase::getByValTypeAlignment(Type *Ty,
1872                                                    const DataLayout &DL) const {
1873   return DL.getABITypeAlign(Ty).value();
1874 }
1875 
1876 bool TargetLoweringBase::allowsMemoryAccessForAlignment(
1877     LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace,
1878     Align Alignment, MachineMemOperand::Flags Flags, unsigned *Fast) const {
1879   // Check if the specified alignment is sufficient based on the data layout.
1880   // TODO: While using the data layout works in practice, a better solution
1881   // would be to implement this check directly (make this a virtual function).
1882   // For example, the ABI alignment may change based on software platform while
1883   // this function should only be affected by hardware implementation.
1884   Type *Ty = VT.getTypeForEVT(Context);
1885   if (VT.isZeroSized() || Alignment >= DL.getABITypeAlign(Ty)) {
1886     // Assume that an access that meets the ABI-specified alignment is fast.
1887     if (Fast != nullptr)
1888       *Fast = 1;
1889     return true;
1890   }
1891 
1892   // This is a misaligned access.
1893   return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Flags, Fast);
1894 }
1895 
1896 bool TargetLoweringBase::allowsMemoryAccessForAlignment(
1897     LLVMContext &Context, const DataLayout &DL, EVT VT,
1898     const MachineMemOperand &MMO, unsigned *Fast) const {
1899   return allowsMemoryAccessForAlignment(Context, DL, VT, MMO.getAddrSpace(),
1900                                         MMO.getAlign(), MMO.getFlags(), Fast);
1901 }
1902 
1903 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
1904                                             const DataLayout &DL, EVT VT,
1905                                             unsigned AddrSpace, Align Alignment,
1906                                             MachineMemOperand::Flags Flags,
1907                                             unsigned *Fast) const {
1908   return allowsMemoryAccessForAlignment(Context, DL, VT, AddrSpace, Alignment,
1909                                         Flags, Fast);
1910 }
1911 
1912 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
1913                                             const DataLayout &DL, EVT VT,
1914                                             const MachineMemOperand &MMO,
1915                                             unsigned *Fast) const {
1916   return allowsMemoryAccess(Context, DL, VT, MMO.getAddrSpace(), MMO.getAlign(),
1917                             MMO.getFlags(), Fast);
1918 }
1919 
1920 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
1921                                             const DataLayout &DL, LLT Ty,
1922                                             const MachineMemOperand &MMO,
1923                                             unsigned *Fast) const {
1924   EVT VT = getApproximateEVTForLLT(Ty, DL, Context);
1925   return allowsMemoryAccess(Context, DL, VT, MMO.getAddrSpace(), MMO.getAlign(),
1926                             MMO.getFlags(), Fast);
1927 }
1928 
1929 //===----------------------------------------------------------------------===//
1930 //  TargetTransformInfo Helpers
1931 //===----------------------------------------------------------------------===//
1932 
1933 int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const {
1934   enum InstructionOpcodes {
1935 #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM,
1936 #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM
1937 #include "llvm/IR/Instruction.def"
1938   };
1939   switch (static_cast<InstructionOpcodes>(Opcode)) {
1940   case Ret:            return 0;
1941   case Br:             return 0;
1942   case Switch:         return 0;
1943   case IndirectBr:     return 0;
1944   case Invoke:         return 0;
1945   case CallBr:         return 0;
1946   case Resume:         return 0;
1947   case Unreachable:    return 0;
1948   case CleanupRet:     return 0;
1949   case CatchRet:       return 0;
1950   case CatchPad:       return 0;
1951   case CatchSwitch:    return 0;
1952   case CleanupPad:     return 0;
1953   case FNeg:           return ISD::FNEG;
1954   case Add:            return ISD::ADD;
1955   case FAdd:           return ISD::FADD;
1956   case Sub:            return ISD::SUB;
1957   case FSub:           return ISD::FSUB;
1958   case Mul:            return ISD::MUL;
1959   case FMul:           return ISD::FMUL;
1960   case UDiv:           return ISD::UDIV;
1961   case SDiv:           return ISD::SDIV;
1962   case FDiv:           return ISD::FDIV;
1963   case URem:           return ISD::UREM;
1964   case SRem:           return ISD::SREM;
1965   case FRem:           return ISD::FREM;
1966   case Shl:            return ISD::SHL;
1967   case LShr:           return ISD::SRL;
1968   case AShr:           return ISD::SRA;
1969   case And:            return ISD::AND;
1970   case Or:             return ISD::OR;
1971   case Xor:            return ISD::XOR;
1972   case Alloca:         return 0;
1973   case Load:           return ISD::LOAD;
1974   case Store:          return ISD::STORE;
1975   case GetElementPtr:  return 0;
1976   case Fence:          return 0;
1977   case AtomicCmpXchg:  return 0;
1978   case AtomicRMW:      return 0;
1979   case Trunc:          return ISD::TRUNCATE;
1980   case ZExt:           return ISD::ZERO_EXTEND;
1981   case SExt:           return ISD::SIGN_EXTEND;
1982   case FPToUI:         return ISD::FP_TO_UINT;
1983   case FPToSI:         return ISD::FP_TO_SINT;
1984   case UIToFP:         return ISD::UINT_TO_FP;
1985   case SIToFP:         return ISD::SINT_TO_FP;
1986   case FPTrunc:        return ISD::FP_ROUND;
1987   case FPExt:          return ISD::FP_EXTEND;
1988   case PtrToInt:       return ISD::BITCAST;
1989   case IntToPtr:       return ISD::BITCAST;
1990   case BitCast:        return ISD::BITCAST;
1991   case AddrSpaceCast:  return ISD::ADDRSPACECAST;
1992   case ICmp:           return ISD::SETCC;
1993   case FCmp:           return ISD::SETCC;
1994   case PHI:            return 0;
1995   case Call:           return 0;
1996   case Select:         return ISD::SELECT;
1997   case UserOp1:        return 0;
1998   case UserOp2:        return 0;
1999   case VAArg:          return 0;
2000   case ExtractElement: return ISD::EXTRACT_VECTOR_ELT;
2001   case InsertElement:  return ISD::INSERT_VECTOR_ELT;
2002   case ShuffleVector:  return ISD::VECTOR_SHUFFLE;
2003   case ExtractValue:   return ISD::MERGE_VALUES;
2004   case InsertValue:    return ISD::MERGE_VALUES;
2005   case LandingPad:     return 0;
2006   case Freeze:         return ISD::FREEZE;
2007   }
2008 
2009   llvm_unreachable("Unknown instruction type encountered!");
2010 }
2011 
2012 Value *
2013 TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilderBase &IRB,
2014                                                        bool UseTLS) const {
2015   // compiler-rt provides a variable with a magic name.  Targets that do not
2016   // link with compiler-rt may also provide such a variable.
2017   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
2018   const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
2019   auto UnsafeStackPtr =
2020       dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar));
2021 
2022   Type *StackPtrTy = PointerType::getUnqual(M->getContext());
2023 
2024   if (!UnsafeStackPtr) {
2025     auto TLSModel = UseTLS ?
2026         GlobalValue::InitialExecTLSModel :
2027         GlobalValue::NotThreadLocal;
2028     // The global variable is not defined yet, define it ourselves.
2029     // We use the initial-exec TLS model because we do not support the
2030     // variable living anywhere other than in the main executable.
2031     UnsafeStackPtr = new GlobalVariable(
2032         *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
2033         UnsafeStackPtrVar, nullptr, TLSModel);
2034   } else {
2035     // The variable exists, check its type and attributes.
2036     if (UnsafeStackPtr->getValueType() != StackPtrTy)
2037       report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
2038     if (UseTLS != UnsafeStackPtr->isThreadLocal())
2039       report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
2040                          (UseTLS ? "" : "not ") + "be thread-local");
2041   }
2042   return UnsafeStackPtr;
2043 }
2044 
2045 Value *
2046 TargetLoweringBase::getSafeStackPointerLocation(IRBuilderBase &IRB) const {
2047   if (!TM.getTargetTriple().isAndroid())
2048     return getDefaultSafeStackPointerLocation(IRB, true);
2049 
2050   // Android provides a libc function to retrieve the address of the current
2051   // thread's unsafe stack pointer.
2052   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
2053   auto *PtrTy = PointerType::getUnqual(M->getContext());
2054   FunctionCallee Fn =
2055       M->getOrInsertFunction("__safestack_pointer_address", PtrTy);
2056   return IRB.CreateCall(Fn);
2057 }
2058 
2059 //===----------------------------------------------------------------------===//
2060 //  Loop Strength Reduction hooks
2061 //===----------------------------------------------------------------------===//
2062 
2063 /// isLegalAddressingMode - Return true if the addressing mode represented
2064 /// by AM is legal for this target, for a load/store of the specified type.
2065 bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL,
2066                                                const AddrMode &AM, Type *Ty,
2067                                                unsigned AS, Instruction *I) const {
2068   // The default implementation of this implements a conservative RISCy, r+r and
2069   // r+i addr mode.
2070 
2071   // Scalable offsets not supported
2072   if (AM.ScalableOffset)
2073     return false;
2074 
2075   // Allows a sign-extended 16-bit immediate field.
2076   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
2077     return false;
2078 
2079   // No global is ever allowed as a base.
2080   if (AM.BaseGV)
2081     return false;
2082 
2083   // Only support r+r,
2084   switch (AM.Scale) {
2085   case 0:  // "r+i" or just "i", depending on HasBaseReg.
2086     break;
2087   case 1:
2088     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
2089       return false;
2090     // Otherwise we have r+r or r+i.
2091     break;
2092   case 2:
2093     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
2094       return false;
2095     // Allow 2*r as r+r.
2096     break;
2097   default: // Don't allow n * r
2098     return false;
2099   }
2100 
2101   return true;
2102 }
2103 
2104 //===----------------------------------------------------------------------===//
2105 //  Stack Protector
2106 //===----------------------------------------------------------------------===//
2107 
2108 // For OpenBSD return its special guard variable. Otherwise return nullptr,
2109 // so that SelectionDAG handle SSP.
2110 Value *TargetLoweringBase::getIRStackGuard(IRBuilderBase &IRB) const {
2111   if (getTargetMachine().getTargetTriple().isOSOpenBSD()) {
2112     Module &M = *IRB.GetInsertBlock()->getParent()->getParent();
2113     PointerType *PtrTy = PointerType::getUnqual(M.getContext());
2114     Constant *C = M.getOrInsertGlobal("__guard_local", PtrTy);
2115     if (GlobalVariable *G = dyn_cast_or_null<GlobalVariable>(C))
2116       G->setVisibility(GlobalValue::HiddenVisibility);
2117     return C;
2118   }
2119   return nullptr;
2120 }
2121 
2122 // Currently only support "standard" __stack_chk_guard.
2123 // TODO: add LOAD_STACK_GUARD support.
2124 void TargetLoweringBase::insertSSPDeclarations(Module &M) const {
2125   if (!M.getNamedValue("__stack_chk_guard")) {
2126     auto *GV = new GlobalVariable(M, PointerType::getUnqual(M.getContext()),
2127                                   false, GlobalVariable::ExternalLinkage,
2128                                   nullptr, "__stack_chk_guard");
2129 
2130     // FreeBSD has "__stack_chk_guard" defined externally on libc.so
2131     if (M.getDirectAccessExternalData() &&
2132         !TM.getTargetTriple().isWindowsGNUEnvironment() &&
2133         !(TM.getTargetTriple().isPPC64() &&
2134           TM.getTargetTriple().isOSFreeBSD()) &&
2135         (!TM.getTargetTriple().isOSDarwin() ||
2136          TM.getRelocationModel() == Reloc::Static))
2137       GV->setDSOLocal(true);
2138   }
2139 }
2140 
2141 // Currently only support "standard" __stack_chk_guard.
2142 // TODO: add LOAD_STACK_GUARD support.
2143 Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const {
2144   return M.getNamedValue("__stack_chk_guard");
2145 }
2146 
2147 Function *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const {
2148   return nullptr;
2149 }
2150 
2151 unsigned TargetLoweringBase::getMinimumJumpTableEntries() const {
2152   return MinimumJumpTableEntries;
2153 }
2154 
2155 void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) {
2156   MinimumJumpTableEntries = Val;
2157 }
2158 
2159 unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const {
2160   return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity;
2161 }
2162 
2163 unsigned TargetLoweringBase::getMaximumJumpTableSize() const {
2164   return MaximumJumpTableSize;
2165 }
2166 
2167 void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) {
2168   MaximumJumpTableSize = Val;
2169 }
2170 
2171 bool TargetLoweringBase::isJumpTableRelative() const {
2172   return getTargetMachine().isPositionIndependent();
2173 }
2174 
2175 Align TargetLoweringBase::getPrefLoopAlignment(MachineLoop *ML) const {
2176   if (TM.Options.LoopAlignment)
2177     return Align(TM.Options.LoopAlignment);
2178   return PrefLoopAlignment;
2179 }
2180 
2181 unsigned TargetLoweringBase::getMaxPermittedBytesForAlignment(
2182     MachineBasicBlock *MBB) const {
2183   return MaxBytesForAlignment;
2184 }
2185 
2186 //===----------------------------------------------------------------------===//
2187 //  Reciprocal Estimates
2188 //===----------------------------------------------------------------------===//
2189 
2190 /// Get the reciprocal estimate attribute string for a function that will
2191 /// override the target defaults.
2192 static StringRef getRecipEstimateForFunc(MachineFunction &MF) {
2193   const Function &F = MF.getFunction();
2194   return F.getFnAttribute("reciprocal-estimates").getValueAsString();
2195 }
2196 
2197 /// Construct a string for the given reciprocal operation of the given type.
2198 /// This string should match the corresponding option to the front-end's
2199 /// "-mrecip" flag assuming those strings have been passed through in an
2200 /// attribute string. For example, "vec-divf" for a division of a vXf32.
2201 static std::string getReciprocalOpName(bool IsSqrt, EVT VT) {
2202   std::string Name = VT.isVector() ? "vec-" : "";
2203 
2204   Name += IsSqrt ? "sqrt" : "div";
2205 
2206   // TODO: Handle other float types?
2207   if (VT.getScalarType() == MVT::f64) {
2208     Name += "d";
2209   } else if (VT.getScalarType() == MVT::f16) {
2210     Name += "h";
2211   } else {
2212     assert(VT.getScalarType() == MVT::f32 &&
2213            "Unexpected FP type for reciprocal estimate");
2214     Name += "f";
2215   }
2216 
2217   return Name;
2218 }
2219 
2220 /// Return the character position and value (a single numeric character) of a
2221 /// customized refinement operation in the input string if it exists. Return
2222 /// false if there is no customized refinement step count.
2223 static bool parseRefinementStep(StringRef In, size_t &Position,
2224                                 uint8_t &Value) {
2225   const char RefStepToken = ':';
2226   Position = In.find(RefStepToken);
2227   if (Position == StringRef::npos)
2228     return false;
2229 
2230   StringRef RefStepString = In.substr(Position + 1);
2231   // Allow exactly one numeric character for the additional refinement
2232   // step parameter.
2233   if (RefStepString.size() == 1) {
2234     char RefStepChar = RefStepString[0];
2235     if (isDigit(RefStepChar)) {
2236       Value = RefStepChar - '0';
2237       return true;
2238     }
2239   }
2240   report_fatal_error("Invalid refinement step for -recip.");
2241 }
2242 
2243 /// For the input attribute string, return one of the ReciprocalEstimate enum
2244 /// status values (enabled, disabled, or not specified) for this operation on
2245 /// the specified data type.
2246 static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) {
2247   if (Override.empty())
2248     return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2249 
2250   SmallVector<StringRef, 4> OverrideVector;
2251   Override.split(OverrideVector, ',');
2252   unsigned NumArgs = OverrideVector.size();
2253 
2254   // Check if "all", "none", or "default" was specified.
2255   if (NumArgs == 1) {
2256     // Look for an optional setting of the number of refinement steps needed
2257     // for this type of reciprocal operation.
2258     size_t RefPos;
2259     uint8_t RefSteps;
2260     if (parseRefinementStep(Override, RefPos, RefSteps)) {
2261       // Split the string for further processing.
2262       Override = Override.substr(0, RefPos);
2263     }
2264 
2265     // All reciprocal types are enabled.
2266     if (Override == "all")
2267       return TargetLoweringBase::ReciprocalEstimate::Enabled;
2268 
2269     // All reciprocal types are disabled.
2270     if (Override == "none")
2271       return TargetLoweringBase::ReciprocalEstimate::Disabled;
2272 
2273     // Target defaults for enablement are used.
2274     if (Override == "default")
2275       return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2276   }
2277 
2278   // The attribute string may omit the size suffix ('f'/'d').
2279   std::string VTName = getReciprocalOpName(IsSqrt, VT);
2280   std::string VTNameNoSize = VTName;
2281   VTNameNoSize.pop_back();
2282   static const char DisabledPrefix = '!';
2283 
2284   for (StringRef RecipType : OverrideVector) {
2285     size_t RefPos;
2286     uint8_t RefSteps;
2287     if (parseRefinementStep(RecipType, RefPos, RefSteps))
2288       RecipType = RecipType.substr(0, RefPos);
2289 
2290     // Ignore the disablement token for string matching.
2291     bool IsDisabled = RecipType[0] == DisabledPrefix;
2292     if (IsDisabled)
2293       RecipType = RecipType.substr(1);
2294 
2295     if (RecipType == VTName || RecipType == VTNameNoSize)
2296       return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled
2297                         : TargetLoweringBase::ReciprocalEstimate::Enabled;
2298   }
2299 
2300   return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2301 }
2302 
2303 /// For the input attribute string, return the customized refinement step count
2304 /// for this operation on the specified data type. If the step count does not
2305 /// exist, return the ReciprocalEstimate enum value for unspecified.
2306 static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) {
2307   if (Override.empty())
2308     return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2309 
2310   SmallVector<StringRef, 4> OverrideVector;
2311   Override.split(OverrideVector, ',');
2312   unsigned NumArgs = OverrideVector.size();
2313 
2314   // Check if "all", "default", or "none" was specified.
2315   if (NumArgs == 1) {
2316     // Look for an optional setting of the number of refinement steps needed
2317     // for this type of reciprocal operation.
2318     size_t RefPos;
2319     uint8_t RefSteps;
2320     if (!parseRefinementStep(Override, RefPos, RefSteps))
2321       return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2322 
2323     // Split the string for further processing.
2324     Override = Override.substr(0, RefPos);
2325     assert(Override != "none" &&
2326            "Disabled reciprocals, but specifed refinement steps?");
2327 
2328     // If this is a general override, return the specified number of steps.
2329     if (Override == "all" || Override == "default")
2330       return RefSteps;
2331   }
2332 
2333   // The attribute string may omit the size suffix ('f'/'d').
2334   std::string VTName = getReciprocalOpName(IsSqrt, VT);
2335   std::string VTNameNoSize = VTName;
2336   VTNameNoSize.pop_back();
2337 
2338   for (StringRef RecipType : OverrideVector) {
2339     size_t RefPos;
2340     uint8_t RefSteps;
2341     if (!parseRefinementStep(RecipType, RefPos, RefSteps))
2342       continue;
2343 
2344     RecipType = RecipType.substr(0, RefPos);
2345     if (RecipType == VTName || RecipType == VTNameNoSize)
2346       return RefSteps;
2347   }
2348 
2349   return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2350 }
2351 
2352 int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT,
2353                                                     MachineFunction &MF) const {
2354   return getOpEnabled(true, VT, getRecipEstimateForFunc(MF));
2355 }
2356 
2357 int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT,
2358                                                    MachineFunction &MF) const {
2359   return getOpEnabled(false, VT, getRecipEstimateForFunc(MF));
2360 }
2361 
2362 int TargetLoweringBase::getSqrtRefinementSteps(EVT VT,
2363                                                MachineFunction &MF) const {
2364   return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF));
2365 }
2366 
2367 int TargetLoweringBase::getDivRefinementSteps(EVT VT,
2368                                               MachineFunction &MF) const {
2369   return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF));
2370 }
2371 
2372 bool TargetLoweringBase::isLoadBitCastBeneficial(
2373     EVT LoadVT, EVT BitcastVT, const SelectionDAG &DAG,
2374     const MachineMemOperand &MMO) const {
2375   // Single-element vectors are scalarized, so we should generally avoid having
2376   // any memory operations on such types, as they would get scalarized too.
2377   if (LoadVT.isFixedLengthVector() && BitcastVT.isFixedLengthVector() &&
2378       BitcastVT.getVectorNumElements() == 1)
2379     return false;
2380 
2381   // Don't do if we could do an indexed load on the original type, but not on
2382   // the new one.
2383   if (!LoadVT.isSimple() || !BitcastVT.isSimple())
2384     return true;
2385 
2386   MVT LoadMVT = LoadVT.getSimpleVT();
2387 
2388   // Don't bother doing this if it's just going to be promoted again later, as
2389   // doing so might interfere with other combines.
2390   if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
2391       getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT())
2392     return false;
2393 
2394   unsigned Fast = 0;
2395   return allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), BitcastVT,
2396                             MMO, &Fast) &&
2397          Fast;
2398 }
2399 
2400 void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const {
2401   MF.getRegInfo().freezeReservedRegs();
2402 }
2403 
2404 MachineMemOperand::Flags TargetLoweringBase::getLoadMemOperandFlags(
2405     const LoadInst &LI, const DataLayout &DL, AssumptionCache *AC,
2406     const TargetLibraryInfo *LibInfo) const {
2407   MachineMemOperand::Flags Flags = MachineMemOperand::MOLoad;
2408   if (LI.isVolatile())
2409     Flags |= MachineMemOperand::MOVolatile;
2410 
2411   if (LI.hasMetadata(LLVMContext::MD_nontemporal))
2412     Flags |= MachineMemOperand::MONonTemporal;
2413 
2414   if (LI.hasMetadata(LLVMContext::MD_invariant_load))
2415     Flags |= MachineMemOperand::MOInvariant;
2416 
2417   if (isDereferenceableAndAlignedPointer(LI.getPointerOperand(), LI.getType(),
2418                                          LI.getAlign(), DL, &LI, AC,
2419                                          /*DT=*/nullptr, LibInfo))
2420     Flags |= MachineMemOperand::MODereferenceable;
2421 
2422   Flags |= getTargetMMOFlags(LI);
2423   return Flags;
2424 }
2425 
2426 MachineMemOperand::Flags
2427 TargetLoweringBase::getStoreMemOperandFlags(const StoreInst &SI,
2428                                             const DataLayout &DL) const {
2429   MachineMemOperand::Flags Flags = MachineMemOperand::MOStore;
2430 
2431   if (SI.isVolatile())
2432     Flags |= MachineMemOperand::MOVolatile;
2433 
2434   if (SI.hasMetadata(LLVMContext::MD_nontemporal))
2435     Flags |= MachineMemOperand::MONonTemporal;
2436 
2437   // FIXME: Not preserving dereferenceable
2438   Flags |= getTargetMMOFlags(SI);
2439   return Flags;
2440 }
2441 
2442 MachineMemOperand::Flags
2443 TargetLoweringBase::getAtomicMemOperandFlags(const Instruction &AI,
2444                                              const DataLayout &DL) const {
2445   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
2446 
2447   if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(&AI)) {
2448     if (RMW->isVolatile())
2449       Flags |= MachineMemOperand::MOVolatile;
2450   } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(&AI)) {
2451     if (CmpX->isVolatile())
2452       Flags |= MachineMemOperand::MOVolatile;
2453   } else
2454     llvm_unreachable("not an atomic instruction");
2455 
2456   // FIXME: Not preserving dereferenceable
2457   Flags |= getTargetMMOFlags(AI);
2458   return Flags;
2459 }
2460 
2461 Instruction *TargetLoweringBase::emitLeadingFence(IRBuilderBase &Builder,
2462                                                   Instruction *Inst,
2463                                                   AtomicOrdering Ord) const {
2464   if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore())
2465     return Builder.CreateFence(Ord);
2466   else
2467     return nullptr;
2468 }
2469 
2470 Instruction *TargetLoweringBase::emitTrailingFence(IRBuilderBase &Builder,
2471                                                    Instruction *Inst,
2472                                                    AtomicOrdering Ord) const {
2473   if (isAcquireOrStronger(Ord))
2474     return Builder.CreateFence(Ord);
2475   else
2476     return nullptr;
2477 }
2478 
2479 //===----------------------------------------------------------------------===//
2480 //  GlobalISel Hooks
2481 //===----------------------------------------------------------------------===//
2482 
2483 bool TargetLoweringBase::shouldLocalize(const MachineInstr &MI,
2484                                         const TargetTransformInfo *TTI) const {
2485   auto &MF = *MI.getMF();
2486   auto &MRI = MF.getRegInfo();
2487   // Assuming a spill and reload of a value has a cost of 1 instruction each,
2488   // this helper function computes the maximum number of uses we should consider
2489   // for remat. E.g. on arm64 global addresses take 2 insts to materialize. We
2490   // break even in terms of code size when the original MI has 2 users vs
2491   // choosing to potentially spill. Any more than 2 users we we have a net code
2492   // size increase. This doesn't take into account register pressure though.
2493   auto maxUses = [](unsigned RematCost) {
2494     // A cost of 1 means remats are basically free.
2495     if (RematCost == 1)
2496       return std::numeric_limits<unsigned>::max();
2497     if (RematCost == 2)
2498       return 2U;
2499 
2500     // Remat is too expensive, only sink if there's one user.
2501     if (RematCost > 2)
2502       return 1U;
2503     llvm_unreachable("Unexpected remat cost");
2504   };
2505 
2506   switch (MI.getOpcode()) {
2507   default:
2508     return false;
2509   // Constants-like instructions should be close to their users.
2510   // We don't want long live-ranges for them.
2511   case TargetOpcode::G_CONSTANT:
2512   case TargetOpcode::G_FCONSTANT:
2513   case TargetOpcode::G_FRAME_INDEX:
2514   case TargetOpcode::G_INTTOPTR:
2515     return true;
2516   case TargetOpcode::G_GLOBAL_VALUE: {
2517     unsigned RematCost = TTI->getGISelRematGlobalCost();
2518     Register Reg = MI.getOperand(0).getReg();
2519     unsigned MaxUses = maxUses(RematCost);
2520     if (MaxUses == UINT_MAX)
2521       return true; // Remats are "free" so always localize.
2522     return MRI.hasAtMostUserInstrs(Reg, MaxUses);
2523   }
2524   }
2525 }
2526