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