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 :
745        enum_seq_inclusive(ISD::DELETED_NODE, ISD::BUILTIN_OP_END,
746                           force_iteration_on_noniterable_enum)) {
747     for (MVT VT : {MVT::i2, MVT::i4})
748       OpActions[(unsigned)VT.SimpleTy][NT] = Expand;
749   }
750   for (MVT AVT : MVT::all_valuetypes()) {
751     for (MVT VT : {MVT::i2, MVT::i4, MVT::v128i2, MVT::v64i4}) {
752       setTruncStoreAction(AVT, VT, Expand);
753       setLoadExtAction(ISD::EXTLOAD, AVT, VT, Expand);
754       setLoadExtAction(ISD::ZEXTLOAD, AVT, VT, Expand);
755     }
756   }
757   for (unsigned IM = (unsigned)ISD::PRE_INC;
758        IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
759     for (MVT VT : {MVT::i2, MVT::i4}) {
760       setIndexedLoadAction(IM, VT, Expand);
761       setIndexedStoreAction(IM, VT, Expand);
762       setIndexedMaskedLoadAction(IM, VT, Expand);
763       setIndexedMaskedStoreAction(IM, VT, Expand);
764     }
765   }
766 
767   for (MVT VT : MVT::fp_valuetypes()) {
768     MVT IntVT = MVT::getIntegerVT(VT.getFixedSizeInBits());
769     if (IntVT.isValid()) {
770       setOperationAction(ISD::ATOMIC_SWAP, VT, Promote);
771       AddPromotedToType(ISD::ATOMIC_SWAP, VT, IntVT);
772     }
773   }
774 
775   // Set default actions for various operations.
776   for (MVT VT : MVT::all_valuetypes()) {
777     // Default all indexed load / store to expand.
778     for (unsigned IM = (unsigned)ISD::PRE_INC;
779          IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
780       setIndexedLoadAction(IM, VT, Expand);
781       setIndexedStoreAction(IM, VT, Expand);
782       setIndexedMaskedLoadAction(IM, VT, Expand);
783       setIndexedMaskedStoreAction(IM, VT, Expand);
784     }
785 
786     // Most backends expect to see the node which just returns the value loaded.
787     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Expand);
788 
789     // These operations default to expand.
790     setOperationAction({ISD::FGETSIGN,       ISD::CONCAT_VECTORS,
791                         ISD::FMINNUM,        ISD::FMAXNUM,
792                         ISD::FMINNUM_IEEE,   ISD::FMAXNUM_IEEE,
793                         ISD::FMINIMUM,       ISD::FMAXIMUM,
794                         ISD::FMAD,           ISD::SMIN,
795                         ISD::SMAX,           ISD::UMIN,
796                         ISD::UMAX,           ISD::ABS,
797                         ISD::FSHL,           ISD::FSHR,
798                         ISD::SADDSAT,        ISD::UADDSAT,
799                         ISD::SSUBSAT,        ISD::USUBSAT,
800                         ISD::SSHLSAT,        ISD::USHLSAT,
801                         ISD::SMULFIX,        ISD::SMULFIXSAT,
802                         ISD::UMULFIX,        ISD::UMULFIXSAT,
803                         ISD::SDIVFIX,        ISD::SDIVFIXSAT,
804                         ISD::UDIVFIX,        ISD::UDIVFIXSAT,
805                         ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT,
806                         ISD::IS_FPCLASS},
807                        VT, Expand);
808 
809     // Overflow operations default to expand
810     setOperationAction({ISD::SADDO, ISD::SSUBO, ISD::UADDO, ISD::USUBO,
811                         ISD::SMULO, ISD::UMULO},
812                        VT, Expand);
813 
814     // ADDCARRY operations default to expand
815     setOperationAction({ISD::ADDCARRY, ISD::SUBCARRY, ISD::SETCCCARRY,
816                         ISD::SADDO_CARRY, ISD::SSUBO_CARRY},
817                        VT, Expand);
818 
819     // ADDC/ADDE/SUBC/SUBE default to expand.
820     setOperationAction({ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}, VT,
821                        Expand);
822 
823     // Halving adds
824     setOperationAction(
825         {ISD::AVGFLOORS, ISD::AVGFLOORU, ISD::AVGCEILS, ISD::AVGCEILU}, VT,
826         Expand);
827 
828     // Absolute difference
829     setOperationAction({ISD::ABDS, ISD::ABDU}, VT, Expand);
830 
831     // These default to Expand so they will be expanded to CTLZ/CTTZ by default.
832     setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
833                        Expand);
834 
835     setOperationAction({ISD::BITREVERSE, ISD::PARITY}, VT, Expand);
836 
837     // These library functions default to expand.
838     setOperationAction({ISD::FROUND, ISD::FROUNDEVEN, ISD::FPOWI}, VT, Expand);
839 
840     // These operations default to expand for vector types.
841     if (VT.isVector())
842       setOperationAction({ISD::FCOPYSIGN, ISD::SIGN_EXTEND_INREG,
843                           ISD::ANY_EXTEND_VECTOR_INREG,
844                           ISD::SIGN_EXTEND_VECTOR_INREG,
845                           ISD::ZERO_EXTEND_VECTOR_INREG, ISD::SPLAT_VECTOR},
846                          VT, Expand);
847 
848     // Constrained floating-point operations default to expand.
849 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
850     setOperationAction(ISD::STRICT_##DAGN, VT, Expand);
851 #include "llvm/IR/ConstrainedOps.def"
852 
853     // For most targets @llvm.get.dynamic.area.offset just returns 0.
854     setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand);
855 
856     // Vector reduction default to expand.
857     setOperationAction(
858         {ISD::VECREDUCE_FADD, ISD::VECREDUCE_FMUL, ISD::VECREDUCE_ADD,
859          ISD::VECREDUCE_MUL, ISD::VECREDUCE_AND, ISD::VECREDUCE_OR,
860          ISD::VECREDUCE_XOR, ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
861          ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN, ISD::VECREDUCE_FMAX,
862          ISD::VECREDUCE_FMIN, ISD::VECREDUCE_SEQ_FADD, ISD::VECREDUCE_SEQ_FMUL},
863         VT, Expand);
864 
865     // Named vector shuffles default to expand.
866     setOperationAction(ISD::VECTOR_SPLICE, VT, Expand);
867   }
868 
869   // Most targets ignore the @llvm.prefetch intrinsic.
870   setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
871 
872   // Most targets also ignore the @llvm.readcyclecounter intrinsic.
873   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand);
874 
875   // ConstantFP nodes default to expand.  Targets can either change this to
876   // Legal, in which case all fp constants are legal, or use isFPImmLegal()
877   // to optimize expansions for certain constants.
878   setOperationAction(ISD::ConstantFP,
879                      {MVT::f16, MVT::f32, MVT::f64, MVT::f80, MVT::f128},
880                      Expand);
881 
882   // These library functions default to expand.
883   setOperationAction({ISD::FCBRT, ISD::FLOG, ISD::FLOG2, ISD::FLOG10, ISD::FEXP,
884                       ISD::FEXP2, ISD::FFLOOR, ISD::FNEARBYINT, ISD::FCEIL,
885                       ISD::FRINT, ISD::FTRUNC, ISD::LROUND, ISD::LLROUND,
886                       ISD::LRINT, ISD::LLRINT},
887                      {MVT::f32, MVT::f64, MVT::f128}, Expand);
888 
889   // Default ISD::TRAP to expand (which turns it into abort).
890   setOperationAction(ISD::TRAP, MVT::Other, Expand);
891 
892   // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
893   // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
894   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand);
895 
896   setOperationAction(ISD::UBSANTRAP, MVT::Other, Expand);
897 }
898 
899 MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL,
900                                                EVT) const {
901   return MVT::getIntegerVT(DL.getPointerSizeInBits(0));
902 }
903 
904 EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
905                                          bool LegalTypes) const {
906   assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
907   if (LHSTy.isVector())
908     return LHSTy;
909   MVT ShiftVT =
910       LegalTypes ? getScalarShiftAmountTy(DL, LHSTy) : getPointerTy(DL);
911   // If any possible shift value won't fit in the prefered type, just use
912   // something safe. Assume it will be legalized when the shift is expanded.
913   if (ShiftVT.getSizeInBits() < Log2_32_Ceil(LHSTy.getSizeInBits()))
914     ShiftVT = MVT::i32;
915   assert(ShiftVT.getSizeInBits() >= Log2_32_Ceil(LHSTy.getSizeInBits()) &&
916          "ShiftVT is still too small!");
917   return ShiftVT;
918 }
919 
920 bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const {
921   assert(isTypeLegal(VT));
922   switch (Op) {
923   default:
924     return false;
925   case ISD::SDIV:
926   case ISD::UDIV:
927   case ISD::SREM:
928   case ISD::UREM:
929     return true;
930   }
931 }
932 
933 bool TargetLoweringBase::isFreeAddrSpaceCast(unsigned SrcAS,
934                                              unsigned DestAS) const {
935   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
936 }
937 
938 void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) {
939   // If the command-line option was specified, ignore this request.
940   if (!JumpIsExpensiveOverride.getNumOccurrences())
941     JumpIsExpensive = isExpensive;
942 }
943 
944 TargetLoweringBase::LegalizeKind
945 TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const {
946   // If this is a simple type, use the ComputeRegisterProp mechanism.
947   if (VT.isSimple()) {
948     MVT SVT = VT.getSimpleVT();
949     assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
950     MVT NVT = TransformToType[SVT.SimpleTy];
951     LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
952 
953     assert((LA == TypeLegal || LA == TypeSoftenFloat ||
954             LA == TypeSoftPromoteHalf ||
955             (NVT.isVector() ||
956              ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger)) &&
957            "Promote may not follow Expand or Promote");
958 
959     if (LA == TypeSplitVector)
960       return LegalizeKind(LA, EVT(SVT).getHalfNumVectorElementsVT(Context));
961     if (LA == TypeScalarizeVector)
962       return LegalizeKind(LA, SVT.getVectorElementType());
963     return LegalizeKind(LA, NVT);
964   }
965 
966   // Handle Extended Scalar Types.
967   if (!VT.isVector()) {
968     assert(VT.isInteger() && "Float types must be simple");
969     unsigned BitSize = VT.getSizeInBits();
970     // First promote to a power-of-two size, then expand if necessary.
971     if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
972       EVT NVT = VT.getRoundIntegerType(Context);
973       assert(NVT != VT && "Unable to round integer VT");
974       LegalizeKind NextStep = getTypeConversion(Context, NVT);
975       // Avoid multi-step promotion.
976       if (NextStep.first == TypePromoteInteger)
977         return NextStep;
978       // Return rounded integer type.
979       return LegalizeKind(TypePromoteInteger, NVT);
980     }
981 
982     return LegalizeKind(TypeExpandInteger,
983                         EVT::getIntegerVT(Context, VT.getSizeInBits() / 2));
984   }
985 
986   // Handle vector types.
987   ElementCount NumElts = VT.getVectorElementCount();
988   EVT EltVT = VT.getVectorElementType();
989 
990   // Vectors with only one element are always scalarized.
991   if (NumElts.isScalar())
992     return LegalizeKind(TypeScalarizeVector, EltVT);
993 
994   // Try to widen vector elements until the element type is a power of two and
995   // promote it to a legal type later on, for example:
996   // <3 x i8> -> <4 x i8> -> <4 x i32>
997   if (EltVT.isInteger()) {
998     // Vectors with a number of elements that is not a power of two are always
999     // widened, for example <3 x i8> -> <4 x i8>.
1000     if (!VT.isPow2VectorType()) {
1001       NumElts = NumElts.coefficientNextPowerOf2();
1002       EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1003       return LegalizeKind(TypeWidenVector, NVT);
1004     }
1005 
1006     // Examine the element type.
1007     LegalizeKind LK = getTypeConversion(Context, EltVT);
1008 
1009     // If type is to be expanded, split the vector.
1010     //  <4 x i140> -> <2 x i140>
1011     if (LK.first == TypeExpandInteger) {
1012       if (VT.getVectorElementCount().isScalable())
1013         return LegalizeKind(TypeScalarizeScalableVector, EltVT);
1014       return LegalizeKind(TypeSplitVector,
1015                           VT.getHalfNumVectorElementsVT(Context));
1016     }
1017 
1018     // Promote the integer element types until a legal vector type is found
1019     // or until the element integer type is too big. If a legal type was not
1020     // found, fallback to the usual mechanism of widening/splitting the
1021     // vector.
1022     EVT OldEltVT = EltVT;
1023     while (true) {
1024       // Increase the bitwidth of the element to the next pow-of-two
1025       // (which is greater than 8 bits).
1026       EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits())
1027                   .getRoundIntegerType(Context);
1028 
1029       // Stop trying when getting a non-simple element type.
1030       // Note that vector elements may be greater than legal vector element
1031       // types. Example: X86 XMM registers hold 64bit element on 32bit
1032       // systems.
1033       if (!EltVT.isSimple())
1034         break;
1035 
1036       // Build a new vector type and check if it is legal.
1037       MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1038       // Found a legal promoted vector type.
1039       if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1040         return LegalizeKind(TypePromoteInteger,
1041                             EVT::getVectorVT(Context, EltVT, NumElts));
1042     }
1043 
1044     // Reset the type to the unexpanded type if we did not find a legal vector
1045     // type with a promoted vector element type.
1046     EltVT = OldEltVT;
1047   }
1048 
1049   // Try to widen the vector until a legal type is found.
1050   // If there is no wider legal type, split the vector.
1051   while (true) {
1052     // Round up to the next power of 2.
1053     NumElts = NumElts.coefficientNextPowerOf2();
1054 
1055     // If there is no simple vector type with this many elements then there
1056     // cannot be a larger legal vector type.  Note that this assumes that
1057     // there are no skipped intermediate vector types in the simple types.
1058     if (!EltVT.isSimple())
1059       break;
1060     MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1061     if (LargerVector == MVT())
1062       break;
1063 
1064     // If this type is legal then widen the vector.
1065     if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1066       return LegalizeKind(TypeWidenVector, LargerVector);
1067   }
1068 
1069   // Widen odd vectors to next power of two.
1070   if (!VT.isPow2VectorType()) {
1071     EVT NVT = VT.getPow2VectorType(Context);
1072     return LegalizeKind(TypeWidenVector, NVT);
1073   }
1074 
1075   if (VT.getVectorElementCount() == ElementCount::getScalable(1))
1076     return LegalizeKind(TypeScalarizeScalableVector, EltVT);
1077 
1078   // Vectors with illegal element types are expanded.
1079   EVT NVT = EVT::getVectorVT(Context, EltVT,
1080                              VT.getVectorElementCount().divideCoefficientBy(2));
1081   return LegalizeKind(TypeSplitVector, NVT);
1082 }
1083 
1084 static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
1085                                           unsigned &NumIntermediates,
1086                                           MVT &RegisterVT,
1087                                           TargetLoweringBase *TLI) {
1088   // Figure out the right, legal destination reg to copy into.
1089   ElementCount EC = VT.getVectorElementCount();
1090   MVT EltTy = VT.getVectorElementType();
1091 
1092   unsigned NumVectorRegs = 1;
1093 
1094   // Scalable vectors cannot be scalarized, so splitting or widening is
1095   // required.
1096   if (VT.isScalableVector() && !isPowerOf2_32(EC.getKnownMinValue()))
1097     llvm_unreachable(
1098         "Splitting or widening of non-power-of-2 MVTs is not implemented.");
1099 
1100   // FIXME: We don't support non-power-of-2-sized vectors for now.
1101   // Ideally we could break down into LHS/RHS like LegalizeDAG does.
1102   if (!isPowerOf2_32(EC.getKnownMinValue())) {
1103     // Split EC to unit size (scalable property is preserved).
1104     NumVectorRegs = EC.getKnownMinValue();
1105     EC = ElementCount::getFixed(1);
1106   }
1107 
1108   // Divide the input until we get to a supported size. This will
1109   // always end up with an EC that represent a scalar or a scalable
1110   // scalar.
1111   while (EC.getKnownMinValue() > 1 &&
1112          !TLI->isTypeLegal(MVT::getVectorVT(EltTy, EC))) {
1113     EC = EC.divideCoefficientBy(2);
1114     NumVectorRegs <<= 1;
1115   }
1116 
1117   NumIntermediates = NumVectorRegs;
1118 
1119   MVT NewVT = MVT::getVectorVT(EltTy, EC);
1120   if (!TLI->isTypeLegal(NewVT))
1121     NewVT = EltTy;
1122   IntermediateVT = NewVT;
1123 
1124   unsigned LaneSizeInBits = NewVT.getScalarSizeInBits();
1125 
1126   // Convert sizes such as i33 to i64.
1127   if (!isPowerOf2_32(LaneSizeInBits))
1128     LaneSizeInBits = NextPowerOf2(LaneSizeInBits);
1129 
1130   MVT DestVT = TLI->getRegisterType(NewVT);
1131   RegisterVT = DestVT;
1132   if (EVT(DestVT).bitsLT(NewVT))    // Value is expanded, e.g. i64 -> i16.
1133     return NumVectorRegs * (LaneSizeInBits / DestVT.getScalarSizeInBits());
1134 
1135   // Otherwise, promotion or legal types use the same number of registers as
1136   // the vector decimated to the appropriate level.
1137   return NumVectorRegs;
1138 }
1139 
1140 /// isLegalRC - Return true if the value types that can be represented by the
1141 /// specified register class are all legal.
1142 bool TargetLoweringBase::isLegalRC(const TargetRegisterInfo &TRI,
1143                                    const TargetRegisterClass &RC) const {
1144   for (auto I = TRI.legalclasstypes_begin(RC); *I != MVT::Other; ++I)
1145     if (isTypeLegal(*I))
1146       return true;
1147   return false;
1148 }
1149 
1150 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
1151 /// sequence of memory operands that is recognized by PrologEpilogInserter.
1152 MachineBasicBlock *
1153 TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI,
1154                                    MachineBasicBlock *MBB) const {
1155   MachineInstr *MI = &InitialMI;
1156   MachineFunction &MF = *MI->getMF();
1157   MachineFrameInfo &MFI = MF.getFrameInfo();
1158 
1159   // We're handling multiple types of operands here:
1160   // PATCHPOINT MetaArgs - live-in, read only, direct
1161   // STATEPOINT Deopt Spill - live-through, read only, indirect
1162   // STATEPOINT Deopt Alloca - live-through, read only, direct
1163   // (We're currently conservative and mark the deopt slots read/write in
1164   // practice.)
1165   // STATEPOINT GC Spill - live-through, read/write, indirect
1166   // STATEPOINT GC Alloca - live-through, read/write, direct
1167   // The live-in vs live-through is handled already (the live through ones are
1168   // all stack slots), but we need to handle the different type of stackmap
1169   // operands and memory effects here.
1170 
1171   if (llvm::none_of(MI->operands(),
1172                     [](MachineOperand &Operand) { return Operand.isFI(); }))
1173     return MBB;
1174 
1175   MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc());
1176 
1177   // Inherit previous memory operands.
1178   MIB.cloneMemRefs(*MI);
1179 
1180   for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
1181     MachineOperand &MO = MI->getOperand(i);
1182     if (!MO.isFI()) {
1183       // Index of Def operand this Use it tied to.
1184       // Since Defs are coming before Uses, if Use is tied, then
1185       // index of Def must be smaller that index of that Use.
1186       // Also, Defs preserve their position in new MI.
1187       unsigned TiedTo = i;
1188       if (MO.isReg() && MO.isTied())
1189         TiedTo = MI->findTiedOperandIdx(i);
1190       MIB.add(MO);
1191       if (TiedTo < i)
1192         MIB->tieOperands(TiedTo, MIB->getNumOperands() - 1);
1193       continue;
1194     }
1195 
1196     // foldMemoryOperand builds a new MI after replacing a single FI operand
1197     // with the canonical set of five x86 addressing-mode operands.
1198     int FI = MO.getIndex();
1199 
1200     // Add frame index operands recognized by stackmaps.cpp
1201     if (MFI.isStatepointSpillSlotObjectIndex(FI)) {
1202       // indirect-mem-ref tag, size, #FI, offset.
1203       // Used for spills inserted by StatepointLowering.  This codepath is not
1204       // used for patchpoints/stackmaps at all, for these spilling is done via
1205       // foldMemoryOperand callback only.
1206       assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity");
1207       MIB.addImm(StackMaps::IndirectMemRefOp);
1208       MIB.addImm(MFI.getObjectSize(FI));
1209       MIB.add(MO);
1210       MIB.addImm(0);
1211     } else {
1212       // direct-mem-ref tag, #FI, offset.
1213       // Used by patchpoint, and direct alloca arguments to statepoints
1214       MIB.addImm(StackMaps::DirectMemRefOp);
1215       MIB.add(MO);
1216       MIB.addImm(0);
1217     }
1218 
1219     assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!");
1220 
1221     // Add a new memory operand for this FI.
1222     assert(MFI.getObjectOffset(FI) != -1);
1223 
1224     // Note: STATEPOINT MMOs are added during SelectionDAG.  STACKMAP, and
1225     // PATCHPOINT should be updated to do the same. (TODO)
1226     if (MI->getOpcode() != TargetOpcode::STATEPOINT) {
1227       auto Flags = MachineMemOperand::MOLoad;
1228       MachineMemOperand *MMO = MF.getMachineMemOperand(
1229           MachinePointerInfo::getFixedStack(MF, FI), Flags,
1230           MF.getDataLayout().getPointerSize(), MFI.getObjectAlign(FI));
1231       MIB->addMemOperand(MF, MMO);
1232     }
1233   }
1234   MBB->insert(MachineBasicBlock::iterator(MI), MIB);
1235   MI->eraseFromParent();
1236   return MBB;
1237 }
1238 
1239 /// findRepresentativeClass - Return the largest legal super-reg register class
1240 /// of the register class for the specified type and its associated "cost".
1241 // This function is in TargetLowering because it uses RegClassForVT which would
1242 // need to be moved to TargetRegisterInfo and would necessitate moving
1243 // isTypeLegal over as well - a massive change that would just require
1244 // TargetLowering having a TargetRegisterInfo class member that it would use.
1245 std::pair<const TargetRegisterClass *, uint8_t>
1246 TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI,
1247                                             MVT VT) const {
1248   const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
1249   if (!RC)
1250     return std::make_pair(RC, 0);
1251 
1252   // Compute the set of all super-register classes.
1253   BitVector SuperRegRC(TRI->getNumRegClasses());
1254   for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
1255     SuperRegRC.setBitsInMask(RCI.getMask());
1256 
1257   // Find the first legal register class with the largest spill size.
1258   const TargetRegisterClass *BestRC = RC;
1259   for (unsigned i : SuperRegRC.set_bits()) {
1260     const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
1261     // We want the largest possible spill size.
1262     if (TRI->getSpillSize(*SuperRC) <= TRI->getSpillSize(*BestRC))
1263       continue;
1264     if (!isLegalRC(*TRI, *SuperRC))
1265       continue;
1266     BestRC = SuperRC;
1267   }
1268   return std::make_pair(BestRC, 1);
1269 }
1270 
1271 /// computeRegisterProperties - Once all of the register classes are added,
1272 /// this allows us to compute derived properties we expose.
1273 void TargetLoweringBase::computeRegisterProperties(
1274     const TargetRegisterInfo *TRI) {
1275   static_assert(MVT::VALUETYPE_SIZE <= MVT::MAX_ALLOWED_VALUETYPE,
1276                 "Too many value types for ValueTypeActions to hold!");
1277 
1278   // Everything defaults to needing one register.
1279   for (unsigned i = 0; i != MVT::VALUETYPE_SIZE; ++i) {
1280     NumRegistersForVT[i] = 1;
1281     RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
1282   }
1283   // ...except isVoid, which doesn't need any registers.
1284   NumRegistersForVT[MVT::isVoid] = 0;
1285 
1286   // Find the largest integer register class.
1287   unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
1288   for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg)
1289     assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
1290 
1291   // Every integer value type larger than this largest register takes twice as
1292   // many registers to represent as the previous ValueType.
1293   for (unsigned ExpandedReg = LargestIntReg + 1;
1294        ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
1295     NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
1296     RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
1297     TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
1298     ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg,
1299                                    TypeExpandInteger);
1300   }
1301 
1302   // Inspect all of the ValueType's smaller than the largest integer
1303   // register to see which ones need promotion.
1304   unsigned LegalIntReg = LargestIntReg;
1305   for (unsigned IntReg = LargestIntReg - 1;
1306        IntReg >= (unsigned)MVT::i1; --IntReg) {
1307     MVT IVT = (MVT::SimpleValueType)IntReg;
1308     if (isTypeLegal(IVT)) {
1309       LegalIntReg = IntReg;
1310     } else {
1311       RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
1312         (MVT::SimpleValueType)LegalIntReg;
1313       ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
1314     }
1315   }
1316 
1317   // ppcf128 type is really two f64's.
1318   if (!isTypeLegal(MVT::ppcf128)) {
1319     if (isTypeLegal(MVT::f64)) {
1320       NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
1321       RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
1322       TransformToType[MVT::ppcf128] = MVT::f64;
1323       ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
1324     } else {
1325       NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128];
1326       RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128];
1327       TransformToType[MVT::ppcf128] = MVT::i128;
1328       ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat);
1329     }
1330   }
1331 
1332   // Decide how to handle f128. If the target does not have native f128 support,
1333   // expand it to i128 and we will be generating soft float library calls.
1334   if (!isTypeLegal(MVT::f128)) {
1335     NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128];
1336     RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128];
1337     TransformToType[MVT::f128] = MVT::i128;
1338     ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
1339   }
1340 
1341   // Decide how to handle f64. If the target does not have native f64 support,
1342   // expand it to i64 and we will be generating soft float library calls.
1343   if (!isTypeLegal(MVT::f64)) {
1344     NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
1345     RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
1346     TransformToType[MVT::f64] = MVT::i64;
1347     ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
1348   }
1349 
1350   // Decide how to handle f32. If the target does not have native f32 support,
1351   // expand it to i32 and we will be generating soft float library calls.
1352   if (!isTypeLegal(MVT::f32)) {
1353     NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
1354     RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
1355     TransformToType[MVT::f32] = MVT::i32;
1356     ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
1357   }
1358 
1359   // Decide how to handle f16. If the target does not have native f16 support,
1360   // promote it to f32, because there are no f16 library calls (except for
1361   // conversions).
1362   if (!isTypeLegal(MVT::f16)) {
1363     // Allow targets to control how we legalize half.
1364     if (softPromoteHalfType()) {
1365       NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::i16];
1366       RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::i16];
1367       TransformToType[MVT::f16] = MVT::f32;
1368       ValueTypeActions.setTypeAction(MVT::f16, TypeSoftPromoteHalf);
1369     } else {
1370       NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32];
1371       RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32];
1372       TransformToType[MVT::f16] = MVT::f32;
1373       ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat);
1374     }
1375   }
1376 
1377   // Loop over all of the vector value types to see which need transformations.
1378   for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
1379        i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1380     MVT VT = (MVT::SimpleValueType) i;
1381     if (isTypeLegal(VT))
1382       continue;
1383 
1384     MVT EltVT = VT.getVectorElementType();
1385     ElementCount EC = VT.getVectorElementCount();
1386     bool IsLegalWiderType = false;
1387     bool IsScalable = VT.isScalableVector();
1388     LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT);
1389     switch (PreferredAction) {
1390     case TypePromoteInteger: {
1391       MVT::SimpleValueType EndVT = IsScalable ?
1392                                    MVT::LAST_INTEGER_SCALABLE_VECTOR_VALUETYPE :
1393                                    MVT::LAST_INTEGER_FIXEDLEN_VECTOR_VALUETYPE;
1394       // Try to promote the elements of integer vectors. If no legal
1395       // promotion was found, fall through to the widen-vector method.
1396       for (unsigned nVT = i + 1;
1397            (MVT::SimpleValueType)nVT <= EndVT; ++nVT) {
1398         MVT SVT = (MVT::SimpleValueType) nVT;
1399         // Promote vectors of integers to vectors with the same number
1400         // of elements, with a wider element type.
1401         if (SVT.getScalarSizeInBits() > EltVT.getFixedSizeInBits() &&
1402             SVT.getVectorElementCount() == EC && isTypeLegal(SVT)) {
1403           TransformToType[i] = SVT;
1404           RegisterTypeForVT[i] = SVT;
1405           NumRegistersForVT[i] = 1;
1406           ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
1407           IsLegalWiderType = true;
1408           break;
1409         }
1410       }
1411       if (IsLegalWiderType)
1412         break;
1413       LLVM_FALLTHROUGH;
1414     }
1415 
1416     case TypeWidenVector:
1417       if (isPowerOf2_32(EC.getKnownMinValue())) {
1418         // Try to widen the vector.
1419         for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
1420           MVT SVT = (MVT::SimpleValueType) nVT;
1421           if (SVT.getVectorElementType() == EltVT &&
1422               SVT.isScalableVector() == IsScalable &&
1423               SVT.getVectorElementCount().getKnownMinValue() >
1424                   EC.getKnownMinValue() &&
1425               isTypeLegal(SVT)) {
1426             TransformToType[i] = SVT;
1427             RegisterTypeForVT[i] = SVT;
1428             NumRegistersForVT[i] = 1;
1429             ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1430             IsLegalWiderType = true;
1431             break;
1432           }
1433         }
1434         if (IsLegalWiderType)
1435           break;
1436       } else {
1437         // Only widen to the next power of 2 to keep consistency with EVT.
1438         MVT NVT = VT.getPow2VectorType();
1439         if (isTypeLegal(NVT)) {
1440           TransformToType[i] = NVT;
1441           ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1442           RegisterTypeForVT[i] = NVT;
1443           NumRegistersForVT[i] = 1;
1444           break;
1445         }
1446       }
1447       LLVM_FALLTHROUGH;
1448 
1449     case TypeSplitVector:
1450     case TypeScalarizeVector: {
1451       MVT IntermediateVT;
1452       MVT RegisterVT;
1453       unsigned NumIntermediates;
1454       unsigned NumRegisters = getVectorTypeBreakdownMVT(VT, IntermediateVT,
1455           NumIntermediates, RegisterVT, this);
1456       NumRegistersForVT[i] = NumRegisters;
1457       assert(NumRegistersForVT[i] == NumRegisters &&
1458              "NumRegistersForVT size cannot represent NumRegisters!");
1459       RegisterTypeForVT[i] = RegisterVT;
1460 
1461       MVT NVT = VT.getPow2VectorType();
1462       if (NVT == VT) {
1463         // Type is already a power of 2.  The default action is to split.
1464         TransformToType[i] = MVT::Other;
1465         if (PreferredAction == TypeScalarizeVector)
1466           ValueTypeActions.setTypeAction(VT, TypeScalarizeVector);
1467         else if (PreferredAction == TypeSplitVector)
1468           ValueTypeActions.setTypeAction(VT, TypeSplitVector);
1469         else if (EC.getKnownMinValue() > 1)
1470           ValueTypeActions.setTypeAction(VT, TypeSplitVector);
1471         else
1472           ValueTypeActions.setTypeAction(VT, EC.isScalable()
1473                                                  ? TypeScalarizeScalableVector
1474                                                  : TypeScalarizeVector);
1475       } else {
1476         TransformToType[i] = NVT;
1477         ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1478       }
1479       break;
1480     }
1481     default:
1482       llvm_unreachable("Unknown vector legalization action!");
1483     }
1484   }
1485 
1486   // Determine the 'representative' register class for each value type.
1487   // An representative register class is the largest (meaning one which is
1488   // not a sub-register class / subreg register class) legal register class for
1489   // a group of value types. For example, on i386, i8, i16, and i32
1490   // representative would be GR32; while on x86_64 it's GR64.
1491   for (unsigned i = 0; i != MVT::VALUETYPE_SIZE; ++i) {
1492     const TargetRegisterClass* RRC;
1493     uint8_t Cost;
1494     std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i);
1495     RepRegClassForVT[i] = RRC;
1496     RepRegClassCostForVT[i] = Cost;
1497   }
1498 }
1499 
1500 EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1501                                            EVT VT) const {
1502   assert(!VT.isVector() && "No default SetCC type for vectors!");
1503   return getPointerTy(DL).SimpleTy;
1504 }
1505 
1506 MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const {
1507   return MVT::i32; // return the default value
1508 }
1509 
1510 /// getVectorTypeBreakdown - Vector types are broken down into some number of
1511 /// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
1512 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
1513 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
1514 ///
1515 /// This method returns the number of registers needed, and the VT for each
1516 /// register.  It also returns the VT and quantity of the intermediate values
1517 /// before they are promoted/expanded.
1518 unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context,
1519                                                     EVT VT, EVT &IntermediateVT,
1520                                                     unsigned &NumIntermediates,
1521                                                     MVT &RegisterVT) const {
1522   ElementCount EltCnt = VT.getVectorElementCount();
1523 
1524   // If there is a wider vector type with the same element type as this one,
1525   // or a promoted vector type that has the same number of elements which
1526   // are wider, then we should convert to that legal vector type.
1527   // This handles things like <2 x float> -> <4 x float> and
1528   // <4 x i1> -> <4 x i32>.
1529   LegalizeTypeAction TA = getTypeAction(Context, VT);
1530   if (!EltCnt.isScalar() &&
1531       (TA == TypeWidenVector || TA == TypePromoteInteger)) {
1532     EVT RegisterEVT = getTypeToTransformTo(Context, VT);
1533     if (isTypeLegal(RegisterEVT)) {
1534       IntermediateVT = RegisterEVT;
1535       RegisterVT = RegisterEVT.getSimpleVT();
1536       NumIntermediates = 1;
1537       return 1;
1538     }
1539   }
1540 
1541   // Figure out the right, legal destination reg to copy into.
1542   EVT EltTy = VT.getVectorElementType();
1543 
1544   unsigned NumVectorRegs = 1;
1545 
1546   // Scalable vectors cannot be scalarized, so handle the legalisation of the
1547   // types like done elsewhere in SelectionDAG.
1548   if (EltCnt.isScalable()) {
1549     LegalizeKind LK;
1550     EVT PartVT = VT;
1551     do {
1552       // Iterate until we've found a legal (part) type to hold VT.
1553       LK = getTypeConversion(Context, PartVT);
1554       PartVT = LK.second;
1555     } while (LK.first != TypeLegal);
1556 
1557     if (!PartVT.isVector()) {
1558       report_fatal_error(
1559           "Don't know how to legalize this scalable vector type");
1560     }
1561 
1562     NumIntermediates =
1563         divideCeil(VT.getVectorElementCount().getKnownMinValue(),
1564                    PartVT.getVectorElementCount().getKnownMinValue());
1565     IntermediateVT = PartVT;
1566     RegisterVT = getRegisterType(Context, IntermediateVT);
1567     return NumIntermediates;
1568   }
1569 
1570   // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally
1571   // we could break down into LHS/RHS like LegalizeDAG does.
1572   if (!isPowerOf2_32(EltCnt.getKnownMinValue())) {
1573     NumVectorRegs = EltCnt.getKnownMinValue();
1574     EltCnt = ElementCount::getFixed(1);
1575   }
1576 
1577   // Divide the input until we get to a supported size.  This will always
1578   // end with a scalar if the target doesn't support vectors.
1579   while (EltCnt.getKnownMinValue() > 1 &&
1580          !isTypeLegal(EVT::getVectorVT(Context, EltTy, EltCnt))) {
1581     EltCnt = EltCnt.divideCoefficientBy(2);
1582     NumVectorRegs <<= 1;
1583   }
1584 
1585   NumIntermediates = NumVectorRegs;
1586 
1587   EVT NewVT = EVT::getVectorVT(Context, EltTy, EltCnt);
1588   if (!isTypeLegal(NewVT))
1589     NewVT = EltTy;
1590   IntermediateVT = NewVT;
1591 
1592   MVT DestVT = getRegisterType(Context, NewVT);
1593   RegisterVT = DestVT;
1594 
1595   if (EVT(DestVT).bitsLT(NewVT)) {  // Value is expanded, e.g. i64 -> i16.
1596     TypeSize NewVTSize = NewVT.getSizeInBits();
1597     // Convert sizes such as i33 to i64.
1598     if (!isPowerOf2_32(NewVTSize.getKnownMinSize()))
1599       NewVTSize = NewVTSize.coefficientNextPowerOf2();
1600     return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
1601   }
1602 
1603   // Otherwise, promotion or legal types use the same number of registers as
1604   // the vector decimated to the appropriate level.
1605   return NumVectorRegs;
1606 }
1607 
1608 bool TargetLoweringBase::isSuitableForJumpTable(const SwitchInst *SI,
1609                                                 uint64_t NumCases,
1610                                                 uint64_t Range,
1611                                                 ProfileSummaryInfo *PSI,
1612                                                 BlockFrequencyInfo *BFI) const {
1613   // FIXME: This function check the maximum table size and density, but the
1614   // minimum size is not checked. It would be nice if the minimum size is
1615   // also combined within this function. Currently, the minimum size check is
1616   // performed in findJumpTable() in SelectionDAGBuiler and
1617   // getEstimatedNumberOfCaseClusters() in BasicTTIImpl.
1618   const bool OptForSize =
1619       SI->getParent()->getParent()->hasOptSize() ||
1620       llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI);
1621   const unsigned MinDensity = getMinimumJumpTableDensity(OptForSize);
1622   const unsigned MaxJumpTableSize = getMaximumJumpTableSize();
1623 
1624   // Check whether the number of cases is small enough and
1625   // the range is dense enough for a jump table.
1626   return (OptForSize || Range <= MaxJumpTableSize) &&
1627          (NumCases * 100 >= Range * MinDensity);
1628 }
1629 
1630 MVT TargetLoweringBase::getPreferredSwitchConditionType(LLVMContext &Context,
1631                                                         EVT ConditionVT) const {
1632   return getRegisterType(Context, ConditionVT);
1633 }
1634 
1635 /// Get the EVTs and ArgFlags collections that represent the legalized return
1636 /// type of the given function.  This does not require a DAG or a return value,
1637 /// and is suitable for use before any DAGs for the function are constructed.
1638 /// TODO: Move this out of TargetLowering.cpp.
1639 void llvm::GetReturnInfo(CallingConv::ID CC, Type *ReturnType,
1640                          AttributeList attr,
1641                          SmallVectorImpl<ISD::OutputArg> &Outs,
1642                          const TargetLowering &TLI, const DataLayout &DL) {
1643   SmallVector<EVT, 4> ValueVTs;
1644   ComputeValueVTs(TLI, DL, ReturnType, ValueVTs);
1645   unsigned NumValues = ValueVTs.size();
1646   if (NumValues == 0) return;
1647 
1648   for (unsigned j = 0, f = NumValues; j != f; ++j) {
1649     EVT VT = ValueVTs[j];
1650     ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1651 
1652     if (attr.hasRetAttr(Attribute::SExt))
1653       ExtendKind = ISD::SIGN_EXTEND;
1654     else if (attr.hasRetAttr(Attribute::ZExt))
1655       ExtendKind = ISD::ZERO_EXTEND;
1656 
1657     // FIXME: C calling convention requires the return type to be promoted to
1658     // at least 32-bit. But this is not necessary for non-C calling
1659     // conventions. The frontend should mark functions whose return values
1660     // require promoting with signext or zeroext attributes.
1661     if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1662       MVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
1663       if (VT.bitsLT(MinVT))
1664         VT = MinVT;
1665     }
1666 
1667     unsigned NumParts =
1668         TLI.getNumRegistersForCallingConv(ReturnType->getContext(), CC, VT);
1669     MVT PartVT =
1670         TLI.getRegisterTypeForCallingConv(ReturnType->getContext(), CC, VT);
1671 
1672     // 'inreg' on function refers to return value
1673     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1674     if (attr.hasRetAttr(Attribute::InReg))
1675       Flags.setInReg();
1676 
1677     // Propagate extension type if any
1678     if (attr.hasRetAttr(Attribute::SExt))
1679       Flags.setSExt();
1680     else if (attr.hasRetAttr(Attribute::ZExt))
1681       Flags.setZExt();
1682 
1683     for (unsigned i = 0; i < NumParts; ++i)
1684       Outs.push_back(ISD::OutputArg(Flags, PartVT, VT, /*isfixed=*/true, 0, 0));
1685   }
1686 }
1687 
1688 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1689 /// function arguments in the caller parameter area.  This is the actual
1690 /// alignment, not its logarithm.
1691 uint64_t TargetLoweringBase::getByValTypeAlignment(Type *Ty,
1692                                                    const DataLayout &DL) const {
1693   return DL.getABITypeAlign(Ty).value();
1694 }
1695 
1696 bool TargetLoweringBase::allowsMemoryAccessForAlignment(
1697     LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace,
1698     Align Alignment, MachineMemOperand::Flags Flags, bool *Fast) const {
1699   // Check if the specified alignment is sufficient based on the data layout.
1700   // TODO: While using the data layout works in practice, a better solution
1701   // would be to implement this check directly (make this a virtual function).
1702   // For example, the ABI alignment may change based on software platform while
1703   // this function should only be affected by hardware implementation.
1704   Type *Ty = VT.getTypeForEVT(Context);
1705   if (VT.isZeroSized() || Alignment >= DL.getABITypeAlign(Ty)) {
1706     // Assume that an access that meets the ABI-specified alignment is fast.
1707     if (Fast != nullptr)
1708       *Fast = true;
1709     return true;
1710   }
1711 
1712   // This is a misaligned access.
1713   return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Flags, Fast);
1714 }
1715 
1716 bool TargetLoweringBase::allowsMemoryAccessForAlignment(
1717     LLVMContext &Context, const DataLayout &DL, EVT VT,
1718     const MachineMemOperand &MMO, bool *Fast) const {
1719   return allowsMemoryAccessForAlignment(Context, DL, VT, MMO.getAddrSpace(),
1720                                         MMO.getAlign(), MMO.getFlags(), Fast);
1721 }
1722 
1723 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
1724                                             const DataLayout &DL, EVT VT,
1725                                             unsigned AddrSpace, Align Alignment,
1726                                             MachineMemOperand::Flags Flags,
1727                                             bool *Fast) const {
1728   return allowsMemoryAccessForAlignment(Context, DL, VT, AddrSpace, Alignment,
1729                                         Flags, Fast);
1730 }
1731 
1732 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
1733                                             const DataLayout &DL, EVT VT,
1734                                             const MachineMemOperand &MMO,
1735                                             bool *Fast) const {
1736   return allowsMemoryAccess(Context, DL, VT, MMO.getAddrSpace(), MMO.getAlign(),
1737                             MMO.getFlags(), Fast);
1738 }
1739 
1740 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
1741                                             const DataLayout &DL, LLT Ty,
1742                                             const MachineMemOperand &MMO,
1743                                             bool *Fast) const {
1744   EVT VT = getApproximateEVTForLLT(Ty, DL, Context);
1745   return allowsMemoryAccess(Context, DL, VT, MMO.getAddrSpace(), MMO.getAlign(),
1746                             MMO.getFlags(), Fast);
1747 }
1748 
1749 //===----------------------------------------------------------------------===//
1750 //  TargetTransformInfo Helpers
1751 //===----------------------------------------------------------------------===//
1752 
1753 int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const {
1754   enum InstructionOpcodes {
1755 #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM,
1756 #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM
1757 #include "llvm/IR/Instruction.def"
1758   };
1759   switch (static_cast<InstructionOpcodes>(Opcode)) {
1760   case Ret:            return 0;
1761   case Br:             return 0;
1762   case Switch:         return 0;
1763   case IndirectBr:     return 0;
1764   case Invoke:         return 0;
1765   case CallBr:         return 0;
1766   case Resume:         return 0;
1767   case Unreachable:    return 0;
1768   case CleanupRet:     return 0;
1769   case CatchRet:       return 0;
1770   case CatchPad:       return 0;
1771   case CatchSwitch:    return 0;
1772   case CleanupPad:     return 0;
1773   case FNeg:           return ISD::FNEG;
1774   case Add:            return ISD::ADD;
1775   case FAdd:           return ISD::FADD;
1776   case Sub:            return ISD::SUB;
1777   case FSub:           return ISD::FSUB;
1778   case Mul:            return ISD::MUL;
1779   case FMul:           return ISD::FMUL;
1780   case UDiv:           return ISD::UDIV;
1781   case SDiv:           return ISD::SDIV;
1782   case FDiv:           return ISD::FDIV;
1783   case URem:           return ISD::UREM;
1784   case SRem:           return ISD::SREM;
1785   case FRem:           return ISD::FREM;
1786   case Shl:            return ISD::SHL;
1787   case LShr:           return ISD::SRL;
1788   case AShr:           return ISD::SRA;
1789   case And:            return ISD::AND;
1790   case Or:             return ISD::OR;
1791   case Xor:            return ISD::XOR;
1792   case Alloca:         return 0;
1793   case Load:           return ISD::LOAD;
1794   case Store:          return ISD::STORE;
1795   case GetElementPtr:  return 0;
1796   case Fence:          return 0;
1797   case AtomicCmpXchg:  return 0;
1798   case AtomicRMW:      return 0;
1799   case Trunc:          return ISD::TRUNCATE;
1800   case ZExt:           return ISD::ZERO_EXTEND;
1801   case SExt:           return ISD::SIGN_EXTEND;
1802   case FPToUI:         return ISD::FP_TO_UINT;
1803   case FPToSI:         return ISD::FP_TO_SINT;
1804   case UIToFP:         return ISD::UINT_TO_FP;
1805   case SIToFP:         return ISD::SINT_TO_FP;
1806   case FPTrunc:        return ISD::FP_ROUND;
1807   case FPExt:          return ISD::FP_EXTEND;
1808   case PtrToInt:       return ISD::BITCAST;
1809   case IntToPtr:       return ISD::BITCAST;
1810   case BitCast:        return ISD::BITCAST;
1811   case AddrSpaceCast:  return ISD::ADDRSPACECAST;
1812   case ICmp:           return ISD::SETCC;
1813   case FCmp:           return ISD::SETCC;
1814   case PHI:            return 0;
1815   case Call:           return 0;
1816   case Select:         return ISD::SELECT;
1817   case UserOp1:        return 0;
1818   case UserOp2:        return 0;
1819   case VAArg:          return 0;
1820   case ExtractElement: return ISD::EXTRACT_VECTOR_ELT;
1821   case InsertElement:  return ISD::INSERT_VECTOR_ELT;
1822   case ShuffleVector:  return ISD::VECTOR_SHUFFLE;
1823   case ExtractValue:   return ISD::MERGE_VALUES;
1824   case InsertValue:    return ISD::MERGE_VALUES;
1825   case LandingPad:     return 0;
1826   case Freeze:         return ISD::FREEZE;
1827   }
1828 
1829   llvm_unreachable("Unknown instruction type encountered!");
1830 }
1831 
1832 std::pair<InstructionCost, MVT>
1833 TargetLoweringBase::getTypeLegalizationCost(const DataLayout &DL,
1834                                             Type *Ty) const {
1835   LLVMContext &C = Ty->getContext();
1836   EVT MTy = getValueType(DL, Ty);
1837 
1838   InstructionCost Cost = 1;
1839   // We keep legalizing the type until we find a legal kind. We assume that
1840   // the only operation that costs anything is the split. After splitting
1841   // we need to handle two types.
1842   while (true) {
1843     LegalizeKind LK = getTypeConversion(C, MTy);
1844 
1845     if (LK.first == TypeScalarizeScalableVector) {
1846       // Ensure we return a sensible simple VT here, since many callers of this
1847       // function require it.
1848       MVT VT = MTy.isSimple() ? MTy.getSimpleVT() : MVT::i64;
1849       return std::make_pair(InstructionCost::getInvalid(), VT);
1850     }
1851 
1852     if (LK.first == TypeLegal)
1853       return std::make_pair(Cost, MTy.getSimpleVT());
1854 
1855     if (LK.first == TypeSplitVector || LK.first == TypeExpandInteger)
1856       Cost *= 2;
1857 
1858     // Do not loop with f128 type.
1859     if (MTy == LK.second)
1860       return std::make_pair(Cost, MTy.getSimpleVT());
1861 
1862     // Keep legalizing the type.
1863     MTy = LK.second;
1864   }
1865 }
1866 
1867 Value *
1868 TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilderBase &IRB,
1869                                                        bool UseTLS) const {
1870   // compiler-rt provides a variable with a magic name.  Targets that do not
1871   // link with compiler-rt may also provide such a variable.
1872   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1873   const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
1874   auto UnsafeStackPtr =
1875       dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar));
1876 
1877   Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
1878 
1879   if (!UnsafeStackPtr) {
1880     auto TLSModel = UseTLS ?
1881         GlobalValue::InitialExecTLSModel :
1882         GlobalValue::NotThreadLocal;
1883     // The global variable is not defined yet, define it ourselves.
1884     // We use the initial-exec TLS model because we do not support the
1885     // variable living anywhere other than in the main executable.
1886     UnsafeStackPtr = new GlobalVariable(
1887         *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
1888         UnsafeStackPtrVar, nullptr, TLSModel);
1889   } else {
1890     // The variable exists, check its type and attributes.
1891     if (UnsafeStackPtr->getValueType() != StackPtrTy)
1892       report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
1893     if (UseTLS != UnsafeStackPtr->isThreadLocal())
1894       report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
1895                          (UseTLS ? "" : "not ") + "be thread-local");
1896   }
1897   return UnsafeStackPtr;
1898 }
1899 
1900 Value *
1901 TargetLoweringBase::getSafeStackPointerLocation(IRBuilderBase &IRB) const {
1902   if (!TM.getTargetTriple().isAndroid())
1903     return getDefaultSafeStackPointerLocation(IRB, true);
1904 
1905   // Android provides a libc function to retrieve the address of the current
1906   // thread's unsafe stack pointer.
1907   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1908   Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
1909   FunctionCallee Fn = M->getOrInsertFunction("__safestack_pointer_address",
1910                                              StackPtrTy->getPointerTo(0));
1911   return IRB.CreateCall(Fn);
1912 }
1913 
1914 //===----------------------------------------------------------------------===//
1915 //  Loop Strength Reduction hooks
1916 //===----------------------------------------------------------------------===//
1917 
1918 /// isLegalAddressingMode - Return true if the addressing mode represented
1919 /// by AM is legal for this target, for a load/store of the specified type.
1920 bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL,
1921                                                const AddrMode &AM, Type *Ty,
1922                                                unsigned AS, Instruction *I) const {
1923   // The default implementation of this implements a conservative RISCy, r+r and
1924   // r+i addr mode.
1925 
1926   // Allows a sign-extended 16-bit immediate field.
1927   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
1928     return false;
1929 
1930   // No global is ever allowed as a base.
1931   if (AM.BaseGV)
1932     return false;
1933 
1934   // Only support r+r,
1935   switch (AM.Scale) {
1936   case 0:  // "r+i" or just "i", depending on HasBaseReg.
1937     break;
1938   case 1:
1939     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
1940       return false;
1941     // Otherwise we have r+r or r+i.
1942     break;
1943   case 2:
1944     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
1945       return false;
1946     // Allow 2*r as r+r.
1947     break;
1948   default: // Don't allow n * r
1949     return false;
1950   }
1951 
1952   return true;
1953 }
1954 
1955 //===----------------------------------------------------------------------===//
1956 //  Stack Protector
1957 //===----------------------------------------------------------------------===//
1958 
1959 // For OpenBSD return its special guard variable. Otherwise return nullptr,
1960 // so that SelectionDAG handle SSP.
1961 Value *TargetLoweringBase::getIRStackGuard(IRBuilderBase &IRB) const {
1962   if (getTargetMachine().getTargetTriple().isOSOpenBSD()) {
1963     Module &M = *IRB.GetInsertBlock()->getParent()->getParent();
1964     PointerType *PtrTy = Type::getInt8PtrTy(M.getContext());
1965     Constant *C = M.getOrInsertGlobal("__guard_local", PtrTy);
1966     if (GlobalVariable *G = dyn_cast_or_null<GlobalVariable>(C))
1967       G->setVisibility(GlobalValue::HiddenVisibility);
1968     return C;
1969   }
1970   return nullptr;
1971 }
1972 
1973 // Currently only support "standard" __stack_chk_guard.
1974 // TODO: add LOAD_STACK_GUARD support.
1975 void TargetLoweringBase::insertSSPDeclarations(Module &M) const {
1976   if (!M.getNamedValue("__stack_chk_guard")) {
1977     auto *GV = new GlobalVariable(M, Type::getInt8PtrTy(M.getContext()), false,
1978                                   GlobalVariable::ExternalLinkage, nullptr,
1979                                   "__stack_chk_guard");
1980 
1981     // FreeBSD has "__stack_chk_guard" defined externally on libc.so
1982     if (TM.getRelocationModel() == Reloc::Static &&
1983         !TM.getTargetTriple().isWindowsGNUEnvironment() &&
1984         !TM.getTargetTriple().isOSFreeBSD())
1985       GV->setDSOLocal(true);
1986   }
1987 }
1988 
1989 // Currently only support "standard" __stack_chk_guard.
1990 // TODO: add LOAD_STACK_GUARD support.
1991 Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const {
1992   return M.getNamedValue("__stack_chk_guard");
1993 }
1994 
1995 Function *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const {
1996   return nullptr;
1997 }
1998 
1999 unsigned TargetLoweringBase::getMinimumJumpTableEntries() const {
2000   return MinimumJumpTableEntries;
2001 }
2002 
2003 void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) {
2004   MinimumJumpTableEntries = Val;
2005 }
2006 
2007 unsigned TargetLoweringBase::getMinimumJumpTableDensity(bool OptForSize) const {
2008   return OptForSize ? OptsizeJumpTableDensity : JumpTableDensity;
2009 }
2010 
2011 unsigned TargetLoweringBase::getMaximumJumpTableSize() const {
2012   return MaximumJumpTableSize;
2013 }
2014 
2015 void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) {
2016   MaximumJumpTableSize = Val;
2017 }
2018 
2019 bool TargetLoweringBase::isJumpTableRelative() const {
2020   return getTargetMachine().isPositionIndependent();
2021 }
2022 
2023 Align TargetLoweringBase::getPrefLoopAlignment(MachineLoop *ML) const {
2024   if (TM.Options.LoopAlignment)
2025     return Align(TM.Options.LoopAlignment);
2026   return PrefLoopAlignment;
2027 }
2028 
2029 unsigned TargetLoweringBase::getMaxPermittedBytesForAlignment(
2030     MachineBasicBlock *MBB) const {
2031   return MaxBytesForAlignment;
2032 }
2033 
2034 //===----------------------------------------------------------------------===//
2035 //  Reciprocal Estimates
2036 //===----------------------------------------------------------------------===//
2037 
2038 /// Get the reciprocal estimate attribute string for a function that will
2039 /// override the target defaults.
2040 static StringRef getRecipEstimateForFunc(MachineFunction &MF) {
2041   const Function &F = MF.getFunction();
2042   return F.getFnAttribute("reciprocal-estimates").getValueAsString();
2043 }
2044 
2045 /// Construct a string for the given reciprocal operation of the given type.
2046 /// This string should match the corresponding option to the front-end's
2047 /// "-mrecip" flag assuming those strings have been passed through in an
2048 /// attribute string. For example, "vec-divf" for a division of a vXf32.
2049 static std::string getReciprocalOpName(bool IsSqrt, EVT VT) {
2050   std::string Name = VT.isVector() ? "vec-" : "";
2051 
2052   Name += IsSqrt ? "sqrt" : "div";
2053 
2054   // TODO: Handle other float types?
2055   if (VT.getScalarType() == MVT::f64) {
2056     Name += "d";
2057   } else if (VT.getScalarType() == MVT::f16) {
2058     Name += "h";
2059   } else {
2060     assert(VT.getScalarType() == MVT::f32 &&
2061            "Unexpected FP type for reciprocal estimate");
2062     Name += "f";
2063   }
2064 
2065   return Name;
2066 }
2067 
2068 /// Return the character position and value (a single numeric character) of a
2069 /// customized refinement operation in the input string if it exists. Return
2070 /// false if there is no customized refinement step count.
2071 static bool parseRefinementStep(StringRef In, size_t &Position,
2072                                 uint8_t &Value) {
2073   const char RefStepToken = ':';
2074   Position = In.find(RefStepToken);
2075   if (Position == StringRef::npos)
2076     return false;
2077 
2078   StringRef RefStepString = In.substr(Position + 1);
2079   // Allow exactly one numeric character for the additional refinement
2080   // step parameter.
2081   if (RefStepString.size() == 1) {
2082     char RefStepChar = RefStepString[0];
2083     if (isDigit(RefStepChar)) {
2084       Value = RefStepChar - '0';
2085       return true;
2086     }
2087   }
2088   report_fatal_error("Invalid refinement step for -recip.");
2089 }
2090 
2091 /// For the input attribute string, return one of the ReciprocalEstimate enum
2092 /// status values (enabled, disabled, or not specified) for this operation on
2093 /// the specified data type.
2094 static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) {
2095   if (Override.empty())
2096     return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2097 
2098   SmallVector<StringRef, 4> OverrideVector;
2099   Override.split(OverrideVector, ',');
2100   unsigned NumArgs = OverrideVector.size();
2101 
2102   // Check if "all", "none", or "default" was specified.
2103   if (NumArgs == 1) {
2104     // Look for an optional setting of the number of refinement steps needed
2105     // for this type of reciprocal operation.
2106     size_t RefPos;
2107     uint8_t RefSteps;
2108     if (parseRefinementStep(Override, RefPos, RefSteps)) {
2109       // Split the string for further processing.
2110       Override = Override.substr(0, RefPos);
2111     }
2112 
2113     // All reciprocal types are enabled.
2114     if (Override == "all")
2115       return TargetLoweringBase::ReciprocalEstimate::Enabled;
2116 
2117     // All reciprocal types are disabled.
2118     if (Override == "none")
2119       return TargetLoweringBase::ReciprocalEstimate::Disabled;
2120 
2121     // Target defaults for enablement are used.
2122     if (Override == "default")
2123       return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2124   }
2125 
2126   // The attribute string may omit the size suffix ('f'/'d').
2127   std::string VTName = getReciprocalOpName(IsSqrt, VT);
2128   std::string VTNameNoSize = VTName;
2129   VTNameNoSize.pop_back();
2130   static const char DisabledPrefix = '!';
2131 
2132   for (StringRef RecipType : OverrideVector) {
2133     size_t RefPos;
2134     uint8_t RefSteps;
2135     if (parseRefinementStep(RecipType, RefPos, RefSteps))
2136       RecipType = RecipType.substr(0, RefPos);
2137 
2138     // Ignore the disablement token for string matching.
2139     bool IsDisabled = RecipType[0] == DisabledPrefix;
2140     if (IsDisabled)
2141       RecipType = RecipType.substr(1);
2142 
2143     if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
2144       return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled
2145                         : TargetLoweringBase::ReciprocalEstimate::Enabled;
2146   }
2147 
2148   return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2149 }
2150 
2151 /// For the input attribute string, return the customized refinement step count
2152 /// for this operation on the specified data type. If the step count does not
2153 /// exist, return the ReciprocalEstimate enum value for unspecified.
2154 static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) {
2155   if (Override.empty())
2156     return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2157 
2158   SmallVector<StringRef, 4> OverrideVector;
2159   Override.split(OverrideVector, ',');
2160   unsigned NumArgs = OverrideVector.size();
2161 
2162   // Check if "all", "default", or "none" was specified.
2163   if (NumArgs == 1) {
2164     // Look for an optional setting of the number of refinement steps needed
2165     // for this type of reciprocal operation.
2166     size_t RefPos;
2167     uint8_t RefSteps;
2168     if (!parseRefinementStep(Override, RefPos, RefSteps))
2169       return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2170 
2171     // Split the string for further processing.
2172     Override = Override.substr(0, RefPos);
2173     assert(Override != "none" &&
2174            "Disabled reciprocals, but specifed refinement steps?");
2175 
2176     // If this is a general override, return the specified number of steps.
2177     if (Override == "all" || Override == "default")
2178       return RefSteps;
2179   }
2180 
2181   // The attribute string may omit the size suffix ('f'/'d').
2182   std::string VTName = getReciprocalOpName(IsSqrt, VT);
2183   std::string VTNameNoSize = VTName;
2184   VTNameNoSize.pop_back();
2185 
2186   for (StringRef RecipType : OverrideVector) {
2187     size_t RefPos;
2188     uint8_t RefSteps;
2189     if (!parseRefinementStep(RecipType, RefPos, RefSteps))
2190       continue;
2191 
2192     RecipType = RecipType.substr(0, RefPos);
2193     if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
2194       return RefSteps;
2195   }
2196 
2197   return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2198 }
2199 
2200 int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT,
2201                                                     MachineFunction &MF) const {
2202   return getOpEnabled(true, VT, getRecipEstimateForFunc(MF));
2203 }
2204 
2205 int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT,
2206                                                    MachineFunction &MF) const {
2207   return getOpEnabled(false, VT, getRecipEstimateForFunc(MF));
2208 }
2209 
2210 int TargetLoweringBase::getSqrtRefinementSteps(EVT VT,
2211                                                MachineFunction &MF) const {
2212   return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF));
2213 }
2214 
2215 int TargetLoweringBase::getDivRefinementSteps(EVT VT,
2216                                               MachineFunction &MF) const {
2217   return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF));
2218 }
2219 
2220 void TargetLoweringBase::finalizeLowering(MachineFunction &MF) const {
2221   MF.getRegInfo().freezeReservedRegs(MF);
2222 }
2223 
2224 MachineMemOperand::Flags
2225 TargetLoweringBase::getLoadMemOperandFlags(const LoadInst &LI,
2226                                            const DataLayout &DL) const {
2227   MachineMemOperand::Flags Flags = MachineMemOperand::MOLoad;
2228   if (LI.isVolatile())
2229     Flags |= MachineMemOperand::MOVolatile;
2230 
2231   if (LI.hasMetadata(LLVMContext::MD_nontemporal))
2232     Flags |= MachineMemOperand::MONonTemporal;
2233 
2234   if (LI.hasMetadata(LLVMContext::MD_invariant_load))
2235     Flags |= MachineMemOperand::MOInvariant;
2236 
2237   if (isDereferenceablePointer(LI.getPointerOperand(), LI.getType(), DL))
2238     Flags |= MachineMemOperand::MODereferenceable;
2239 
2240   Flags |= getTargetMMOFlags(LI);
2241   return Flags;
2242 }
2243 
2244 MachineMemOperand::Flags
2245 TargetLoweringBase::getStoreMemOperandFlags(const StoreInst &SI,
2246                                             const DataLayout &DL) const {
2247   MachineMemOperand::Flags Flags = MachineMemOperand::MOStore;
2248 
2249   if (SI.isVolatile())
2250     Flags |= MachineMemOperand::MOVolatile;
2251 
2252   if (SI.hasMetadata(LLVMContext::MD_nontemporal))
2253     Flags |= MachineMemOperand::MONonTemporal;
2254 
2255   // FIXME: Not preserving dereferenceable
2256   Flags |= getTargetMMOFlags(SI);
2257   return Flags;
2258 }
2259 
2260 MachineMemOperand::Flags
2261 TargetLoweringBase::getAtomicMemOperandFlags(const Instruction &AI,
2262                                              const DataLayout &DL) const {
2263   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
2264 
2265   if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(&AI)) {
2266     if (RMW->isVolatile())
2267       Flags |= MachineMemOperand::MOVolatile;
2268   } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(&AI)) {
2269     if (CmpX->isVolatile())
2270       Flags |= MachineMemOperand::MOVolatile;
2271   } else
2272     llvm_unreachable("not an atomic instruction");
2273 
2274   // FIXME: Not preserving dereferenceable
2275   Flags |= getTargetMMOFlags(AI);
2276   return Flags;
2277 }
2278 
2279 Instruction *TargetLoweringBase::emitLeadingFence(IRBuilderBase &Builder,
2280                                                   Instruction *Inst,
2281                                                   AtomicOrdering Ord) const {
2282   if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore())
2283     return Builder.CreateFence(Ord);
2284   else
2285     return nullptr;
2286 }
2287 
2288 Instruction *TargetLoweringBase::emitTrailingFence(IRBuilderBase &Builder,
2289                                                    Instruction *Inst,
2290                                                    AtomicOrdering Ord) const {
2291   if (isAcquireOrStronger(Ord))
2292     return Builder.CreateFence(Ord);
2293   else
2294     return nullptr;
2295 }
2296 
2297 //===----------------------------------------------------------------------===//
2298 //  GlobalISel Hooks
2299 //===----------------------------------------------------------------------===//
2300 
2301 bool TargetLoweringBase::shouldLocalize(const MachineInstr &MI,
2302                                         const TargetTransformInfo *TTI) const {
2303   auto &MF = *MI.getMF();
2304   auto &MRI = MF.getRegInfo();
2305   // Assuming a spill and reload of a value has a cost of 1 instruction each,
2306   // this helper function computes the maximum number of uses we should consider
2307   // for remat. E.g. on arm64 global addresses take 2 insts to materialize. We
2308   // break even in terms of code size when the original MI has 2 users vs
2309   // choosing to potentially spill. Any more than 2 users we we have a net code
2310   // size increase. This doesn't take into account register pressure though.
2311   auto maxUses = [](unsigned RematCost) {
2312     // A cost of 1 means remats are basically free.
2313     if (RematCost == 1)
2314       return UINT_MAX;
2315     if (RematCost == 2)
2316       return 2U;
2317 
2318     // Remat is too expensive, only sink if there's one user.
2319     if (RematCost > 2)
2320       return 1U;
2321     llvm_unreachable("Unexpected remat cost");
2322   };
2323 
2324   // Helper to walk through uses and terminate if we've reached a limit. Saves
2325   // us spending time traversing uses if all we want to know is if it's >= min.
2326   auto isUsesAtMost = [&](unsigned Reg, unsigned MaxUses) {
2327     unsigned NumUses = 0;
2328     auto UI = MRI.use_instr_nodbg_begin(Reg), UE = MRI.use_instr_nodbg_end();
2329     for (; UI != UE && NumUses < MaxUses; ++UI) {
2330       NumUses++;
2331     }
2332     // If we haven't reached the end yet then there are more than MaxUses users.
2333     return UI == UE;
2334   };
2335 
2336   switch (MI.getOpcode()) {
2337   default:
2338     return false;
2339   // Constants-like instructions should be close to their users.
2340   // We don't want long live-ranges for them.
2341   case TargetOpcode::G_CONSTANT:
2342   case TargetOpcode::G_FCONSTANT:
2343   case TargetOpcode::G_FRAME_INDEX:
2344   case TargetOpcode::G_INTTOPTR:
2345     return true;
2346   case TargetOpcode::G_GLOBAL_VALUE: {
2347     unsigned RematCost = TTI->getGISelRematGlobalCost();
2348     Register Reg = MI.getOperand(0).getReg();
2349     unsigned MaxUses = maxUses(RematCost);
2350     if (MaxUses == UINT_MAX)
2351       return true; // Remats are "free" so always localize.
2352     bool B = isUsesAtMost(Reg, MaxUses);
2353     return B;
2354   }
2355   }
2356 }
2357