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