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/Target/TargetLowering.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.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/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <cctype>
41 using namespace llvm;
42 
43 static cl::opt<bool> JumpIsExpensiveOverride(
44     "jump-is-expensive", cl::init(false),
45     cl::desc("Do not create extra branches to split comparison logic."),
46     cl::Hidden);
47 
48 static cl::opt<unsigned> MinimumJumpTableEntries
49   ("min-jump-table-entries", cl::init(4), cl::Hidden,
50    cl::desc("Set minimum number of entries to use a jump table."));
51 
52 static cl::opt<unsigned> MaximumJumpTableSize
53   ("max-jump-table-size", cl::init(0), cl::Hidden,
54    cl::desc("Set maximum size of jump tables; zero for no limit."));
55 
56 // Although this default value is arbitrary, it is not random. It is assumed
57 // that a condition that evaluates the same way by a higher percentage than this
58 // is best represented as control flow. Therefore, the default value N should be
59 // set such that the win from N% correct executions is greater than the loss
60 // from (100 - N)% mispredicted executions for the majority of intended targets.
61 static cl::opt<int> MinPercentageForPredictableBranch(
62     "min-predictable-branch", cl::init(99),
63     cl::desc("Minimum percentage (0-100) that a condition must be either true "
64              "or false to assume that the condition is predictable"),
65     cl::Hidden);
66 
67 /// InitLibcallNames - Set default libcall names.
68 ///
69 static void InitLibcallNames(const char **Names, const Triple &TT) {
70   Names[RTLIB::SHL_I16] = "__ashlhi3";
71   Names[RTLIB::SHL_I32] = "__ashlsi3";
72   Names[RTLIB::SHL_I64] = "__ashldi3";
73   Names[RTLIB::SHL_I128] = "__ashlti3";
74   Names[RTLIB::SRL_I16] = "__lshrhi3";
75   Names[RTLIB::SRL_I32] = "__lshrsi3";
76   Names[RTLIB::SRL_I64] = "__lshrdi3";
77   Names[RTLIB::SRL_I128] = "__lshrti3";
78   Names[RTLIB::SRA_I16] = "__ashrhi3";
79   Names[RTLIB::SRA_I32] = "__ashrsi3";
80   Names[RTLIB::SRA_I64] = "__ashrdi3";
81   Names[RTLIB::SRA_I128] = "__ashrti3";
82   Names[RTLIB::MUL_I8] = "__mulqi3";
83   Names[RTLIB::MUL_I16] = "__mulhi3";
84   Names[RTLIB::MUL_I32] = "__mulsi3";
85   Names[RTLIB::MUL_I64] = "__muldi3";
86   Names[RTLIB::MUL_I128] = "__multi3";
87   Names[RTLIB::MULO_I32] = "__mulosi4";
88   Names[RTLIB::MULO_I64] = "__mulodi4";
89   Names[RTLIB::MULO_I128] = "__muloti4";
90   Names[RTLIB::SDIV_I8] = "__divqi3";
91   Names[RTLIB::SDIV_I16] = "__divhi3";
92   Names[RTLIB::SDIV_I32] = "__divsi3";
93   Names[RTLIB::SDIV_I64] = "__divdi3";
94   Names[RTLIB::SDIV_I128] = "__divti3";
95   Names[RTLIB::UDIV_I8] = "__udivqi3";
96   Names[RTLIB::UDIV_I16] = "__udivhi3";
97   Names[RTLIB::UDIV_I32] = "__udivsi3";
98   Names[RTLIB::UDIV_I64] = "__udivdi3";
99   Names[RTLIB::UDIV_I128] = "__udivti3";
100   Names[RTLIB::SREM_I8] = "__modqi3";
101   Names[RTLIB::SREM_I16] = "__modhi3";
102   Names[RTLIB::SREM_I32] = "__modsi3";
103   Names[RTLIB::SREM_I64] = "__moddi3";
104   Names[RTLIB::SREM_I128] = "__modti3";
105   Names[RTLIB::UREM_I8] = "__umodqi3";
106   Names[RTLIB::UREM_I16] = "__umodhi3";
107   Names[RTLIB::UREM_I32] = "__umodsi3";
108   Names[RTLIB::UREM_I64] = "__umoddi3";
109   Names[RTLIB::UREM_I128] = "__umodti3";
110 
111   Names[RTLIB::NEG_I32] = "__negsi2";
112   Names[RTLIB::NEG_I64] = "__negdi2";
113   Names[RTLIB::ADD_F32] = "__addsf3";
114   Names[RTLIB::ADD_F64] = "__adddf3";
115   Names[RTLIB::ADD_F80] = "__addxf3";
116   Names[RTLIB::ADD_F128] = "__addtf3";
117   Names[RTLIB::ADD_PPCF128] = "__gcc_qadd";
118   Names[RTLIB::SUB_F32] = "__subsf3";
119   Names[RTLIB::SUB_F64] = "__subdf3";
120   Names[RTLIB::SUB_F80] = "__subxf3";
121   Names[RTLIB::SUB_F128] = "__subtf3";
122   Names[RTLIB::SUB_PPCF128] = "__gcc_qsub";
123   Names[RTLIB::MUL_F32] = "__mulsf3";
124   Names[RTLIB::MUL_F64] = "__muldf3";
125   Names[RTLIB::MUL_F80] = "__mulxf3";
126   Names[RTLIB::MUL_F128] = "__multf3";
127   Names[RTLIB::MUL_PPCF128] = "__gcc_qmul";
128   Names[RTLIB::DIV_F32] = "__divsf3";
129   Names[RTLIB::DIV_F64] = "__divdf3";
130   Names[RTLIB::DIV_F80] = "__divxf3";
131   Names[RTLIB::DIV_F128] = "__divtf3";
132   Names[RTLIB::DIV_PPCF128] = "__gcc_qdiv";
133   Names[RTLIB::REM_F32] = "fmodf";
134   Names[RTLIB::REM_F64] = "fmod";
135   Names[RTLIB::REM_F80] = "fmodl";
136   Names[RTLIB::REM_F128] = "fmodl";
137   Names[RTLIB::REM_PPCF128] = "fmodl";
138   Names[RTLIB::FMA_F32] = "fmaf";
139   Names[RTLIB::FMA_F64] = "fma";
140   Names[RTLIB::FMA_F80] = "fmal";
141   Names[RTLIB::FMA_F128] = "fmal";
142   Names[RTLIB::FMA_PPCF128] = "fmal";
143   Names[RTLIB::POWI_F32] = "__powisf2";
144   Names[RTLIB::POWI_F64] = "__powidf2";
145   Names[RTLIB::POWI_F80] = "__powixf2";
146   Names[RTLIB::POWI_F128] = "__powitf2";
147   Names[RTLIB::POWI_PPCF128] = "__powitf2";
148   Names[RTLIB::SQRT_F32] = "sqrtf";
149   Names[RTLIB::SQRT_F64] = "sqrt";
150   Names[RTLIB::SQRT_F80] = "sqrtl";
151   Names[RTLIB::SQRT_F128] = "sqrtl";
152   Names[RTLIB::SQRT_PPCF128] = "sqrtl";
153   Names[RTLIB::LOG_F32] = "logf";
154   Names[RTLIB::LOG_F64] = "log";
155   Names[RTLIB::LOG_F80] = "logl";
156   Names[RTLIB::LOG_F128] = "logl";
157   Names[RTLIB::LOG_PPCF128] = "logl";
158   Names[RTLIB::LOG2_F32] = "log2f";
159   Names[RTLIB::LOG2_F64] = "log2";
160   Names[RTLIB::LOG2_F80] = "log2l";
161   Names[RTLIB::LOG2_F128] = "log2l";
162   Names[RTLIB::LOG2_PPCF128] = "log2l";
163   Names[RTLIB::LOG10_F32] = "log10f";
164   Names[RTLIB::LOG10_F64] = "log10";
165   Names[RTLIB::LOG10_F80] = "log10l";
166   Names[RTLIB::LOG10_F128] = "log10l";
167   Names[RTLIB::LOG10_PPCF128] = "log10l";
168   Names[RTLIB::EXP_F32] = "expf";
169   Names[RTLIB::EXP_F64] = "exp";
170   Names[RTLIB::EXP_F80] = "expl";
171   Names[RTLIB::EXP_F128] = "expl";
172   Names[RTLIB::EXP_PPCF128] = "expl";
173   Names[RTLIB::EXP2_F32] = "exp2f";
174   Names[RTLIB::EXP2_F64] = "exp2";
175   Names[RTLIB::EXP2_F80] = "exp2l";
176   Names[RTLIB::EXP2_F128] = "exp2l";
177   Names[RTLIB::EXP2_PPCF128] = "exp2l";
178   Names[RTLIB::SIN_F32] = "sinf";
179   Names[RTLIB::SIN_F64] = "sin";
180   Names[RTLIB::SIN_F80] = "sinl";
181   Names[RTLIB::SIN_F128] = "sinl";
182   Names[RTLIB::SIN_PPCF128] = "sinl";
183   Names[RTLIB::COS_F32] = "cosf";
184   Names[RTLIB::COS_F64] = "cos";
185   Names[RTLIB::COS_F80] = "cosl";
186   Names[RTLIB::COS_F128] = "cosl";
187   Names[RTLIB::COS_PPCF128] = "cosl";
188   Names[RTLIB::POW_F32] = "powf";
189   Names[RTLIB::POW_F64] = "pow";
190   Names[RTLIB::POW_F80] = "powl";
191   Names[RTLIB::POW_F128] = "powl";
192   Names[RTLIB::POW_PPCF128] = "powl";
193   Names[RTLIB::CEIL_F32] = "ceilf";
194   Names[RTLIB::CEIL_F64] = "ceil";
195   Names[RTLIB::CEIL_F80] = "ceill";
196   Names[RTLIB::CEIL_F128] = "ceill";
197   Names[RTLIB::CEIL_PPCF128] = "ceill";
198   Names[RTLIB::TRUNC_F32] = "truncf";
199   Names[RTLIB::TRUNC_F64] = "trunc";
200   Names[RTLIB::TRUNC_F80] = "truncl";
201   Names[RTLIB::TRUNC_F128] = "truncl";
202   Names[RTLIB::TRUNC_PPCF128] = "truncl";
203   Names[RTLIB::RINT_F32] = "rintf";
204   Names[RTLIB::RINT_F64] = "rint";
205   Names[RTLIB::RINT_F80] = "rintl";
206   Names[RTLIB::RINT_F128] = "rintl";
207   Names[RTLIB::RINT_PPCF128] = "rintl";
208   Names[RTLIB::NEARBYINT_F32] = "nearbyintf";
209   Names[RTLIB::NEARBYINT_F64] = "nearbyint";
210   Names[RTLIB::NEARBYINT_F80] = "nearbyintl";
211   Names[RTLIB::NEARBYINT_F128] = "nearbyintl";
212   Names[RTLIB::NEARBYINT_PPCF128] = "nearbyintl";
213   Names[RTLIB::ROUND_F32] = "roundf";
214   Names[RTLIB::ROUND_F64] = "round";
215   Names[RTLIB::ROUND_F80] = "roundl";
216   Names[RTLIB::ROUND_F128] = "roundl";
217   Names[RTLIB::ROUND_PPCF128] = "roundl";
218   Names[RTLIB::FLOOR_F32] = "floorf";
219   Names[RTLIB::FLOOR_F64] = "floor";
220   Names[RTLIB::FLOOR_F80] = "floorl";
221   Names[RTLIB::FLOOR_F128] = "floorl";
222   Names[RTLIB::FLOOR_PPCF128] = "floorl";
223   Names[RTLIB::FMIN_F32] = "fminf";
224   Names[RTLIB::FMIN_F64] = "fmin";
225   Names[RTLIB::FMIN_F80] = "fminl";
226   Names[RTLIB::FMIN_F128] = "fminl";
227   Names[RTLIB::FMIN_PPCF128] = "fminl";
228   Names[RTLIB::FMAX_F32] = "fmaxf";
229   Names[RTLIB::FMAX_F64] = "fmax";
230   Names[RTLIB::FMAX_F80] = "fmaxl";
231   Names[RTLIB::FMAX_F128] = "fmaxl";
232   Names[RTLIB::FMAX_PPCF128] = "fmaxl";
233   Names[RTLIB::ROUND_F32] = "roundf";
234   Names[RTLIB::ROUND_F64] = "round";
235   Names[RTLIB::ROUND_F80] = "roundl";
236   Names[RTLIB::ROUND_F128] = "roundl";
237   Names[RTLIB::ROUND_PPCF128] = "roundl";
238   Names[RTLIB::COPYSIGN_F32] = "copysignf";
239   Names[RTLIB::COPYSIGN_F64] = "copysign";
240   Names[RTLIB::COPYSIGN_F80] = "copysignl";
241   Names[RTLIB::COPYSIGN_F128] = "copysignl";
242   Names[RTLIB::COPYSIGN_PPCF128] = "copysignl";
243   Names[RTLIB::FPEXT_F32_PPCF128] = "__gcc_stoq";
244   Names[RTLIB::FPEXT_F64_PPCF128] = "__gcc_dtoq";
245   Names[RTLIB::FPEXT_F64_F128] = "__extenddftf2";
246   Names[RTLIB::FPEXT_F32_F128] = "__extendsftf2";
247   Names[RTLIB::FPEXT_F32_F64] = "__extendsfdf2";
248   if (TT.isOSDarwin()) {
249     // For f16/f32 conversions, Darwin uses the standard naming scheme, instead
250     // of the gnueabi-style __gnu_*_ieee.
251     // FIXME: What about other targets?
252     Names[RTLIB::FPEXT_F16_F32] = "__extendhfsf2";
253     Names[RTLIB::FPROUND_F32_F16] = "__truncsfhf2";
254   } else {
255     Names[RTLIB::FPEXT_F16_F32] = "__gnu_h2f_ieee";
256     Names[RTLIB::FPROUND_F32_F16] = "__gnu_f2h_ieee";
257   }
258   Names[RTLIB::FPROUND_F64_F16] = "__truncdfhf2";
259   Names[RTLIB::FPROUND_F80_F16] = "__truncxfhf2";
260   Names[RTLIB::FPROUND_F128_F16] = "__trunctfhf2";
261   Names[RTLIB::FPROUND_PPCF128_F16] = "__trunctfhf2";
262   Names[RTLIB::FPROUND_F64_F32] = "__truncdfsf2";
263   Names[RTLIB::FPROUND_F80_F32] = "__truncxfsf2";
264   Names[RTLIB::FPROUND_F128_F32] = "__trunctfsf2";
265   Names[RTLIB::FPROUND_PPCF128_F32] = "__gcc_qtos";
266   Names[RTLIB::FPROUND_F80_F64] = "__truncxfdf2";
267   Names[RTLIB::FPROUND_F128_F64] = "__trunctfdf2";
268   Names[RTLIB::FPROUND_PPCF128_F64] = "__gcc_qtod";
269   Names[RTLIB::FPTOSINT_F32_I32] = "__fixsfsi";
270   Names[RTLIB::FPTOSINT_F32_I64] = "__fixsfdi";
271   Names[RTLIB::FPTOSINT_F32_I128] = "__fixsfti";
272   Names[RTLIB::FPTOSINT_F64_I32] = "__fixdfsi";
273   Names[RTLIB::FPTOSINT_F64_I64] = "__fixdfdi";
274   Names[RTLIB::FPTOSINT_F64_I128] = "__fixdfti";
275   Names[RTLIB::FPTOSINT_F80_I32] = "__fixxfsi";
276   Names[RTLIB::FPTOSINT_F80_I64] = "__fixxfdi";
277   Names[RTLIB::FPTOSINT_F80_I128] = "__fixxfti";
278   Names[RTLIB::FPTOSINT_F128_I32] = "__fixtfsi";
279   Names[RTLIB::FPTOSINT_F128_I64] = "__fixtfdi";
280   Names[RTLIB::FPTOSINT_F128_I128] = "__fixtfti";
281   Names[RTLIB::FPTOSINT_PPCF128_I32] = "__gcc_qtou";
282   Names[RTLIB::FPTOSINT_PPCF128_I64] = "__fixtfdi";
283   Names[RTLIB::FPTOSINT_PPCF128_I128] = "__fixtfti";
284   Names[RTLIB::FPTOUINT_F32_I32] = "__fixunssfsi";
285   Names[RTLIB::FPTOUINT_F32_I64] = "__fixunssfdi";
286   Names[RTLIB::FPTOUINT_F32_I128] = "__fixunssfti";
287   Names[RTLIB::FPTOUINT_F64_I32] = "__fixunsdfsi";
288   Names[RTLIB::FPTOUINT_F64_I64] = "__fixunsdfdi";
289   Names[RTLIB::FPTOUINT_F64_I128] = "__fixunsdfti";
290   Names[RTLIB::FPTOUINT_F80_I32] = "__fixunsxfsi";
291   Names[RTLIB::FPTOUINT_F80_I64] = "__fixunsxfdi";
292   Names[RTLIB::FPTOUINT_F80_I128] = "__fixunsxfti";
293   Names[RTLIB::FPTOUINT_F128_I32] = "__fixunstfsi";
294   Names[RTLIB::FPTOUINT_F128_I64] = "__fixunstfdi";
295   Names[RTLIB::FPTOUINT_F128_I128] = "__fixunstfti";
296   Names[RTLIB::FPTOUINT_PPCF128_I32] = "__fixunstfsi";
297   Names[RTLIB::FPTOUINT_PPCF128_I64] = "__fixunstfdi";
298   Names[RTLIB::FPTOUINT_PPCF128_I128] = "__fixunstfti";
299   Names[RTLIB::SINTTOFP_I32_F32] = "__floatsisf";
300   Names[RTLIB::SINTTOFP_I32_F64] = "__floatsidf";
301   Names[RTLIB::SINTTOFP_I32_F80] = "__floatsixf";
302   Names[RTLIB::SINTTOFP_I32_F128] = "__floatsitf";
303   Names[RTLIB::SINTTOFP_I32_PPCF128] = "__gcc_itoq";
304   Names[RTLIB::SINTTOFP_I64_F32] = "__floatdisf";
305   Names[RTLIB::SINTTOFP_I64_F64] = "__floatdidf";
306   Names[RTLIB::SINTTOFP_I64_F80] = "__floatdixf";
307   Names[RTLIB::SINTTOFP_I64_F128] = "__floatditf";
308   Names[RTLIB::SINTTOFP_I64_PPCF128] = "__floatditf";
309   Names[RTLIB::SINTTOFP_I128_F32] = "__floattisf";
310   Names[RTLIB::SINTTOFP_I128_F64] = "__floattidf";
311   Names[RTLIB::SINTTOFP_I128_F80] = "__floattixf";
312   Names[RTLIB::SINTTOFP_I128_F128] = "__floattitf";
313   Names[RTLIB::SINTTOFP_I128_PPCF128] = "__floattitf";
314   Names[RTLIB::UINTTOFP_I32_F32] = "__floatunsisf";
315   Names[RTLIB::UINTTOFP_I32_F64] = "__floatunsidf";
316   Names[RTLIB::UINTTOFP_I32_F80] = "__floatunsixf";
317   Names[RTLIB::UINTTOFP_I32_F128] = "__floatunsitf";
318   Names[RTLIB::UINTTOFP_I32_PPCF128] = "__gcc_utoq";
319   Names[RTLIB::UINTTOFP_I64_F32] = "__floatundisf";
320   Names[RTLIB::UINTTOFP_I64_F64] = "__floatundidf";
321   Names[RTLIB::UINTTOFP_I64_F80] = "__floatundixf";
322   Names[RTLIB::UINTTOFP_I64_F128] = "__floatunditf";
323   Names[RTLIB::UINTTOFP_I64_PPCF128] = "__floatunditf";
324   Names[RTLIB::UINTTOFP_I128_F32] = "__floatuntisf";
325   Names[RTLIB::UINTTOFP_I128_F64] = "__floatuntidf";
326   Names[RTLIB::UINTTOFP_I128_F80] = "__floatuntixf";
327   Names[RTLIB::UINTTOFP_I128_F128] = "__floatuntitf";
328   Names[RTLIB::UINTTOFP_I128_PPCF128] = "__floatuntitf";
329   Names[RTLIB::OEQ_F32] = "__eqsf2";
330   Names[RTLIB::OEQ_F64] = "__eqdf2";
331   Names[RTLIB::OEQ_F128] = "__eqtf2";
332   Names[RTLIB::OEQ_PPCF128] = "__gcc_qeq";
333   Names[RTLIB::UNE_F32] = "__nesf2";
334   Names[RTLIB::UNE_F64] = "__nedf2";
335   Names[RTLIB::UNE_F128] = "__netf2";
336   Names[RTLIB::UNE_PPCF128] = "__gcc_qne";
337   Names[RTLIB::OGE_F32] = "__gesf2";
338   Names[RTLIB::OGE_F64] = "__gedf2";
339   Names[RTLIB::OGE_F128] = "__getf2";
340   Names[RTLIB::OGE_PPCF128] = "__gcc_qge";
341   Names[RTLIB::OLT_F32] = "__ltsf2";
342   Names[RTLIB::OLT_F64] = "__ltdf2";
343   Names[RTLIB::OLT_F128] = "__lttf2";
344   Names[RTLIB::OLT_PPCF128] = "__gcc_qlt";
345   Names[RTLIB::OLE_F32] = "__lesf2";
346   Names[RTLIB::OLE_F64] = "__ledf2";
347   Names[RTLIB::OLE_F128] = "__letf2";
348   Names[RTLIB::OLE_PPCF128] = "__gcc_qle";
349   Names[RTLIB::OGT_F32] = "__gtsf2";
350   Names[RTLIB::OGT_F64] = "__gtdf2";
351   Names[RTLIB::OGT_F128] = "__gttf2";
352   Names[RTLIB::OGT_PPCF128] = "__gcc_qgt";
353   Names[RTLIB::UO_F32] = "__unordsf2";
354   Names[RTLIB::UO_F64] = "__unorddf2";
355   Names[RTLIB::UO_F128] = "__unordtf2";
356   Names[RTLIB::UO_PPCF128] = "__gcc_qunord";
357   Names[RTLIB::O_F32] = "__unordsf2";
358   Names[RTLIB::O_F64] = "__unorddf2";
359   Names[RTLIB::O_F128] = "__unordtf2";
360   Names[RTLIB::O_PPCF128] = "__gcc_qunord";
361   Names[RTLIB::MEMCPY] = "memcpy";
362   Names[RTLIB::MEMMOVE] = "memmove";
363   Names[RTLIB::MEMSET] = "memset";
364   Names[RTLIB::UNWIND_RESUME] = "_Unwind_Resume";
365   Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1] = "__sync_val_compare_and_swap_1";
366   Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2] = "__sync_val_compare_and_swap_2";
367   Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4] = "__sync_val_compare_and_swap_4";
368   Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8] = "__sync_val_compare_and_swap_8";
369   Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_16] = "__sync_val_compare_and_swap_16";
370   Names[RTLIB::SYNC_LOCK_TEST_AND_SET_1] = "__sync_lock_test_and_set_1";
371   Names[RTLIB::SYNC_LOCK_TEST_AND_SET_2] = "__sync_lock_test_and_set_2";
372   Names[RTLIB::SYNC_LOCK_TEST_AND_SET_4] = "__sync_lock_test_and_set_4";
373   Names[RTLIB::SYNC_LOCK_TEST_AND_SET_8] = "__sync_lock_test_and_set_8";
374   Names[RTLIB::SYNC_LOCK_TEST_AND_SET_16] = "__sync_lock_test_and_set_16";
375   Names[RTLIB::SYNC_FETCH_AND_ADD_1] = "__sync_fetch_and_add_1";
376   Names[RTLIB::SYNC_FETCH_AND_ADD_2] = "__sync_fetch_and_add_2";
377   Names[RTLIB::SYNC_FETCH_AND_ADD_4] = "__sync_fetch_and_add_4";
378   Names[RTLIB::SYNC_FETCH_AND_ADD_8] = "__sync_fetch_and_add_8";
379   Names[RTLIB::SYNC_FETCH_AND_ADD_16] = "__sync_fetch_and_add_16";
380   Names[RTLIB::SYNC_FETCH_AND_SUB_1] = "__sync_fetch_and_sub_1";
381   Names[RTLIB::SYNC_FETCH_AND_SUB_2] = "__sync_fetch_and_sub_2";
382   Names[RTLIB::SYNC_FETCH_AND_SUB_4] = "__sync_fetch_and_sub_4";
383   Names[RTLIB::SYNC_FETCH_AND_SUB_8] = "__sync_fetch_and_sub_8";
384   Names[RTLIB::SYNC_FETCH_AND_SUB_16] = "__sync_fetch_and_sub_16";
385   Names[RTLIB::SYNC_FETCH_AND_AND_1] = "__sync_fetch_and_and_1";
386   Names[RTLIB::SYNC_FETCH_AND_AND_2] = "__sync_fetch_and_and_2";
387   Names[RTLIB::SYNC_FETCH_AND_AND_4] = "__sync_fetch_and_and_4";
388   Names[RTLIB::SYNC_FETCH_AND_AND_8] = "__sync_fetch_and_and_8";
389   Names[RTLIB::SYNC_FETCH_AND_AND_16] = "__sync_fetch_and_and_16";
390   Names[RTLIB::SYNC_FETCH_AND_OR_1] = "__sync_fetch_and_or_1";
391   Names[RTLIB::SYNC_FETCH_AND_OR_2] = "__sync_fetch_and_or_2";
392   Names[RTLIB::SYNC_FETCH_AND_OR_4] = "__sync_fetch_and_or_4";
393   Names[RTLIB::SYNC_FETCH_AND_OR_8] = "__sync_fetch_and_or_8";
394   Names[RTLIB::SYNC_FETCH_AND_OR_16] = "__sync_fetch_and_or_16";
395   Names[RTLIB::SYNC_FETCH_AND_XOR_1] = "__sync_fetch_and_xor_1";
396   Names[RTLIB::SYNC_FETCH_AND_XOR_2] = "__sync_fetch_and_xor_2";
397   Names[RTLIB::SYNC_FETCH_AND_XOR_4] = "__sync_fetch_and_xor_4";
398   Names[RTLIB::SYNC_FETCH_AND_XOR_8] = "__sync_fetch_and_xor_8";
399   Names[RTLIB::SYNC_FETCH_AND_XOR_16] = "__sync_fetch_and_xor_16";
400   Names[RTLIB::SYNC_FETCH_AND_NAND_1] = "__sync_fetch_and_nand_1";
401   Names[RTLIB::SYNC_FETCH_AND_NAND_2] = "__sync_fetch_and_nand_2";
402   Names[RTLIB::SYNC_FETCH_AND_NAND_4] = "__sync_fetch_and_nand_4";
403   Names[RTLIB::SYNC_FETCH_AND_NAND_8] = "__sync_fetch_and_nand_8";
404   Names[RTLIB::SYNC_FETCH_AND_NAND_16] = "__sync_fetch_and_nand_16";
405   Names[RTLIB::SYNC_FETCH_AND_MAX_1] = "__sync_fetch_and_max_1";
406   Names[RTLIB::SYNC_FETCH_AND_MAX_2] = "__sync_fetch_and_max_2";
407   Names[RTLIB::SYNC_FETCH_AND_MAX_4] = "__sync_fetch_and_max_4";
408   Names[RTLIB::SYNC_FETCH_AND_MAX_8] = "__sync_fetch_and_max_8";
409   Names[RTLIB::SYNC_FETCH_AND_MAX_16] = "__sync_fetch_and_max_16";
410   Names[RTLIB::SYNC_FETCH_AND_UMAX_1] = "__sync_fetch_and_umax_1";
411   Names[RTLIB::SYNC_FETCH_AND_UMAX_2] = "__sync_fetch_and_umax_2";
412   Names[RTLIB::SYNC_FETCH_AND_UMAX_4] = "__sync_fetch_and_umax_4";
413   Names[RTLIB::SYNC_FETCH_AND_UMAX_8] = "__sync_fetch_and_umax_8";
414   Names[RTLIB::SYNC_FETCH_AND_UMAX_16] = "__sync_fetch_and_umax_16";
415   Names[RTLIB::SYNC_FETCH_AND_MIN_1] = "__sync_fetch_and_min_1";
416   Names[RTLIB::SYNC_FETCH_AND_MIN_2] = "__sync_fetch_and_min_2";
417   Names[RTLIB::SYNC_FETCH_AND_MIN_4] = "__sync_fetch_and_min_4";
418   Names[RTLIB::SYNC_FETCH_AND_MIN_8] = "__sync_fetch_and_min_8";
419   Names[RTLIB::SYNC_FETCH_AND_MIN_16] = "__sync_fetch_and_min_16";
420   Names[RTLIB::SYNC_FETCH_AND_UMIN_1] = "__sync_fetch_and_umin_1";
421   Names[RTLIB::SYNC_FETCH_AND_UMIN_2] = "__sync_fetch_and_umin_2";
422   Names[RTLIB::SYNC_FETCH_AND_UMIN_4] = "__sync_fetch_and_umin_4";
423   Names[RTLIB::SYNC_FETCH_AND_UMIN_8] = "__sync_fetch_and_umin_8";
424   Names[RTLIB::SYNC_FETCH_AND_UMIN_16] = "__sync_fetch_and_umin_16";
425 
426   Names[RTLIB::ATOMIC_LOAD] = "__atomic_load";
427   Names[RTLIB::ATOMIC_LOAD_1] = "__atomic_load_1";
428   Names[RTLIB::ATOMIC_LOAD_2] = "__atomic_load_2";
429   Names[RTLIB::ATOMIC_LOAD_4] = "__atomic_load_4";
430   Names[RTLIB::ATOMIC_LOAD_8] = "__atomic_load_8";
431   Names[RTLIB::ATOMIC_LOAD_16] = "__atomic_load_16";
432 
433   Names[RTLIB::ATOMIC_STORE] = "__atomic_store";
434   Names[RTLIB::ATOMIC_STORE_1] = "__atomic_store_1";
435   Names[RTLIB::ATOMIC_STORE_2] = "__atomic_store_2";
436   Names[RTLIB::ATOMIC_STORE_4] = "__atomic_store_4";
437   Names[RTLIB::ATOMIC_STORE_8] = "__atomic_store_8";
438   Names[RTLIB::ATOMIC_STORE_16] = "__atomic_store_16";
439 
440   Names[RTLIB::ATOMIC_EXCHANGE] = "__atomic_exchange";
441   Names[RTLIB::ATOMIC_EXCHANGE_1] = "__atomic_exchange_1";
442   Names[RTLIB::ATOMIC_EXCHANGE_2] = "__atomic_exchange_2";
443   Names[RTLIB::ATOMIC_EXCHANGE_4] = "__atomic_exchange_4";
444   Names[RTLIB::ATOMIC_EXCHANGE_8] = "__atomic_exchange_8";
445   Names[RTLIB::ATOMIC_EXCHANGE_16] = "__atomic_exchange_16";
446 
447   Names[RTLIB::ATOMIC_COMPARE_EXCHANGE] = "__atomic_compare_exchange";
448   Names[RTLIB::ATOMIC_COMPARE_EXCHANGE_1] = "__atomic_compare_exchange_1";
449   Names[RTLIB::ATOMIC_COMPARE_EXCHANGE_2] = "__atomic_compare_exchange_2";
450   Names[RTLIB::ATOMIC_COMPARE_EXCHANGE_4] = "__atomic_compare_exchange_4";
451   Names[RTLIB::ATOMIC_COMPARE_EXCHANGE_8] = "__atomic_compare_exchange_8";
452   Names[RTLIB::ATOMIC_COMPARE_EXCHANGE_16] = "__atomic_compare_exchange_16";
453 
454   Names[RTLIB::ATOMIC_FETCH_ADD_1] = "__atomic_fetch_add_1";
455   Names[RTLIB::ATOMIC_FETCH_ADD_2] = "__atomic_fetch_add_2";
456   Names[RTLIB::ATOMIC_FETCH_ADD_4] = "__atomic_fetch_add_4";
457   Names[RTLIB::ATOMIC_FETCH_ADD_8] = "__atomic_fetch_add_8";
458   Names[RTLIB::ATOMIC_FETCH_ADD_16] = "__atomic_fetch_add_16";
459   Names[RTLIB::ATOMIC_FETCH_SUB_1] = "__atomic_fetch_sub_1";
460   Names[RTLIB::ATOMIC_FETCH_SUB_2] = "__atomic_fetch_sub_2";
461   Names[RTLIB::ATOMIC_FETCH_SUB_4] = "__atomic_fetch_sub_4";
462   Names[RTLIB::ATOMIC_FETCH_SUB_8] = "__atomic_fetch_sub_8";
463   Names[RTLIB::ATOMIC_FETCH_SUB_16] = "__atomic_fetch_sub_16";
464   Names[RTLIB::ATOMIC_FETCH_AND_1] = "__atomic_fetch_and_1";
465   Names[RTLIB::ATOMIC_FETCH_AND_2] = "__atomic_fetch_and_2";
466   Names[RTLIB::ATOMIC_FETCH_AND_4] = "__atomic_fetch_and_4";
467   Names[RTLIB::ATOMIC_FETCH_AND_8] = "__atomic_fetch_and_8";
468   Names[RTLIB::ATOMIC_FETCH_AND_16] = "__atomic_fetch_and_16";
469   Names[RTLIB::ATOMIC_FETCH_OR_1] = "__atomic_fetch_or_1";
470   Names[RTLIB::ATOMIC_FETCH_OR_2] = "__atomic_fetch_or_2";
471   Names[RTLIB::ATOMIC_FETCH_OR_4] = "__atomic_fetch_or_4";
472   Names[RTLIB::ATOMIC_FETCH_OR_8] = "__atomic_fetch_or_8";
473   Names[RTLIB::ATOMIC_FETCH_OR_16] = "__atomic_fetch_or_16";
474   Names[RTLIB::ATOMIC_FETCH_XOR_1] = "__atomic_fetch_xor_1";
475   Names[RTLIB::ATOMIC_FETCH_XOR_2] = "__atomic_fetch_xor_2";
476   Names[RTLIB::ATOMIC_FETCH_XOR_4] = "__atomic_fetch_xor_4";
477   Names[RTLIB::ATOMIC_FETCH_XOR_8] = "__atomic_fetch_xor_8";
478   Names[RTLIB::ATOMIC_FETCH_XOR_16] = "__atomic_fetch_xor_16";
479   Names[RTLIB::ATOMIC_FETCH_NAND_1] = "__atomic_fetch_nand_1";
480   Names[RTLIB::ATOMIC_FETCH_NAND_2] = "__atomic_fetch_nand_2";
481   Names[RTLIB::ATOMIC_FETCH_NAND_4] = "__atomic_fetch_nand_4";
482   Names[RTLIB::ATOMIC_FETCH_NAND_8] = "__atomic_fetch_nand_8";
483   Names[RTLIB::ATOMIC_FETCH_NAND_16] = "__atomic_fetch_nand_16";
484 
485   if (TT.isGNUEnvironment()) {
486     Names[RTLIB::SINCOS_F32] = "sincosf";
487     Names[RTLIB::SINCOS_F64] = "sincos";
488     Names[RTLIB::SINCOS_F80] = "sincosl";
489     Names[RTLIB::SINCOS_F128] = "sincosl";
490     Names[RTLIB::SINCOS_PPCF128] = "sincosl";
491   }
492 
493   if (!TT.isOSOpenBSD()) {
494     Names[RTLIB::STACKPROTECTOR_CHECK_FAIL] = "__stack_chk_fail";
495   }
496 
497   Names[RTLIB::DEOPTIMIZE] = "__llvm_deoptimize";
498 }
499 
500 /// Set default libcall CallingConvs.
501 static void InitLibcallCallingConvs(CallingConv::ID *CCs) {
502   for (int LC = 0; LC < RTLIB::UNKNOWN_LIBCALL; ++LC)
503     CCs[LC] = CallingConv::C;
504 }
505 
506 /// getFPEXT - Return the FPEXT_*_* value for the given types, or
507 /// UNKNOWN_LIBCALL if there is none.
508 RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) {
509   if (OpVT == MVT::f16) {
510     if (RetVT == MVT::f32)
511       return FPEXT_F16_F32;
512   } else if (OpVT == MVT::f32) {
513     if (RetVT == MVT::f64)
514       return FPEXT_F32_F64;
515     if (RetVT == MVT::f128)
516       return FPEXT_F32_F128;
517     if (RetVT == MVT::ppcf128)
518       return FPEXT_F32_PPCF128;
519   } else if (OpVT == MVT::f64) {
520     if (RetVT == MVT::f128)
521       return FPEXT_F64_F128;
522     else if (RetVT == MVT::ppcf128)
523       return FPEXT_F64_PPCF128;
524   }
525 
526   return UNKNOWN_LIBCALL;
527 }
528 
529 /// getFPROUND - Return the FPROUND_*_* value for the given types, or
530 /// UNKNOWN_LIBCALL if there is none.
531 RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) {
532   if (RetVT == MVT::f16) {
533     if (OpVT == MVT::f32)
534       return FPROUND_F32_F16;
535     if (OpVT == MVT::f64)
536       return FPROUND_F64_F16;
537     if (OpVT == MVT::f80)
538       return FPROUND_F80_F16;
539     if (OpVT == MVT::f128)
540       return FPROUND_F128_F16;
541     if (OpVT == MVT::ppcf128)
542       return FPROUND_PPCF128_F16;
543   } else if (RetVT == MVT::f32) {
544     if (OpVT == MVT::f64)
545       return FPROUND_F64_F32;
546     if (OpVT == MVT::f80)
547       return FPROUND_F80_F32;
548     if (OpVT == MVT::f128)
549       return FPROUND_F128_F32;
550     if (OpVT == MVT::ppcf128)
551       return FPROUND_PPCF128_F32;
552   } else if (RetVT == MVT::f64) {
553     if (OpVT == MVT::f80)
554       return FPROUND_F80_F64;
555     if (OpVT == MVT::f128)
556       return FPROUND_F128_F64;
557     if (OpVT == MVT::ppcf128)
558       return FPROUND_PPCF128_F64;
559   }
560 
561   return UNKNOWN_LIBCALL;
562 }
563 
564 /// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or
565 /// UNKNOWN_LIBCALL if there is none.
566 RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) {
567   if (OpVT == MVT::f32) {
568     if (RetVT == MVT::i32)
569       return FPTOSINT_F32_I32;
570     if (RetVT == MVT::i64)
571       return FPTOSINT_F32_I64;
572     if (RetVT == MVT::i128)
573       return FPTOSINT_F32_I128;
574   } else if (OpVT == MVT::f64) {
575     if (RetVT == MVT::i32)
576       return FPTOSINT_F64_I32;
577     if (RetVT == MVT::i64)
578       return FPTOSINT_F64_I64;
579     if (RetVT == MVT::i128)
580       return FPTOSINT_F64_I128;
581   } else if (OpVT == MVT::f80) {
582     if (RetVT == MVT::i32)
583       return FPTOSINT_F80_I32;
584     if (RetVT == MVT::i64)
585       return FPTOSINT_F80_I64;
586     if (RetVT == MVT::i128)
587       return FPTOSINT_F80_I128;
588   } else if (OpVT == MVT::f128) {
589     if (RetVT == MVT::i32)
590       return FPTOSINT_F128_I32;
591     if (RetVT == MVT::i64)
592       return FPTOSINT_F128_I64;
593     if (RetVT == MVT::i128)
594       return FPTOSINT_F128_I128;
595   } else if (OpVT == MVT::ppcf128) {
596     if (RetVT == MVT::i32)
597       return FPTOSINT_PPCF128_I32;
598     if (RetVT == MVT::i64)
599       return FPTOSINT_PPCF128_I64;
600     if (RetVT == MVT::i128)
601       return FPTOSINT_PPCF128_I128;
602   }
603   return UNKNOWN_LIBCALL;
604 }
605 
606 /// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or
607 /// UNKNOWN_LIBCALL if there is none.
608 RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) {
609   if (OpVT == MVT::f32) {
610     if (RetVT == MVT::i32)
611       return FPTOUINT_F32_I32;
612     if (RetVT == MVT::i64)
613       return FPTOUINT_F32_I64;
614     if (RetVT == MVT::i128)
615       return FPTOUINT_F32_I128;
616   } else if (OpVT == MVT::f64) {
617     if (RetVT == MVT::i32)
618       return FPTOUINT_F64_I32;
619     if (RetVT == MVT::i64)
620       return FPTOUINT_F64_I64;
621     if (RetVT == MVT::i128)
622       return FPTOUINT_F64_I128;
623   } else if (OpVT == MVT::f80) {
624     if (RetVT == MVT::i32)
625       return FPTOUINT_F80_I32;
626     if (RetVT == MVT::i64)
627       return FPTOUINT_F80_I64;
628     if (RetVT == MVT::i128)
629       return FPTOUINT_F80_I128;
630   } else if (OpVT == MVT::f128) {
631     if (RetVT == MVT::i32)
632       return FPTOUINT_F128_I32;
633     if (RetVT == MVT::i64)
634       return FPTOUINT_F128_I64;
635     if (RetVT == MVT::i128)
636       return FPTOUINT_F128_I128;
637   } else if (OpVT == MVT::ppcf128) {
638     if (RetVT == MVT::i32)
639       return FPTOUINT_PPCF128_I32;
640     if (RetVT == MVT::i64)
641       return FPTOUINT_PPCF128_I64;
642     if (RetVT == MVT::i128)
643       return FPTOUINT_PPCF128_I128;
644   }
645   return UNKNOWN_LIBCALL;
646 }
647 
648 /// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or
649 /// UNKNOWN_LIBCALL if there is none.
650 RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) {
651   if (OpVT == MVT::i32) {
652     if (RetVT == MVT::f32)
653       return SINTTOFP_I32_F32;
654     if (RetVT == MVT::f64)
655       return SINTTOFP_I32_F64;
656     if (RetVT == MVT::f80)
657       return SINTTOFP_I32_F80;
658     if (RetVT == MVT::f128)
659       return SINTTOFP_I32_F128;
660     if (RetVT == MVT::ppcf128)
661       return SINTTOFP_I32_PPCF128;
662   } else if (OpVT == MVT::i64) {
663     if (RetVT == MVT::f32)
664       return SINTTOFP_I64_F32;
665     if (RetVT == MVT::f64)
666       return SINTTOFP_I64_F64;
667     if (RetVT == MVT::f80)
668       return SINTTOFP_I64_F80;
669     if (RetVT == MVT::f128)
670       return SINTTOFP_I64_F128;
671     if (RetVT == MVT::ppcf128)
672       return SINTTOFP_I64_PPCF128;
673   } else if (OpVT == MVT::i128) {
674     if (RetVT == MVT::f32)
675       return SINTTOFP_I128_F32;
676     if (RetVT == MVT::f64)
677       return SINTTOFP_I128_F64;
678     if (RetVT == MVT::f80)
679       return SINTTOFP_I128_F80;
680     if (RetVT == MVT::f128)
681       return SINTTOFP_I128_F128;
682     if (RetVT == MVT::ppcf128)
683       return SINTTOFP_I128_PPCF128;
684   }
685   return UNKNOWN_LIBCALL;
686 }
687 
688 /// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or
689 /// UNKNOWN_LIBCALL if there is none.
690 RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) {
691   if (OpVT == MVT::i32) {
692     if (RetVT == MVT::f32)
693       return UINTTOFP_I32_F32;
694     if (RetVT == MVT::f64)
695       return UINTTOFP_I32_F64;
696     if (RetVT == MVT::f80)
697       return UINTTOFP_I32_F80;
698     if (RetVT == MVT::f128)
699       return UINTTOFP_I32_F128;
700     if (RetVT == MVT::ppcf128)
701       return UINTTOFP_I32_PPCF128;
702   } else if (OpVT == MVT::i64) {
703     if (RetVT == MVT::f32)
704       return UINTTOFP_I64_F32;
705     if (RetVT == MVT::f64)
706       return UINTTOFP_I64_F64;
707     if (RetVT == MVT::f80)
708       return UINTTOFP_I64_F80;
709     if (RetVT == MVT::f128)
710       return UINTTOFP_I64_F128;
711     if (RetVT == MVT::ppcf128)
712       return UINTTOFP_I64_PPCF128;
713   } else if (OpVT == MVT::i128) {
714     if (RetVT == MVT::f32)
715       return UINTTOFP_I128_F32;
716     if (RetVT == MVT::f64)
717       return UINTTOFP_I128_F64;
718     if (RetVT == MVT::f80)
719       return UINTTOFP_I128_F80;
720     if (RetVT == MVT::f128)
721       return UINTTOFP_I128_F128;
722     if (RetVT == MVT::ppcf128)
723       return UINTTOFP_I128_PPCF128;
724   }
725   return UNKNOWN_LIBCALL;
726 }
727 
728 RTLIB::Libcall RTLIB::getSYNC(unsigned Opc, MVT VT) {
729 #define OP_TO_LIBCALL(Name, Enum)                                              \
730   case Name:                                                                   \
731     switch (VT.SimpleTy) {                                                     \
732     default:                                                                   \
733       return UNKNOWN_LIBCALL;                                                  \
734     case MVT::i8:                                                              \
735       return Enum##_1;                                                         \
736     case MVT::i16:                                                             \
737       return Enum##_2;                                                         \
738     case MVT::i32:                                                             \
739       return Enum##_4;                                                         \
740     case MVT::i64:                                                             \
741       return Enum##_8;                                                         \
742     case MVT::i128:                                                            \
743       return Enum##_16;                                                        \
744     }
745 
746   switch (Opc) {
747     OP_TO_LIBCALL(ISD::ATOMIC_SWAP, SYNC_LOCK_TEST_AND_SET)
748     OP_TO_LIBCALL(ISD::ATOMIC_CMP_SWAP, SYNC_VAL_COMPARE_AND_SWAP)
749     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_ADD, SYNC_FETCH_AND_ADD)
750     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_SUB, SYNC_FETCH_AND_SUB)
751     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_AND, SYNC_FETCH_AND_AND)
752     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_OR, SYNC_FETCH_AND_OR)
753     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_XOR, SYNC_FETCH_AND_XOR)
754     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_NAND, SYNC_FETCH_AND_NAND)
755     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MAX, SYNC_FETCH_AND_MAX)
756     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMAX, SYNC_FETCH_AND_UMAX)
757     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_MIN, SYNC_FETCH_AND_MIN)
758     OP_TO_LIBCALL(ISD::ATOMIC_LOAD_UMIN, SYNC_FETCH_AND_UMIN)
759   }
760 
761 #undef OP_TO_LIBCALL
762 
763   return UNKNOWN_LIBCALL;
764 }
765 
766 /// InitCmpLibcallCCs - Set default comparison libcall CC.
767 ///
768 static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
769   memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
770   CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
771   CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
772   CCs[RTLIB::OEQ_F128] = ISD::SETEQ;
773   CCs[RTLIB::OEQ_PPCF128] = ISD::SETEQ;
774   CCs[RTLIB::UNE_F32] = ISD::SETNE;
775   CCs[RTLIB::UNE_F64] = ISD::SETNE;
776   CCs[RTLIB::UNE_F128] = ISD::SETNE;
777   CCs[RTLIB::UNE_PPCF128] = ISD::SETNE;
778   CCs[RTLIB::OGE_F32] = ISD::SETGE;
779   CCs[RTLIB::OGE_F64] = ISD::SETGE;
780   CCs[RTLIB::OGE_F128] = ISD::SETGE;
781   CCs[RTLIB::OGE_PPCF128] = ISD::SETGE;
782   CCs[RTLIB::OLT_F32] = ISD::SETLT;
783   CCs[RTLIB::OLT_F64] = ISD::SETLT;
784   CCs[RTLIB::OLT_F128] = ISD::SETLT;
785   CCs[RTLIB::OLT_PPCF128] = ISD::SETLT;
786   CCs[RTLIB::OLE_F32] = ISD::SETLE;
787   CCs[RTLIB::OLE_F64] = ISD::SETLE;
788   CCs[RTLIB::OLE_F128] = ISD::SETLE;
789   CCs[RTLIB::OLE_PPCF128] = ISD::SETLE;
790   CCs[RTLIB::OGT_F32] = ISD::SETGT;
791   CCs[RTLIB::OGT_F64] = ISD::SETGT;
792   CCs[RTLIB::OGT_F128] = ISD::SETGT;
793   CCs[RTLIB::OGT_PPCF128] = ISD::SETGT;
794   CCs[RTLIB::UO_F32] = ISD::SETNE;
795   CCs[RTLIB::UO_F64] = ISD::SETNE;
796   CCs[RTLIB::UO_F128] = ISD::SETNE;
797   CCs[RTLIB::UO_PPCF128] = ISD::SETNE;
798   CCs[RTLIB::O_F32] = ISD::SETEQ;
799   CCs[RTLIB::O_F64] = ISD::SETEQ;
800   CCs[RTLIB::O_F128] = ISD::SETEQ;
801   CCs[RTLIB::O_PPCF128] = ISD::SETEQ;
802 }
803 
804 /// NOTE: The TargetMachine owns TLOF.
805 TargetLoweringBase::TargetLoweringBase(const TargetMachine &tm) : TM(tm) {
806   initActions();
807 
808   // Perform these initializations only once.
809   MaxStoresPerMemset = MaxStoresPerMemcpy = MaxStoresPerMemmove = 8;
810   MaxStoresPerMemsetOptSize = MaxStoresPerMemcpyOptSize
811     = MaxStoresPerMemmoveOptSize = 4;
812   UseUnderscoreSetJmp = false;
813   UseUnderscoreLongJmp = false;
814   HasMultipleConditionRegisters = false;
815   HasExtractBitsInsn = false;
816   JumpIsExpensive = JumpIsExpensiveOverride;
817   PredictableSelectIsExpensive = false;
818   MaskAndBranchFoldingIsLegal = false;
819   EnableExtLdPromotion = false;
820   HasFloatingPointExceptions = true;
821   StackPointerRegisterToSaveRestore = 0;
822   BooleanContents = UndefinedBooleanContent;
823   BooleanFloatContents = UndefinedBooleanContent;
824   BooleanVectorContents = UndefinedBooleanContent;
825   SchedPreferenceInfo = Sched::ILP;
826   JumpBufSize = 0;
827   JumpBufAlignment = 0;
828   MinFunctionAlignment = 0;
829   PrefFunctionAlignment = 0;
830   PrefLoopAlignment = 0;
831   GatherAllAliasesMaxDepth = 6;
832   MinStackArgumentAlignment = 1;
833   // TODO: the default will be switched to 0 in the next commit, along
834   // with the Target-specific changes necessary.
835   MaxAtomicSizeInBitsSupported = 1024;
836 
837   MinCmpXchgSizeInBits = 0;
838 
839   std::fill(std::begin(LibcallRoutineNames), std::end(LibcallRoutineNames), nullptr);
840 
841   InitLibcallNames(LibcallRoutineNames, TM.getTargetTriple());
842   InitCmpLibcallCCs(CmpLibcallCCs);
843   InitLibcallCallingConvs(LibcallCallingConvs);
844 }
845 
846 void TargetLoweringBase::initActions() {
847   // All operations default to being supported.
848   memset(OpActions, 0, sizeof(OpActions));
849   memset(LoadExtActions, 0, sizeof(LoadExtActions));
850   memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
851   memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
852   memset(CondCodeActions, 0, sizeof(CondCodeActions));
853   std::fill(std::begin(RegClassForVT), std::end(RegClassForVT), nullptr);
854   std::fill(std::begin(TargetDAGCombineArray),
855             std::end(TargetDAGCombineArray), 0);
856 
857   // Set default actions for various operations.
858   for (MVT VT : MVT::all_valuetypes()) {
859     // Default all indexed load / store to expand.
860     for (unsigned IM = (unsigned)ISD::PRE_INC;
861          IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
862       setIndexedLoadAction(IM, VT, Expand);
863       setIndexedStoreAction(IM, VT, Expand);
864     }
865 
866     // Most backends expect to see the node which just returns the value loaded.
867     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Expand);
868 
869     // These operations default to expand.
870     setOperationAction(ISD::FGETSIGN, VT, Expand);
871     setOperationAction(ISD::CONCAT_VECTORS, VT, Expand);
872     setOperationAction(ISD::FMINNUM, VT, Expand);
873     setOperationAction(ISD::FMAXNUM, VT, Expand);
874     setOperationAction(ISD::FMINNAN, VT, Expand);
875     setOperationAction(ISD::FMAXNAN, VT, Expand);
876     setOperationAction(ISD::FMAD, VT, Expand);
877     setOperationAction(ISD::SMIN, VT, Expand);
878     setOperationAction(ISD::SMAX, VT, Expand);
879     setOperationAction(ISD::UMIN, VT, Expand);
880     setOperationAction(ISD::UMAX, VT, Expand);
881 
882     // Overflow operations default to expand
883     setOperationAction(ISD::SADDO, VT, Expand);
884     setOperationAction(ISD::SSUBO, VT, Expand);
885     setOperationAction(ISD::UADDO, VT, Expand);
886     setOperationAction(ISD::USUBO, VT, Expand);
887     setOperationAction(ISD::SMULO, VT, Expand);
888     setOperationAction(ISD::UMULO, VT, Expand);
889 
890     // These default to Expand so they will be expanded to CTLZ/CTTZ by default.
891     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
892     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
893 
894     setOperationAction(ISD::BITREVERSE, VT, Expand);
895 
896     // These library functions default to expand.
897     setOperationAction(ISD::FROUND, VT, Expand);
898 
899     // These operations default to expand for vector types.
900     if (VT.isVector()) {
901       setOperationAction(ISD::FCOPYSIGN, VT, Expand);
902       setOperationAction(ISD::ANY_EXTEND_VECTOR_INREG, VT, Expand);
903       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Expand);
904       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Expand);
905     }
906 
907     // For most targets @llvm.get.dynamic.area.offset just returns 0.
908     setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, VT, Expand);
909   }
910 
911   // Most targets ignore the @llvm.prefetch intrinsic.
912   setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
913 
914   // Most targets also ignore the @llvm.readcyclecounter intrinsic.
915   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Expand);
916 
917   // ConstantFP nodes default to expand.  Targets can either change this to
918   // Legal, in which case all fp constants are legal, or use isFPImmLegal()
919   // to optimize expansions for certain constants.
920   setOperationAction(ISD::ConstantFP, MVT::f16, Expand);
921   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
922   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
923   setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
924   setOperationAction(ISD::ConstantFP, MVT::f128, Expand);
925 
926   // These library functions default to expand.
927   for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
928     setOperationAction(ISD::FLOG ,      VT, Expand);
929     setOperationAction(ISD::FLOG2,      VT, Expand);
930     setOperationAction(ISD::FLOG10,     VT, Expand);
931     setOperationAction(ISD::FEXP ,      VT, Expand);
932     setOperationAction(ISD::FEXP2,      VT, Expand);
933     setOperationAction(ISD::FFLOOR,     VT, Expand);
934     setOperationAction(ISD::FNEARBYINT, VT, Expand);
935     setOperationAction(ISD::FCEIL,      VT, Expand);
936     setOperationAction(ISD::FRINT,      VT, Expand);
937     setOperationAction(ISD::FTRUNC,     VT, Expand);
938     setOperationAction(ISD::FROUND,     VT, Expand);
939   }
940 
941   // Default ISD::TRAP to expand (which turns it into abort).
942   setOperationAction(ISD::TRAP, MVT::Other, Expand);
943 
944   // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
945   // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
946   //
947   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand);
948 }
949 
950 MVT TargetLoweringBase::getScalarShiftAmountTy(const DataLayout &DL,
951                                                EVT) const {
952   return MVT::getIntegerVT(8 * DL.getPointerSize(0));
953 }
954 
955 EVT TargetLoweringBase::getShiftAmountTy(EVT LHSTy,
956                                          const DataLayout &DL) const {
957   assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
958   if (LHSTy.isVector())
959     return LHSTy;
960   return getScalarShiftAmountTy(DL, LHSTy);
961 }
962 
963 bool TargetLoweringBase::canOpTrap(unsigned Op, EVT VT) const {
964   assert(isTypeLegal(VT));
965   switch (Op) {
966   default:
967     return false;
968   case ISD::SDIV:
969   case ISD::UDIV:
970   case ISD::SREM:
971   case ISD::UREM:
972     return true;
973   }
974 }
975 
976 void TargetLoweringBase::setJumpIsExpensive(bool isExpensive) {
977   // If the command-line option was specified, ignore this request.
978   if (!JumpIsExpensiveOverride.getNumOccurrences())
979     JumpIsExpensive = isExpensive;
980 }
981 
982 TargetLoweringBase::LegalizeKind
983 TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const {
984   // If this is a simple type, use the ComputeRegisterProp mechanism.
985   if (VT.isSimple()) {
986     MVT SVT = VT.getSimpleVT();
987     assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
988     MVT NVT = TransformToType[SVT.SimpleTy];
989     LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);
990 
991     assert((LA == TypeLegal || LA == TypeSoftenFloat ||
992             ValueTypeActions.getTypeAction(NVT) != TypePromoteInteger) &&
993            "Promote may not follow Expand or Promote");
994 
995     if (LA == TypeSplitVector)
996       return LegalizeKind(LA,
997                           EVT::getVectorVT(Context, SVT.getVectorElementType(),
998                                            SVT.getVectorNumElements() / 2));
999     if (LA == TypeScalarizeVector)
1000       return LegalizeKind(LA, SVT.getVectorElementType());
1001     return LegalizeKind(LA, NVT);
1002   }
1003 
1004   // Handle Extended Scalar Types.
1005   if (!VT.isVector()) {
1006     assert(VT.isInteger() && "Float types must be simple");
1007     unsigned BitSize = VT.getSizeInBits();
1008     // First promote to a power-of-two size, then expand if necessary.
1009     if (BitSize < 8 || !isPowerOf2_32(BitSize)) {
1010       EVT NVT = VT.getRoundIntegerType(Context);
1011       assert(NVT != VT && "Unable to round integer VT");
1012       LegalizeKind NextStep = getTypeConversion(Context, NVT);
1013       // Avoid multi-step promotion.
1014       if (NextStep.first == TypePromoteInteger)
1015         return NextStep;
1016       // Return rounded integer type.
1017       return LegalizeKind(TypePromoteInteger, NVT);
1018     }
1019 
1020     return LegalizeKind(TypeExpandInteger,
1021                         EVT::getIntegerVT(Context, VT.getSizeInBits() / 2));
1022   }
1023 
1024   // Handle vector types.
1025   unsigned NumElts = VT.getVectorNumElements();
1026   EVT EltVT = VT.getVectorElementType();
1027 
1028   // Vectors with only one element are always scalarized.
1029   if (NumElts == 1)
1030     return LegalizeKind(TypeScalarizeVector, EltVT);
1031 
1032   // Try to widen vector elements until the element type is a power of two and
1033   // promote it to a legal type later on, for example:
1034   // <3 x i8> -> <4 x i8> -> <4 x i32>
1035   if (EltVT.isInteger()) {
1036     // Vectors with a number of elements that is not a power of two are always
1037     // widened, for example <3 x i8> -> <4 x i8>.
1038     if (!VT.isPow2VectorType()) {
1039       NumElts = (unsigned)NextPowerOf2(NumElts);
1040       EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts);
1041       return LegalizeKind(TypeWidenVector, NVT);
1042     }
1043 
1044     // Examine the element type.
1045     LegalizeKind LK = getTypeConversion(Context, EltVT);
1046 
1047     // If type is to be expanded, split the vector.
1048     //  <4 x i140> -> <2 x i140>
1049     if (LK.first == TypeExpandInteger)
1050       return LegalizeKind(TypeSplitVector,
1051                           EVT::getVectorVT(Context, EltVT, NumElts / 2));
1052 
1053     // Promote the integer element types until a legal vector type is found
1054     // or until the element integer type is too big. If a legal type was not
1055     // found, fallback to the usual mechanism of widening/splitting the
1056     // vector.
1057     EVT OldEltVT = EltVT;
1058     while (1) {
1059       // Increase the bitwidth of the element to the next pow-of-two
1060       // (which is greater than 8 bits).
1061       EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits())
1062                   .getRoundIntegerType(Context);
1063 
1064       // Stop trying when getting a non-simple element type.
1065       // Note that vector elements may be greater than legal vector element
1066       // types. Example: X86 XMM registers hold 64bit element on 32bit
1067       // systems.
1068       if (!EltVT.isSimple())
1069         break;
1070 
1071       // Build a new vector type and check if it is legal.
1072       MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1073       // Found a legal promoted vector type.
1074       if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal)
1075         return LegalizeKind(TypePromoteInteger,
1076                             EVT::getVectorVT(Context, EltVT, NumElts));
1077     }
1078 
1079     // Reset the type to the unexpanded type if we did not find a legal vector
1080     // type with a promoted vector element type.
1081     EltVT = OldEltVT;
1082   }
1083 
1084   // Try to widen the vector until a legal type is found.
1085   // If there is no wider legal type, split the vector.
1086   while (1) {
1087     // Round up to the next power of 2.
1088     NumElts = (unsigned)NextPowerOf2(NumElts);
1089 
1090     // If there is no simple vector type with this many elements then there
1091     // cannot be a larger legal vector type.  Note that this assumes that
1092     // there are no skipped intermediate vector types in the simple types.
1093     if (!EltVT.isSimple())
1094       break;
1095     MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts);
1096     if (LargerVector == MVT())
1097       break;
1098 
1099     // If this type is legal then widen the vector.
1100     if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal)
1101       return LegalizeKind(TypeWidenVector, LargerVector);
1102   }
1103 
1104   // Widen odd vectors to next power of two.
1105   if (!VT.isPow2VectorType()) {
1106     EVT NVT = VT.getPow2VectorType(Context);
1107     return LegalizeKind(TypeWidenVector, NVT);
1108   }
1109 
1110   // Vectors with illegal element types are expanded.
1111   EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2);
1112   return LegalizeKind(TypeSplitVector, NVT);
1113 }
1114 
1115 static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
1116                                           unsigned &NumIntermediates,
1117                                           MVT &RegisterVT,
1118                                           TargetLoweringBase *TLI) {
1119   // Figure out the right, legal destination reg to copy into.
1120   unsigned NumElts = VT.getVectorNumElements();
1121   MVT EltTy = VT.getVectorElementType();
1122 
1123   unsigned NumVectorRegs = 1;
1124 
1125   // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally we
1126   // could break down into LHS/RHS like LegalizeDAG does.
1127   if (!isPowerOf2_32(NumElts)) {
1128     NumVectorRegs = NumElts;
1129     NumElts = 1;
1130   }
1131 
1132   // Divide the input until we get to a supported size.  This will always
1133   // end with a scalar if the target doesn't support vectors.
1134   while (NumElts > 1 && !TLI->isTypeLegal(MVT::getVectorVT(EltTy, NumElts))) {
1135     NumElts >>= 1;
1136     NumVectorRegs <<= 1;
1137   }
1138 
1139   NumIntermediates = NumVectorRegs;
1140 
1141   MVT NewVT = MVT::getVectorVT(EltTy, NumElts);
1142   if (!TLI->isTypeLegal(NewVT))
1143     NewVT = EltTy;
1144   IntermediateVT = NewVT;
1145 
1146   unsigned NewVTSize = NewVT.getSizeInBits();
1147 
1148   // Convert sizes such as i33 to i64.
1149   if (!isPowerOf2_32(NewVTSize))
1150     NewVTSize = NextPowerOf2(NewVTSize);
1151 
1152   MVT DestVT = TLI->getRegisterType(NewVT);
1153   RegisterVT = DestVT;
1154   if (EVT(DestVT).bitsLT(NewVT))    // Value is expanded, e.g. i64 -> i16.
1155     return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
1156 
1157   // Otherwise, promotion or legal types use the same number of registers as
1158   // the vector decimated to the appropriate level.
1159   return NumVectorRegs;
1160 }
1161 
1162 /// isLegalRC - Return true if the value types that can be represented by the
1163 /// specified register class are all legal.
1164 bool TargetLoweringBase::isLegalRC(const TargetRegisterClass *RC) const {
1165   for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1166        I != E; ++I) {
1167     if (isTypeLegal(*I))
1168       return true;
1169   }
1170   return false;
1171 }
1172 
1173 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
1174 /// sequence of memory operands that is recognized by PrologEpilogInserter.
1175 MachineBasicBlock *
1176 TargetLoweringBase::emitPatchPoint(MachineInstr &InitialMI,
1177                                    MachineBasicBlock *MBB) const {
1178   MachineInstr *MI = &InitialMI;
1179   MachineFunction &MF = *MI->getParent()->getParent();
1180   MachineFrameInfo &MFI = MF.getFrameInfo();
1181 
1182   // We're handling multiple types of operands here:
1183   // PATCHPOINT MetaArgs - live-in, read only, direct
1184   // STATEPOINT Deopt Spill - live-through, read only, indirect
1185   // STATEPOINT Deopt Alloca - live-through, read only, direct
1186   // (We're currently conservative and mark the deopt slots read/write in
1187   // practice.)
1188   // STATEPOINT GC Spill - live-through, read/write, indirect
1189   // STATEPOINT GC Alloca - live-through, read/write, direct
1190   // The live-in vs live-through is handled already (the live through ones are
1191   // all stack slots), but we need to handle the different type of stackmap
1192   // operands and memory effects here.
1193 
1194   // MI changes inside this loop as we grow operands.
1195   for(unsigned OperIdx = 0; OperIdx != MI->getNumOperands(); ++OperIdx) {
1196     MachineOperand &MO = MI->getOperand(OperIdx);
1197     if (!MO.isFI())
1198       continue;
1199 
1200     // foldMemoryOperand builds a new MI after replacing a single FI operand
1201     // with the canonical set of five x86 addressing-mode operands.
1202     int FI = MO.getIndex();
1203     MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), MI->getDesc());
1204 
1205     // Copy operands before the frame-index.
1206     for (unsigned i = 0; i < OperIdx; ++i)
1207       MIB.addOperand(MI->getOperand(i));
1208     // Add frame index operands recognized by stackmaps.cpp
1209     if (MFI.isStatepointSpillSlotObjectIndex(FI)) {
1210       // indirect-mem-ref tag, size, #FI, offset.
1211       // Used for spills inserted by StatepointLowering.  This codepath is not
1212       // used for patchpoints/stackmaps at all, for these spilling is done via
1213       // foldMemoryOperand callback only.
1214       assert(MI->getOpcode() == TargetOpcode::STATEPOINT && "sanity");
1215       MIB.addImm(StackMaps::IndirectMemRefOp);
1216       MIB.addImm(MFI.getObjectSize(FI));
1217       MIB.addOperand(MI->getOperand(OperIdx));
1218       MIB.addImm(0);
1219     } else {
1220       // direct-mem-ref tag, #FI, offset.
1221       // Used by patchpoint, and direct alloca arguments to statepoints
1222       MIB.addImm(StackMaps::DirectMemRefOp);
1223       MIB.addOperand(MI->getOperand(OperIdx));
1224       MIB.addImm(0);
1225     }
1226     // Copy the operands after the frame index.
1227     for (unsigned i = OperIdx + 1; i != MI->getNumOperands(); ++i)
1228       MIB.addOperand(MI->getOperand(i));
1229 
1230     // Inherit previous memory operands.
1231     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1232     assert(MIB->mayLoad() && "Folded a stackmap use to a non-load!");
1233 
1234     // Add a new memory operand for this FI.
1235     assert(MFI.getObjectOffset(FI) != -1);
1236 
1237     auto Flags = MachineMemOperand::MOLoad;
1238     if (MI->getOpcode() == TargetOpcode::STATEPOINT) {
1239       Flags |= MachineMemOperand::MOStore;
1240       Flags |= MachineMemOperand::MOVolatile;
1241     }
1242     MachineMemOperand *MMO = MF.getMachineMemOperand(
1243         MachinePointerInfo::getFixedStack(MF, FI), Flags,
1244         MF.getDataLayout().getPointerSize(), MFI.getObjectAlignment(FI));
1245     MIB->addMemOperand(MF, MMO);
1246 
1247     // Replace the instruction and update the operand index.
1248     MBB->insert(MachineBasicBlock::iterator(MI), MIB);
1249     OperIdx += (MIB->getNumOperands() - MI->getNumOperands()) - 1;
1250     MI->eraseFromParent();
1251     MI = MIB;
1252   }
1253   return MBB;
1254 }
1255 
1256 /// findRepresentativeClass - Return the largest legal super-reg register class
1257 /// of the register class for the specified type and its associated "cost".
1258 // This function is in TargetLowering because it uses RegClassForVT which would
1259 // need to be moved to TargetRegisterInfo and would necessitate moving
1260 // isTypeLegal over as well - a massive change that would just require
1261 // TargetLowering having a TargetRegisterInfo class member that it would use.
1262 std::pair<const TargetRegisterClass *, uint8_t>
1263 TargetLoweringBase::findRepresentativeClass(const TargetRegisterInfo *TRI,
1264                                             MVT VT) const {
1265   const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
1266   if (!RC)
1267     return std::make_pair(RC, 0);
1268 
1269   // Compute the set of all super-register classes.
1270   BitVector SuperRegRC(TRI->getNumRegClasses());
1271   for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
1272     SuperRegRC.setBitsInMask(RCI.getMask());
1273 
1274   // Find the first legal register class with the largest spill size.
1275   const TargetRegisterClass *BestRC = RC;
1276   for (int i = SuperRegRC.find_first(); i >= 0; i = SuperRegRC.find_next(i)) {
1277     const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
1278     // We want the largest possible spill size.
1279     if (SuperRC->getSize() <= BestRC->getSize())
1280       continue;
1281     if (!isLegalRC(SuperRC))
1282       continue;
1283     BestRC = SuperRC;
1284   }
1285   return std::make_pair(BestRC, 1);
1286 }
1287 
1288 /// computeRegisterProperties - Once all of the register classes are added,
1289 /// this allows us to compute derived properties we expose.
1290 void TargetLoweringBase::computeRegisterProperties(
1291     const TargetRegisterInfo *TRI) {
1292   static_assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE,
1293                 "Too many value types for ValueTypeActions to hold!");
1294 
1295   // Everything defaults to needing one register.
1296   for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
1297     NumRegistersForVT[i] = 1;
1298     RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
1299   }
1300   // ...except isVoid, which doesn't need any registers.
1301   NumRegistersForVT[MVT::isVoid] = 0;
1302 
1303   // Find the largest integer register class.
1304   unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
1305   for (; RegClassForVT[LargestIntReg] == nullptr; --LargestIntReg)
1306     assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
1307 
1308   // Every integer value type larger than this largest register takes twice as
1309   // many registers to represent as the previous ValueType.
1310   for (unsigned ExpandedReg = LargestIntReg + 1;
1311        ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
1312     NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
1313     RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
1314     TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
1315     ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg,
1316                                    TypeExpandInteger);
1317   }
1318 
1319   // Inspect all of the ValueType's smaller than the largest integer
1320   // register to see which ones need promotion.
1321   unsigned LegalIntReg = LargestIntReg;
1322   for (unsigned IntReg = LargestIntReg - 1;
1323        IntReg >= (unsigned)MVT::i1; --IntReg) {
1324     MVT IVT = (MVT::SimpleValueType)IntReg;
1325     if (isTypeLegal(IVT)) {
1326       LegalIntReg = IntReg;
1327     } else {
1328       RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
1329         (const MVT::SimpleValueType)LegalIntReg;
1330       ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
1331     }
1332   }
1333 
1334   // ppcf128 type is really two f64's.
1335   if (!isTypeLegal(MVT::ppcf128)) {
1336     if (isTypeLegal(MVT::f64)) {
1337       NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
1338       RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
1339       TransformToType[MVT::ppcf128] = MVT::f64;
1340       ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
1341     } else {
1342       NumRegistersForVT[MVT::ppcf128] = NumRegistersForVT[MVT::i128];
1343       RegisterTypeForVT[MVT::ppcf128] = RegisterTypeForVT[MVT::i128];
1344       TransformToType[MVT::ppcf128] = MVT::i128;
1345       ValueTypeActions.setTypeAction(MVT::ppcf128, TypeSoftenFloat);
1346     }
1347   }
1348 
1349   // Decide how to handle f128. If the target does not have native f128 support,
1350   // expand it to i128 and we will be generating soft float library calls.
1351   if (!isTypeLegal(MVT::f128)) {
1352     NumRegistersForVT[MVT::f128] = NumRegistersForVT[MVT::i128];
1353     RegisterTypeForVT[MVT::f128] = RegisterTypeForVT[MVT::i128];
1354     TransformToType[MVT::f128] = MVT::i128;
1355     ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
1356   }
1357 
1358   // Decide how to handle f64. If the target does not have native f64 support,
1359   // expand it to i64 and we will be generating soft float library calls.
1360   if (!isTypeLegal(MVT::f64)) {
1361     NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
1362     RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
1363     TransformToType[MVT::f64] = MVT::i64;
1364     ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
1365   }
1366 
1367   // Decide how to handle f32. If the target does not have native f32 support,
1368   // expand it to i32 and we will be generating soft float library calls.
1369   if (!isTypeLegal(MVT::f32)) {
1370     NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
1371     RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
1372     TransformToType[MVT::f32] = MVT::i32;
1373     ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
1374   }
1375 
1376   // Decide how to handle f16. If the target does not have native f16 support,
1377   // promote it to f32, because there are no f16 library calls (except for
1378   // conversions).
1379   if (!isTypeLegal(MVT::f16)) {
1380     NumRegistersForVT[MVT::f16] = NumRegistersForVT[MVT::f32];
1381     RegisterTypeForVT[MVT::f16] = RegisterTypeForVT[MVT::f32];
1382     TransformToType[MVT::f16] = MVT::f32;
1383     ValueTypeActions.setTypeAction(MVT::f16, TypePromoteFloat);
1384   }
1385 
1386   // Loop over all of the vector value types to see which need transformations.
1387   for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
1388        i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1389     MVT VT = (MVT::SimpleValueType) i;
1390     if (isTypeLegal(VT))
1391       continue;
1392 
1393     MVT EltVT = VT.getVectorElementType();
1394     unsigned NElts = VT.getVectorNumElements();
1395     bool IsLegalWiderType = false;
1396     LegalizeTypeAction PreferredAction = getPreferredVectorAction(VT);
1397     switch (PreferredAction) {
1398     case TypePromoteInteger: {
1399       // Try to promote the elements of integer vectors. If no legal
1400       // promotion was found, fall through to the widen-vector method.
1401       for (unsigned nVT = i + 1; nVT <= MVT::LAST_INTEGER_VECTOR_VALUETYPE; ++nVT) {
1402         MVT SVT = (MVT::SimpleValueType) nVT;
1403         // Promote vectors of integers to vectors with the same number
1404         // of elements, with a wider element type.
1405         if (SVT.getScalarSizeInBits() > EltVT.getSizeInBits() &&
1406             SVT.getVectorNumElements() == NElts && isTypeLegal(SVT)) {
1407           TransformToType[i] = SVT;
1408           RegisterTypeForVT[i] = SVT;
1409           NumRegistersForVT[i] = 1;
1410           ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
1411           IsLegalWiderType = true;
1412           break;
1413         }
1414       }
1415       if (IsLegalWiderType)
1416         break;
1417     }
1418     case TypeWidenVector: {
1419       // Try to widen the vector.
1420       for (unsigned nVT = i + 1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
1421         MVT SVT = (MVT::SimpleValueType) nVT;
1422         if (SVT.getVectorElementType() == EltVT
1423             && SVT.getVectorNumElements() > NElts && isTypeLegal(SVT)) {
1424           TransformToType[i] = SVT;
1425           RegisterTypeForVT[i] = SVT;
1426           NumRegistersForVT[i] = 1;
1427           ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1428           IsLegalWiderType = true;
1429           break;
1430         }
1431       }
1432       if (IsLegalWiderType)
1433         break;
1434     }
1435     case TypeSplitVector:
1436     case TypeScalarizeVector: {
1437       MVT IntermediateVT;
1438       MVT RegisterVT;
1439       unsigned NumIntermediates;
1440       NumRegistersForVT[i] = getVectorTypeBreakdownMVT(VT, IntermediateVT,
1441           NumIntermediates, RegisterVT, this);
1442       RegisterTypeForVT[i] = RegisterVT;
1443 
1444       MVT NVT = VT.getPow2VectorType();
1445       if (NVT == VT) {
1446         // Type is already a power of 2.  The default action is to split.
1447         TransformToType[i] = MVT::Other;
1448         if (PreferredAction == TypeScalarizeVector)
1449           ValueTypeActions.setTypeAction(VT, TypeScalarizeVector);
1450         else if (PreferredAction == TypeSplitVector)
1451           ValueTypeActions.setTypeAction(VT, TypeSplitVector);
1452         else
1453           // Set type action according to the number of elements.
1454           ValueTypeActions.setTypeAction(VT, NElts == 1 ? TypeScalarizeVector
1455                                                         : TypeSplitVector);
1456       } else {
1457         TransformToType[i] = NVT;
1458         ValueTypeActions.setTypeAction(VT, TypeWidenVector);
1459       }
1460       break;
1461     }
1462     default:
1463       llvm_unreachable("Unknown vector legalization action!");
1464     }
1465   }
1466 
1467   // Determine the 'representative' register class for each value type.
1468   // An representative register class is the largest (meaning one which is
1469   // not a sub-register class / subreg register class) legal register class for
1470   // a group of value types. For example, on i386, i8, i16, and i32
1471   // representative would be GR32; while on x86_64 it's GR64.
1472   for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
1473     const TargetRegisterClass* RRC;
1474     uint8_t Cost;
1475     std::tie(RRC, Cost) = findRepresentativeClass(TRI, (MVT::SimpleValueType)i);
1476     RepRegClassForVT[i] = RRC;
1477     RepRegClassCostForVT[i] = Cost;
1478   }
1479 }
1480 
1481 EVT TargetLoweringBase::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1482                                            EVT VT) const {
1483   assert(!VT.isVector() && "No default SetCC type for vectors!");
1484   return getPointerTy(DL).SimpleTy;
1485 }
1486 
1487 MVT::SimpleValueType TargetLoweringBase::getCmpLibcallReturnType() const {
1488   return MVT::i32; // return the default value
1489 }
1490 
1491 /// getVectorTypeBreakdown - Vector types are broken down into some number of
1492 /// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
1493 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
1494 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
1495 ///
1496 /// This method returns the number of registers needed, and the VT for each
1497 /// register.  It also returns the VT and quantity of the intermediate values
1498 /// before they are promoted/expanded.
1499 ///
1500 unsigned TargetLoweringBase::getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
1501                                                 EVT &IntermediateVT,
1502                                                 unsigned &NumIntermediates,
1503                                                 MVT &RegisterVT) const {
1504   unsigned NumElts = VT.getVectorNumElements();
1505 
1506   // If there is a wider vector type with the same element type as this one,
1507   // or a promoted vector type that has the same number of elements which
1508   // are wider, then we should convert to that legal vector type.
1509   // This handles things like <2 x float> -> <4 x float> and
1510   // <4 x i1> -> <4 x i32>.
1511   LegalizeTypeAction TA = getTypeAction(Context, VT);
1512   if (NumElts != 1 && (TA == TypeWidenVector || TA == TypePromoteInteger)) {
1513     EVT RegisterEVT = getTypeToTransformTo(Context, VT);
1514     if (isTypeLegal(RegisterEVT)) {
1515       IntermediateVT = RegisterEVT;
1516       RegisterVT = RegisterEVT.getSimpleVT();
1517       NumIntermediates = 1;
1518       return 1;
1519     }
1520   }
1521 
1522   // Figure out the right, legal destination reg to copy into.
1523   EVT EltTy = VT.getVectorElementType();
1524 
1525   unsigned NumVectorRegs = 1;
1526 
1527   // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally we
1528   // could break down into LHS/RHS like LegalizeDAG does.
1529   if (!isPowerOf2_32(NumElts)) {
1530     NumVectorRegs = NumElts;
1531     NumElts = 1;
1532   }
1533 
1534   // Divide the input until we get to a supported size.  This will always
1535   // end with a scalar if the target doesn't support vectors.
1536   while (NumElts > 1 && !isTypeLegal(
1537                                    EVT::getVectorVT(Context, EltTy, NumElts))) {
1538     NumElts >>= 1;
1539     NumVectorRegs <<= 1;
1540   }
1541 
1542   NumIntermediates = NumVectorRegs;
1543 
1544   EVT NewVT = EVT::getVectorVT(Context, EltTy, NumElts);
1545   if (!isTypeLegal(NewVT))
1546     NewVT = EltTy;
1547   IntermediateVT = NewVT;
1548 
1549   MVT DestVT = getRegisterType(Context, NewVT);
1550   RegisterVT = DestVT;
1551   unsigned NewVTSize = NewVT.getSizeInBits();
1552 
1553   // Convert sizes such as i33 to i64.
1554   if (!isPowerOf2_32(NewVTSize))
1555     NewVTSize = NextPowerOf2(NewVTSize);
1556 
1557   if (EVT(DestVT).bitsLT(NewVT))   // Value is expanded, e.g. i64 -> i16.
1558     return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
1559 
1560   // Otherwise, promotion or legal types use the same number of registers as
1561   // the vector decimated to the appropriate level.
1562   return NumVectorRegs;
1563 }
1564 
1565 /// Get the EVTs and ArgFlags collections that represent the legalized return
1566 /// type of the given function.  This does not require a DAG or a return value,
1567 /// and is suitable for use before any DAGs for the function are constructed.
1568 /// TODO: Move this out of TargetLowering.cpp.
1569 void llvm::GetReturnInfo(Type *ReturnType, AttributeSet attr,
1570                          SmallVectorImpl<ISD::OutputArg> &Outs,
1571                          const TargetLowering &TLI, const DataLayout &DL) {
1572   SmallVector<EVT, 4> ValueVTs;
1573   ComputeValueVTs(TLI, DL, ReturnType, ValueVTs);
1574   unsigned NumValues = ValueVTs.size();
1575   if (NumValues == 0) return;
1576 
1577   for (unsigned j = 0, f = NumValues; j != f; ++j) {
1578     EVT VT = ValueVTs[j];
1579     ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1580 
1581     if (attr.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
1582       ExtendKind = ISD::SIGN_EXTEND;
1583     else if (attr.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt))
1584       ExtendKind = ISD::ZERO_EXTEND;
1585 
1586     // FIXME: C calling convention requires the return type to be promoted to
1587     // at least 32-bit. But this is not necessary for non-C calling
1588     // conventions. The frontend should mark functions whose return values
1589     // require promoting with signext or zeroext attributes.
1590     if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1591       MVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
1592       if (VT.bitsLT(MinVT))
1593         VT = MinVT;
1594     }
1595 
1596     unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
1597     MVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
1598 
1599     // 'inreg' on function refers to return value
1600     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1601     if (attr.hasAttribute(AttributeSet::ReturnIndex, Attribute::InReg))
1602       Flags.setInReg();
1603 
1604     // Propagate extension type if any
1605     if (attr.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
1606       Flags.setSExt();
1607     else if (attr.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt))
1608       Flags.setZExt();
1609 
1610     for (unsigned i = 0; i < NumParts; ++i)
1611       Outs.push_back(ISD::OutputArg(Flags, PartVT, VT, /*isFixed=*/true, 0, 0));
1612   }
1613 }
1614 
1615 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1616 /// function arguments in the caller parameter area.  This is the actual
1617 /// alignment, not its logarithm.
1618 unsigned TargetLoweringBase::getByValTypeAlignment(Type *Ty,
1619                                                    const DataLayout &DL) const {
1620   return DL.getABITypeAlignment(Ty);
1621 }
1622 
1623 bool TargetLoweringBase::allowsMemoryAccess(LLVMContext &Context,
1624                                             const DataLayout &DL, EVT VT,
1625                                             unsigned AddrSpace,
1626                                             unsigned Alignment,
1627                                             bool *Fast) const {
1628   // Check if the specified alignment is sufficient based on the data layout.
1629   // TODO: While using the data layout works in practice, a better solution
1630   // would be to implement this check directly (make this a virtual function).
1631   // For example, the ABI alignment may change based on software platform while
1632   // this function should only be affected by hardware implementation.
1633   Type *Ty = VT.getTypeForEVT(Context);
1634   if (Alignment >= DL.getABITypeAlignment(Ty)) {
1635     // Assume that an access that meets the ABI-specified alignment is fast.
1636     if (Fast != nullptr)
1637       *Fast = true;
1638     return true;
1639   }
1640 
1641   // This is a misaligned access.
1642   return allowsMisalignedMemoryAccesses(VT, AddrSpace, Alignment, Fast);
1643 }
1644 
1645 BranchProbability TargetLoweringBase::getPredictableBranchThreshold() const {
1646   return BranchProbability(MinPercentageForPredictableBranch, 100);
1647 }
1648 
1649 //===----------------------------------------------------------------------===//
1650 //  TargetTransformInfo Helpers
1651 //===----------------------------------------------------------------------===//
1652 
1653 int TargetLoweringBase::InstructionOpcodeToISD(unsigned Opcode) const {
1654   enum InstructionOpcodes {
1655 #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM,
1656 #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM
1657 #include "llvm/IR/Instruction.def"
1658   };
1659   switch (static_cast<InstructionOpcodes>(Opcode)) {
1660   case Ret:            return 0;
1661   case Br:             return 0;
1662   case Switch:         return 0;
1663   case IndirectBr:     return 0;
1664   case Invoke:         return 0;
1665   case Resume:         return 0;
1666   case Unreachable:    return 0;
1667   case CleanupRet:     return 0;
1668   case CatchRet:       return 0;
1669   case CatchPad:       return 0;
1670   case CatchSwitch:    return 0;
1671   case CleanupPad:     return 0;
1672   case Add:            return ISD::ADD;
1673   case FAdd:           return ISD::FADD;
1674   case Sub:            return ISD::SUB;
1675   case FSub:           return ISD::FSUB;
1676   case Mul:            return ISD::MUL;
1677   case FMul:           return ISD::FMUL;
1678   case UDiv:           return ISD::UDIV;
1679   case SDiv:           return ISD::SDIV;
1680   case FDiv:           return ISD::FDIV;
1681   case URem:           return ISD::UREM;
1682   case SRem:           return ISD::SREM;
1683   case FRem:           return ISD::FREM;
1684   case Shl:            return ISD::SHL;
1685   case LShr:           return ISD::SRL;
1686   case AShr:           return ISD::SRA;
1687   case And:            return ISD::AND;
1688   case Or:             return ISD::OR;
1689   case Xor:            return ISD::XOR;
1690   case Alloca:         return 0;
1691   case Load:           return ISD::LOAD;
1692   case Store:          return ISD::STORE;
1693   case GetElementPtr:  return 0;
1694   case Fence:          return 0;
1695   case AtomicCmpXchg:  return 0;
1696   case AtomicRMW:      return 0;
1697   case Trunc:          return ISD::TRUNCATE;
1698   case ZExt:           return ISD::ZERO_EXTEND;
1699   case SExt:           return ISD::SIGN_EXTEND;
1700   case FPToUI:         return ISD::FP_TO_UINT;
1701   case FPToSI:         return ISD::FP_TO_SINT;
1702   case UIToFP:         return ISD::UINT_TO_FP;
1703   case SIToFP:         return ISD::SINT_TO_FP;
1704   case FPTrunc:        return ISD::FP_ROUND;
1705   case FPExt:          return ISD::FP_EXTEND;
1706   case PtrToInt:       return ISD::BITCAST;
1707   case IntToPtr:       return ISD::BITCAST;
1708   case BitCast:        return ISD::BITCAST;
1709   case AddrSpaceCast:  return ISD::ADDRSPACECAST;
1710   case ICmp:           return ISD::SETCC;
1711   case FCmp:           return ISD::SETCC;
1712   case PHI:            return 0;
1713   case Call:           return 0;
1714   case Select:         return ISD::SELECT;
1715   case UserOp1:        return 0;
1716   case UserOp2:        return 0;
1717   case VAArg:          return 0;
1718   case ExtractElement: return ISD::EXTRACT_VECTOR_ELT;
1719   case InsertElement:  return ISD::INSERT_VECTOR_ELT;
1720   case ShuffleVector:  return ISD::VECTOR_SHUFFLE;
1721   case ExtractValue:   return ISD::MERGE_VALUES;
1722   case InsertValue:    return ISD::MERGE_VALUES;
1723   case LandingPad:     return 0;
1724   }
1725 
1726   llvm_unreachable("Unknown instruction type encountered!");
1727 }
1728 
1729 std::pair<int, MVT>
1730 TargetLoweringBase::getTypeLegalizationCost(const DataLayout &DL,
1731                                             Type *Ty) const {
1732   LLVMContext &C = Ty->getContext();
1733   EVT MTy = getValueType(DL, Ty);
1734 
1735   int Cost = 1;
1736   // We keep legalizing the type until we find a legal kind. We assume that
1737   // the only operation that costs anything is the split. After splitting
1738   // we need to handle two types.
1739   while (true) {
1740     LegalizeKind LK = getTypeConversion(C, MTy);
1741 
1742     if (LK.first == TypeLegal)
1743       return std::make_pair(Cost, MTy.getSimpleVT());
1744 
1745     if (LK.first == TypeSplitVector || LK.first == TypeExpandInteger)
1746       Cost *= 2;
1747 
1748     // Do not loop with f128 type.
1749     if (MTy == LK.second)
1750       return std::make_pair(Cost, MTy.getSimpleVT());
1751 
1752     // Keep legalizing the type.
1753     MTy = LK.second;
1754   }
1755 }
1756 
1757 Value *TargetLoweringBase::getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1758                                                               bool UseTLS) const {
1759   // compiler-rt provides a variable with a magic name.  Targets that do not
1760   // link with compiler-rt may also provide such a variable.
1761   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1762   const char *UnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
1763   auto UnsafeStackPtr =
1764       dyn_cast_or_null<GlobalVariable>(M->getNamedValue(UnsafeStackPtrVar));
1765 
1766   Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
1767 
1768   if (!UnsafeStackPtr) {
1769     auto TLSModel = UseTLS ?
1770         GlobalValue::InitialExecTLSModel :
1771         GlobalValue::NotThreadLocal;
1772     // The global variable is not defined yet, define it ourselves.
1773     // We use the initial-exec TLS model because we do not support the
1774     // variable living anywhere other than in the main executable.
1775     UnsafeStackPtr = new GlobalVariable(
1776         *M, StackPtrTy, false, GlobalValue::ExternalLinkage, nullptr,
1777         UnsafeStackPtrVar, nullptr, TLSModel);
1778   } else {
1779     // The variable exists, check its type and attributes.
1780     if (UnsafeStackPtr->getValueType() != StackPtrTy)
1781       report_fatal_error(Twine(UnsafeStackPtrVar) + " must have void* type");
1782     if (UseTLS != UnsafeStackPtr->isThreadLocal())
1783       report_fatal_error(Twine(UnsafeStackPtrVar) + " must " +
1784                          (UseTLS ? "" : "not ") + "be thread-local");
1785   }
1786   return UnsafeStackPtr;
1787 }
1788 
1789 Value *TargetLoweringBase::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
1790   if (!TM.getTargetTriple().isAndroid())
1791     return getDefaultSafeStackPointerLocation(IRB, true);
1792 
1793   // Android provides a libc function to retrieve the address of the current
1794   // thread's unsafe stack pointer.
1795   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1796   Type *StackPtrTy = Type::getInt8PtrTy(M->getContext());
1797   Value *Fn = M->getOrInsertFunction("__safestack_pointer_address",
1798                                      StackPtrTy->getPointerTo(0), nullptr);
1799   return IRB.CreateCall(Fn);
1800 }
1801 
1802 //===----------------------------------------------------------------------===//
1803 //  Loop Strength Reduction hooks
1804 //===----------------------------------------------------------------------===//
1805 
1806 /// isLegalAddressingMode - Return true if the addressing mode represented
1807 /// by AM is legal for this target, for a load/store of the specified type.
1808 bool TargetLoweringBase::isLegalAddressingMode(const DataLayout &DL,
1809                                                const AddrMode &AM, Type *Ty,
1810                                                unsigned AS) const {
1811   // The default implementation of this implements a conservative RISCy, r+r and
1812   // r+i addr mode.
1813 
1814   // Allows a sign-extended 16-bit immediate field.
1815   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
1816     return false;
1817 
1818   // No global is ever allowed as a base.
1819   if (AM.BaseGV)
1820     return false;
1821 
1822   // Only support r+r,
1823   switch (AM.Scale) {
1824   case 0:  // "r+i" or just "i", depending on HasBaseReg.
1825     break;
1826   case 1:
1827     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
1828       return false;
1829     // Otherwise we have r+r or r+i.
1830     break;
1831   case 2:
1832     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
1833       return false;
1834     // Allow 2*r as r+r.
1835     break;
1836   default: // Don't allow n * r
1837     return false;
1838   }
1839 
1840   return true;
1841 }
1842 
1843 //===----------------------------------------------------------------------===//
1844 //  Stack Protector
1845 //===----------------------------------------------------------------------===//
1846 
1847 // For OpenBSD return its special guard variable. Otherwise return nullptr,
1848 // so that SelectionDAG handle SSP.
1849 Value *TargetLoweringBase::getIRStackGuard(IRBuilder<> &IRB) const {
1850   if (getTargetMachine().getTargetTriple().isOSOpenBSD()) {
1851     Module &M = *IRB.GetInsertBlock()->getParent()->getParent();
1852     PointerType *PtrTy = Type::getInt8PtrTy(M.getContext());
1853     return M.getOrInsertGlobal("__guard_local", PtrTy);
1854   }
1855   return nullptr;
1856 }
1857 
1858 // Currently only support "standard" __stack_chk_guard.
1859 // TODO: add LOAD_STACK_GUARD support.
1860 void TargetLoweringBase::insertSSPDeclarations(Module &M) const {
1861   M.getOrInsertGlobal("__stack_chk_guard", Type::getInt8PtrTy(M.getContext()));
1862 }
1863 
1864 // Currently only support "standard" __stack_chk_guard.
1865 // TODO: add LOAD_STACK_GUARD support.
1866 Value *TargetLoweringBase::getSDagStackGuard(const Module &M) const {
1867   return M.getGlobalVariable("__stack_chk_guard", true);
1868 }
1869 
1870 Value *TargetLoweringBase::getSSPStackGuardCheck(const Module &M) const {
1871   return nullptr;
1872 }
1873 
1874 unsigned TargetLoweringBase::getMinimumJumpTableEntries() const {
1875   return MinimumJumpTableEntries;
1876 }
1877 
1878 void TargetLoweringBase::setMinimumJumpTableEntries(unsigned Val) {
1879   MinimumJumpTableEntries = Val;
1880 }
1881 
1882 unsigned TargetLoweringBase::getMaximumJumpTableSize() const {
1883   return MaximumJumpTableSize;
1884 }
1885 
1886 void TargetLoweringBase::setMaximumJumpTableSize(unsigned Val) {
1887   MaximumJumpTableSize = Val;
1888 }
1889 
1890 //===----------------------------------------------------------------------===//
1891 //  Reciprocal Estimates
1892 //===----------------------------------------------------------------------===//
1893 
1894 /// Get the reciprocal estimate attribute string for a function that will
1895 /// override the target defaults.
1896 static StringRef getRecipEstimateForFunc(MachineFunction &MF) {
1897   const Function *F = MF.getFunction();
1898   StringRef RecipAttrName = "reciprocal-estimates";
1899   if (!F->hasFnAttribute(RecipAttrName))
1900     return StringRef();
1901 
1902   return F->getFnAttribute(RecipAttrName).getValueAsString();
1903 }
1904 
1905 /// Construct a string for the given reciprocal operation of the given type.
1906 /// This string should match the corresponding option to the front-end's
1907 /// "-mrecip" flag assuming those strings have been passed through in an
1908 /// attribute string. For example, "vec-divf" for a division of a vXf32.
1909 static std::string getReciprocalOpName(bool IsSqrt, EVT VT) {
1910   std::string Name = VT.isVector() ? "vec-" : "";
1911 
1912   Name += IsSqrt ? "sqrt" : "div";
1913 
1914   // TODO: Handle "half" or other float types?
1915   if (VT.getScalarType() == MVT::f64) {
1916     Name += "d";
1917   } else {
1918     assert(VT.getScalarType() == MVT::f32 &&
1919            "Unexpected FP type for reciprocal estimate");
1920     Name += "f";
1921   }
1922 
1923   return Name;
1924 }
1925 
1926 /// Return the character position and value (a single numeric character) of a
1927 /// customized refinement operation in the input string if it exists. Return
1928 /// false if there is no customized refinement step count.
1929 static bool parseRefinementStep(StringRef In, size_t &Position,
1930                                 uint8_t &Value) {
1931   const char RefStepToken = ':';
1932   Position = In.find(RefStepToken);
1933   if (Position == StringRef::npos)
1934     return false;
1935 
1936   StringRef RefStepString = In.substr(Position + 1);
1937   // Allow exactly one numeric character for the additional refinement
1938   // step parameter.
1939   if (RefStepString.size() == 1) {
1940     char RefStepChar = RefStepString[0];
1941     if (RefStepChar >= '0' && RefStepChar <= '9') {
1942       Value = RefStepChar - '0';
1943       return true;
1944     }
1945   }
1946   report_fatal_error("Invalid refinement step for -recip.");
1947 }
1948 
1949 /// For the input attribute string, return one of the ReciprocalEstimate enum
1950 /// status values (enabled, disabled, or not specified) for this operation on
1951 /// the specified data type.
1952 static int getOpEnabled(bool IsSqrt, EVT VT, StringRef Override) {
1953   if (Override.empty())
1954     return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1955 
1956   SmallVector<StringRef, 4> OverrideVector;
1957   SplitString(Override, OverrideVector, ",");
1958   unsigned NumArgs = OverrideVector.size();
1959 
1960   // Check if "all", "none", or "default" was specified.
1961   if (NumArgs == 1) {
1962     // Look for an optional setting of the number of refinement steps needed
1963     // for this type of reciprocal operation.
1964     size_t RefPos;
1965     uint8_t RefSteps;
1966     if (parseRefinementStep(Override, RefPos, RefSteps)) {
1967       // Split the string for further processing.
1968       Override = Override.substr(0, RefPos);
1969     }
1970 
1971     // All reciprocal types are enabled.
1972     if (Override == "all")
1973       return TargetLoweringBase::ReciprocalEstimate::Enabled;
1974 
1975     // All reciprocal types are disabled.
1976     if (Override == "none")
1977       return TargetLoweringBase::ReciprocalEstimate::Disabled;
1978 
1979     // Target defaults for enablement are used.
1980     if (Override == "default")
1981       return TargetLoweringBase::ReciprocalEstimate::Unspecified;
1982   }
1983 
1984   // The attribute string may omit the size suffix ('f'/'d').
1985   std::string VTName = getReciprocalOpName(IsSqrt, VT);
1986   std::string VTNameNoSize = VTName;
1987   VTNameNoSize.pop_back();
1988   static const char DisabledPrefix = '!';
1989 
1990   for (StringRef RecipType : OverrideVector) {
1991     size_t RefPos;
1992     uint8_t RefSteps;
1993     if (parseRefinementStep(RecipType, RefPos, RefSteps))
1994       RecipType = RecipType.substr(0, RefPos);
1995 
1996     // Ignore the disablement token for string matching.
1997     bool IsDisabled = RecipType[0] == DisabledPrefix;
1998     if (IsDisabled)
1999       RecipType = RecipType.substr(1);
2000 
2001     if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
2002       return IsDisabled ? TargetLoweringBase::ReciprocalEstimate::Disabled
2003                         : TargetLoweringBase::ReciprocalEstimate::Enabled;
2004   }
2005 
2006   return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2007 }
2008 
2009 /// For the input attribute string, return the customized refinement step count
2010 /// for this operation on the specified data type. If the step count does not
2011 /// exist, return the ReciprocalEstimate enum value for unspecified.
2012 static int getOpRefinementSteps(bool IsSqrt, EVT VT, StringRef Override) {
2013   if (Override.empty())
2014     return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2015 
2016   SmallVector<StringRef, 4> OverrideVector;
2017   SplitString(Override, OverrideVector, ",");
2018   unsigned NumArgs = OverrideVector.size();
2019 
2020   // Check if "all", "default", or "none" was specified.
2021   if (NumArgs == 1) {
2022     // Look for an optional setting of the number of refinement steps needed
2023     // for this type of reciprocal operation.
2024     size_t RefPos;
2025     uint8_t RefSteps;
2026     if (!parseRefinementStep(Override, RefPos, RefSteps))
2027       return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2028 
2029     // Split the string for further processing.
2030     Override = Override.substr(0, RefPos);
2031     assert(Override != "none" &&
2032            "Disabled reciprocals, but specifed refinement steps?");
2033 
2034     // If this is a general override, return the specified number of steps.
2035     if (Override == "all" || Override == "default")
2036       return RefSteps;
2037   }
2038 
2039   // The attribute string may omit the size suffix ('f'/'d').
2040   std::string VTName = getReciprocalOpName(IsSqrt, VT);
2041   std::string VTNameNoSize = VTName;
2042   VTNameNoSize.pop_back();
2043 
2044   for (StringRef RecipType : OverrideVector) {
2045     size_t RefPos;
2046     uint8_t RefSteps;
2047     if (!parseRefinementStep(RecipType, RefPos, RefSteps))
2048       continue;
2049 
2050     RecipType = RecipType.substr(0, RefPos);
2051     if (RecipType.equals(VTName) || RecipType.equals(VTNameNoSize))
2052       return RefSteps;
2053   }
2054 
2055   return TargetLoweringBase::ReciprocalEstimate::Unspecified;
2056 }
2057 
2058 int TargetLoweringBase::getRecipEstimateSqrtEnabled(EVT VT,
2059                                                     MachineFunction &MF) const {
2060   return getOpEnabled(true, VT, getRecipEstimateForFunc(MF));
2061 }
2062 
2063 int TargetLoweringBase::getRecipEstimateDivEnabled(EVT VT,
2064                                                    MachineFunction &MF) const {
2065   return getOpEnabled(false, VT, getRecipEstimateForFunc(MF));
2066 }
2067 
2068 int TargetLoweringBase::getSqrtRefinementSteps(EVT VT,
2069                                                MachineFunction &MF) const {
2070   return getOpRefinementSteps(true, VT, getRecipEstimateForFunc(MF));
2071 }
2072 
2073 int TargetLoweringBase::getDivRefinementSteps(EVT VT,
2074                                               MachineFunction &MF) const {
2075   return getOpRefinementSteps(false, VT, getRecipEstimateForFunc(MF));
2076 }
2077