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/Triple.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/Analysis/Loads.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/IR/Attributes.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalValue.h"
43 #include "llvm/IR/GlobalVariable.h"
44 #include "llvm/IR/IRBuilder.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/Support/BranchProbability.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/MachineValueType.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include <algorithm>
56 #include <cassert>
57 #include <cstddef>
58 #include <cstdint>
59 #include <cstring>
60 #include <iterator>
61 #include <string>
62 #include <tuple>
63 #include <utility>
64 
65 using namespace llvm;
66 
67 static cl::opt<bool> JumpIsExpensiveOverride(
68     "jump-is-expensive", cl::init(false),
69     cl::desc("Do not create extra branches to split comparison logic."),
70     cl::Hidden);
71 
72 static cl::opt<unsigned> MinimumJumpTableEntries
73   ("min-jump-table-entries", cl::init(4), cl::Hidden,
74    cl::desc("Set minimum number of entries to use a jump table."));
75 
76 static cl::opt<unsigned> MaximumJumpTableSize
77   ("max-jump-table-size", cl::init(UINT_MAX), cl::Hidden,
78    cl::desc("Set maximum size of jump tables."));
79 
80 /// Minimum jump table density for normal functions.
81 static cl::opt<unsigned>
82     JumpTableDensity("jump-table-density", cl::init(10), cl::Hidden,
83                      cl::desc("Minimum density for building a jump table in "
84                               "a normal function"));
85 
86 /// Minimum jump table density for -Os or -Oz functions.
87 static cl::opt<unsigned> OptsizeJumpTableDensity(
88     "optsize-jump-table-density", cl::init(40), cl::Hidden,
89     cl::desc("Minimum density for building a jump table in "
90              "an optsize function"));
91 
92 // FIXME: This option is only to test if the strict fp operation processed
93 // correctly by preventing mutating strict fp operation to normal fp operation
94 // during development. When the backend supports strict float operation, this
95 // option will be meaningless.
96 static cl::opt<bool> DisableStrictNodeMutation("disable-strictnode-mutation",
97        cl::desc("Don't mutate strict-float node to a legalize node"),
98        cl::init(false), cl::Hidden);
99 
100 static bool darwinHasSinCos(const Triple &TT) {
101   assert(TT.isOSDarwin() && "should be called with darwin triple");
102   // Don't bother with 32 bit x86.
103   if (TT.getArch() == Triple::x86)
104     return false;
105   // Macos < 10.9 has no sincos_stret.
106   if (TT.isMacOSX())
107     return !TT.isMacOSXVersionLT(10, 9) && TT.isArch64Bit();
108   // iOS < 7.0 has no sincos_stret.
109   if (TT.isiOS())
110     return !TT.isOSVersionLT(7, 0);
111   // Any other darwin such as WatchOS/TvOS is new enough.
112   return true;
113 }
114 
115 // Although this default value is arbitrary, it is not random. It is assumed
116 // that a condition that evaluates the same way by a higher percentage than this
117 // is best represented as control flow. Therefore, the default value N should be
118 // set such that the win from N% correct executions is greater than the loss
119 // from (100 - N)% mispredicted executions for the majority of intended targets.
120 static cl::opt<int> MinPercentageForPredictableBranch(
121     "min-predictable-branch", cl::init(99),
122     cl::desc("Minimum percentage (0-100) that a condition must be either true "
123              "or false to assume that the condition is predictable"),
124     cl::Hidden);
125 
126 void TargetLoweringBase::InitLibcalls(const Triple &TT) {
127 #define HANDLE_LIBCALL(code, name) \
128   setLibcallName(RTLIB::code, name);
129 #include "llvm/IR/RuntimeLibcalls.def"
130 #undef HANDLE_LIBCALL
131   // Initialize calling conventions to their default.
132   for (int LC = 0; LC < RTLIB::UNKNOWN_LIBCALL; ++LC)
133     setLibcallCallingConv((RTLIB::Libcall)LC, CallingConv::C);
134 
135   // For IEEE quad-precision libcall names, PPC uses "kf" instead of "tf".
136   if (TT.getArch() == Triple::ppc || TT.isPPC64()) {
137     setLibcallName(RTLIB::ADD_F128, "__addkf3");
138     setLibcallName(RTLIB::SUB_F128, "__subkf3");
139     setLibcallName(RTLIB::MUL_F128, "__mulkf3");
140     setLibcallName(RTLIB::DIV_F128, "__divkf3");
141     setLibcallName(RTLIB::FPEXT_F32_F128, "__extendsfkf2");
142     setLibcallName(RTLIB::FPEXT_F64_F128, "__extenddfkf2");
143     setLibcallName(RTLIB::FPROUND_F128_F32, "__trunckfsf2");
144     setLibcallName(RTLIB::FPROUND_F128_F64, "__trunckfdf2");
145     setLibcallName(RTLIB::FPTOSINT_F128_I32, "__fixkfsi");
146     setLibcallName(RTLIB::FPTOSINT_F128_I64, "__fixkfdi");
147     setLibcallName(RTLIB::FPTOUINT_F128_I32, "__fixunskfsi");
148     setLibcallName(RTLIB::FPTOUINT_F128_I64, "__fixunskfdi");
149     setLibcallName(RTLIB::SINTTOFP_I32_F128, "__floatsikf");
150     setLibcallName(RTLIB::SINTTOFP_I64_F128, "__floatdikf");
151     setLibcallName(RTLIB::UINTTOFP_I32_F128, "__floatunsikf");
152     setLibcallName(RTLIB::UINTTOFP_I64_F128, "__floatundikf");
153     setLibcallName(RTLIB::OEQ_F128, "__eqkf2");
154     setLibcallName(RTLIB::UNE_F128, "__nekf2");
155     setLibcallName(RTLIB::OGE_F128, "__gekf2");
156     setLibcallName(RTLIB::OLT_F128, "__ltkf2");
157     setLibcallName(RTLIB::OLE_F128, "__lekf2");
158     setLibcallName(RTLIB::OGT_F128, "__gtkf2");
159     setLibcallName(RTLIB::UO_F128, "__unordkf2");
160   }
161 
162   // A few names are different on particular architectures or environments.
163   if (TT.isOSDarwin()) {
164     // For f16/f32 conversions, Darwin uses the standard naming scheme, instead
165     // of the gnueabi-style __gnu_*_ieee.
166     // FIXME: What about other targets?
167     setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
168     setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
169 
170     // Some darwins have an optimized __bzero/bzero function.
171     switch (TT.getArch()) {
172     case Triple::x86:
173     case Triple::x86_64:
174       if (TT.isMacOSX() && !TT.isMacOSXVersionLT(10, 6))
175         setLibcallName(RTLIB::BZERO, "__bzero");
176       break;
177     case Triple::aarch64:
178     case Triple::aarch64_32:
179       setLibcallName(RTLIB::BZERO, "bzero");
180       break;
181     default:
182       break;
183     }
184 
185     if (darwinHasSinCos(TT)) {
186       setLibcallName(RTLIB::SINCOS_STRET_F32, "__sincosf_stret");
187       setLibcallName(RTLIB::SINCOS_STRET_F64, "__sincos_stret");
188       if (TT.isWatchABI()) {
189         setLibcallCallingConv(RTLIB::SINCOS_STRET_F32,
190                               CallingConv::ARM_AAPCS_VFP);
191         setLibcallCallingConv(RTLIB::SINCOS_STRET_F64,
192                               CallingConv::ARM_AAPCS_VFP);
193       }
194     }
195   } else {
196     setLibcallName(RTLIB::FPEXT_F16_F32, "__gnu_h2f_ieee");
197     setLibcallName(RTLIB::FPROUND_F32_F16, "__gnu_f2h_ieee");
198   }
199 
200   if (TT.isGNUEnvironment() || TT.isOSFuchsia() ||
201       (TT.isAndroid() && !TT.isAndroidVersionLT(9))) {
202     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
203     setLibcallName(RTLIB::SINCOS_F64, "sincos");
204     setLibcallName(RTLIB::SINCOS_F80, "sincosl");
205     setLibcallName(RTLIB::SINCOS_F128, "sincosl");
206     setLibcallName(RTLIB::SINCOS_PPCF128, "sincosl");
207   }
208 
209   if (TT.isPS4CPU()) {
210     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
211     setLibcallName(RTLIB::SINCOS_F64, "sincos");
212   }
213 
214   if (TT.isOSOpenBSD()) {
215     setLibcallName(RTLIB::STACKPROTECTOR_CHECK_FAIL, nullptr);
216   }
217 }
218 
219 /// getFPEXT - Return the FPEXT_*_* value for the given types, or
220 /// UNKNOWN_LIBCALL if there is none.
221 RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) {
222   if (OpVT == MVT::f16) {
223     if (RetVT == MVT::f32)
224       return FPEXT_F16_F32;
225   } else if (OpVT == MVT::f32) {
226     if (RetVT == MVT::f64)
227       return FPEXT_F32_F64;
228     if (RetVT == MVT::f128)
229       return FPEXT_F32_F128;
230     if (RetVT == MVT::ppcf128)
231       return FPEXT_F32_PPCF128;
232   } else if (OpVT == MVT::f64) {
233     if (RetVT == MVT::f128)
234       return FPEXT_F64_F128;
235     else if (RetVT == MVT::ppcf128)
236       return FPEXT_F64_PPCF128;
237   } else if (OpVT == MVT::f80) {
238     if (RetVT == MVT::f128)
239       return FPEXT_F80_F128;
240   }
241 
242   return UNKNOWN_LIBCALL;
243 }
244 
245 /// getFPROUND - Return the FPROUND_*_* value for the given types, or
246 /// UNKNOWN_LIBCALL if there is none.
247 RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) {
248   if (RetVT == MVT::f16) {
249     if (OpVT == MVT::f32)
250       return FPROUND_F32_F16;
251     if (OpVT == MVT::f64)
252       return FPROUND_F64_F16;
253     if (OpVT == MVT::f80)
254       return FPROUND_F80_F16;
255     if (OpVT == MVT::f128)
256       return FPROUND_F128_F16;
257     if (OpVT == MVT::ppcf128)
258       return FPROUND_PPCF128_F16;
259   } else if (RetVT == MVT::f32) {
260     if (OpVT == MVT::f64)
261       return FPROUND_F64_F32;
262     if (OpVT == MVT::f80)
263       return FPROUND_F80_F32;
264     if (OpVT == MVT::f128)
265       return FPROUND_F128_F32;
266     if (OpVT == MVT::ppcf128)
267       return FPROUND_PPCF128_F32;
268   } else if (RetVT == MVT::f64) {
269     if (OpVT == MVT::f80)
270       return FPROUND_F80_F64;
271     if (OpVT == MVT::f128)
272       return FPROUND_F128_F64;
273     if (OpVT == MVT::ppcf128)
274       return FPROUND_PPCF128_F64;
275   } else if (RetVT == MVT::f80) {
276     if (OpVT == MVT::f128)
277       return FPROUND_F128_F80;
278   }
279 
280   return UNKNOWN_LIBCALL;
281 }
282 
283 /// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or
284 /// UNKNOWN_LIBCALL if there is none.
285 RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) {
286   if (OpVT == MVT::f32) {
287     if (RetVT == MVT::i32)
288       return FPTOSINT_F32_I32;
289     if (RetVT == MVT::i64)
290       return FPTOSINT_F32_I64;
291     if (RetVT == MVT::i128)
292       return FPTOSINT_F32_I128;
293   } else if (OpVT == MVT::f64) {
294     if (RetVT == MVT::i32)
295       return FPTOSINT_F64_I32;
296     if (RetVT == MVT::i64)
297       return FPTOSINT_F64_I64;
298     if (RetVT == MVT::i128)
299       return FPTOSINT_F64_I128;
300   } else if (OpVT == MVT::f80) {
301     if (RetVT == MVT::i32)
302       return FPTOSINT_F80_I32;
303     if (RetVT == MVT::i64)
304       return FPTOSINT_F80_I64;
305     if (RetVT == MVT::i128)
306       return FPTOSINT_F80_I128;
307   } else if (OpVT == MVT::f128) {
308     if (RetVT == MVT::i32)
309       return FPTOSINT_F128_I32;
310     if (RetVT == MVT::i64)
311       return FPTOSINT_F128_I64;
312     if (RetVT == MVT::i128)
313       return FPTOSINT_F128_I128;
314   } else if (OpVT == MVT::ppcf128) {
315     if (RetVT == MVT::i32)
316       return FPTOSINT_PPCF128_I32;
317     if (RetVT == MVT::i64)
318       return FPTOSINT_PPCF128_I64;
319     if (RetVT == MVT::i128)
320       return FPTOSINT_PPCF128_I128;
321   }
322   return UNKNOWN_LIBCALL;
323 }
324 
325 /// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or
326 /// UNKNOWN_LIBCALL if there is none.
327 RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) {
328   if (OpVT == MVT::f32) {
329     if (RetVT == MVT::i32)
330       return FPTOUINT_F32_I32;
331     if (RetVT == MVT::i64)
332       return FPTOUINT_F32_I64;
333     if (RetVT == MVT::i128)
334       return FPTOUINT_F32_I128;
335   } else if (OpVT == MVT::f64) {
336     if (RetVT == MVT::i32)
337       return FPTOUINT_F64_I32;
338     if (RetVT == MVT::i64)
339       return FPTOUINT_F64_I64;
340     if (RetVT == MVT::i128)
341       return FPTOUINT_F64_I128;
342   } else if (OpVT == MVT::f80) {
343     if (RetVT == MVT::i32)
344       return FPTOUINT_F80_I32;
345     if (RetVT == MVT::i64)
346       return FPTOUINT_F80_I64;
347     if (RetVT == MVT::i128)
348       return FPTOUINT_F80_I128;
349   } else if (OpVT == MVT::f128) {
350     if (RetVT == MVT::i32)
351       return FPTOUINT_F128_I32;
352     if (RetVT == MVT::i64)
353       return FPTOUINT_F128_I64;
354     if (RetVT == MVT::i128)
355       return FPTOUINT_F128_I128;
356   } else if (OpVT == MVT::ppcf128) {
357     if (RetVT == MVT::i32)
358       return FPTOUINT_PPCF128_I32;
359     if (RetVT == MVT::i64)
360       return FPTOUINT_PPCF128_I64;
361     if (RetVT == MVT::i128)
362       return FPTOUINT_PPCF128_I128;
363   }
364   return UNKNOWN_LIBCALL;
365 }
366 
367 /// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or
368 /// UNKNOWN_LIBCALL if there is none.
369 RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) {
370   if (OpVT == MVT::i32) {
371     if (RetVT == MVT::f32)
372       return SINTTOFP_I32_F32;
373     if (RetVT == MVT::f64)
374       return SINTTOFP_I32_F64;
375     if (RetVT == MVT::f80)
376       return SINTTOFP_I32_F80;
377     if (RetVT == MVT::f128)
378       return SINTTOFP_I32_F128;
379     if (RetVT == MVT::ppcf128)
380       return SINTTOFP_I32_PPCF128;
381   } else if (OpVT == MVT::i64) {
382     if (RetVT == MVT::f32)
383       return SINTTOFP_I64_F32;
384     if (RetVT == MVT::f64)
385       return SINTTOFP_I64_F64;
386     if (RetVT == MVT::f80)
387       return SINTTOFP_I64_F80;
388     if (RetVT == MVT::f128)
389       return SINTTOFP_I64_F128;
390     if (RetVT == MVT::ppcf128)
391       return SINTTOFP_I64_PPCF128;
392   } else if (OpVT == MVT::i128) {
393     if (RetVT == MVT::f32)
394       return SINTTOFP_I128_F32;
395     if (RetVT == MVT::f64)
396       return SINTTOFP_I128_F64;
397     if (RetVT == MVT::f80)
398       return SINTTOFP_I128_F80;
399     if (RetVT == MVT::f128)
400       return SINTTOFP_I128_F128;
401     if (RetVT == MVT::ppcf128)
402       return SINTTOFP_I128_PPCF128;
403   }
404   return UNKNOWN_LIBCALL;
405 }
406 
407 /// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or
408 /// UNKNOWN_LIBCALL if there is none.
409 RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) {
410   if (OpVT == MVT::i32) {
411     if (RetVT == MVT::f32)
412       return UINTTOFP_I32_F32;
413     if (RetVT == MVT::f64)
414       return UINTTOFP_I32_F64;
415     if (RetVT == MVT::f80)
416       return UINTTOFP_I32_F80;
417     if (RetVT == MVT::f128)
418       return UINTTOFP_I32_F128;
419     if (RetVT == MVT::ppcf128)
420       return UINTTOFP_I32_PPCF128;
421   } else if (OpVT == MVT::i64) {
422     if (RetVT == MVT::f32)
423       return UINTTOFP_I64_F32;
424     if (RetVT == MVT::f64)
425       return UINTTOFP_I64_F64;
426     if (RetVT == MVT::f80)
427       return UINTTOFP_I64_F80;
428     if (RetVT == MVT::f128)
429       return UINTTOFP_I64_F128;
430     if (RetVT == MVT::ppcf128)
431       return UINTTOFP_I64_PPCF128;
432   } else if (OpVT == MVT::i128) {
433     if (RetVT == MVT::f32)
434       return UINTTOFP_I128_F32;
435     if (RetVT == MVT::f64)
436       return UINTTOFP_I128_F64;
437     if (RetVT == MVT::f80)
438       return UINTTOFP_I128_F80;
439     if (RetVT == MVT::f128)
440       return UINTTOFP_I128_F128;
441     if (RetVT == MVT::ppcf128)
442       return UINTTOFP_I128_PPCF128;
443   }
444   return UNKNOWN_LIBCALL;
445 }
446 
447 RTLIB::Libcall RTLIB::getSYNC(unsigned Opc, MVT VT) {
448 #define OP_TO_LIBCALL(Name, Enum)                                              \
449   case Name:                                                                   \
450     switch (VT.SimpleTy) {                                                     \
451     default:                                                                   \
452       return UNKNOWN_LIBCALL;                                                  \
453     case MVT::i8:                                                              \
454       return Enum##_1;                                                         \
455     case MVT::i16:                                                             \
456       return Enum##_2;                                                         \
457     case MVT::i32:                                                             \
458       return Enum##_4;                                                         \
459     case MVT::i64:                                                             \
460       return Enum##_8;                                                         \
461     case MVT::i128:                                                            \
462       return Enum##_16;                                                        \
463     }
464 
465   switch (Opc) {
466     OP_TO_LIBCALL(ISD::ATOMIC_SWAP, SYNC_LOCK_TEST_AND_SET)
467     OP_TO_LIBCALL(ISD::ATOMIC_CMP_SWAP, SYNC_VAL_COMPARE_AND_SWAP)
468     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_ADD, SYNC_FETCH_AND_ADD)
469     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_SUB, SYNC_FETCH_AND_SUB)
470     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_AND, SYNC_FETCH_AND_AND)
471     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_OR, SYNC_FETCH_AND_OR)
472     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_XOR, SYNC_FETCH_AND_XOR)
473     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_NAND, SYNC_FETCH_AND_NAND)
474     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MAX, SYNC_FETCH_AND_MAX)
475     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMAX, SYNC_FETCH_AND_UMAX)
476     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MIN, SYNC_FETCH_AND_MIN)
477     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMIN, SYNC_FETCH_AND_UMIN)
478   }
479 
480 #undef OP_TO_LIBCALL
481 
482   return UNKNOWN_LIBCALL;
483 }
484 
485 RTLIB::Libcall RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
486   switch (ElementSize) {
487   case 1:
488     return MEMCPY_ELEMENT_UNORDERED_ATOMIC_1;
489   case 2:
490     return MEMCPY_ELEMENT_UNORDERED_ATOMIC_2;
491   case 4:
492     return MEMCPY_ELEMENT_UNORDERED_ATOMIC_4;
493   case 8:
494     return MEMCPY_ELEMENT_UNORDERED_ATOMIC_8;
495   case 16:
496     return MEMCPY_ELEMENT_UNORDERED_ATOMIC_16;
497   default:
498     return UNKNOWN_LIBCALL;
499   }
500 }
501 
502 RTLIB::Libcall RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
503   switch (ElementSize) {
504   case 1:
505     return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_1;
506   case 2:
507     return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_2;
508   case 4:
509     return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_4;
510   case 8:
511     return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_8;
512   case 16:
513     return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_16;
514   default:
515     return UNKNOWN_LIBCALL;
516   }
517 }
518 
519 RTLIB::Libcall RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize) {
520   switch (ElementSize) {
521   case 1:
522     return MEMSET_ELEMENT_UNORDERED_ATOMIC_1;
523   case 2:
524     return MEMSET_ELEMENT_UNORDERED_ATOMIC_2;
525   case 4:
526     return MEMSET_ELEMENT_UNORDERED_ATOMIC_4;
527   case 8:
528     return MEMSET_ELEMENT_UNORDERED_ATOMIC_8;
529   case 16:
530     return MEMSET_ELEMENT_UNORDERED_ATOMIC_16;
531   default:
532     return UNKNOWN_LIBCALL;
533   }
534 }
535 
536 /// InitCmpLibcallCCs - Set default comparison libcall CC.
537 static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
538   memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
539   CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
540   CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
541   CCs[RTLIB::OEQ_F128] = ISD::SETEQ;
542   CCs[RTLIB::OEQ_PPCF128] = ISD::SETEQ;
543   CCs[RTLIB::UNE_F32] = ISD::SETNE;
544   CCs[RTLIB::UNE_F64] = ISD::SETNE;
545   CCs[RTLIB::UNE_F128] = ISD::SETNE;
546   CCs[RTLIB::UNE_PPCF128] = ISD::SETNE;
547   CCs[RTLIB::OGE_F32] = ISD::SETGE;
548   CCs[RTLIB::OGE_F64] = ISD::SETGE;
549   CCs[RTLIB::OGE_F128] = ISD::SETGE;
550   CCs[RTLIB::OGE_PPCF128] = ISD::SETGE;
551   CCs[RTLIB::OLT_F32] = ISD::SETLT;
552   CCs[RTLIB::OLT_F64] = ISD::SETLT;
553   CCs[RTLIB::OLT_F128] = ISD::SETLT;
554   CCs[RTLIB::OLT_PPCF128] = ISD::SETLT;
555   CCs[RTLIB::OLE_F32] = ISD::SETLE;
556   CCs[RTLIB::OLE_F64] = ISD::SETLE;
557   CCs[RTLIB::OLE_F128] = ISD::SETLE;
558   CCs[RTLIB::OLE_PPCF128] = ISD::SETLE;
559   CCs[RTLIB::OGT_F32] = ISD::SETGT;
560   CCs[RTLIB::OGT_F64] = ISD::SETGT;
561   CCs[RTLIB::OGT_F128] = ISD::SETGT;
562   CCs[RTLIB::OGT_PPCF128] = ISD::SETGT;
563   CCs[RTLIB::UO_F32] = ISD::SETNE;
564   CCs[RTLIB::UO_F64] = ISD::SETNE;
565   CCs[RTLIB::UO_F128] = ISD::SETNE;
566   CCs[RTLIB::UO_PPCF128] = ISD::SETNE;
567 }
568 
569 /// NOTE: The TargetMachine owns TLOF.
570 TargetLoweringBase::TargetLoweringBase(const TargetMachine &tm) : TM(tm) {
571   initActions();
572 
573   // Perform these initializations only once.
574   MaxStoresPerMemset = MaxStoresPerMemcpy = MaxStoresPerMemmove =
575       MaxLoadsPerMemcmp = 8;
576   MaxGluedStoresPerMemcpy = 0;
577   MaxStoresPerMemsetOptSize = MaxStoresPerMemcpyOptSize =
578       MaxStoresPerMemmoveOptSize = MaxLoadsPerMemcmpOptSize = 4;
579   HasMultipleConditionRegisters = false;
580   HasExtractBitsInsn = false;
581   JumpIsExpensive = JumpIsExpensiveOverride;
582   PredictableSelectIsExpensive = false;
583   EnableExtLdPromotion = false;
584   StackPointerRegisterToSaveRestore = 0;
585   BooleanContents = UndefinedBooleanContent;
586   BooleanFloatContents = UndefinedBooleanContent;
587   BooleanVectorContents = UndefinedBooleanContent;
588   SchedPreferenceInfo = Sched::ILP;
589   GatherAllAliasesMaxDepth = 18;
590   IsStrictFPEnabled = DisableStrictNodeMutation;
591   // TODO: the default will be switched to 0 in the next commit, along
592   // with the Target-specific changes necessary.
593   MaxAtomicSizeInBitsSupported = 1024;
594 
595   MinCmpXchgSizeInBits = 0;
596   SupportsUnalignedAtomics = false;
597 
598   std::fill(std::begin(LibcallRoutineNames), std::end(LibcallRoutineNames), nullptr);
599 
600   InitLibcalls(TM.getTargetTriple());
601   InitCmpLibcallCCs(CmpLibcallCCs);
602 }
603 
604 void TargetLoweringBase::initActions() {
605   // All operations default to being supported.
606   memset(OpActions, 0, sizeof(OpActions));
607   memset(LoadExtActions, 0, sizeof(LoadExtActions));
608   memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
609   memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
610   memset(CondCodeActions, 0, sizeof(CondCodeActions));
611   std::fill(std::begin(RegClassForVT), std::end(RegClassForVT), nullptr);
612   std::fill(std::begin(TargetDAGCombineArray),
613             std::end(TargetDAGCombineArray), 0);
614 
615   for (MVT VT : MVT::fp_valuetypes()) {
616     MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
617     if (IntVT.isValid()) {
618       setOperationAction(ISD::ATOMIC_SWAP, VT, Promote);
619       AddPromotedToType(ISD::ATOMIC_SWAP, VT, IntVT);
620     }
621   }
622 
623   // Set default actions for various operations.
624   for (MVT VT : MVT::all_valuetypes()) {
625     // Default all indexed load / store to expand.
626     for (unsigned IM = (unsigned)ISD::PRE_INC;
627          IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
628       setIndexedLoadAction(IM, VT, Expand);
629       setIndexedStoreAction(IM, VT, Expand);
630       setIndexedMaskedLoadAction(IM, VT, Expand);
631       setIndexedMaskedStoreAction(IM, VT, Expand);
632     }
633 
634     // Most backends expect to see the node which just returns the value loaded.
635     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Expand);
636 
637     // These operations default to expand.
638     setOperationAction(ISD::FGETSIGN, VT, Expand);
639     setOperationAction(ISD::CONCAT_VECTORS, VT, Expand);
640     setOperationAction(ISD::FMINNUM, VT, Expand);
641     setOperationAction(ISD::FMAXNUM, VT, Expand);
642     setOperationAction(ISD::FMINNUM_IEEE, VT, Expand);
643     setOperationAction(ISD::FMAXNUM_IEEE, VT, Expand);
644     setOperationAction(ISD::FMINIMUM, VT, Expand);
645     setOperationAction(ISD::FMAXIMUM, VT, Expand);
646     setOperationAction(ISD::FMAD, VT, Expand);
647     setOperationAction(ISD::SMIN, VT, Expand);
648     setOperationAction(ISD::SMAX, VT, Expand);
649     setOperationAction(ISD::UMIN, VT, Expand);
650     setOperationAction(ISD::UMAX, VT, Expand);
651     setOperationAction(ISD::ABS, VT, Expand);
652     setOperationAction(ISD::FSHL, VT, Expand);
653     setOperationAction(ISD::FSHR, VT, Expand);
654     setOperationAction(ISD::SADDSAT, VT, Expand);
655     setOperationAction(ISD::UADDSAT, VT, Expand);
656     setOperationAction(ISD::SSUBSAT, VT, Expand);
657     setOperationAction(ISD::USUBSAT, VT, Expand);
658     setOperationAction(ISD::SMULFIX, VT, Expand);
659     setOperationAction(ISD::SMULFIXSAT, VT, Expand);
660     setOperationAction(ISD::UMULFIX, VT, Expand);
661     setOperationAction(ISD::UMULFIXSAT, VT, Expand);
662     setOperationAction(ISD::SDIVFIX, VT, Expand);
663     setOperationAction(ISD::SDIVFIXSAT, VT, Expand);
664     setOperationAction(ISD::UDIVFIX, VT, Expand);
665     setOperationAction(ISD::UDIVFIXSAT, VT, Expand);
666 
667     // Overflow operations default to expand
668     setOperationAction(ISD::SADDO, VT, Expand);
669     setOperationAction(ISD::SSUBO, VT, Expand);
670     setOperationAction(ISD::UADDO, VT, Expand);
671     setOperationAction(ISD::USUBO, VT, Expand);
672     setOperationAction(ISD::SMULO, VT, Expand);
673     setOperationAction(ISD::UMULO, VT, Expand);
674 
675     // ADDCARRY operations default to expand
676     setOperationAction(ISD::ADDCARRY, VT, Expand);
677     setOperationAction(ISD::SUBCARRY, VT, Expand);
678     setOperationAction(ISD::SETCCCARRY, VT, Expand);
679 
680     // ADDC/ADDE/SUBC/SUBE default to expand.
681     setOperationAction(ISD::ADDC, VT, Expand);
682     setOperationAction(ISD::ADDE, VT, Expand);
683     setOperationAction(ISD::SUBC, VT, Expand);
684     setOperationAction(ISD::SUBE, VT, Expand);
685 
686     // These default to Expand so they will be expanded to CTLZ/CTTZ by default.
687     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
688     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
689 
690     setOperationAction(ISD::BITREVERSE, VT, Expand);
691 
692     // These library functions default to expand.
693     setOperationAction(ISD::FROUND, VT, Expand);
694     setOperationAction(ISD::FPOWI, VT, Expand);
695 
696     // These operations default to expand for vector types.
697     if (VT.isVector()) {
698       setOperationAction(ISD::FCOPYSIGN, VT, Expand);
699       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
700       setOperationAction(ISD::ANY_EXTEND_VECTOR_INREG, VT, Expand);
701       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Expand);
702       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Expand);
703       setOperationAction(ISD::SPLAT_VECTOR, VT, Expand);
704     }
705 
706     // Constrained floating-point operations default to expand.
707 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
708     setOperationAction(ISD::STRICT_##DAGN, VT, Expand);
709 #include "llvm/IR/ConstrainedOps.def"
710 
711     // For most targets @llvm.get.dynamic.area.offset just returns 0.
712     setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand);
713 
714     // Vector reduction default to expand.
715     setOperationAction(ISD::VECREDUCE_FADD, VT, Expand);
716     setOperationAction(ISD::VECREDUCE_FMUL, VT, Expand);
717     setOperationAction(ISD::VECREDUCE_ADD, VT, Expand);
718     setOperationAction(ISD::VECREDUCE_MUL, VT, Expand);
719     setOperationAction(ISD::VECREDUCE_AND, VT, Expand);
720     setOperationAction(ISD::VECREDUCE_OR, VT, Expand);
721     setOperationAction(ISD::VECREDUCE_XOR, VT, Expand);
722     setOperationAction(ISD::VECREDUCE_SMAX, VT, Expand);
723     setOperationAction(ISD::VECREDUCE_SMIN, VT, Expand);
724     setOperationAction(ISD::VECREDUCE_UMAX, VT, Expand);
725     setOperationAction(ISD::VECREDUCE_UMIN, VT, Expand);
726     setOperationAction(ISD::VECREDUCE_FMAX, VT, Expand);
727     setOperationAction(ISD::VECREDUCE_FMIN, VT, Expand);
728   }
729 
730   // Most targets ignore the @llvm.prefetch intrinsic.
731   setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
732 
733   // Most targets also ignore the @llvm.readcyclecounter intrinsic.
734   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand);
735 
736   // ConstantFP nodes default to expand.  Targets can either change this to
737   // Legal, in which case all fp constants are legal, or use isFPImmLegal()
738   // to optimize expansions for certain constants.
739   setOperationAction(ISD::ConstantFP, MVT::f16, Expand);
740   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
741   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
742   setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
743   setOperationAction(ISD::ConstantFP, MVT::f128, Expand);
744 
745   // These library functions default to expand.
746   for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
747     setOperationAction(ISD::FCBRT,      VT, Expand);
748     setOperationAction(ISD::FLOG ,      VT, Expand);
749     setOperationAction(ISD::FLOG2,      VT, Expand);
750     setOperationAction(ISD::FLOG10,     VT, Expand);
751     setOperationAction(ISD::FEXP ,      VT, Expand);
752     setOperationAction(ISD::FEXP2,      VT, Expand);
753     setOperationAction(ISD::FFLOOR,     VT, Expand);
754     setOperationAction(ISD::FNEARBYINT, VT, Expand);
755     setOperationAction(ISD::FCEIL,      VT, Expand);
756     setOperationAction(ISD::FRINT,      VT, Expand);
757     setOperationAction(ISD::FTRUNC,     VT, Expand);
758     setOperationAction(ISD::FROUND,     VT, Expand);
759     setOperationAction(ISD::LROUND,     VT, Expand);
760     setOperationAction(ISD::LLROUND,    VT, Expand);
761     setOperationAction(ISD::LRINT,      VT, Expand);
762     setOperationAction(ISD::LLRINT,     VT, Expand);
763   }
764 
765   // Default ISD::TRAP to expand (which turns it into abort).
766   setOperationAction(ISD::TRAP, MVT::Other, Expand);
767 
768   // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
769   // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
770   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand);
771 }
772 
773 MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL,
774                                                EVT) const {
775   return MVT::getIntegerVT(DL.getPointerSizeInBits(0));
776 }
777 
778 EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
779                                          bool LegalTypes) const {
780   assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
781   if (LHSTy.isVector())
782     return LHSTy;
783   return LegalTypes ? getScalarShiftAmountTy(DL, LHSTy)
784                     : getPointerTy(DL);
785 }
786 
787 bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const {
788   assert(isTypeLegal(VT));
789   switch (Op) {
790   default:
791     return false;
792   case ISD::SDIV:
793   case ISD::UDIV:
794   case ISD::SREM:
795   case ISD::UREM:
796     return true;
797   }
798 }
799 
800 void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) {
801   // If the command-line option was specified, ignore this request.
802   if (!JumpIsExpensiveOverride.getNumOccurrences())
803     JumpIsExpensive = isExpensive;
804 }
805 
806 TargetLoweringBase::LegalizeKind
807 TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const {
808   // If this is a simple type, use the ComputeRegisterProp mechanism.
809   if (VT.isSimple()) {
810     MVT SVT = VT.getSimpleVT();
811     assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
812     MVT NVT = TransformToType[SVT.SimpleTy];
813     LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
814 
815     assert((LA == TypeLegal || LA == TypeSoftenFloat ||
816             LA == TypeSoftPromoteHalf ||
817             (NVT.isVector() ||
818              ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)) &&
819            "Promote may not follow Expand or Promote");
820 
821     if (LA == TypeSplitVector)
822       return LegalizeKind(LA,
823                           EVT::getVectorVT(Context, SVT.getVectorElementType(),
824                                            SVT.getVectorNumElements() / 2));
825     if (LA == TypeScalarizeVector)
826       return LegalizeKind(LA, SVT.getVectorElementType());
827     return LegalizeKind(LA, NVT);
828   }
829 
830   // Handle Extended Scalar Types.
831   if (!VT.isVector()) {
832     assert(VT.isInteger() && "Float types must be simple");
833     unsigned BitSize = VT.getSizeInBits();
834     // First promote to a power-of-two size, then expand if necessary.
835     if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
836       EVT NVT = VT.getRoundIntegerType(Context);
837       assert(NVT != VT && "Unable to round integer VT");
838       LegalizeKind NextStep = getTypeConversion(Context, NVT);
839       // Avoid multi-step promotion.
840       if (NextStep.first == TypePromoteInteger)
841         return NextStep;
842       // Return rounded integer type.
843       return LegalizeKind(TypePromoteInteger, NVT);
844     }
845 
846     return LegalizeKind(TypeExpandInteger,
847                         EVT::getIntegerVT(Context, VT.getSizeInBits() / 2));
848   }
849 
850   // Handle vector types.
851   unsigned NumElts = VT.getVectorNumElements();
852   EVT EltVT = VT.getVectorElementType();
853 
854   // Vectors with only one element are always scalarized.
855   if (NumElts == 1)
856     return LegalizeKind(TypeScalarizeVector, EltVT);
857 
858   // Try to widen vector elements until the element type is a power of two and
859   // promote it to a legal type later on, for example:
860   // <3 x i8> -> <4 x i8> -> <4 x i32>
861   if (EltVT.isInteger()) {
862     // Vectors with a number of elements that is not a power of two are always
863     // widened, for example <3 x i8> -> <4 x i8>.
864     if (!VT.isPow2VectorType()) {
865       NumElts = (unsigned)NextPowerOf2(NumElts);
866       EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
867       return LegalizeKind(TypeWidenVector, NVT);
868     }
869 
870     // Examine the element type.
871     LegalizeKind LK = getTypeConversion(Context, EltVT);
872 
873     // If type is to be expanded, split the vector.
874     //  <4 x i140> -> <2 x i140>
875     if (LK.first == TypeExpandInteger)
876       return LegalizeKind(TypeSplitVector,
877                           EVT::getVectorVT(Context, EltVT, NumElts / 2));
878 
879     // Promote the integer element types until a legal vector type is found
880     // or until the element integer type is too big. If a legal type was not
881     // found, fallback to the usual mechanism of widening/splitting the
882     // vector.
883     EVT OldEltVT = EltVT;
884     while (true) {
885       // Increase the bitwidth of the element to the next pow-of-two
886       // (which is greater than 8 bits).
887       EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits())
888                   .getRoundIntegerType(Context);
889 
890       // Stop trying when getting a non-simple element type.
891       // Note that vector elements may be greater than legal vector element
892       // types. Example: X86 XMM registers hold 64bit element on 32bit
893       // systems.
894       if (!EltVT.isSimple())
895         break;
896 
897       // Build a new vector type and check if it is legal.
898       MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
899       // Found a legal promoted vector type.
900       if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
901         return LegalizeKind(TypePromoteInteger,
902                             EVT::getVectorVT(Context, EltVT, NumElts));
903     }
904 
905     // Reset the type to the unexpanded type if we did not find a legal vector
906     // type with a promoted vector element type.
907     EltVT = OldEltVT;
908   }
909 
910   // Try to widen the vector until a legal type is found.
911   // If there is no wider legal type, split the vector.
912   while (true) {
913     // Round up to the next power of 2.
914     NumElts = (unsigned)NextPowerOf2(NumElts);
915 
916     // If there is no simple vector type with this many elements then there
917     // cannot be a larger legal vector type.  Note that this assumes that
918     // there are no skipped intermediate vector types in the simple types.
919     if (!EltVT.isSimple())
920       break;
921     MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
922     if (LargerVector == MVT())
923       break;
924 
925     // If this type is legal then widen the vector.
926     if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
927       return LegalizeKind(TypeWidenVector, LargerVector);
928   }
929 
930   // Widen odd vectors to next power of two.
931   if (!VT.isPow2VectorType()) {
932     EVT NVT = VT.getPow2VectorType(Context);
933     return LegalizeKind(TypeWidenVector, NVT);
934   }
935 
936   // Vectors with illegal element types are expanded.
937   EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
938   return LegalizeKind(TypeSplitVector, NVT);
939 }
940 
941 static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
942                                           unsigned &NumIntermediates,
943                                           MVT &RegisterVT,
944                                           TargetLoweringBase *TLI) {
945   // Figure out the right, legal destination reg to copy into.
946   unsigned NumElts = VT.getVectorNumElements();
947   MVT EltTy = VT.getVectorElementType();
948 
949   unsigned NumVectorRegs = 1;
950 
951   // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally we
952   // could break down into LHS/RHS like LegalizeDAG does.
953   if (!isPowerOf2_32(NumElts)) {
954     NumVectorRegs = NumElts;
955     NumElts = 1;
956   }
957 
958   // Divide the input until we get to a supported size.  This will always
959   // end with a scalar if the target doesn't support vectors.
960   while (NumElts > 1 && !TLI->isTypeLegal(MVT::getVectorVT(EltTy, NumElts))) {
961     NumElts >>= 1;
962     NumVectorRegs <<= 1;
963   }
964 
965   NumIntermediates = NumVectorRegs;
966 
967   MVT NewVT = MVT::getVectorVT(EltTy, NumElts);
968   if (!TLI->isTypeLegal(NewVT))
969     NewVT = EltTy;
970   IntermediateVT = NewVT;
971 
972   unsigned NewVTSize = NewVT.getSizeInBits();
973 
974   // Convert sizes such as i33 to i64.
975   if (!isPowerOf2_32(NewVTSize))
976     NewVTSize = NextPowerOf2(NewVTSize);
977 
978   MVT DestVT = TLI->getRegisterType(NewVT);
979   RegisterVT = DestVT;
980   if (EVT(DestVT).bitsLT(NewVT))    // Value is expanded, e.g. i64 -> i16.
981     return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
982 
983   // Otherwise, promotion or legal types use the same number of registers as
984   // the vector decimated to the appropriate level.
985   return NumVectorRegs;
986 }
987 
988 /// isLegalRC - Return true if the value types that can be represented by the
989 /// specified register class are all legal.
990 bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI,
991                                    const TargetRegisterClass &RC) const {
992   for (auto I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I)
993     if (isTypeLegal(*I))
994       return true;
995   return false;
996 }
997 
998 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
999 /// sequence of memory operands that is recognized by PrologEpilogInserter.
1000 MachineBasicBlock *
1001 TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI,
1002                                    MachineBasicBlock *MBB) const {
1003   MachineInstr *MI = &InitialMI;
1004   MachineFunction &MF = *MI->getMF();
1005   MachineFrameInfo &MFI = MF.getFrameInfo();
1006 
1007   // We're handling multiple types of operands here:
1008   // PATCHPOINT MetaArgs - live-in, read only, direct
1009   // STATEPOINT Deopt Spill - live-through, read only, indirect
1010   // STATEPOINT Deopt Alloca - live-through, read only, direct
1011   // (We're currently conservative and mark the deopt slots read/write in
1012   // practice.)
1013   // STATEPOINT GC Spill - live-through, read/write, indirect
1014   // STATEPOINT GC Alloca - live-through, read/write, direct
1015   // The live-in vs live-through is handled already (the live through ones are
1016   // all stack slots), but we need to handle the different type of stackmap
1017   // operands and memory effects here.
1018 
1019   // MI changes inside this loop as we grow operands.
1020   for(unsigned OperIdx = 0; OperIdx != MI->getNumOperands(); ++OperIdx) {
1021     MachineOperand &MO = MI->getOperand(OperIdx);
1022     if (!MO.isFI())
1023       continue;
1024 
1025     // foldMemoryOperand builds a new MI after replacing a single FI operand
1026     // with the canonical set of five x86 addressing-mode operands.
1027     int FI = MO.getIndex();
1028     MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc());
1029 
1030     // Copy operands before the frame-index.
1031     for (unsigned i = 0; i < OperIdx; ++i)
1032       MIB.add(MI->getOperand(i));
1033     // Add frame index operands recognized by stackmaps.cpp
1034     if (MFI.isStatepointSpillSlotObjectIndex(FI)) {
1035       // indirect-mem-ref tag, size, #FI, offset.
1036       // Used for spills inserted by StatepointLowering.  This codepath is not
1037       // used for patchpoints/stackmaps at all, for these spilling is done via
1038       // foldMemoryOperand callback only.
1039       assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity");
1040       MIB.addImm(StackMaps::IndirectMemRefOp);
1041       MIB.addImm(MFI.getObjectSize(FI));
1042       MIB.add(MI->getOperand(OperIdx));
1043       MIB.addImm(0);
1044     } else {
1045       // direct-mem-ref tag, #FI, offset.
1046       // Used by patchpoint, and direct alloca arguments to statepoints
1047       MIB.addImm(StackMaps::DirectMemRefOp);
1048       MIB.add(MI->getOperand(OperIdx));
1049       MIB.addImm(0);
1050     }
1051     // Copy the operands after the frame index.
1052     for (unsigned i = OperIdx + 1; i != MI->getNumOperands(); ++i)
1053       MIB.add(MI->getOperand(i));
1054 
1055     // Inherit previous memory operands.
1056     MIB.cloneMemRefs(*MI);
1057     assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!");
1058 
1059     // Add a new memory operand for this FI.
1060     assert(MFI.getObjectOffset(FI) != -1);
1061 
1062     // Note: STATEPOINT MMOs are added during SelectionDAG.  STACKMAP, and
1063     // PATCHPOINT should be updated to do the same. (TODO)
1064     if (MI->getOpcode() != TargetOpcode::STATEPOINT) {
1065       auto Flags = MachineMemOperand::MOLoad;
1066       MachineMemOperand *MMO = MF.getMachineMemOperand(
1067           MachinePointerInfo::getFixedStack(MF, FI), Flags,
1068           MF.getDataLayout().getPointerSize(), MFI.getObjectAlignment(FI));
1069       MIB->addMemOperand(MF, MMO);
1070     }
1071 
1072     // Replace the instruction and update the operand index.
1073     MBB->insert(MachineBasicBlock::iterator(MI), MIB);
1074     OperIdx += (MIB->getNumOperands() - MI->getNumOperands()) - 1;
1075     MI->eraseFromParent();
1076     MI = MIB;
1077   }
1078   return MBB;
1079 }
1080 
1081 MachineBasicBlock *
1082 TargetLoweringBase::emitXRayCustomEvent(MachineInstr &MI,
1083                                         MachineBasicBlock *MBB) const {
1084   assert(MI.getOpcode() == TargetOpcode::PATCHABLE_EVENT_CALL &&
1085          "Called emitXRayCustomEvent on the wrong MI!");
1086   auto &MF = *MI.getMF();
1087   auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
1088   for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
1089     MIB.add(MI.getOperand(OpIdx));
1090 
1091   MBB->insert(MachineBasicBlock::iterator(MI), MIB);
1092   MI.eraseFromParent();
1093   return MBB;
1094 }
1095 
1096 MachineBasicBlock *
1097 TargetLoweringBase::emitXRayTypedEvent(MachineInstr &MI,
1098                                        MachineBasicBlock *MBB) const {
1099   assert(MI.getOpcode() == TargetOpcode::PATCHABLE_TYPED_EVENT_CALL &&
1100          "Called emitXRayTypedEvent on the wrong MI!");
1101   auto &MF = *MI.getMF();
1102   auto MIB = BuildMI(MF, MI.getDebugLoc(), MI.getDesc());
1103   for (unsigned OpIdx = 0; OpIdx != MI.getNumOperands(); ++OpIdx)
1104     MIB.add(MI.getOperand(OpIdx));
1105 
1106   MBB->insert(MachineBasicBlock::iterator(MI), MIB);
1107   MI.eraseFromParent();
1108   return MBB;
1109 }
1110 
1111 /// findRepresentativeClass - Return the largest legal super-reg register class
1112 /// of the register class for the specified type and its associated "cost".
1113 // This function is in TargetLowering because it uses RegClassForVT which would
1114 // need to be moved to TargetRegisterInfo and would necessitate moving
1115 // isTypeLegal over as well - a massive change that would just require
1116 // TargetLowering having a TargetRegisterInfo class member that it would use.
1117 std::pair<const TargetRegisterClass *, uint8_t>
1118 TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI,
1119                                             MVT VT) const {
1120   const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
1121   if (!RC)
1122     return std::make_pair(RC, 0);
1123 
1124   // Compute the set of all super-register classes.
1125   BitVector SuperRegRC(TRI->getNumRegClasses());
1126   for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
1127     SuperRegRC.setBitsInMask(RCI.getMask());
1128 
1129   // Find the first legal register class with the largest spill size.
1130   const TargetRegisterClass *BestRC = RC;
1131   for (unsigned i : SuperRegRC.set_bits()) {
1132     const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
1133     // We want the largest possible spill size.
1134     if (TRI->getSpillSize(*SuperRC) <= TRI->getSpillSize(*BestRC))
1135       continue;
1136     if (!isLegalRC(*TRI, *SuperRC))
1137       continue;
1138     BestRC = SuperRC;
1139   }
1140   return std::make_pair(BestRC, 1);
1141 }
1142 
1143 /// computeRegisterProperties - Once all of the register classes are added,
1144 /// this allows us to compute derived properties we expose.
1145 void TargetLoweringBase::computeRegisterProperties(
1146     const TargetRegisterInfo *TRI) {
1147   static_assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE,
1148                 "Too many value types for ValueTypeActions to hold!");
1149 
1150   // Everything defaults to needing one register.
1151   for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
1152     NumRegistersForVT[i] = 1;
1153     RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
1154   }
1155   // ...except isVoid, which doesn't need any registers.
1156   NumRegistersForVT[MVT::isVoid] = 0;
1157 
1158   // Find the largest integer register class.
1159   unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
1160   for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg)
1161     assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
1162 
1163   // Every integer value type larger than this largest register takes twice as
1164   // many registers to represent as the previous ValueType.
1165   for (unsigned ExpandedReg = LargestIntReg + 1;
1166        ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
1167     NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
1168     RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
1169     TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
1170     ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg,
1171                                    TypeExpandInteger);
1172   }
1173 
1174   // Inspect all of the ValueType's smaller than the largest integer
1175   // register to see which ones need promotion.
1176   unsigned LegalIntReg = LargestIntReg;
1177   for (unsigned IntReg = LargestIntReg - 1;
1178        IntReg >= (unsigned)MVT::i1; --IntReg) {
1179     MVT IVT = (MVT::SimpleValueType)IntReg;
1180     if (isTypeLegal(IVT)) {
1181       LegalIntReg = IntReg;
1182     } else {
1183       RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
1184         (MVT::SimpleValueType)LegalIntReg;
1185       ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
1186     }
1187   }
1188 
1189   // ppcf128 type is really two f64's.
1190   if (!isTypeLegal(MVT::ppcf128)) {
1191     if (isTypeLegal(MVT::f64)) {
1192       NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
1193       RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
1194       TransformToType[MVT::ppcf128] = MVT::f64;
1195       ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
1196     } else {
1197       NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128];
1198       RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128];
1199       TransformToType[MVT::ppcf128] = MVT::i128;
1200       ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat);
1201     }
1202   }
1203 
1204   // Decide how to handle f128. If the target does not have native f128 support,
1205   // expand it to i128 and we will be generating soft float library calls.
1206   if (!isTypeLegal(MVT::f128)) {
1207     NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128];
1208     RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128];
1209     TransformToType[MVT::f128] = MVT::i128;
1210     ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
1211   }
1212 
1213   // Decide how to handle f64. If the target does not have native f64 support,
1214   // expand it to i64 and we will be generating soft float library calls.
1215   if (!isTypeLegal(MVT::f64)) {
1216     NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
1217     RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
1218     TransformToType[MVT::f64] = MVT::i64;
1219     ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
1220   }
1221 
1222   // Decide how to handle f32. If the target does not have native f32 support,
1223   // expand it to i32 and we will be generating soft float library calls.
1224   if (!isTypeLegal(MVT::f32)) {
1225     NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
1226     RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
1227     TransformToType[MVT::f32] = MVT::i32;
1228     ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
1229   }
1230 
1231   // Decide how to handle f16. If the target does not have native f16 support,
1232   // promote it to f32, because there are no f16 library calls (except for
1233   // conversions).
1234   if (!isTypeLegal(MVT::f16)) {
1235     // Allow targets to control how we legalize half.
1236     if (softPromoteHalfType()) {
1237       NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::i16];
1238       RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::i16];
1239       TransformToType[MVT::f16] = MVT::f32;
1240       ValueTypeActions.setTypeAction(MVT::f16, TypeSoftPromoteHalf);
1241     } else {
1242       NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32];
1243       RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32];
1244       TransformToType[MVT::f16] = MVT::f32;
1245       ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat);
1246     }
1247   }
1248 
1249   // Loop over all of the vector value types to see which need transformations.
1250   for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
1251        i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1252     MVT VT = (MVT::SimpleValueType) i;
1253     if (isTypeLegal(VT))
1254       continue;
1255 
1256     MVT EltVT = VT.getVectorElementType();
1257     unsigned NElts = VT.getVectorNumElements();
1258     bool IsLegalWiderType = false;
1259     bool IsScalable = VT.isScalableVector();
1260     LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT);
1261     switch (PreferredAction) {
1262     case TypePromoteInteger: {
1263       MVT::SimpleValueType EndVT = IsScalable ?
1264                                    MVT::LAST_INTEGER_SCALABLE_VECTOR_VALUETYPE :
1265                                    MVT::LAST_INTEGER_FIXEDLEN_VECTOR_VALUETYPE;
1266       // Try to promote the elements of integer vectors. If no legal
1267       // promotion was found, fall through to the widen-vector method.
1268       for (unsigned nVT = i + 1;
1269            (MVT::SimpleValueType)nVT <= EndVT; ++nVT) {
1270         MVT SVT = (MVT::SimpleValueType) nVT;
1271         // Promote vectors of integers to vectors with the same number
1272         // of elements, with a wider element type.
1273         if (SVT.getScalarSizeInBits() > EltVT.getSizeInBits() &&
1274             SVT.getVectorNumElements() == NElts &&
1275             SVT.isScalableVector() == IsScalable && isTypeLegal(SVT)) {
1276           TransformToType[i] = SVT;
1277           RegisterTypeForVT[i] = SVT;
1278           NumRegistersForVT[i] = 1;
1279           ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
1280           IsLegalWiderType = true;
1281           break;
1282         }
1283       }
1284       if (IsLegalWiderType)
1285         break;
1286       LLVM_FALLTHROUGH;
1287     }
1288 
1289     case TypeWidenVector:
1290       if (isPowerOf2_32(NElts)) {
1291         // Try to widen the vector.
1292         for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
1293           MVT SVT = (MVT::SimpleValueType) nVT;
1294           if (SVT.getVectorElementType() == EltVT
1295               && SVT.getVectorNumElements() > NElts
1296               && SVT.isScalableVector() == IsScalable && isTypeLegal(SVT)) {
1297             TransformToType[i] = SVT;
1298             RegisterTypeForVT[i] = SVT;
1299             NumRegistersForVT[i] = 1;
1300             ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1301             IsLegalWiderType = true;
1302             break;
1303           }
1304         }
1305         if (IsLegalWiderType)
1306           break;
1307       } else {
1308         // Only widen to the next power of 2 to keep consistency with EVT.
1309         MVT NVT = VT.getPow2VectorType();
1310         if (isTypeLegal(NVT)) {
1311           TransformToType[i] = NVT;
1312           ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1313           RegisterTypeForVT[i] = NVT;
1314           NumRegistersForVT[i] = 1;
1315           break;
1316         }
1317       }
1318       LLVM_FALLTHROUGH;
1319 
1320     case TypeSplitVector:
1321     case TypeScalarizeVector: {
1322       MVT IntermediateVT;
1323       MVT RegisterVT;
1324       unsigned NumIntermediates;
1325       unsigned NumRegisters = getVectorTypeBreakdownMVT(VT, IntermediateVT,
1326           NumIntermediates, RegisterVT, this);
1327       NumRegistersForVT[i] = NumRegisters;
1328       assert(NumRegistersForVT[i] == NumRegisters &&
1329              "NumRegistersForVT size cannot represent NumRegisters!");
1330       RegisterTypeForVT[i] = RegisterVT;
1331 
1332       MVT NVT = VT.getPow2VectorType();
1333       if (NVT == VT) {
1334         // Type is already a power of 2.  The default action is to split.
1335         TransformToType[i] = MVT::Other;
1336         if (PreferredAction == TypeScalarizeVector)
1337           ValueTypeActions.setTypeAction(VT, TypeScalarizeVector);
1338         else if (PreferredAction == TypeSplitVector)
1339           ValueTypeActions.setTypeAction(VT, TypeSplitVector);
1340         else
1341           // Set type action according to the number of elements.
1342           ValueTypeActions.setTypeAction(VT, NElts == 1 ? TypeScalarizeVector
1343                                                         : TypeSplitVector);
1344       } else {
1345         TransformToType[i] = NVT;
1346         ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1347       }
1348       break;
1349     }
1350     default:
1351       llvm_unreachable("Unknown vector legalization action!");
1352     }
1353   }
1354 
1355   // Determine the 'representative' register class for each value type.
1356   // An representative register class is the largest (meaning one which is
1357   // not a sub-register class / subreg register class) legal register class for
1358   // a group of value types. For example, on i386, i8, i16, and i32
1359   // representative would be GR32; while on x86_64 it's GR64.
1360   for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
1361     const TargetRegisterClass* RRC;
1362     uint8_t Cost;
1363     std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i);
1364     RepRegClassForVT[i] = RRC;
1365     RepRegClassCostForVT[i] = Cost;
1366   }
1367 }
1368 
1369 EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1370                                            EVT VT) const {
1371   assert(!VT.isVector() && "No default SetCC type for vectors!");
1372   return getPointerTy(DL).SimpleTy;
1373 }
1374 
1375 MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const {
1376   return MVT::i32; // return the default value
1377 }
1378 
1379 /// getVectorTypeBreakdown - Vector types are broken down into some number of
1380 /// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
1381 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
1382 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
1383 ///
1384 /// This method returns the number of registers needed, and the VT for each
1385 /// register.  It also returns the VT and quantity of the intermediate values
1386 /// before they are promoted/expanded.
1387 unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
1388                                                 EVT &IntermediateVT,
1389                                                 unsigned &NumIntermediates,
1390                                                 MVT &RegisterVT) const {
1391   unsigned NumElts = VT.getVectorNumElements();
1392 
1393   // If there is a wider vector type with the same element type as this one,
1394   // or a promoted vector type that has the same number of elements which
1395   // are wider, then we should convert to that legal vector type.
1396   // This handles things like <2 x float> -> <4 x float> and
1397   // <4 x i1> -> <4 x i32>.
1398   LegalizeTypeAction TA = getTypeAction(Context, VT);
1399   if (NumElts != 1 && (TA == TypeWidenVector || TA == TypePromoteInteger)) {
1400     EVT RegisterEVT = getTypeToTransformTo(Context, VT);
1401     if (isTypeLegal(RegisterEVT)) {
1402       IntermediateVT = RegisterEVT;
1403       RegisterVT = RegisterEVT.getSimpleVT();
1404       NumIntermediates = 1;
1405       return 1;
1406     }
1407   }
1408 
1409   // Figure out the right, legal destination reg to copy into.
1410   EVT EltTy = VT.getVectorElementType();
1411 
1412   unsigned NumVectorRegs = 1;
1413 
1414   // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally we
1415   // could break down into LHS/RHS like LegalizeDAG does.
1416   if (!isPowerOf2_32(NumElts)) {
1417     NumVectorRegs = NumElts;
1418     NumElts = 1;
1419   }
1420 
1421   // Divide the input until we get to a supported size.  This will always
1422   // end with a scalar if the target doesn't support vectors.
1423   while (NumElts > 1 && !isTypeLegal(
1424                                    EVT::getVectorVT(Context, EltTy, NumElts))) {
1425     NumElts >>= 1;
1426     NumVectorRegs <<= 1;
1427   }
1428 
1429   NumIntermediates = NumVectorRegs;
1430 
1431   EVT NewVT = EVT::getVectorVT(Context, EltTy, NumElts);
1432   if (!isTypeLegal(NewVT))
1433     NewVT = EltTy;
1434   IntermediateVT = NewVT;
1435 
1436   MVT DestVT = getRegisterType(Context, NewVT);
1437   RegisterVT = DestVT;
1438   unsigned NewVTSize = NewVT.getSizeInBits();
1439 
1440   // Convert sizes such as i33 to i64.
1441   if (!isPowerOf2_32(NewVTSize))
1442     NewVTSize = NextPowerOf2(NewVTSize);
1443 
1444   if (EVT(DestVT).bitsLT(NewVT))   // Value is expanded, e.g. i64 -> i16.
1445     return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
1446 
1447   // Otherwise, promotion or legal types use the same number of registers as
1448   // the vector decimated to the appropriate level.
1449   return NumVectorRegs;
1450 }
1451 
1452 bool TargetLoweringBase::isSuitableForJumpTable(const SwitchInst *SI,
1453                                                 uint64_t NumCases,
1454                                                 uint64_t Range,
1455                                                 ProfileSummaryInfo *PSI,
1456                                                 BlockFrequencyInfo *BFI) const {
1457   // FIXME: This function check the maximum table size and density, but the
1458   // minimum size is not checked. It would be nice if the minimum size is
1459   // also combined within this function. Currently, the minimum size check is
1460   // performed in findJumpTable() in SelectionDAGBuiler and
1461   // getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
1462   const bool OptForSize =
1463       SI->getParent()->getParent()->hasOptSize() ||
1464       llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI);
1465   const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize);
1466   const unsigned MaxJumpTableSize = getMaximumJumpTableSize();
1467 
1468   // Check whether the number of cases is small enough and
1469   // the range is dense enough for a jump table.
1470   return (OptForSize || Range <= MaxJumpTableSize) &&
1471          (NumCases * 100 >= Range * MinDensity);
1472 }
1473 
1474 /// Get the EVTs and ArgFlags collections that represent the legalized return
1475 /// type of the given function.  This does not require a DAG or a return value,
1476 /// and is suitable for use before any DAGs for the function are constructed.
1477 /// TODO: Move this out of TargetLowering.cpp.
1478 void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType,
1479                          AttributeList attr,
1480                          SmallVectorImpl<ISD::OutputArg> &Outs,
1481                          const TargetLowering &TLI, const DataLayout &DL) {
1482   SmallVector<EVT, 4> ValueVTs;
1483   ComputeValueVTs(TLI, DL, ReturnType, ValueVTs);
1484   unsigned NumValues = ValueVTs.size();
1485   if (NumValues == 0) return;
1486 
1487   for (unsigned j = 0, f = NumValues; j != f; ++j) {
1488     EVT VT = ValueVTs[j];
1489     ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1490 
1491     if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
1492       ExtendKind = ISD::SIGN_EXTEND;
1493     else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
1494       ExtendKind = ISD::ZERO_EXTEND;
1495 
1496     // FIXME: C calling convention requires the return type to be promoted to
1497     // at least 32-bit. But this is not necessary for non-C calling
1498     // conventions. The frontend should mark functions whose return values
1499     // require promoting with signext or zeroext attributes.
1500     if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1501       MVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
1502       if (VT.bitsLT(MinVT))
1503         VT = MinVT;
1504     }
1505 
1506     unsigned NumParts =
1507         TLI.getNumRegistersForCallingConv(ReturnType->getContext(), CC, VT);
1508     MVT PartVT =
1509         TLI.getRegisterTypeForCallingConv(ReturnType->getContext(), CC, VT);
1510 
1511     // 'inreg' on function refers to return value
1512     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1513     if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::InReg))
1514       Flags.setInReg();
1515 
1516     // Propagate extension type if any
1517     if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
1518       Flags.setSExt();
1519     else if (attr.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt))
1520       Flags.setZExt();
1521 
1522     for (unsigned i = 0; i < NumParts; ++i)
1523       Outs.push_back(ISD::OutputArg(Flags, PartVT, VT, /*isfixed=*/true, 0, 0));
1524   }
1525 }
1526 
1527 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1528 /// function arguments in the caller parameter area.  This is the actual
1529 /// alignment, not its logarithm.
1530 unsigned TargetLoweringBase::getByValTypeAlignment(Type *Ty,
1531                                                    const DataLayout &DL) const {
1532   return DL.getABITypeAlignment(Ty);
1533 }
1534 
1535 bool TargetLoweringBase::allowsMemoryAccessForAlignment(
1536     LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace,
1537     unsigned Alignment, MachineMemOperand::Flags Flags, bool *Fast) const {
1538   // Check if the specified alignment is sufficient based on the data layout.
1539   // TODO: While using the data layout works in practice, a better solution
1540   // would be to implement this check directly (make this a virtual function).
1541   // For example, the ABI alignment may change based on software platform while
1542   // this function should only be affected by hardware implementation.
1543   Type *Ty = VT.getTypeForEVT(Context);
1544   if (Alignment >= DL.getABITypeAlignment(Ty)) {
1545     // Assume that an access that meets the ABI-specified alignment is fast.
1546     if (Fast != nullptr)
1547       *Fast = true;
1548     return true;
1549   }
1550 
1551   // This is a misaligned access.
1552   return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Flags, Fast);
1553 }
1554 
1555 bool TargetLoweringBase::allowsMemoryAccessForAlignment(
1556     LLVMContext &Context, const DataLayout &DL, EVT VT,
1557     const MachineMemOperand &MMO, bool *Fast) const {
1558   return allowsMemoryAccessForAlignment(Context, DL, VT, MMO.getAddrSpace(),
1559                                         MMO.getAlignment(), MMO.getFlags(),
1560                                         Fast);
1561 }
1562 
1563 bool TargetLoweringBase::allowsMemoryAccess(
1564     LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace,
1565     unsigned Alignment, MachineMemOperand::Flags Flags, bool *Fast) const {
1566   return allowsMemoryAccessForAlignment(Context, DL, VT, AddrSpace, Alignment,
1567                                         Flags, Fast);
1568 }
1569 
1570 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
1571                                             const DataLayout &DL, EVT VT,
1572                                             const MachineMemOperand &MMO,
1573                                             bool *Fast) const {
1574   return allowsMemoryAccess(Context, DL, VT, MMO.getAddrSpace(),
1575                             MMO.getAlignment(), MMO.getFlags(), Fast);
1576 }
1577 
1578 BranchProbability TargetLoweringBase::getPredictableBranchThreshold() const {
1579   return BranchProbability(MinPercentageForPredictableBranch, 100);
1580 }
1581 
1582 //===----------------------------------------------------------------------===//
1583 //  TargetTransformInfo Helpers
1584 //===----------------------------------------------------------------------===//
1585 
1586 int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const {
1587   enum InstructionOpcodes {
1588 #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM,
1589 #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM
1590 #include "llvm/IR/Instruction.def"
1591   };
1592   switch (static_cast<InstructionOpcodes>(Opcode)) {
1593   case Ret:            return 0;
1594   case Br:             return 0;
1595   case Switch:         return 0;
1596   case IndirectBr:     return 0;
1597   case Invoke:         return 0;
1598   case CallBr:         return 0;
1599   case Resume:         return 0;
1600   case Unreachable:    return 0;
1601   case CleanupRet:     return 0;
1602   case CatchRet:       return 0;
1603   case CatchPad:       return 0;
1604   case CatchSwitch:    return 0;
1605   case CleanupPad:     return 0;
1606   case FNeg:           return ISD::FNEG;
1607   case Add:            return ISD::ADD;
1608   case FAdd:           return ISD::FADD;
1609   case Sub:            return ISD::SUB;
1610   case FSub:           return ISD::FSUB;
1611   case Mul:            return ISD::MUL;
1612   case FMul:           return ISD::FMUL;
1613   case UDiv:           return ISD::UDIV;
1614   case SDiv:           return ISD::SDIV;
1615   case FDiv:           return ISD::FDIV;
1616   case URem:           return ISD::UREM;
1617   case SRem:           return ISD::SREM;
1618   case FRem:           return ISD::FREM;
1619   case Shl:            return ISD::SHL;
1620   case LShr:           return ISD::SRL;
1621   case AShr:           return ISD::SRA;
1622   case And:            return ISD::AND;
1623   case Or:             return ISD::OR;
1624   case Xor:            return ISD::XOR;
1625   case Alloca:         return 0;
1626   case Load:           return ISD::LOAD;
1627   case Store:          return ISD::STORE;
1628   case GetElementPtr:  return 0;
1629   case Fence:          return 0;
1630   case AtomicCmpXchg:  return 0;
1631   case AtomicRMW:      return 0;
1632   case Trunc:          return ISD::TRUNCATE;
1633   case ZExt:           return ISD::ZERO_EXTEND;
1634   case SExt:           return ISD::SIGN_EXTEND;
1635   case FPToUI:         return ISD::FP_TO_UINT;
1636   case FPToSI:         return ISD::FP_TO_SINT;
1637   case UIToFP:         return ISD::UINT_TO_FP;
1638   case SIToFP:         return ISD::SINT_TO_FP;
1639   case FPTrunc:        return ISD::FP_ROUND;
1640   case FPExt:          return ISD::FP_EXTEND;
1641   case PtrToInt:       return ISD::BITCAST;
1642   case IntToPtr:       return ISD::BITCAST;
1643   case BitCast:        return ISD::BITCAST;
1644   case AddrSpaceCast:  return ISD::ADDRSPACECAST;
1645   case ICmp:           return ISD::SETCC;
1646   case FCmp:           return ISD::SETCC;
1647   case PHI:            return 0;
1648   case Call:           return 0;
1649   case Select:         return ISD::SELECT;
1650   case UserOp1:        return 0;
1651   case UserOp2:        return 0;
1652   case VAArg:          return 0;
1653   case ExtractElement: return ISD::EXTRACT_VECTOR_ELT;
1654   case InsertElement:  return ISD::INSERT_VECTOR_ELT;
1655   case ShuffleVector:  return ISD::VECTOR_SHUFFLE;
1656   case ExtractValue:   return ISD::MERGE_VALUES;
1657   case InsertValue:    return ISD::MERGE_VALUES;
1658   case LandingPad:     return 0;
1659   case Freeze:         return 0;
1660   }
1661 
1662   llvm_unreachable("Unknown instruction type encountered!");
1663 }
1664 
1665 std::pair<int, MVT>
1666 TargetLoweringBase::getTypeLegalizationCost(const DataLayout &DL,
1667                                             Type *Ty) const {
1668   LLVMContext &C = Ty->getContext();
1669   EVT MTy = getValueType(DL, Ty);
1670 
1671   int Cost = 1;
1672   // We keep legalizing the type until we find a legal kind. We assume that
1673   // the only operation that costs anything is the split. After splitting
1674   // we need to handle two types.
1675   while (true) {
1676     LegalizeKind LK = getTypeConversion(C, MTy);
1677 
1678     if (LK.first == TypeLegal)
1679       return std::make_pair(Cost, MTy.getSimpleVT());
1680 
1681     if (LK.first == TypeSplitVector || LK.first == TypeExpandInteger)
1682       Cost *= 2;
1683 
1684     // Do not loop with f128 type.
1685     if (MTy == LK.second)
1686       return std::make_pair(Cost, MTy.getSimpleVT());
1687 
1688     // Keep legalizing the type.
1689     MTy = LK.second;
1690   }
1691 }
1692 
1693 Value *TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1694                                                               bool UseTLS) const {
1695   // compiler-rt provides a variable with a magic name.  Targets that do not
1696   // link with compiler-rt may also provide such a variable.
1697   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1698   const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
1699   auto UnsafeStackPtr =
1700       dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar));
1701 
1702   Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
1703 
1704   if (!UnsafeStackPtr) {
1705     auto TLSModel = UseTLS ?
1706         GlobalValue::InitialExecTLSModel :
1707         GlobalValue::NotThreadLocal;
1708     // The global variable is not defined yet, define it ourselves.
1709     // We use the initial-exec TLS model because we do not support the
1710     // variable living anywhere other than in the main executable.
1711     UnsafeStackPtr = new GlobalVariable(
1712         *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
1713         UnsafeStackPtrVar, nullptr, TLSModel);
1714   } else {
1715     // The variable exists, check its type and attributes.
1716     if (UnsafeStackPtr->getValueType() != StackPtrTy)
1717       report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
1718     if (UseTLS != UnsafeStackPtr->isThreadLocal())
1719       report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
1720                          (UseTLS ? "" : "not ") + "be thread-local");
1721   }
1722   return UnsafeStackPtr;
1723 }
1724 
1725 Value *TargetLoweringBase::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
1726   if (!TM.getTargetTriple().isAndroid())
1727     return getDefaultSafeStackPointerLocation(IRB, true);
1728 
1729   // Android provides a libc function to retrieve the address of the current
1730   // thread's unsafe stack pointer.
1731   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1732   Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
1733   FunctionCallee Fn = M->getOrInsertFunction("__safestack_pointer_address",
1734                                              StackPtrTy->getPointerTo(0));
1735   return IRB.CreateCall(Fn);
1736 }
1737 
1738 //===----------------------------------------------------------------------===//
1739 //  Loop Strength Reduction hooks
1740 //===----------------------------------------------------------------------===//
1741 
1742 /// isLegalAddressingMode - Return true if the addressing mode represented
1743 /// by AM is legal for this target, for a load/store of the specified type.
1744 bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL,
1745                                                const AddrMode &AM, Type *Ty,
1746                                                unsigned AS, Instruction *I) const {
1747   // The default implementation of this implements a conservative RISCy, r+r and
1748   // r+i addr mode.
1749 
1750   // Allows a sign-extended 16-bit immediate field.
1751   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
1752     return false;
1753 
1754   // No global is ever allowed as a base.
1755   if (AM.BaseGV)
1756     return false;
1757 
1758   // Only support r+r,
1759   switch (AM.Scale) {
1760   case 0:  // "r+i" or just "i", depending on HasBaseReg.
1761     break;
1762   case 1:
1763     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
1764       return false;
1765     // Otherwise we have r+r or r+i.
1766     break;
1767   case 2:
1768     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
1769       return false;
1770     // Allow 2*r as r+r.
1771     break;
1772   default: // Don't allow n * r
1773     return false;
1774   }
1775 
1776   return true;
1777 }
1778 
1779 //===----------------------------------------------------------------------===//
1780 //  Stack Protector
1781 //===----------------------------------------------------------------------===//
1782 
1783 // For OpenBSD return its special guard variable. Otherwise return nullptr,
1784 // so that SelectionDAG handle SSP.
1785 Value *TargetLoweringBase::getIRStackGuard(IRBuilder<> &IRB) const {
1786   if (getTargetMachine().getTargetTriple().isOSOpenBSD()) {
1787     Module &M = *IRB.GetInsertBlock()->getParent()->getParent();
1788     PointerType *PtrTy = Type::getInt8PtrTy(M.getContext());
1789     return M.getOrInsertGlobal("__guard_local", PtrTy);
1790   }
1791   return nullptr;
1792 }
1793 
1794 // Currently only support "standard" __stack_chk_guard.
1795 // TODO: add LOAD_STACK_GUARD support.
1796 void TargetLoweringBase::insertSSPDeclarations(Module &M) const {
1797   if (!M.getNamedValue("__stack_chk_guard"))
1798     new GlobalVariable(M, Type::getInt8PtrTy(M.getContext()), false,
1799                        GlobalVariable::ExternalLinkage,
1800                        nullptr, "__stack_chk_guard");
1801 }
1802 
1803 // Currently only support "standard" __stack_chk_guard.
1804 // TODO: add LOAD_STACK_GUARD support.
1805 Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const {
1806   return M.getNamedValue("__stack_chk_guard");
1807 }
1808 
1809 Function *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const {
1810   return nullptr;
1811 }
1812 
1813 unsigned TargetLoweringBase::getMinimumJumpTableEntries() const {
1814   return MinimumJumpTableEntries;
1815 }
1816 
1817 void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) {
1818   MinimumJumpTableEntries = Val;
1819 }
1820 
1821 unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const {
1822   return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity;
1823 }
1824 
1825 unsigned TargetLoweringBase::getMaximumJumpTableSize() const {
1826   return MaximumJumpTableSize;
1827 }
1828 
1829 void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) {
1830   MaximumJumpTableSize = Val;
1831 }
1832 
1833 //===----------------------------------------------------------------------===//
1834 //  Reciprocal Estimates
1835 //===----------------------------------------------------------------------===//
1836 
1837 /// Get the reciprocal estimate attribute string for a function that will
1838 /// override the target defaults.
1839 static StringRef getRecipEstimateForFunc(MachineFunction &MF) {
1840   const Function &F = MF.getFunction();
1841   return F.getFnAttribute("reciprocal-estimates").getValueAsString();
1842 }
1843 
1844 /// Construct a string for the given reciprocal operation of the given type.
1845 /// This string should match the corresponding option to the front-end's
1846 /// "-mrecip" flag assuming those strings have been passed through in an
1847 /// attribute string. For example, "vec-divf" for a division of a vXf32.
1848 static std::string getReciprocalOpName(bool IsSqrt, EVT VT) {
1849   std::string Name = VT.isVector() ? "vec-" : "";
1850 
1851   Name += IsSqrt ? "sqrt" : "div";
1852 
1853   // TODO: Handle "half" or other float types?
1854   if (VT.getScalarType() == MVT::f64) {
1855     Name += "d";
1856   } else {
1857     assert(VT.getScalarType() == MVT::f32 &&
1858            "Unexpected FP type for reciprocal estimate");
1859     Name += "f";
1860   }
1861 
1862   return Name;
1863 }
1864 
1865 /// Return the character position and value (a single numeric character) of a
1866 /// customized refinement operation in the input string if it exists. Return
1867 /// false if there is no customized refinement step count.
1868 static bool parseRefinementStep(StringRef In, size_t &Position,
1869                                 uint8_t &Value) {
1870   const char RefStepToken = ':';
1871   Position = In.find(RefStepToken);
1872   if (Position == StringRef::npos)
1873     return false;
1874 
1875   StringRef RefStepString = In.substr(Position + 1);
1876   // Allow exactly one numeric character for the additional refinement
1877   // step parameter.
1878   if (RefStepString.size() == 1) {
1879     char RefStepChar = RefStepString[0];
1880     if (RefStepChar >= '0' && RefStepChar <= '9') {
1881       Value = RefStepChar - '0';
1882       return true;
1883     }
1884   }
1885   report_fatal_error("Invalid refinement step for -recip.");
1886 }
1887 
1888 /// For the input attribute string, return one of the ReciprocalEstimate enum
1889 /// status values (enabled, disabled, or not specified) for this operation on
1890 /// the specified data type.
1891 static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) {
1892   if (Override.empty())
1893     return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1894 
1895   SmallVector<StringRef, 4> OverrideVector;
1896   Override.split(OverrideVector, ',');
1897   unsigned NumArgs = OverrideVector.size();
1898 
1899   // Check if "all", "none", or "default" was specified.
1900   if (NumArgs == 1) {
1901     // Look for an optional setting of the number of refinement steps needed
1902     // for this type of reciprocal operation.
1903     size_t RefPos;
1904     uint8_t RefSteps;
1905     if (parseRefinementStep(Override, RefPos, RefSteps)) {
1906       // Split the string for further processing.
1907       Override = Override.substr(0, RefPos);
1908     }
1909 
1910     // All reciprocal types are enabled.
1911     if (Override == "all")
1912       return TargetLoweringBase::ReciprocalEstimate::Enabled;
1913 
1914     // All reciprocal types are disabled.
1915     if (Override == "none")
1916       return TargetLoweringBase::ReciprocalEstimate::Disabled;
1917 
1918     // Target defaults for enablement are used.
1919     if (Override == "default")
1920       return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1921   }
1922 
1923   // The attribute string may omit the size suffix ('f'/'d').
1924   std::string VTName = getReciprocalOpName(IsSqrt, VT);
1925   std::string VTNameNoSize = VTName;
1926   VTNameNoSize.pop_back();
1927   static const char DisabledPrefix = '!';
1928 
1929   for (StringRef RecipType : OverrideVector) {
1930     size_t RefPos;
1931     uint8_t RefSteps;
1932     if (parseRefinementStep(RecipType, RefPos, RefSteps))
1933       RecipType = RecipType.substr(0, RefPos);
1934 
1935     // Ignore the disablement token for string matching.
1936     bool IsDisabled = RecipType[0] == DisabledPrefix;
1937     if (IsDisabled)
1938       RecipType = RecipType.substr(1);
1939 
1940     if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
1941       return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled
1942                         : TargetLoweringBase::ReciprocalEstimate::Enabled;
1943   }
1944 
1945   return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1946 }
1947 
1948 /// For the input attribute string, return the customized refinement step count
1949 /// for this operation on the specified data type. If the step count does not
1950 /// exist, return the ReciprocalEstimate enum value for unspecified.
1951 static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) {
1952   if (Override.empty())
1953     return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1954 
1955   SmallVector<StringRef, 4> OverrideVector;
1956   Override.split(OverrideVector, ',');
1957   unsigned NumArgs = OverrideVector.size();
1958 
1959   // Check if "all", "default", or "none" was specified.
1960   if (NumArgs == 1) {
1961     // Look for an optional setting of the number of refinement steps needed
1962     // for this type of reciprocal operation.
1963     size_t RefPos;
1964     uint8_t RefSteps;
1965     if (!parseRefinementStep(Override, RefPos, RefSteps))
1966       return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1967 
1968     // Split the string for further processing.
1969     Override = Override.substr(0, RefPos);
1970     assert(Override != "none" &&
1971            "Disabled reciprocals, but specifed refinement steps?");
1972 
1973     // If this is a general override, return the specified number of steps.
1974     if (Override == "all" || Override == "default")
1975       return RefSteps;
1976   }
1977 
1978   // The attribute string may omit the size suffix ('f'/'d').
1979   std::string VTName = getReciprocalOpName(IsSqrt, VT);
1980   std::string VTNameNoSize = VTName;
1981   VTNameNoSize.pop_back();
1982 
1983   for (StringRef RecipType : OverrideVector) {
1984     size_t RefPos;
1985     uint8_t RefSteps;
1986     if (!parseRefinementStep(RecipType, RefPos, RefSteps))
1987       continue;
1988 
1989     RecipType = RecipType.substr(0, RefPos);
1990     if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
1991       return RefSteps;
1992   }
1993 
1994   return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1995 }
1996 
1997 int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT,
1998                                                     MachineFunction &MF) const {
1999   return getOpEnabled(true, VT, getRecipEstimateForFunc(MF));
2000 }
2001 
2002 int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT,
2003                                                    MachineFunction &MF) const {
2004   return getOpEnabled(false, VT, getRecipEstimateForFunc(MF));
2005 }
2006 
2007 int TargetLoweringBase::getSqrtRefinementSteps(EVT VT,
2008                                                MachineFunction &MF) const {
2009   return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF));
2010 }
2011 
2012 int TargetLoweringBase::getDivRefinementSteps(EVT VT,
2013                                               MachineFunction &MF) const {
2014   return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF));
2015 }
2016 
2017 void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const {
2018   MF.getRegInfo().freezeReservedRegs(MF);
2019 }
2020 
2021 MachineMemOperand::Flags
2022 TargetLoweringBase::getLoadMemOperandFlags(const LoadInst &LI,
2023                                            const DataLayout &DL) const {
2024   MachineMemOperand::Flags Flags = MachineMemOperand::MOLoad;
2025   if (LI.isVolatile())
2026     Flags |= MachineMemOperand::MOVolatile;
2027 
2028   if (LI.hasMetadata(LLVMContext::MD_nontemporal))
2029     Flags |= MachineMemOperand::MONonTemporal;
2030 
2031   if (LI.hasMetadata(LLVMContext::MD_invariant_load))
2032     Flags |= MachineMemOperand::MOInvariant;
2033 
2034   if (isDereferenceablePointer(LI.getPointerOperand(), LI.getType(), DL))
2035     Flags |= MachineMemOperand::MODereferenceable;
2036 
2037   Flags |= getTargetMMOFlags(LI);
2038   return Flags;
2039 }
2040 
2041 MachineMemOperand::Flags
2042 TargetLoweringBase::getStoreMemOperandFlags(const StoreInst &SI,
2043                                             const DataLayout &DL) const {
2044   MachineMemOperand::Flags Flags = MachineMemOperand::MOStore;
2045 
2046   if (SI.isVolatile())
2047     Flags |= MachineMemOperand::MOVolatile;
2048 
2049   if (SI.hasMetadata(LLVMContext::MD_nontemporal))
2050     Flags |= MachineMemOperand::MONonTemporal;
2051 
2052   // FIXME: Not preserving dereferenceable
2053   Flags |= getTargetMMOFlags(SI);
2054   return Flags;
2055 }
2056 
2057 MachineMemOperand::Flags
2058 TargetLoweringBase::getAtomicMemOperandFlags(const Instruction &AI,
2059                                              const DataLayout &DL) const {
2060   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
2061 
2062   if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(&AI)) {
2063     if (RMW->isVolatile())
2064       Flags |= MachineMemOperand::MOVolatile;
2065   } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(&AI)) {
2066     if (CmpX->isVolatile())
2067       Flags |= MachineMemOperand::MOVolatile;
2068   } else
2069     llvm_unreachable("not an atomic instruction");
2070 
2071   // FIXME: Not preserving dereferenceable
2072   Flags |= getTargetMMOFlags(AI);
2073   return Flags;
2074 }
2075