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