OSDN Git Service

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