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