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