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