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