TargetLowering.cpp revision c698d3a2a40f0909d16cbe857685f0f22cb9ae43
1//===-- TargetLowering.cpp - Implement the TargetLowering 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 TargetLowering 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/CodeGen/Analysis.h"
18#include "llvm/CodeGen/MachineFrameInfo.h"
19#include "llvm/CodeGen/MachineFunction.h"
20#include "llvm/CodeGen/MachineJumpTableInfo.h"
21#include "llvm/CodeGen/SelectionDAG.h"
22#include "llvm/DataLayout.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/GlobalVariable.h"
25#include "llvm/MC/MCAsmInfo.h"
26#include "llvm/MC/MCExpr.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/MathExtras.h"
30#include "llvm/Target/TargetLoweringObjectFile.h"
31#include "llvm/Target/TargetMachine.h"
32#include "llvm/Target/TargetRegisterInfo.h"
33#include <cctype>
34using namespace llvm;
35
36/// InitLibcallNames - Set default libcall names.
37///
38static void InitLibcallNames(const char **Names) {
39  Names[RTLIB::SHL_I16] = "__ashlhi3";
40  Names[RTLIB::SHL_I32] = "__ashlsi3";
41  Names[RTLIB::SHL_I64] = "__ashldi3";
42  Names[RTLIB::SHL_I128] = "__ashlti3";
43  Names[RTLIB::SRL_I16] = "__lshrhi3";
44  Names[RTLIB::SRL_I32] = "__lshrsi3";
45  Names[RTLIB::SRL_I64] = "__lshrdi3";
46  Names[RTLIB::SRL_I128] = "__lshrti3";
47  Names[RTLIB::SRA_I16] = "__ashrhi3";
48  Names[RTLIB::SRA_I32] = "__ashrsi3";
49  Names[RTLIB::SRA_I64] = "__ashrdi3";
50  Names[RTLIB::SRA_I128] = "__ashrti3";
51  Names[RTLIB::MUL_I8] = "__mulqi3";
52  Names[RTLIB::MUL_I16] = "__mulhi3";
53  Names[RTLIB::MUL_I32] = "__mulsi3";
54  Names[RTLIB::MUL_I64] = "__muldi3";
55  Names[RTLIB::MUL_I128] = "__multi3";
56  Names[RTLIB::MULO_I32] = "__mulosi4";
57  Names[RTLIB::MULO_I64] = "__mulodi4";
58  Names[RTLIB::MULO_I128] = "__muloti4";
59  Names[RTLIB::SDIV_I8] = "__divqi3";
60  Names[RTLIB::SDIV_I16] = "__divhi3";
61  Names[RTLIB::SDIV_I32] = "__divsi3";
62  Names[RTLIB::SDIV_I64] = "__divdi3";
63  Names[RTLIB::SDIV_I128] = "__divti3";
64  Names[RTLIB::UDIV_I8] = "__udivqi3";
65  Names[RTLIB::UDIV_I16] = "__udivhi3";
66  Names[RTLIB::UDIV_I32] = "__udivsi3";
67  Names[RTLIB::UDIV_I64] = "__udivdi3";
68  Names[RTLIB::UDIV_I128] = "__udivti3";
69  Names[RTLIB::SREM_I8] = "__modqi3";
70  Names[RTLIB::SREM_I16] = "__modhi3";
71  Names[RTLIB::SREM_I32] = "__modsi3";
72  Names[RTLIB::SREM_I64] = "__moddi3";
73  Names[RTLIB::SREM_I128] = "__modti3";
74  Names[RTLIB::UREM_I8] = "__umodqi3";
75  Names[RTLIB::UREM_I16] = "__umodhi3";
76  Names[RTLIB::UREM_I32] = "__umodsi3";
77  Names[RTLIB::UREM_I64] = "__umoddi3";
78  Names[RTLIB::UREM_I128] = "__umodti3";
79
80  // These are generally not available.
81  Names[RTLIB::SDIVREM_I8] = 0;
82  Names[RTLIB::SDIVREM_I16] = 0;
83  Names[RTLIB::SDIVREM_I32] = 0;
84  Names[RTLIB::SDIVREM_I64] = 0;
85  Names[RTLIB::SDIVREM_I128] = 0;
86  Names[RTLIB::UDIVREM_I8] = 0;
87  Names[RTLIB::UDIVREM_I16] = 0;
88  Names[RTLIB::UDIVREM_I32] = 0;
89  Names[RTLIB::UDIVREM_I64] = 0;
90  Names[RTLIB::UDIVREM_I128] = 0;
91
92  Names[RTLIB::NEG_I32] = "__negsi2";
93  Names[RTLIB::NEG_I64] = "__negdi2";
94  Names[RTLIB::ADD_F32] = "__addsf3";
95  Names[RTLIB::ADD_F64] = "__adddf3";
96  Names[RTLIB::ADD_F80] = "__addxf3";
97  Names[RTLIB::ADD_PPCF128] = "__gcc_qadd";
98  Names[RTLIB::SUB_F32] = "__subsf3";
99  Names[RTLIB::SUB_F64] = "__subdf3";
100  Names[RTLIB::SUB_F80] = "__subxf3";
101  Names[RTLIB::SUB_PPCF128] = "__gcc_qsub";
102  Names[RTLIB::MUL_F32] = "__mulsf3";
103  Names[RTLIB::MUL_F64] = "__muldf3";
104  Names[RTLIB::MUL_F80] = "__mulxf3";
105  Names[RTLIB::MUL_PPCF128] = "__gcc_qmul";
106  Names[RTLIB::DIV_F32] = "__divsf3";
107  Names[RTLIB::DIV_F64] = "__divdf3";
108  Names[RTLIB::DIV_F80] = "__divxf3";
109  Names[RTLIB::DIV_PPCF128] = "__gcc_qdiv";
110  Names[RTLIB::REM_F32] = "fmodf";
111  Names[RTLIB::REM_F64] = "fmod";
112  Names[RTLIB::REM_F80] = "fmodl";
113  Names[RTLIB::REM_PPCF128] = "fmodl";
114  Names[RTLIB::FMA_F32] = "fmaf";
115  Names[RTLIB::FMA_F64] = "fma";
116  Names[RTLIB::FMA_F80] = "fmal";
117  Names[RTLIB::FMA_PPCF128] = "fmal";
118  Names[RTLIB::POWI_F32] = "__powisf2";
119  Names[RTLIB::POWI_F64] = "__powidf2";
120  Names[RTLIB::POWI_F80] = "__powixf2";
121  Names[RTLIB::POWI_PPCF128] = "__powitf2";
122  Names[RTLIB::SQRT_F32] = "sqrtf";
123  Names[RTLIB::SQRT_F64] = "sqrt";
124  Names[RTLIB::SQRT_F80] = "sqrtl";
125  Names[RTLIB::SQRT_PPCF128] = "sqrtl";
126  Names[RTLIB::LOG_F32] = "logf";
127  Names[RTLIB::LOG_F64] = "log";
128  Names[RTLIB::LOG_F80] = "logl";
129  Names[RTLIB::LOG_PPCF128] = "logl";
130  Names[RTLIB::LOG2_F32] = "log2f";
131  Names[RTLIB::LOG2_F64] = "log2";
132  Names[RTLIB::LOG2_F80] = "log2l";
133  Names[RTLIB::LOG2_PPCF128] = "log2l";
134  Names[RTLIB::LOG10_F32] = "log10f";
135  Names[RTLIB::LOG10_F64] = "log10";
136  Names[RTLIB::LOG10_F80] = "log10l";
137  Names[RTLIB::LOG10_PPCF128] = "log10l";
138  Names[RTLIB::EXP_F32] = "expf";
139  Names[RTLIB::EXP_F64] = "exp";
140  Names[RTLIB::EXP_F80] = "expl";
141  Names[RTLIB::EXP_PPCF128] = "expl";
142  Names[RTLIB::EXP2_F32] = "exp2f";
143  Names[RTLIB::EXP2_F64] = "exp2";
144  Names[RTLIB::EXP2_F80] = "exp2l";
145  Names[RTLIB::EXP2_PPCF128] = "exp2l";
146  Names[RTLIB::SIN_F32] = "sinf";
147  Names[RTLIB::SIN_F64] = "sin";
148  Names[RTLIB::SIN_F80] = "sinl";
149  Names[RTLIB::SIN_PPCF128] = "sinl";
150  Names[RTLIB::COS_F32] = "cosf";
151  Names[RTLIB::COS_F64] = "cos";
152  Names[RTLIB::COS_F80] = "cosl";
153  Names[RTLIB::COS_PPCF128] = "cosl";
154  Names[RTLIB::POW_F32] = "powf";
155  Names[RTLIB::POW_F64] = "pow";
156  Names[RTLIB::POW_F80] = "powl";
157  Names[RTLIB::POW_PPCF128] = "powl";
158  Names[RTLIB::CEIL_F32] = "ceilf";
159  Names[RTLIB::CEIL_F64] = "ceil";
160  Names[RTLIB::CEIL_F80] = "ceill";
161  Names[RTLIB::CEIL_PPCF128] = "ceill";
162  Names[RTLIB::TRUNC_F32] = "truncf";
163  Names[RTLIB::TRUNC_F64] = "trunc";
164  Names[RTLIB::TRUNC_F80] = "truncl";
165  Names[RTLIB::TRUNC_PPCF128] = "truncl";
166  Names[RTLIB::RINT_F32] = "rintf";
167  Names[RTLIB::RINT_F64] = "rint";
168  Names[RTLIB::RINT_F80] = "rintl";
169  Names[RTLIB::RINT_PPCF128] = "rintl";
170  Names[RTLIB::NEARBYINT_F32] = "nearbyintf";
171  Names[RTLIB::NEARBYINT_F64] = "nearbyint";
172  Names[RTLIB::NEARBYINT_F80] = "nearbyintl";
173  Names[RTLIB::NEARBYINT_PPCF128] = "nearbyintl";
174  Names[RTLIB::FLOOR_F32] = "floorf";
175  Names[RTLIB::FLOOR_F64] = "floor";
176  Names[RTLIB::FLOOR_F80] = "floorl";
177  Names[RTLIB::FLOOR_PPCF128] = "floorl";
178  Names[RTLIB::COPYSIGN_F32] = "copysignf";
179  Names[RTLIB::COPYSIGN_F64] = "copysign";
180  Names[RTLIB::COPYSIGN_F80] = "copysignl";
181  Names[RTLIB::COPYSIGN_PPCF128] = "copysignl";
182  Names[RTLIB::FPEXT_F32_F64] = "__extendsfdf2";
183  Names[RTLIB::FPEXT_F16_F32] = "__gnu_h2f_ieee";
184  Names[RTLIB::FPROUND_F32_F16] = "__gnu_f2h_ieee";
185  Names[RTLIB::FPROUND_F64_F32] = "__truncdfsf2";
186  Names[RTLIB::FPROUND_F80_F32] = "__truncxfsf2";
187  Names[RTLIB::FPROUND_PPCF128_F32] = "__trunctfsf2";
188  Names[RTLIB::FPROUND_F80_F64] = "__truncxfdf2";
189  Names[RTLIB::FPROUND_PPCF128_F64] = "__trunctfdf2";
190  Names[RTLIB::FPTOSINT_F32_I8] = "__fixsfqi";
191  Names[RTLIB::FPTOSINT_F32_I16] = "__fixsfhi";
192  Names[RTLIB::FPTOSINT_F32_I32] = "__fixsfsi";
193  Names[RTLIB::FPTOSINT_F32_I64] = "__fixsfdi";
194  Names[RTLIB::FPTOSINT_F32_I128] = "__fixsfti";
195  Names[RTLIB::FPTOSINT_F64_I8] = "__fixdfqi";
196  Names[RTLIB::FPTOSINT_F64_I16] = "__fixdfhi";
197  Names[RTLIB::FPTOSINT_F64_I32] = "__fixdfsi";
198  Names[RTLIB::FPTOSINT_F64_I64] = "__fixdfdi";
199  Names[RTLIB::FPTOSINT_F64_I128] = "__fixdfti";
200  Names[RTLIB::FPTOSINT_F80_I32] = "__fixxfsi";
201  Names[RTLIB::FPTOSINT_F80_I64] = "__fixxfdi";
202  Names[RTLIB::FPTOSINT_F80_I128] = "__fixxfti";
203  Names[RTLIB::FPTOSINT_PPCF128_I32] = "__fixtfsi";
204  Names[RTLIB::FPTOSINT_PPCF128_I64] = "__fixtfdi";
205  Names[RTLIB::FPTOSINT_PPCF128_I128] = "__fixtfti";
206  Names[RTLIB::FPTOUINT_F32_I8] = "__fixunssfqi";
207  Names[RTLIB::FPTOUINT_F32_I16] = "__fixunssfhi";
208  Names[RTLIB::FPTOUINT_F32_I32] = "__fixunssfsi";
209  Names[RTLIB::FPTOUINT_F32_I64] = "__fixunssfdi";
210  Names[RTLIB::FPTOUINT_F32_I128] = "__fixunssfti";
211  Names[RTLIB::FPTOUINT_F64_I8] = "__fixunsdfqi";
212  Names[RTLIB::FPTOUINT_F64_I16] = "__fixunsdfhi";
213  Names[RTLIB::FPTOUINT_F64_I32] = "__fixunsdfsi";
214  Names[RTLIB::FPTOUINT_F64_I64] = "__fixunsdfdi";
215  Names[RTLIB::FPTOUINT_F64_I128] = "__fixunsdfti";
216  Names[RTLIB::FPTOUINT_F80_I32] = "__fixunsxfsi";
217  Names[RTLIB::FPTOUINT_F80_I64] = "__fixunsxfdi";
218  Names[RTLIB::FPTOUINT_F80_I128] = "__fixunsxfti";
219  Names[RTLIB::FPTOUINT_PPCF128_I32] = "__fixunstfsi";
220  Names[RTLIB::FPTOUINT_PPCF128_I64] = "__fixunstfdi";
221  Names[RTLIB::FPTOUINT_PPCF128_I128] = "__fixunstfti";
222  Names[RTLIB::SINTTOFP_I32_F32] = "__floatsisf";
223  Names[RTLIB::SINTTOFP_I32_F64] = "__floatsidf";
224  Names[RTLIB::SINTTOFP_I32_F80] = "__floatsixf";
225  Names[RTLIB::SINTTOFP_I32_PPCF128] = "__floatsitf";
226  Names[RTLIB::SINTTOFP_I64_F32] = "__floatdisf";
227  Names[RTLIB::SINTTOFP_I64_F64] = "__floatdidf";
228  Names[RTLIB::SINTTOFP_I64_F80] = "__floatdixf";
229  Names[RTLIB::SINTTOFP_I64_PPCF128] = "__floatditf";
230  Names[RTLIB::SINTTOFP_I128_F32] = "__floattisf";
231  Names[RTLIB::SINTTOFP_I128_F64] = "__floattidf";
232  Names[RTLIB::SINTTOFP_I128_F80] = "__floattixf";
233  Names[RTLIB::SINTTOFP_I128_PPCF128] = "__floattitf";
234  Names[RTLIB::UINTTOFP_I32_F32] = "__floatunsisf";
235  Names[RTLIB::UINTTOFP_I32_F64] = "__floatunsidf";
236  Names[RTLIB::UINTTOFP_I32_F80] = "__floatunsixf";
237  Names[RTLIB::UINTTOFP_I32_PPCF128] = "__floatunsitf";
238  Names[RTLIB::UINTTOFP_I64_F32] = "__floatundisf";
239  Names[RTLIB::UINTTOFP_I64_F64] = "__floatundidf";
240  Names[RTLIB::UINTTOFP_I64_F80] = "__floatundixf";
241  Names[RTLIB::UINTTOFP_I64_PPCF128] = "__floatunditf";
242  Names[RTLIB::UINTTOFP_I128_F32] = "__floatuntisf";
243  Names[RTLIB::UINTTOFP_I128_F64] = "__floatuntidf";
244  Names[RTLIB::UINTTOFP_I128_F80] = "__floatuntixf";
245  Names[RTLIB::UINTTOFP_I128_PPCF128] = "__floatuntitf";
246  Names[RTLIB::OEQ_F32] = "__eqsf2";
247  Names[RTLIB::OEQ_F64] = "__eqdf2";
248  Names[RTLIB::UNE_F32] = "__nesf2";
249  Names[RTLIB::UNE_F64] = "__nedf2";
250  Names[RTLIB::OGE_F32] = "__gesf2";
251  Names[RTLIB::OGE_F64] = "__gedf2";
252  Names[RTLIB::OLT_F32] = "__ltsf2";
253  Names[RTLIB::OLT_F64] = "__ltdf2";
254  Names[RTLIB::OLE_F32] = "__lesf2";
255  Names[RTLIB::OLE_F64] = "__ledf2";
256  Names[RTLIB::OGT_F32] = "__gtsf2";
257  Names[RTLIB::OGT_F64] = "__gtdf2";
258  Names[RTLIB::UO_F32] = "__unordsf2";
259  Names[RTLIB::UO_F64] = "__unorddf2";
260  Names[RTLIB::O_F32] = "__unordsf2";
261  Names[RTLIB::O_F64] = "__unorddf2";
262  Names[RTLIB::MEMCPY] = "memcpy";
263  Names[RTLIB::MEMMOVE] = "memmove";
264  Names[RTLIB::MEMSET] = "memset";
265  Names[RTLIB::UNWIND_RESUME] = "_Unwind_Resume";
266  Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1] = "__sync_val_compare_and_swap_1";
267  Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2] = "__sync_val_compare_and_swap_2";
268  Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4] = "__sync_val_compare_and_swap_4";
269  Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8] = "__sync_val_compare_and_swap_8";
270  Names[RTLIB::SYNC_LOCK_TEST_AND_SET_1] = "__sync_lock_test_and_set_1";
271  Names[RTLIB::SYNC_LOCK_TEST_AND_SET_2] = "__sync_lock_test_and_set_2";
272  Names[RTLIB::SYNC_LOCK_TEST_AND_SET_4] = "__sync_lock_test_and_set_4";
273  Names[RTLIB::SYNC_LOCK_TEST_AND_SET_8] = "__sync_lock_test_and_set_8";
274  Names[RTLIB::SYNC_FETCH_AND_ADD_1] = "__sync_fetch_and_add_1";
275  Names[RTLIB::SYNC_FETCH_AND_ADD_2] = "__sync_fetch_and_add_2";
276  Names[RTLIB::SYNC_FETCH_AND_ADD_4] = "__sync_fetch_and_add_4";
277  Names[RTLIB::SYNC_FETCH_AND_ADD_8] = "__sync_fetch_and_add_8";
278  Names[RTLIB::SYNC_FETCH_AND_SUB_1] = "__sync_fetch_and_sub_1";
279  Names[RTLIB::SYNC_FETCH_AND_SUB_2] = "__sync_fetch_and_sub_2";
280  Names[RTLIB::SYNC_FETCH_AND_SUB_4] = "__sync_fetch_and_sub_4";
281  Names[RTLIB::SYNC_FETCH_AND_SUB_8] = "__sync_fetch_and_sub_8";
282  Names[RTLIB::SYNC_FETCH_AND_AND_1] = "__sync_fetch_and_and_1";
283  Names[RTLIB::SYNC_FETCH_AND_AND_2] = "__sync_fetch_and_and_2";
284  Names[RTLIB::SYNC_FETCH_AND_AND_4] = "__sync_fetch_and_and_4";
285  Names[RTLIB::SYNC_FETCH_AND_AND_8] = "__sync_fetch_and_and_8";
286  Names[RTLIB::SYNC_FETCH_AND_OR_1] = "__sync_fetch_and_or_1";
287  Names[RTLIB::SYNC_FETCH_AND_OR_2] = "__sync_fetch_and_or_2";
288  Names[RTLIB::SYNC_FETCH_AND_OR_4] = "__sync_fetch_and_or_4";
289  Names[RTLIB::SYNC_FETCH_AND_OR_8] = "__sync_fetch_and_or_8";
290  Names[RTLIB::SYNC_FETCH_AND_XOR_1] = "__sync_fetch_and_xor_1";
291  Names[RTLIB::SYNC_FETCH_AND_XOR_2] = "__sync_fetch_and_xor_2";
292  Names[RTLIB::SYNC_FETCH_AND_XOR_4] = "__sync_fetch_and_xor_4";
293  Names[RTLIB::SYNC_FETCH_AND_XOR_8] = "__sync_fetch_and_xor_8";
294  Names[RTLIB::SYNC_FETCH_AND_NAND_1] = "__sync_fetch_and_nand_1";
295  Names[RTLIB::SYNC_FETCH_AND_NAND_2] = "__sync_fetch_and_nand_2";
296  Names[RTLIB::SYNC_FETCH_AND_NAND_4] = "__sync_fetch_and_nand_4";
297  Names[RTLIB::SYNC_FETCH_AND_NAND_8] = "__sync_fetch_and_nand_8";
298}
299
300/// InitLibcallCallingConvs - Set default libcall CallingConvs.
301///
302static void InitLibcallCallingConvs(CallingConv::ID *CCs) {
303  for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) {
304    CCs[i] = CallingConv::C;
305  }
306}
307
308/// getFPEXT - Return the FPEXT_*_* value for the given types, or
309/// UNKNOWN_LIBCALL if there is none.
310RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) {
311  if (OpVT == MVT::f32) {
312    if (RetVT == MVT::f64)
313      return FPEXT_F32_F64;
314  }
315
316  return UNKNOWN_LIBCALL;
317}
318
319/// getFPROUND - Return the FPROUND_*_* value for the given types, or
320/// UNKNOWN_LIBCALL if there is none.
321RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) {
322  if (RetVT == MVT::f32) {
323    if (OpVT == MVT::f64)
324      return FPROUND_F64_F32;
325    if (OpVT == MVT::f80)
326      return FPROUND_F80_F32;
327    if (OpVT == MVT::ppcf128)
328      return FPROUND_PPCF128_F32;
329  } else if (RetVT == MVT::f64) {
330    if (OpVT == MVT::f80)
331      return FPROUND_F80_F64;
332    if (OpVT == MVT::ppcf128)
333      return FPROUND_PPCF128_F64;
334  }
335
336  return UNKNOWN_LIBCALL;
337}
338
339/// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or
340/// UNKNOWN_LIBCALL if there is none.
341RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) {
342  if (OpVT == MVT::f32) {
343    if (RetVT == MVT::i8)
344      return FPTOSINT_F32_I8;
345    if (RetVT == MVT::i16)
346      return FPTOSINT_F32_I16;
347    if (RetVT == MVT::i32)
348      return FPTOSINT_F32_I32;
349    if (RetVT == MVT::i64)
350      return FPTOSINT_F32_I64;
351    if (RetVT == MVT::i128)
352      return FPTOSINT_F32_I128;
353  } else if (OpVT == MVT::f64) {
354    if (RetVT == MVT::i8)
355      return FPTOSINT_F64_I8;
356    if (RetVT == MVT::i16)
357      return FPTOSINT_F64_I16;
358    if (RetVT == MVT::i32)
359      return FPTOSINT_F64_I32;
360    if (RetVT == MVT::i64)
361      return FPTOSINT_F64_I64;
362    if (RetVT == MVT::i128)
363      return FPTOSINT_F64_I128;
364  } else if (OpVT == MVT::f80) {
365    if (RetVT == MVT::i32)
366      return FPTOSINT_F80_I32;
367    if (RetVT == MVT::i64)
368      return FPTOSINT_F80_I64;
369    if (RetVT == MVT::i128)
370      return FPTOSINT_F80_I128;
371  } else if (OpVT == MVT::ppcf128) {
372    if (RetVT == MVT::i32)
373      return FPTOSINT_PPCF128_I32;
374    if (RetVT == MVT::i64)
375      return FPTOSINT_PPCF128_I64;
376    if (RetVT == MVT::i128)
377      return FPTOSINT_PPCF128_I128;
378  }
379  return UNKNOWN_LIBCALL;
380}
381
382/// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or
383/// UNKNOWN_LIBCALL if there is none.
384RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) {
385  if (OpVT == MVT::f32) {
386    if (RetVT == MVT::i8)
387      return FPTOUINT_F32_I8;
388    if (RetVT == MVT::i16)
389      return FPTOUINT_F32_I16;
390    if (RetVT == MVT::i32)
391      return FPTOUINT_F32_I32;
392    if (RetVT == MVT::i64)
393      return FPTOUINT_F32_I64;
394    if (RetVT == MVT::i128)
395      return FPTOUINT_F32_I128;
396  } else if (OpVT == MVT::f64) {
397    if (RetVT == MVT::i8)
398      return FPTOUINT_F64_I8;
399    if (RetVT == MVT::i16)
400      return FPTOUINT_F64_I16;
401    if (RetVT == MVT::i32)
402      return FPTOUINT_F64_I32;
403    if (RetVT == MVT::i64)
404      return FPTOUINT_F64_I64;
405    if (RetVT == MVT::i128)
406      return FPTOUINT_F64_I128;
407  } else if (OpVT == MVT::f80) {
408    if (RetVT == MVT::i32)
409      return FPTOUINT_F80_I32;
410    if (RetVT == MVT::i64)
411      return FPTOUINT_F80_I64;
412    if (RetVT == MVT::i128)
413      return FPTOUINT_F80_I128;
414  } else if (OpVT == MVT::ppcf128) {
415    if (RetVT == MVT::i32)
416      return FPTOUINT_PPCF128_I32;
417    if (RetVT == MVT::i64)
418      return FPTOUINT_PPCF128_I64;
419    if (RetVT == MVT::i128)
420      return FPTOUINT_PPCF128_I128;
421  }
422  return UNKNOWN_LIBCALL;
423}
424
425/// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or
426/// UNKNOWN_LIBCALL if there is none.
427RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) {
428  if (OpVT == MVT::i32) {
429    if (RetVT == MVT::f32)
430      return SINTTOFP_I32_F32;
431    if (RetVT == MVT::f64)
432      return SINTTOFP_I32_F64;
433    if (RetVT == MVT::f80)
434      return SINTTOFP_I32_F80;
435    if (RetVT == MVT::ppcf128)
436      return SINTTOFP_I32_PPCF128;
437  } else if (OpVT == MVT::i64) {
438    if (RetVT == MVT::f32)
439      return SINTTOFP_I64_F32;
440    if (RetVT == MVT::f64)
441      return SINTTOFP_I64_F64;
442    if (RetVT == MVT::f80)
443      return SINTTOFP_I64_F80;
444    if (RetVT == MVT::ppcf128)
445      return SINTTOFP_I64_PPCF128;
446  } else if (OpVT == MVT::i128) {
447    if (RetVT == MVT::f32)
448      return SINTTOFP_I128_F32;
449    if (RetVT == MVT::f64)
450      return SINTTOFP_I128_F64;
451    if (RetVT == MVT::f80)
452      return SINTTOFP_I128_F80;
453    if (RetVT == MVT::ppcf128)
454      return SINTTOFP_I128_PPCF128;
455  }
456  return UNKNOWN_LIBCALL;
457}
458
459/// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or
460/// UNKNOWN_LIBCALL if there is none.
461RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) {
462  if (OpVT == MVT::i32) {
463    if (RetVT == MVT::f32)
464      return UINTTOFP_I32_F32;
465    if (RetVT == MVT::f64)
466      return UINTTOFP_I32_F64;
467    if (RetVT == MVT::f80)
468      return UINTTOFP_I32_F80;
469    if (RetVT == MVT::ppcf128)
470      return UINTTOFP_I32_PPCF128;
471  } else if (OpVT == MVT::i64) {
472    if (RetVT == MVT::f32)
473      return UINTTOFP_I64_F32;
474    if (RetVT == MVT::f64)
475      return UINTTOFP_I64_F64;
476    if (RetVT == MVT::f80)
477      return UINTTOFP_I64_F80;
478    if (RetVT == MVT::ppcf128)
479      return UINTTOFP_I64_PPCF128;
480  } else if (OpVT == MVT::i128) {
481    if (RetVT == MVT::f32)
482      return UINTTOFP_I128_F32;
483    if (RetVT == MVT::f64)
484      return UINTTOFP_I128_F64;
485    if (RetVT == MVT::f80)
486      return UINTTOFP_I128_F80;
487    if (RetVT == MVT::ppcf128)
488      return UINTTOFP_I128_PPCF128;
489  }
490  return UNKNOWN_LIBCALL;
491}
492
493/// InitCmpLibcallCCs - Set default comparison libcall CC.
494///
495static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
496  memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
497  CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
498  CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
499  CCs[RTLIB::UNE_F32] = ISD::SETNE;
500  CCs[RTLIB::UNE_F64] = ISD::SETNE;
501  CCs[RTLIB::OGE_F32] = ISD::SETGE;
502  CCs[RTLIB::OGE_F64] = ISD::SETGE;
503  CCs[RTLIB::OLT_F32] = ISD::SETLT;
504  CCs[RTLIB::OLT_F64] = ISD::SETLT;
505  CCs[RTLIB::OLE_F32] = ISD::SETLE;
506  CCs[RTLIB::OLE_F64] = ISD::SETLE;
507  CCs[RTLIB::OGT_F32] = ISD::SETGT;
508  CCs[RTLIB::OGT_F64] = ISD::SETGT;
509  CCs[RTLIB::UO_F32] = ISD::SETNE;
510  CCs[RTLIB::UO_F64] = ISD::SETNE;
511  CCs[RTLIB::O_F32] = ISD::SETEQ;
512  CCs[RTLIB::O_F64] = ISD::SETEQ;
513}
514
515/// NOTE: The constructor takes ownership of TLOF.
516TargetLowering::TargetLowering(const TargetMachine &tm,
517                               const TargetLoweringObjectFile *tlof)
518  : TM(tm), TD(TM.getDataLayout()), TLOF(*tlof) {
519  // All operations default to being supported.
520  memset(OpActions, 0, sizeof(OpActions));
521  memset(LoadExtActions, 0, sizeof(LoadExtActions));
522  memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
523  memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
524  memset(CondCodeActions, 0, sizeof(CondCodeActions));
525
526  // Set default actions for various operations.
527  for (unsigned VT = 0; VT != (unsigned)MVT::LAST_VALUETYPE; ++VT) {
528    // Default all indexed load / store to expand.
529    for (unsigned IM = (unsigned)ISD::PRE_INC;
530         IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
531      setIndexedLoadAction(IM, (MVT::SimpleValueType)VT, Expand);
532      setIndexedStoreAction(IM, (MVT::SimpleValueType)VT, Expand);
533    }
534
535    // These operations default to expand.
536    setOperationAction(ISD::FGETSIGN, (MVT::SimpleValueType)VT, Expand);
537    setOperationAction(ISD::CONCAT_VECTORS, (MVT::SimpleValueType)VT, Expand);
538  }
539
540  // Most targets ignore the @llvm.prefetch intrinsic.
541  setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
542
543  // ConstantFP nodes default to expand.  Targets can either change this to
544  // Legal, in which case all fp constants are legal, or use isFPImmLegal()
545  // to optimize expansions for certain constants.
546  setOperationAction(ISD::ConstantFP, MVT::f16, Expand);
547  setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
548  setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
549  setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
550
551  // These library functions default to expand.
552  setOperationAction(ISD::FLOG ,  MVT::f16, Expand);
553  setOperationAction(ISD::FLOG2,  MVT::f16, Expand);
554  setOperationAction(ISD::FLOG10, MVT::f16, Expand);
555  setOperationAction(ISD::FEXP ,  MVT::f16, Expand);
556  setOperationAction(ISD::FEXP2,  MVT::f16, Expand);
557  setOperationAction(ISD::FFLOOR, MVT::f16, Expand);
558  setOperationAction(ISD::FNEARBYINT, MVT::f16, Expand);
559  setOperationAction(ISD::FCEIL,  MVT::f16, Expand);
560  setOperationAction(ISD::FRINT,  MVT::f16, Expand);
561  setOperationAction(ISD::FTRUNC, MVT::f16, Expand);
562  setOperationAction(ISD::FLOG ,  MVT::f32, Expand);
563  setOperationAction(ISD::FLOG2,  MVT::f32, Expand);
564  setOperationAction(ISD::FLOG10, MVT::f32, Expand);
565  setOperationAction(ISD::FEXP ,  MVT::f32, Expand);
566  setOperationAction(ISD::FEXP2,  MVT::f32, Expand);
567  setOperationAction(ISD::FFLOOR, MVT::f32, Expand);
568  setOperationAction(ISD::FNEARBYINT, MVT::f32, Expand);
569  setOperationAction(ISD::FCEIL,  MVT::f32, Expand);
570  setOperationAction(ISD::FRINT,  MVT::f32, Expand);
571  setOperationAction(ISD::FTRUNC, MVT::f32, Expand);
572  setOperationAction(ISD::FLOG ,  MVT::f64, Expand);
573  setOperationAction(ISD::FLOG2,  MVT::f64, Expand);
574  setOperationAction(ISD::FLOG10, MVT::f64, Expand);
575  setOperationAction(ISD::FEXP ,  MVT::f64, Expand);
576  setOperationAction(ISD::FEXP2,  MVT::f64, Expand);
577  setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
578  setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
579  setOperationAction(ISD::FCEIL,  MVT::f64, Expand);
580  setOperationAction(ISD::FRINT,  MVT::f64, Expand);
581  setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
582
583  // Default ISD::TRAP to expand (which turns it into abort).
584  setOperationAction(ISD::TRAP, MVT::Other, Expand);
585
586  // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
587  // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
588  //
589  setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand);
590
591  IsLittleEndian = TD->isLittleEndian();
592  PointerTy = MVT::getIntegerVT(8*TD->getPointerSize(0));
593  memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*));
594  memset(TargetDAGCombineArray, 0, array_lengthof(TargetDAGCombineArray));
595  maxStoresPerMemset = maxStoresPerMemcpy = maxStoresPerMemmove = 8;
596  maxStoresPerMemsetOptSize = maxStoresPerMemcpyOptSize
597    = maxStoresPerMemmoveOptSize = 4;
598  benefitFromCodePlacementOpt = false;
599  UseUnderscoreSetJmp = false;
600  UseUnderscoreLongJmp = false;
601  SelectIsExpensive = false;
602  IntDivIsCheap = false;
603  Pow2DivIsCheap = false;
604  JumpIsExpensive = false;
605  predictableSelectIsExpensive = false;
606  StackPointerRegisterToSaveRestore = 0;
607  ExceptionPointerRegister = 0;
608  ExceptionSelectorRegister = 0;
609  BooleanContents = UndefinedBooleanContent;
610  BooleanVectorContents = UndefinedBooleanContent;
611  SchedPreferenceInfo = Sched::ILP;
612  JumpBufSize = 0;
613  JumpBufAlignment = 0;
614  MinFunctionAlignment = 0;
615  PrefFunctionAlignment = 0;
616  PrefLoopAlignment = 0;
617  MinStackArgumentAlignment = 1;
618  ShouldFoldAtomicFences = false;
619  InsertFencesForAtomic = false;
620  SupportJumpTables = true;
621  MinimumJumpTableEntries = 4;
622
623  InitLibcallNames(LibcallRoutineNames);
624  InitCmpLibcallCCs(CmpLibcallCCs);
625  InitLibcallCallingConvs(LibcallCallingConvs);
626}
627
628TargetLowering::~TargetLowering() {
629  delete &TLOF;
630}
631
632MVT TargetLowering::getShiftAmountTy(EVT LHSTy) const {
633  return MVT::getIntegerVT(8*TD->getPointerSize(0));
634}
635
636/// canOpTrap - Returns true if the operation can trap for the value type.
637/// VT must be a legal type.
638bool TargetLowering::canOpTrap(unsigned Op, EVT VT) const {
639  assert(isTypeLegal(VT));
640  switch (Op) {
641  default:
642    return false;
643  case ISD::FDIV:
644  case ISD::FREM:
645  case ISD::SDIV:
646  case ISD::UDIV:
647  case ISD::SREM:
648  case ISD::UREM:
649    return true;
650  }
651}
652
653
654static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
655                                          unsigned &NumIntermediates,
656                                          MVT &RegisterVT,
657                                          TargetLowering *TLI) {
658  // Figure out the right, legal destination reg to copy into.
659  unsigned NumElts = VT.getVectorNumElements();
660  MVT EltTy = VT.getVectorElementType();
661
662  unsigned NumVectorRegs = 1;
663
664  // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally we
665  // could break down into LHS/RHS like LegalizeDAG does.
666  if (!isPowerOf2_32(NumElts)) {
667    NumVectorRegs = NumElts;
668    NumElts = 1;
669  }
670
671  // Divide the input until we get to a supported size.  This will always
672  // end with a scalar if the target doesn't support vectors.
673  while (NumElts > 1 && !TLI->isTypeLegal(MVT::getVectorVT(EltTy, NumElts))) {
674    NumElts >>= 1;
675    NumVectorRegs <<= 1;
676  }
677
678  NumIntermediates = NumVectorRegs;
679
680  MVT NewVT = MVT::getVectorVT(EltTy, NumElts);
681  if (!TLI->isTypeLegal(NewVT))
682    NewVT = EltTy;
683  IntermediateVT = NewVT;
684
685  unsigned NewVTSize = NewVT.getSizeInBits();
686
687  // Convert sizes such as i33 to i64.
688  if (!isPowerOf2_32(NewVTSize))
689    NewVTSize = NextPowerOf2(NewVTSize);
690
691  MVT DestVT = TLI->getRegisterType(NewVT);
692  RegisterVT = DestVT;
693  if (EVT(DestVT).bitsLT(NewVT))    // Value is expanded, e.g. i64 -> i16.
694    return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
695
696  // Otherwise, promotion or legal types use the same number of registers as
697  // the vector decimated to the appropriate level.
698  return NumVectorRegs;
699}
700
701/// isLegalRC - Return true if the value types that can be represented by the
702/// specified register class are all legal.
703bool TargetLowering::isLegalRC(const TargetRegisterClass *RC) const {
704  for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
705       I != E; ++I) {
706    if (isTypeLegal(*I))
707      return true;
708  }
709  return false;
710}
711
712/// findRepresentativeClass - Return the largest legal super-reg register class
713/// of the register class for the specified type and its associated "cost".
714std::pair<const TargetRegisterClass*, uint8_t>
715TargetLowering::findRepresentativeClass(MVT VT) const {
716  const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
717  const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
718  if (!RC)
719    return std::make_pair(RC, 0);
720
721  // Compute the set of all super-register classes.
722  BitVector SuperRegRC(TRI->getNumRegClasses());
723  for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
724    SuperRegRC.setBitsInMask(RCI.getMask());
725
726  // Find the first legal register class with the largest spill size.
727  const TargetRegisterClass *BestRC = RC;
728  for (int i = SuperRegRC.find_first(); i >= 0; i = SuperRegRC.find_next(i)) {
729    const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
730    // We want the largest possible spill size.
731    if (SuperRC->getSize() <= BestRC->getSize())
732      continue;
733    if (!isLegalRC(SuperRC))
734      continue;
735    BestRC = SuperRC;
736  }
737  return std::make_pair(BestRC, 1);
738}
739
740/// computeRegisterProperties - Once all of the register classes are added,
741/// this allows us to compute derived properties we expose.
742void TargetLowering::computeRegisterProperties() {
743  assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE &&
744         "Too many value types for ValueTypeActions to hold!");
745
746  // Everything defaults to needing one register.
747  for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
748    NumRegistersForVT[i] = 1;
749    RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
750  }
751  // ...except isVoid, which doesn't need any registers.
752  NumRegistersForVT[MVT::isVoid] = 0;
753
754  // Find the largest integer register class.
755  unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
756  for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg)
757    assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
758
759  // Every integer value type larger than this largest register takes twice as
760  // many registers to represent as the previous ValueType.
761  for (unsigned ExpandedReg = LargestIntReg + 1;
762       ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
763    NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
764    RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
765    TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
766    ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg,
767                                   TypeExpandInteger);
768  }
769
770  // Inspect all of the ValueType's smaller than the largest integer
771  // register to see which ones need promotion.
772  unsigned LegalIntReg = LargestIntReg;
773  for (unsigned IntReg = LargestIntReg - 1;
774       IntReg >= (unsigned)MVT::i1; --IntReg) {
775    MVT IVT = (MVT::SimpleValueType)IntReg;
776    if (isTypeLegal(IVT)) {
777      LegalIntReg = IntReg;
778    } else {
779      RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
780        (const MVT::SimpleValueType)LegalIntReg;
781      ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
782    }
783  }
784
785  // ppcf128 type is really two f64's.
786  if (!isTypeLegal(MVT::ppcf128)) {
787    NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
788    RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
789    TransformToType[MVT::ppcf128] = MVT::f64;
790    ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
791  }
792
793  // Decide how to handle f64. If the target does not have native f64 support,
794  // expand it to i64 and we will be generating soft float library calls.
795  if (!isTypeLegal(MVT::f64)) {
796    NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
797    RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
798    TransformToType[MVT::f64] = MVT::i64;
799    ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
800  }
801
802  // Decide how to handle f32. If the target does not have native support for
803  // f32, promote it to f64 if it is legal. Otherwise, expand it to i32.
804  if (!isTypeLegal(MVT::f32)) {
805    if (isTypeLegal(MVT::f64)) {
806      NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::f64];
807      RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::f64];
808      TransformToType[MVT::f32] = MVT::f64;
809      ValueTypeActions.setTypeAction(MVT::f32, TypePromoteInteger);
810    } else {
811      NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
812      RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
813      TransformToType[MVT::f32] = MVT::i32;
814      ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
815    }
816  }
817
818  // Loop over all of the vector value types to see which need transformations.
819  for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
820       i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
821    MVT VT = (MVT::SimpleValueType)i;
822    if (isTypeLegal(VT)) continue;
823
824    // Determine if there is a legal wider type.  If so, we should promote to
825    // that wider vector type.
826    MVT EltVT = VT.getVectorElementType();
827    unsigned NElts = VT.getVectorNumElements();
828    if (NElts != 1 && !shouldSplitVectorElementType(EltVT)) {
829      bool IsLegalWiderType = false;
830      // First try to promote the elements of integer vectors. If no legal
831      // promotion was found, fallback to the widen-vector method.
832      for (unsigned nVT = i+1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
833        MVT SVT = (MVT::SimpleValueType)nVT;
834        // Promote vectors of integers to vectors with the same number
835        // of elements, with a wider element type.
836        if (SVT.getVectorElementType().getSizeInBits() > EltVT.getSizeInBits()
837            && SVT.getVectorNumElements() == NElts &&
838            isTypeLegal(SVT) && SVT.getScalarType().isInteger()) {
839          TransformToType[i] = SVT;
840          RegisterTypeForVT[i] = SVT;
841          NumRegistersForVT[i] = 1;
842          ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
843          IsLegalWiderType = true;
844          break;
845        }
846      }
847
848      if (IsLegalWiderType) continue;
849
850      // Try to widen the vector.
851      for (unsigned nVT = i+1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
852        MVT SVT = (MVT::SimpleValueType)nVT;
853        if (SVT.getVectorElementType() == EltVT &&
854            SVT.getVectorNumElements() > NElts &&
855            isTypeLegal(SVT)) {
856          TransformToType[i] = SVT;
857          RegisterTypeForVT[i] = SVT;
858          NumRegistersForVT[i] = 1;
859          ValueTypeActions.setTypeAction(VT, TypeWidenVector);
860          IsLegalWiderType = true;
861          break;
862        }
863      }
864      if (IsLegalWiderType) continue;
865    }
866
867    MVT IntermediateVT;
868    MVT RegisterVT;
869    unsigned NumIntermediates;
870    NumRegistersForVT[i] =
871      getVectorTypeBreakdownMVT(VT, IntermediateVT, NumIntermediates,
872                                RegisterVT, this);
873    RegisterTypeForVT[i] = RegisterVT;
874
875    MVT NVT = VT.getPow2VectorType();
876    if (NVT == VT) {
877      // Type is already a power of 2.  The default action is to split.
878      TransformToType[i] = MVT::Other;
879      unsigned NumElts = VT.getVectorNumElements();
880      ValueTypeActions.setTypeAction(VT,
881            NumElts > 1 ? TypeSplitVector : TypeScalarizeVector);
882    } else {
883      TransformToType[i] = NVT;
884      ValueTypeActions.setTypeAction(VT, TypeWidenVector);
885    }
886  }
887
888  // Determine the 'representative' register class for each value type.
889  // An representative register class is the largest (meaning one which is
890  // not a sub-register class / subreg register class) legal register class for
891  // a group of value types. For example, on i386, i8, i16, and i32
892  // representative would be GR32; while on x86_64 it's GR64.
893  for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
894    const TargetRegisterClass* RRC;
895    uint8_t Cost;
896    tie(RRC, Cost) =  findRepresentativeClass((MVT::SimpleValueType)i);
897    RepRegClassForVT[i] = RRC;
898    RepRegClassCostForVT[i] = Cost;
899  }
900}
901
902const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
903  return NULL;
904}
905
906EVT TargetLowering::getSetCCResultType(EVT VT) const {
907  assert(!VT.isVector() && "No default SetCC type for vectors!");
908  return getPointerTy(0).SimpleTy;
909}
910
911MVT::SimpleValueType TargetLowering::getCmpLibcallReturnType() const {
912  return MVT::i32; // return the default value
913}
914
915/// getVectorTypeBreakdown - Vector types are broken down into some number of
916/// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
917/// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
918/// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
919///
920/// This method returns the number of registers needed, and the VT for each
921/// register.  It also returns the VT and quantity of the intermediate values
922/// before they are promoted/expanded.
923///
924unsigned TargetLowering::getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
925                                                EVT &IntermediateVT,
926                                                unsigned &NumIntermediates,
927                                                MVT &RegisterVT) const {
928  unsigned NumElts = VT.getVectorNumElements();
929
930  // If there is a wider vector type with the same element type as this one,
931  // or a promoted vector type that has the same number of elements which
932  // are wider, then we should convert to that legal vector type.
933  // This handles things like <2 x float> -> <4 x float> and
934  // <4 x i1> -> <4 x i32>.
935  LegalizeTypeAction TA = getTypeAction(Context, VT);
936  if (NumElts != 1 && (TA == TypeWidenVector || TA == TypePromoteInteger)) {
937    EVT RegisterEVT = getTypeToTransformTo(Context, VT);
938    if (isTypeLegal(RegisterEVT)) {
939      IntermediateVT = RegisterEVT;
940      RegisterVT = RegisterEVT.getSimpleVT();
941      NumIntermediates = 1;
942      return 1;
943    }
944  }
945
946  // Figure out the right, legal destination reg to copy into.
947  EVT EltTy = VT.getVectorElementType();
948
949  unsigned NumVectorRegs = 1;
950
951  // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally we
952  // could break down into LHS/RHS like LegalizeDAG does.
953  if (!isPowerOf2_32(NumElts)) {
954    NumVectorRegs = NumElts;
955    NumElts = 1;
956  }
957
958  // Divide the input until we get to a supported size.  This will always
959  // end with a scalar if the target doesn't support vectors.
960  while (NumElts > 1 && !isTypeLegal(
961                                   EVT::getVectorVT(Context, EltTy, NumElts))) {
962    NumElts >>= 1;
963    NumVectorRegs <<= 1;
964  }
965
966  NumIntermediates = NumVectorRegs;
967
968  EVT NewVT = EVT::getVectorVT(Context, EltTy, NumElts);
969  if (!isTypeLegal(NewVT))
970    NewVT = EltTy;
971  IntermediateVT = NewVT;
972
973  MVT DestVT = getRegisterType(Context, NewVT);
974  RegisterVT = DestVT;
975  unsigned NewVTSize = NewVT.getSizeInBits();
976
977  // Convert sizes such as i33 to i64.
978  if (!isPowerOf2_32(NewVTSize))
979    NewVTSize = NextPowerOf2(NewVTSize);
980
981  if (EVT(DestVT).bitsLT(NewVT))   // Value is expanded, e.g. i64 -> i16.
982    return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
983
984  // Otherwise, promotion or legal types use the same number of registers as
985  // the vector decimated to the appropriate level.
986  return NumVectorRegs;
987}
988
989/// Get the EVTs and ArgFlags collections that represent the legalized return
990/// type of the given function.  This does not require a DAG or a return value,
991/// and is suitable for use before any DAGs for the function are constructed.
992/// TODO: Move this out of TargetLowering.cpp.
993void llvm::GetReturnInfo(Type* ReturnType, Attribute attr,
994                         SmallVectorImpl<ISD::OutputArg> &Outs,
995                         const TargetLowering &TLI) {
996  SmallVector<EVT, 4> ValueVTs;
997  ComputeValueVTs(TLI, ReturnType, ValueVTs);
998  unsigned NumValues = ValueVTs.size();
999  if (NumValues == 0) return;
1000
1001  for (unsigned j = 0, f = NumValues; j != f; ++j) {
1002    EVT VT = ValueVTs[j];
1003    ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1004
1005    if (attr.hasAttribute(Attribute::SExt))
1006      ExtendKind = ISD::SIGN_EXTEND;
1007    else if (attr.hasAttribute(Attribute::ZExt))
1008      ExtendKind = ISD::ZERO_EXTEND;
1009
1010    // FIXME: C calling convention requires the return type to be promoted to
1011    // at least 32-bit. But this is not necessary for non-C calling
1012    // conventions. The frontend should mark functions whose return values
1013    // require promoting with signext or zeroext attributes.
1014    if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1015      MVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
1016      if (VT.bitsLT(MinVT))
1017        VT = MinVT;
1018    }
1019
1020    unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
1021    MVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
1022
1023    // 'inreg' on function refers to return value
1024    ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1025    if (attr.hasAttribute(Attribute::InReg))
1026      Flags.setInReg();
1027
1028    // Propagate extension type if any
1029    if (attr.hasAttribute(Attribute::SExt))
1030      Flags.setSExt();
1031    else if (attr.hasAttribute(Attribute::ZExt))
1032      Flags.setZExt();
1033
1034    for (unsigned i = 0; i < NumParts; ++i)
1035      Outs.push_back(ISD::OutputArg(Flags, PartVT, /*isFixed=*/true, 0, 0));
1036  }
1037}
1038
1039/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1040/// function arguments in the caller parameter area.  This is the actual
1041/// alignment, not its logarithm.
1042unsigned TargetLowering::getByValTypeAlignment(Type *Ty) const {
1043  return TD->getCallFrameTypeAlignment(Ty);
1044}
1045
1046/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1047/// current function.  The returned value is a member of the
1048/// MachineJumpTableInfo::JTEntryKind enum.
1049unsigned TargetLowering::getJumpTableEncoding() const {
1050  // In non-pic modes, just use the address of a block.
1051  if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
1052    return MachineJumpTableInfo::EK_BlockAddress;
1053
1054  // In PIC mode, if the target supports a GPRel32 directive, use it.
1055  if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != 0)
1056    return MachineJumpTableInfo::EK_GPRel32BlockAddress;
1057
1058  // Otherwise, use a label difference.
1059  return MachineJumpTableInfo::EK_LabelDifference32;
1060}
1061
1062SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1063                                                 SelectionDAG &DAG) const {
1064  // If our PIC model is GP relative, use the global offset table as the base.
1065  unsigned JTEncoding = getJumpTableEncoding();
1066
1067  if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
1068      (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
1069    return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(0));
1070
1071  return Table;
1072}
1073
1074/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1075/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1076/// MCExpr.
1077const MCExpr *
1078TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
1079                                             unsigned JTI,MCContext &Ctx) const{
1080  // The normal PIC reloc base is the label at the start of the jump table.
1081  return MCSymbolRefExpr::Create(MF->getJTISymbol(JTI, Ctx), Ctx);
1082}
1083
1084bool
1085TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1086  // Assume that everything is safe in static mode.
1087  if (getTargetMachine().getRelocationModel() == Reloc::Static)
1088    return true;
1089
1090  // In dynamic-no-pic mode, assume that known defined values are safe.
1091  if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC &&
1092      GA &&
1093      !GA->getGlobal()->isDeclaration() &&
1094      !GA->getGlobal()->isWeakForLinker())
1095    return true;
1096
1097  // Otherwise assume nothing is safe.
1098  return false;
1099}
1100
1101//===----------------------------------------------------------------------===//
1102//  Optimization Methods
1103//===----------------------------------------------------------------------===//
1104
1105/// ShrinkDemandedConstant - Check to see if the specified operand of the
1106/// specified instruction is a constant integer.  If so, check to see if there
1107/// are any bits set in the constant that are not demanded.  If so, shrink the
1108/// constant and return true.
1109bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
1110                                                        const APInt &Demanded) {
1111  DebugLoc dl = Op.getDebugLoc();
1112
1113  // FIXME: ISD::SELECT, ISD::SELECT_CC
1114  switch (Op.getOpcode()) {
1115  default: break;
1116  case ISD::XOR:
1117  case ISD::AND:
1118  case ISD::OR: {
1119    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1120    if (!C) return false;
1121
1122    if (Op.getOpcode() == ISD::XOR &&
1123        (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
1124      return false;
1125
1126    // if we can expand it to have all bits set, do it
1127    if (C->getAPIntValue().intersects(~Demanded)) {
1128      EVT VT = Op.getValueType();
1129      SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
1130                                DAG.getConstant(Demanded &
1131                                                C->getAPIntValue(),
1132                                                VT));
1133      return CombineTo(Op, New);
1134    }
1135
1136    break;
1137  }
1138  }
1139
1140  return false;
1141}
1142
1143/// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
1144/// casts are free.  This uses isZExtFree and ZERO_EXTEND for the widening
1145/// cast, but it could be generalized for targets with other types of
1146/// implicit widening casts.
1147bool
1148TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
1149                                                    unsigned BitWidth,
1150                                                    const APInt &Demanded,
1151                                                    DebugLoc dl) {
1152  assert(Op.getNumOperands() == 2 &&
1153         "ShrinkDemandedOp only supports binary operators!");
1154  assert(Op.getNode()->getNumValues() == 1 &&
1155         "ShrinkDemandedOp only supports nodes with one result!");
1156
1157  // Don't do this if the node has another user, which may require the
1158  // full value.
1159  if (!Op.getNode()->hasOneUse())
1160    return false;
1161
1162  // Search for the smallest integer type with free casts to and from
1163  // Op's type. For expedience, just check power-of-2 integer types.
1164  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1165  unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
1166  unsigned SmallVTBits = DemandedSize;
1167  if (!isPowerOf2_32(SmallVTBits))
1168    SmallVTBits = NextPowerOf2(SmallVTBits);
1169  for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
1170    EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
1171    if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
1172        TLI.isZExtFree(SmallVT, Op.getValueType())) {
1173      // We found a type with free casts.
1174      SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
1175                              DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
1176                                          Op.getNode()->getOperand(0)),
1177                              DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
1178                                          Op.getNode()->getOperand(1)));
1179      bool NeedZext = DemandedSize > SmallVTBits;
1180      SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
1181                              dl, Op.getValueType(), X);
1182      return CombineTo(Op, Z);
1183    }
1184  }
1185  return false;
1186}
1187
1188/// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
1189/// DemandedMask bits of the result of Op are ever used downstream.  If we can
1190/// use this information to simplify Op, create a new simplified DAG node and
1191/// return true, returning the original and new nodes in Old and New. Otherwise,
1192/// analyze the expression and return a mask of KnownOne and KnownZero bits for
1193/// the expression (used to simplify the caller).  The KnownZero/One bits may
1194/// only be accurate for those bits in the DemandedMask.
1195bool TargetLowering::SimplifyDemandedBits(SDValue Op,
1196                                          const APInt &DemandedMask,
1197                                          APInt &KnownZero,
1198                                          APInt &KnownOne,
1199                                          TargetLoweringOpt &TLO,
1200                                          unsigned Depth) const {
1201  unsigned BitWidth = DemandedMask.getBitWidth();
1202  assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
1203         "Mask size mismatches value type size!");
1204  APInt NewMask = DemandedMask;
1205  DebugLoc dl = Op.getDebugLoc();
1206
1207  // Don't know anything.
1208  KnownZero = KnownOne = APInt(BitWidth, 0);
1209
1210  // Other users may use these bits.
1211  if (!Op.getNode()->hasOneUse()) {
1212    if (Depth != 0) {
1213      // If not at the root, Just compute the KnownZero/KnownOne bits to
1214      // simplify things downstream.
1215      TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
1216      return false;
1217    }
1218    // If this is the root being simplified, allow it to have multiple uses,
1219    // just set the NewMask to all bits.
1220    NewMask = APInt::getAllOnesValue(BitWidth);
1221  } else if (DemandedMask == 0) {
1222    // Not demanding any bits from Op.
1223    if (Op.getOpcode() != ISD::UNDEF)
1224      return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
1225    return false;
1226  } else if (Depth == 6) {        // Limit search depth.
1227    return false;
1228  }
1229
1230  APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
1231  switch (Op.getOpcode()) {
1232  case ISD::Constant:
1233    // We know all of the bits for a constant!
1234    KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
1235    KnownZero = ~KnownOne;
1236    return false;   // Don't fall through, will infinitely loop.
1237  case ISD::AND:
1238    // If the RHS is a constant, check to see if the LHS would be zero without
1239    // using the bits from the RHS.  Below, we use knowledge about the RHS to
1240    // simplify the LHS, here we're using information from the LHS to simplify
1241    // the RHS.
1242    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1243      APInt LHSZero, LHSOne;
1244      // Do not increment Depth here; that can cause an infinite loop.
1245      TLO.DAG.ComputeMaskedBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
1246      // If the LHS already has zeros where RHSC does, this and is dead.
1247      if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
1248        return TLO.CombineTo(Op, Op.getOperand(0));
1249      // If any of the set bits in the RHS are known zero on the LHS, shrink
1250      // the constant.
1251      if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
1252        return true;
1253    }
1254
1255    if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
1256                             KnownOne, TLO, Depth+1))
1257      return true;
1258    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1259    if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
1260                             KnownZero2, KnownOne2, TLO, Depth+1))
1261      return true;
1262    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1263
1264    // If all of the demanded bits are known one on one side, return the other.
1265    // These bits cannot contribute to the result of the 'and'.
1266    if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
1267      return TLO.CombineTo(Op, Op.getOperand(0));
1268    if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
1269      return TLO.CombineTo(Op, Op.getOperand(1));
1270    // If all of the demanded bits in the inputs are known zeros, return zero.
1271    if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
1272      return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
1273    // If the RHS is a constant, see if we can simplify it.
1274    if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
1275      return true;
1276    // If the operation can be done in a smaller type, do so.
1277    if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1278      return true;
1279
1280    // Output known-1 bits are only known if set in both the LHS & RHS.
1281    KnownOne &= KnownOne2;
1282    // Output known-0 are known to be clear if zero in either the LHS | RHS.
1283    KnownZero |= KnownZero2;
1284    break;
1285  case ISD::OR:
1286    if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
1287                             KnownOne, TLO, Depth+1))
1288      return true;
1289    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1290    if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
1291                             KnownZero2, KnownOne2, TLO, Depth+1))
1292      return true;
1293    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1294
1295    // If all of the demanded bits are known zero on one side, return the other.
1296    // These bits cannot contribute to the result of the 'or'.
1297    if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
1298      return TLO.CombineTo(Op, Op.getOperand(0));
1299    if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
1300      return TLO.CombineTo(Op, Op.getOperand(1));
1301    // If all of the potentially set bits on one side are known to be set on
1302    // the other side, just use the 'other' side.
1303    if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
1304      return TLO.CombineTo(Op, Op.getOperand(0));
1305    if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
1306      return TLO.CombineTo(Op, Op.getOperand(1));
1307    // If the RHS is a constant, see if we can simplify it.
1308    if (TLO.ShrinkDemandedConstant(Op, NewMask))
1309      return true;
1310    // If the operation can be done in a smaller type, do so.
1311    if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1312      return true;
1313
1314    // Output known-0 bits are only known if clear in both the LHS & RHS.
1315    KnownZero &= KnownZero2;
1316    // Output known-1 are known to be set if set in either the LHS | RHS.
1317    KnownOne |= KnownOne2;
1318    break;
1319  case ISD::XOR:
1320    if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
1321                             KnownOne, TLO, Depth+1))
1322      return true;
1323    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1324    if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
1325                             KnownOne2, TLO, Depth+1))
1326      return true;
1327    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1328
1329    // If all of the demanded bits are known zero on one side, return the other.
1330    // These bits cannot contribute to the result of the 'xor'.
1331    if ((KnownZero & NewMask) == NewMask)
1332      return TLO.CombineTo(Op, Op.getOperand(0));
1333    if ((KnownZero2 & NewMask) == NewMask)
1334      return TLO.CombineTo(Op, Op.getOperand(1));
1335    // If the operation can be done in a smaller type, do so.
1336    if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1337      return true;
1338
1339    // If all of the unknown bits are known to be zero on one side or the other
1340    // (but not both) turn this into an *inclusive* or.
1341    //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1342    if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
1343      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
1344                                               Op.getOperand(0),
1345                                               Op.getOperand(1)));
1346
1347    // Output known-0 bits are known if clear or set in both the LHS & RHS.
1348    KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1349    // Output known-1 are known to be set if set in only one of the LHS, RHS.
1350    KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1351
1352    // If all of the demanded bits on one side are known, and all of the set
1353    // bits on that side are also known to be set on the other side, turn this
1354    // into an AND, as we know the bits will be cleared.
1355    //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1356    // NB: it is okay if more bits are known than are requested
1357    if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
1358      if (KnownOne == KnownOne2) { // set bits are the same on both sides
1359        EVT VT = Op.getValueType();
1360        SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT);
1361        return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
1362                                                 Op.getOperand(0), ANDC));
1363      }
1364    }
1365
1366    // If the RHS is a constant, see if we can simplify it.
1367    // for XOR, we prefer to force bits to 1 if they will make a -1.
1368    // if we can't force bits, try to shrink constant
1369    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1370      APInt Expanded = C->getAPIntValue() | (~NewMask);
1371      // if we can expand it to have all bits set, do it
1372      if (Expanded.isAllOnesValue()) {
1373        if (Expanded != C->getAPIntValue()) {
1374          EVT VT = Op.getValueType();
1375          SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
1376                                          TLO.DAG.getConstant(Expanded, VT));
1377          return TLO.CombineTo(Op, New);
1378        }
1379        // if it already has all the bits set, nothing to change
1380        // but don't shrink either!
1381      } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
1382        return true;
1383      }
1384    }
1385
1386    KnownZero = KnownZeroOut;
1387    KnownOne  = KnownOneOut;
1388    break;
1389  case ISD::SELECT:
1390    if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
1391                             KnownOne, TLO, Depth+1))
1392      return true;
1393    if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
1394                             KnownOne2, TLO, Depth+1))
1395      return true;
1396    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1397    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1398
1399    // If the operands are constants, see if we can simplify them.
1400    if (TLO.ShrinkDemandedConstant(Op, NewMask))
1401      return true;
1402
1403    // Only known if known in both the LHS and RHS.
1404    KnownOne &= KnownOne2;
1405    KnownZero &= KnownZero2;
1406    break;
1407  case ISD::SELECT_CC:
1408    if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
1409                             KnownOne, TLO, Depth+1))
1410      return true;
1411    if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
1412                             KnownOne2, TLO, Depth+1))
1413      return true;
1414    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1415    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1416
1417    // If the operands are constants, see if we can simplify them.
1418    if (TLO.ShrinkDemandedConstant(Op, NewMask))
1419      return true;
1420
1421    // Only known if known in both the LHS and RHS.
1422    KnownOne &= KnownOne2;
1423    KnownZero &= KnownZero2;
1424    break;
1425  case ISD::SHL:
1426    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1427      unsigned ShAmt = SA->getZExtValue();
1428      SDValue InOp = Op.getOperand(0);
1429
1430      // If the shift count is an invalid immediate, don't do anything.
1431      if (ShAmt >= BitWidth)
1432        break;
1433
1434      // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1435      // single shift.  We can do this if the bottom bits (which are shifted
1436      // out) are never demanded.
1437      if (InOp.getOpcode() == ISD::SRL &&
1438          isa<ConstantSDNode>(InOp.getOperand(1))) {
1439        if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
1440          unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
1441          unsigned Opc = ISD::SHL;
1442          int Diff = ShAmt-C1;
1443          if (Diff < 0) {
1444            Diff = -Diff;
1445            Opc = ISD::SRL;
1446          }
1447
1448          SDValue NewSA =
1449            TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
1450          EVT VT = Op.getValueType();
1451          return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
1452                                                   InOp.getOperand(0), NewSA));
1453        }
1454      }
1455
1456      if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
1457                               KnownZero, KnownOne, TLO, Depth+1))
1458        return true;
1459
1460      // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1461      // are not demanded. This will likely allow the anyext to be folded away.
1462      if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
1463        SDValue InnerOp = InOp.getNode()->getOperand(0);
1464        EVT InnerVT = InnerOp.getValueType();
1465        unsigned InnerBits = InnerVT.getSizeInBits();
1466        if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
1467            isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1468          EVT ShTy = getShiftAmountTy(InnerVT);
1469          if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
1470            ShTy = InnerVT;
1471          SDValue NarrowShl =
1472            TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
1473                            TLO.DAG.getConstant(ShAmt, ShTy));
1474          return
1475            TLO.CombineTo(Op,
1476                          TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
1477                                          NarrowShl));
1478        }
1479      }
1480
1481      KnownZero <<= SA->getZExtValue();
1482      KnownOne  <<= SA->getZExtValue();
1483      // low bits known zero.
1484      KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
1485    }
1486    break;
1487  case ISD::SRL:
1488    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1489      EVT VT = Op.getValueType();
1490      unsigned ShAmt = SA->getZExtValue();
1491      unsigned VTSize = VT.getSizeInBits();
1492      SDValue InOp = Op.getOperand(0);
1493
1494      // If the shift count is an invalid immediate, don't do anything.
1495      if (ShAmt >= BitWidth)
1496        break;
1497
1498      // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1499      // single shift.  We can do this if the top bits (which are shifted out)
1500      // are never demanded.
1501      if (InOp.getOpcode() == ISD::SHL &&
1502          isa<ConstantSDNode>(InOp.getOperand(1))) {
1503        if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
1504          unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
1505          unsigned Opc = ISD::SRL;
1506          int Diff = ShAmt-C1;
1507          if (Diff < 0) {
1508            Diff = -Diff;
1509            Opc = ISD::SHL;
1510          }
1511
1512          SDValue NewSA =
1513            TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
1514          return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
1515                                                   InOp.getOperand(0), NewSA));
1516        }
1517      }
1518
1519      // Compute the new bits that are at the top now.
1520      if (SimplifyDemandedBits(InOp, (NewMask << ShAmt),
1521                               KnownZero, KnownOne, TLO, Depth+1))
1522        return true;
1523      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1524      KnownZero = KnownZero.lshr(ShAmt);
1525      KnownOne  = KnownOne.lshr(ShAmt);
1526
1527      APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1528      KnownZero |= HighBits;  // High bits known zero.
1529    }
1530    break;
1531  case ISD::SRA:
1532    // If this is an arithmetic shift right and only the low-bit is set, we can
1533    // always convert this into a logical shr, even if the shift amount is
1534    // variable.  The low bit of the shift cannot be an input sign bit unless
1535    // the shift amount is >= the size of the datatype, which is undefined.
1536    if (NewMask == 1)
1537      return TLO.CombineTo(Op,
1538                           TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
1539                                           Op.getOperand(0), Op.getOperand(1)));
1540
1541    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1542      EVT VT = Op.getValueType();
1543      unsigned ShAmt = SA->getZExtValue();
1544
1545      // If the shift count is an invalid immediate, don't do anything.
1546      if (ShAmt >= BitWidth)
1547        break;
1548
1549      APInt InDemandedMask = (NewMask << ShAmt);
1550
1551      // If any of the demanded bits are produced by the sign extension, we also
1552      // demand the input sign bit.
1553      APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1554      if (HighBits.intersects(NewMask))
1555        InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
1556
1557      if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
1558                               KnownZero, KnownOne, TLO, Depth+1))
1559        return true;
1560      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1561      KnownZero = KnownZero.lshr(ShAmt);
1562      KnownOne  = KnownOne.lshr(ShAmt);
1563
1564      // Handle the sign bit, adjusted to where it is now in the mask.
1565      APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
1566
1567      // If the input sign bit is known to be zero, or if none of the top bits
1568      // are demanded, turn this into an unsigned shift right.
1569      if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
1570        return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
1571                                                 Op.getOperand(0),
1572                                                 Op.getOperand(1)));
1573      } else if (KnownOne.intersects(SignBit)) { // New bits are known one.
1574        KnownOne |= HighBits;
1575      }
1576    }
1577    break;
1578  case ISD::SIGN_EXTEND_INREG: {
1579    EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1580
1581    APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
1582    // If we only care about the highest bit, don't bother shifting right.
1583    if (MsbMask == DemandedMask) {
1584      unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
1585      SDValue InOp = Op.getOperand(0);
1586
1587      // Compute the correct shift amount type, which must be getShiftAmountTy
1588      // for scalar types after legalization.
1589      EVT ShiftAmtTy = Op.getValueType();
1590      if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
1591        ShiftAmtTy = getShiftAmountTy(ShiftAmtTy);
1592
1593      SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, ShiftAmtTy);
1594      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1595                                            Op.getValueType(), InOp, ShiftAmt));
1596    }
1597
1598    // Sign extension.  Compute the demanded bits in the result that are not
1599    // present in the input.
1600    APInt NewBits =
1601      APInt::getHighBitsSet(BitWidth,
1602                            BitWidth - ExVT.getScalarType().getSizeInBits());
1603
1604    // If none of the extended bits are demanded, eliminate the sextinreg.
1605    if ((NewBits & NewMask) == 0)
1606      return TLO.CombineTo(Op, Op.getOperand(0));
1607
1608    APInt InSignBit =
1609      APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
1610    APInt InputDemandedBits =
1611      APInt::getLowBitsSet(BitWidth,
1612                           ExVT.getScalarType().getSizeInBits()) &
1613      NewMask;
1614
1615    // Since the sign extended bits are demanded, we know that the sign
1616    // bit is demanded.
1617    InputDemandedBits |= InSignBit;
1618
1619    if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
1620                             KnownZero, KnownOne, TLO, Depth+1))
1621      return true;
1622    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1623
1624    // If the sign bit of the input is known set or clear, then we know the
1625    // top bits of the result.
1626
1627    // If the input sign bit is known zero, convert this into a zero extension.
1628    if (KnownZero.intersects(InSignBit))
1629      return TLO.CombineTo(Op,
1630                          TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
1631
1632    if (KnownOne.intersects(InSignBit)) {    // Input sign bit known set
1633      KnownOne |= NewBits;
1634      KnownZero &= ~NewBits;
1635    } else {                       // Input sign bit unknown
1636      KnownZero &= ~NewBits;
1637      KnownOne &= ~NewBits;
1638    }
1639    break;
1640  }
1641  case ISD::ZERO_EXTEND: {
1642    unsigned OperandBitWidth =
1643      Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1644    APInt InMask = NewMask.trunc(OperandBitWidth);
1645
1646    // If none of the top bits are demanded, convert this into an any_extend.
1647    APInt NewBits =
1648      APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
1649    if (!NewBits.intersects(NewMask))
1650      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1651                                               Op.getValueType(),
1652                                               Op.getOperand(0)));
1653
1654    if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1655                             KnownZero, KnownOne, TLO, Depth+1))
1656      return true;
1657    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1658    KnownZero = KnownZero.zext(BitWidth);
1659    KnownOne = KnownOne.zext(BitWidth);
1660    KnownZero |= NewBits;
1661    break;
1662  }
1663  case ISD::SIGN_EXTEND: {
1664    EVT InVT = Op.getOperand(0).getValueType();
1665    unsigned InBits = InVT.getScalarType().getSizeInBits();
1666    APInt InMask    = APInt::getLowBitsSet(BitWidth, InBits);
1667    APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
1668    APInt NewBits   = ~InMask & NewMask;
1669
1670    // If none of the top bits are demanded, convert this into an any_extend.
1671    if (NewBits == 0)
1672      return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1673                                              Op.getValueType(),
1674                                              Op.getOperand(0)));
1675
1676    // Since some of the sign extended bits are demanded, we know that the sign
1677    // bit is demanded.
1678    APInt InDemandedBits = InMask & NewMask;
1679    InDemandedBits |= InSignBit;
1680    InDemandedBits = InDemandedBits.trunc(InBits);
1681
1682    if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1683                             KnownOne, TLO, Depth+1))
1684      return true;
1685    KnownZero = KnownZero.zext(BitWidth);
1686    KnownOne = KnownOne.zext(BitWidth);
1687
1688    // If the sign bit is known zero, convert this to a zero extend.
1689    if (KnownZero.intersects(InSignBit))
1690      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
1691                                               Op.getValueType(),
1692                                               Op.getOperand(0)));
1693
1694    // If the sign bit is known one, the top bits match.
1695    if (KnownOne.intersects(InSignBit)) {
1696      KnownOne |= NewBits;
1697      assert((KnownZero & NewBits) == 0);
1698    } else {   // Otherwise, top bits aren't known.
1699      assert((KnownOne & NewBits) == 0);
1700      assert((KnownZero & NewBits) == 0);
1701    }
1702    break;
1703  }
1704  case ISD::ANY_EXTEND: {
1705    unsigned OperandBitWidth =
1706      Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1707    APInt InMask = NewMask.trunc(OperandBitWidth);
1708    if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1709                             KnownZero, KnownOne, TLO, Depth+1))
1710      return true;
1711    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1712    KnownZero = KnownZero.zext(BitWidth);
1713    KnownOne = KnownOne.zext(BitWidth);
1714    break;
1715  }
1716  case ISD::TRUNCATE: {
1717    // Simplify the input, using demanded bit information, and compute the known
1718    // zero/one bits live out.
1719    unsigned OperandBitWidth =
1720      Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1721    APInt TruncMask = NewMask.zext(OperandBitWidth);
1722    if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
1723                             KnownZero, KnownOne, TLO, Depth+1))
1724      return true;
1725    KnownZero = KnownZero.trunc(BitWidth);
1726    KnownOne = KnownOne.trunc(BitWidth);
1727
1728    // If the input is only used by this truncate, see if we can shrink it based
1729    // on the known demanded bits.
1730    if (Op.getOperand(0).getNode()->hasOneUse()) {
1731      SDValue In = Op.getOperand(0);
1732      switch (In.getOpcode()) {
1733      default: break;
1734      case ISD::SRL:
1735        // Shrink SRL by a constant if none of the high bits shifted in are
1736        // demanded.
1737        if (TLO.LegalTypes() &&
1738            !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1739          // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1740          // undesirable.
1741          break;
1742        ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1743        if (!ShAmt)
1744          break;
1745        SDValue Shift = In.getOperand(1);
1746        if (TLO.LegalTypes()) {
1747          uint64_t ShVal = ShAmt->getZExtValue();
1748          Shift =
1749            TLO.DAG.getConstant(ShVal, getShiftAmountTy(Op.getValueType()));
1750        }
1751
1752        APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1753                                               OperandBitWidth - BitWidth);
1754        HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
1755
1756        if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
1757          // None of the shifted in bits are needed.  Add a truncate of the
1758          // shift input, then shift it.
1759          SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
1760                                             Op.getValueType(),
1761                                             In.getOperand(0));
1762          return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1763                                                   Op.getValueType(),
1764                                                   NewTrunc,
1765                                                   Shift));
1766        }
1767        break;
1768      }
1769    }
1770
1771    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1772    break;
1773  }
1774  case ISD::AssertZext: {
1775    // AssertZext demands all of the high bits, plus any of the low bits
1776    // demanded by its users.
1777    EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1778    APInt InMask = APInt::getLowBitsSet(BitWidth,
1779                                        VT.getSizeInBits());
1780    if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
1781                             KnownZero, KnownOne, TLO, Depth+1))
1782      return true;
1783    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1784
1785    KnownZero |= ~InMask & NewMask;
1786    break;
1787  }
1788  case ISD::BITCAST:
1789    // If this is an FP->Int bitcast and if the sign bit is the only
1790    // thing demanded, turn this into a FGETSIGN.
1791    if (!TLO.LegalOperations() &&
1792        !Op.getValueType().isVector() &&
1793        !Op.getOperand(0).getValueType().isVector() &&
1794        NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
1795        Op.getOperand(0).getValueType().isFloatingPoint()) {
1796      bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1797      bool i32Legal  = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1798      if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple()) {
1799        EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
1800        // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1801        // place.  We expect the SHL to be eliminated by other optimizations.
1802        SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
1803        unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
1804        if (!OpVTLegal && OpVTSizeInBits > 32)
1805          Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
1806        unsigned ShVal = Op.getValueType().getSizeInBits()-1;
1807        SDValue ShAmt = TLO.DAG.getConstant(ShVal, Op.getValueType());
1808        return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1809                                                 Op.getValueType(),
1810                                                 Sign, ShAmt));
1811      }
1812    }
1813    break;
1814  case ISD::ADD:
1815  case ISD::MUL:
1816  case ISD::SUB: {
1817    // Add, Sub, and Mul don't demand any bits in positions beyond that
1818    // of the highest bit demanded of them.
1819    APInt LoMask = APInt::getLowBitsSet(BitWidth,
1820                                        BitWidth - NewMask.countLeadingZeros());
1821    if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1822                             KnownOne2, TLO, Depth+1))
1823      return true;
1824    if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1825                             KnownOne2, TLO, Depth+1))
1826      return true;
1827    // See if the operation should be performed at a smaller bit width.
1828    if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1829      return true;
1830  }
1831  // FALL THROUGH
1832  default:
1833    // Just use ComputeMaskedBits to compute output bits.
1834    TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
1835    break;
1836  }
1837
1838  // If we know the value of all of the demanded bits, return this as a
1839  // constant.
1840  if ((NewMask & (KnownZero|KnownOne)) == NewMask)
1841    return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
1842
1843  return false;
1844}
1845
1846/// computeMaskedBitsForTargetNode - Determine which of the bits specified
1847/// in Mask are known to be either zero or one and return them in the
1848/// KnownZero/KnownOne bitsets.
1849void TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1850                                                    APInt &KnownZero,
1851                                                    APInt &KnownOne,
1852                                                    const SelectionDAG &DAG,
1853                                                    unsigned Depth) const {
1854  assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1855          Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1856          Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1857          Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1858         "Should use MaskedValueIsZero if you don't know whether Op"
1859         " is a target node!");
1860  KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
1861}
1862
1863/// ComputeNumSignBitsForTargetNode - This method can be implemented by
1864/// targets that want to expose additional information about sign bits to the
1865/// DAG Combiner.
1866unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1867                                                         unsigned Depth) const {
1868  assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1869          Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1870          Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1871          Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1872         "Should use ComputeNumSignBits if you don't know whether Op"
1873         " is a target node!");
1874  return 1;
1875}
1876
1877/// ValueHasExactlyOneBitSet - Test if the given value is known to have exactly
1878/// one bit set. This differs from ComputeMaskedBits in that it doesn't need to
1879/// determine which bit is set.
1880///
1881static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
1882  // A left-shift of a constant one will have exactly one bit set, because
1883  // shifting the bit off the end is undefined.
1884  if (Val.getOpcode() == ISD::SHL)
1885    if (ConstantSDNode *C =
1886         dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1887      if (C->getAPIntValue() == 1)
1888        return true;
1889
1890  // Similarly, a right-shift of a constant sign-bit will have exactly
1891  // one bit set.
1892  if (Val.getOpcode() == ISD::SRL)
1893    if (ConstantSDNode *C =
1894         dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1895      if (C->getAPIntValue().isSignBit())
1896        return true;
1897
1898  // More could be done here, though the above checks are enough
1899  // to handle some common cases.
1900
1901  // Fall back to ComputeMaskedBits to catch other known cases.
1902  EVT OpVT = Val.getValueType();
1903  unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
1904  APInt KnownZero, KnownOne;
1905  DAG.ComputeMaskedBits(Val, KnownZero, KnownOne);
1906  return (KnownZero.countPopulation() == BitWidth - 1) &&
1907         (KnownOne.countPopulation() == 1);
1908}
1909
1910/// SimplifySetCC - Try to simplify a setcc built with the specified operands
1911/// and cc. If it is unable to simplify it, return a null SDValue.
1912SDValue
1913TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1914                              ISD::CondCode Cond, bool foldBooleans,
1915                              DAGCombinerInfo &DCI, DebugLoc dl) const {
1916  SelectionDAG &DAG = DCI.DAG;
1917
1918  // These setcc operations always fold.
1919  switch (Cond) {
1920  default: break;
1921  case ISD::SETFALSE:
1922  case ISD::SETFALSE2: return DAG.getConstant(0, VT);
1923  case ISD::SETTRUE:
1924  case ISD::SETTRUE2:  return DAG.getConstant(1, VT);
1925  }
1926
1927  // Ensure that the constant occurs on the RHS, and fold constant
1928  // comparisons.
1929  if (isa<ConstantSDNode>(N0.getNode()))
1930    return DAG.getSetCC(dl, VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
1931
1932  if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1933    const APInt &C1 = N1C->getAPIntValue();
1934
1935    // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1936    // equality comparison, then we're just comparing whether X itself is
1937    // zero.
1938    if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1939        N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1940        N0.getOperand(1).getOpcode() == ISD::Constant) {
1941      const APInt &ShAmt
1942        = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1943      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1944          ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1945        if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1946          // (srl (ctlz x), 5) == 0  -> X != 0
1947          // (srl (ctlz x), 5) != 1  -> X != 0
1948          Cond = ISD::SETNE;
1949        } else {
1950          // (srl (ctlz x), 5) != 0  -> X == 0
1951          // (srl (ctlz x), 5) == 1  -> X == 0
1952          Cond = ISD::SETEQ;
1953        }
1954        SDValue Zero = DAG.getConstant(0, N0.getValueType());
1955        return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1956                            Zero, Cond);
1957      }
1958    }
1959
1960    SDValue CTPOP = N0;
1961    // Look through truncs that don't change the value of a ctpop.
1962    if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1963      CTPOP = N0.getOperand(0);
1964
1965    if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
1966        (N0 == CTPOP || N0.getValueType().getSizeInBits() >
1967                        Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
1968      EVT CTVT = CTPOP.getValueType();
1969      SDValue CTOp = CTPOP.getOperand(0);
1970
1971      // (ctpop x) u< 2 -> (x & x-1) == 0
1972      // (ctpop x) u> 1 -> (x & x-1) != 0
1973      if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1974        SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
1975                                  DAG.getConstant(1, CTVT));
1976        SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1977        ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
1978        return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, CTVT), CC);
1979      }
1980
1981      // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
1982    }
1983
1984    // (zext x) == C --> x == (trunc C)
1985    if (DCI.isBeforeLegalize() && N0->hasOneUse() &&
1986        (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1987      unsigned MinBits = N0.getValueSizeInBits();
1988      SDValue PreZExt;
1989      if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1990        // ZExt
1991        MinBits = N0->getOperand(0).getValueSizeInBits();
1992        PreZExt = N0->getOperand(0);
1993      } else if (N0->getOpcode() == ISD::AND) {
1994        // DAGCombine turns costly ZExts into ANDs
1995        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
1996          if ((C->getAPIntValue()+1).isPowerOf2()) {
1997            MinBits = C->getAPIntValue().countTrailingOnes();
1998            PreZExt = N0->getOperand(0);
1999          }
2000      } else if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(N0)) {
2001        // ZEXTLOAD
2002        if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
2003          MinBits = LN0->getMemoryVT().getSizeInBits();
2004          PreZExt = N0;
2005        }
2006      }
2007
2008      // Make sure we're not losing bits from the constant.
2009      if (MinBits < C1.getBitWidth() && MinBits > C1.getActiveBits()) {
2010        EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
2011        if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
2012          // Will get folded away.
2013          SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreZExt);
2014          SDValue C = DAG.getConstant(C1.trunc(MinBits), MinVT);
2015          return DAG.getSetCC(dl, VT, Trunc, C, Cond);
2016        }
2017      }
2018    }
2019
2020    // If the LHS is '(and load, const)', the RHS is 0,
2021    // the test is for equality or unsigned, and all 1 bits of the const are
2022    // in the same partial word, see if we can shorten the load.
2023    if (DCI.isBeforeLegalize() &&
2024        N0.getOpcode() == ISD::AND && C1 == 0 &&
2025        N0.getNode()->hasOneUse() &&
2026        isa<LoadSDNode>(N0.getOperand(0)) &&
2027        N0.getOperand(0).getNode()->hasOneUse() &&
2028        isa<ConstantSDNode>(N0.getOperand(1))) {
2029      LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
2030      APInt bestMask;
2031      unsigned bestWidth = 0, bestOffset = 0;
2032      if (!Lod->isVolatile() && Lod->isUnindexed()) {
2033        unsigned origWidth = N0.getValueType().getSizeInBits();
2034        unsigned maskWidth = origWidth;
2035        // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
2036        // 8 bits, but have to be careful...
2037        if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
2038          origWidth = Lod->getMemoryVT().getSizeInBits();
2039        const APInt &Mask =
2040          cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2041        for (unsigned width = origWidth / 2; width>=8; width /= 2) {
2042          APInt newMask = APInt::getLowBitsSet(maskWidth, width);
2043          for (unsigned offset=0; offset<origWidth/width; offset++) {
2044            if ((newMask & Mask) == Mask) {
2045              if (!TD->isLittleEndian())
2046                bestOffset = (origWidth/width - offset - 1) * (width/8);
2047              else
2048                bestOffset = (uint64_t)offset * (width/8);
2049              bestMask = Mask.lshr(offset * (width/8) * 8);
2050              bestWidth = width;
2051              break;
2052            }
2053            newMask = newMask << width;
2054          }
2055        }
2056      }
2057      if (bestWidth) {
2058        EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
2059        if (newVT.isRound()) {
2060          EVT PtrType = Lod->getOperand(1).getValueType();
2061          SDValue Ptr = Lod->getBasePtr();
2062          if (bestOffset != 0)
2063            Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
2064                              DAG.getConstant(bestOffset, PtrType));
2065          unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
2066          SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
2067                                Lod->getPointerInfo().getWithOffset(bestOffset),
2068                                        false, false, false, NewAlign);
2069          return DAG.getSetCC(dl, VT,
2070                              DAG.getNode(ISD::AND, dl, newVT, NewLoad,
2071                                      DAG.getConstant(bestMask.trunc(bestWidth),
2072                                                      newVT)),
2073                              DAG.getConstant(0LL, newVT), Cond);
2074        }
2075      }
2076    }
2077
2078    // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
2079    if (N0.getOpcode() == ISD::ZERO_EXTEND) {
2080      unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
2081
2082      // If the comparison constant has bits in the upper part, the
2083      // zero-extended value could never match.
2084      if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
2085                                              C1.getBitWidth() - InSize))) {
2086        switch (Cond) {
2087        case ISD::SETUGT:
2088        case ISD::SETUGE:
2089        case ISD::SETEQ: return DAG.getConstant(0, VT);
2090        case ISD::SETULT:
2091        case ISD::SETULE:
2092        case ISD::SETNE: return DAG.getConstant(1, VT);
2093        case ISD::SETGT:
2094        case ISD::SETGE:
2095          // True if the sign bit of C1 is set.
2096          return DAG.getConstant(C1.isNegative(), VT);
2097        case ISD::SETLT:
2098        case ISD::SETLE:
2099          // True if the sign bit of C1 isn't set.
2100          return DAG.getConstant(C1.isNonNegative(), VT);
2101        default:
2102          break;
2103        }
2104      }
2105
2106      // Otherwise, we can perform the comparison with the low bits.
2107      switch (Cond) {
2108      case ISD::SETEQ:
2109      case ISD::SETNE:
2110      case ISD::SETUGT:
2111      case ISD::SETUGE:
2112      case ISD::SETULT:
2113      case ISD::SETULE: {
2114        EVT newVT = N0.getOperand(0).getValueType();
2115        if (DCI.isBeforeLegalizeOps() ||
2116            (isOperationLegal(ISD::SETCC, newVT) &&
2117             getCondCodeAction(Cond, newVT.getSimpleVT())==Legal))
2118          return DAG.getSetCC(dl, VT, N0.getOperand(0),
2119                              DAG.getConstant(C1.trunc(InSize), newVT),
2120                              Cond);
2121        break;
2122      }
2123      default:
2124        break;   // todo, be more careful with signed comparisons
2125      }
2126    } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2127               (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2128      EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
2129      unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
2130      EVT ExtDstTy = N0.getValueType();
2131      unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
2132
2133      // If the constant doesn't fit into the number of bits for the source of
2134      // the sign extension, it is impossible for both sides to be equal.
2135      if (C1.getMinSignedBits() > ExtSrcTyBits)
2136        return DAG.getConstant(Cond == ISD::SETNE, VT);
2137
2138      SDValue ZextOp;
2139      EVT Op0Ty = N0.getOperand(0).getValueType();
2140      if (Op0Ty == ExtSrcTy) {
2141        ZextOp = N0.getOperand(0);
2142      } else {
2143        APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
2144        ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
2145                              DAG.getConstant(Imm, Op0Ty));
2146      }
2147      if (!DCI.isCalledByLegalizer())
2148        DCI.AddToWorklist(ZextOp.getNode());
2149      // Otherwise, make this a use of a zext.
2150      return DAG.getSetCC(dl, VT, ZextOp,
2151                          DAG.getConstant(C1 & APInt::getLowBitsSet(
2152                                                              ExtDstTyBits,
2153                                                              ExtSrcTyBits),
2154                                          ExtDstTy),
2155                          Cond);
2156    } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
2157                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2158      // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
2159      if (N0.getOpcode() == ISD::SETCC &&
2160          isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
2161        bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
2162        if (TrueWhenTrue)
2163          return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
2164        // Invert the condition.
2165        ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
2166        CC = ISD::getSetCCInverse(CC,
2167                                  N0.getOperand(0).getValueType().isInteger());
2168        return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
2169      }
2170
2171      if ((N0.getOpcode() == ISD::XOR ||
2172           (N0.getOpcode() == ISD::AND &&
2173            N0.getOperand(0).getOpcode() == ISD::XOR &&
2174            N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
2175          isa<ConstantSDNode>(N0.getOperand(1)) &&
2176          cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
2177        // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
2178        // can only do this if the top bits are known zero.
2179        unsigned BitWidth = N0.getValueSizeInBits();
2180        if (DAG.MaskedValueIsZero(N0,
2181                                  APInt::getHighBitsSet(BitWidth,
2182                                                        BitWidth-1))) {
2183          // Okay, get the un-inverted input value.
2184          SDValue Val;
2185          if (N0.getOpcode() == ISD::XOR)
2186            Val = N0.getOperand(0);
2187          else {
2188            assert(N0.getOpcode() == ISD::AND &&
2189                    N0.getOperand(0).getOpcode() == ISD::XOR);
2190            // ((X^1)&1)^1 -> X & 1
2191            Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
2192                              N0.getOperand(0).getOperand(0),
2193                              N0.getOperand(1));
2194          }
2195
2196          return DAG.getSetCC(dl, VT, Val, N1,
2197                              Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2198        }
2199      } else if (N1C->getAPIntValue() == 1 &&
2200                 (VT == MVT::i1 ||
2201                  getBooleanContents(false) == ZeroOrOneBooleanContent)) {
2202        SDValue Op0 = N0;
2203        if (Op0.getOpcode() == ISD::TRUNCATE)
2204          Op0 = Op0.getOperand(0);
2205
2206        if ((Op0.getOpcode() == ISD::XOR) &&
2207            Op0.getOperand(0).getOpcode() == ISD::SETCC &&
2208            Op0.getOperand(1).getOpcode() == ISD::SETCC) {
2209          // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
2210          Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
2211          return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
2212                              Cond);
2213        }
2214        if (Op0.getOpcode() == ISD::AND &&
2215            isa<ConstantSDNode>(Op0.getOperand(1)) &&
2216            cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
2217          // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
2218          if (Op0.getValueType().bitsGT(VT))
2219            Op0 = DAG.getNode(ISD::AND, dl, VT,
2220                          DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
2221                          DAG.getConstant(1, VT));
2222          else if (Op0.getValueType().bitsLT(VT))
2223            Op0 = DAG.getNode(ISD::AND, dl, VT,
2224                        DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
2225                        DAG.getConstant(1, VT));
2226
2227          return DAG.getSetCC(dl, VT, Op0,
2228                              DAG.getConstant(0, Op0.getValueType()),
2229                              Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2230        }
2231        if (Op0.getOpcode() == ISD::AssertZext &&
2232            cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
2233          return DAG.getSetCC(dl, VT, Op0,
2234                              DAG.getConstant(0, Op0.getValueType()),
2235                              Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2236      }
2237    }
2238
2239    APInt MinVal, MaxVal;
2240    unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
2241    if (ISD::isSignedIntSetCC(Cond)) {
2242      MinVal = APInt::getSignedMinValue(OperandBitSize);
2243      MaxVal = APInt::getSignedMaxValue(OperandBitSize);
2244    } else {
2245      MinVal = APInt::getMinValue(OperandBitSize);
2246      MaxVal = APInt::getMaxValue(OperandBitSize);
2247    }
2248
2249    // Canonicalize GE/LE comparisons to use GT/LT comparisons.
2250    if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
2251      if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
2252      // X >= C0 --> X > (C0-1)
2253      return DAG.getSetCC(dl, VT, N0,
2254                          DAG.getConstant(C1-1, N1.getValueType()),
2255                          (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
2256    }
2257
2258    if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
2259      if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
2260      // X <= C0 --> X < (C0+1)
2261      return DAG.getSetCC(dl, VT, N0,
2262                          DAG.getConstant(C1+1, N1.getValueType()),
2263                          (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
2264    }
2265
2266    if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
2267      return DAG.getConstant(0, VT);      // X < MIN --> false
2268    if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
2269      return DAG.getConstant(1, VT);      // X >= MIN --> true
2270    if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
2271      return DAG.getConstant(0, VT);      // X > MAX --> false
2272    if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
2273      return DAG.getConstant(1, VT);      // X <= MAX --> true
2274
2275    // Canonicalize setgt X, Min --> setne X, Min
2276    if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
2277      return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
2278    // Canonicalize setlt X, Max --> setne X, Max
2279    if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
2280      return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
2281
2282    // If we have setult X, 1, turn it into seteq X, 0
2283    if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
2284      return DAG.getSetCC(dl, VT, N0,
2285                          DAG.getConstant(MinVal, N0.getValueType()),
2286                          ISD::SETEQ);
2287    // If we have setugt X, Max-1, turn it into seteq X, Max
2288    if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
2289      return DAG.getSetCC(dl, VT, N0,
2290                          DAG.getConstant(MaxVal, N0.getValueType()),
2291                          ISD::SETEQ);
2292
2293    // If we have "setcc X, C0", check to see if we can shrink the immediate
2294    // by changing cc.
2295
2296    // SETUGT X, SINTMAX  -> SETLT X, 0
2297    if (Cond == ISD::SETUGT &&
2298        C1 == APInt::getSignedMaxValue(OperandBitSize))
2299      return DAG.getSetCC(dl, VT, N0,
2300                          DAG.getConstant(0, N1.getValueType()),
2301                          ISD::SETLT);
2302
2303    // SETULT X, SINTMIN  -> SETGT X, -1
2304    if (Cond == ISD::SETULT &&
2305        C1 == APInt::getSignedMinValue(OperandBitSize)) {
2306      SDValue ConstMinusOne =
2307          DAG.getConstant(APInt::getAllOnesValue(OperandBitSize),
2308                          N1.getValueType());
2309      return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
2310    }
2311
2312    // Fold bit comparisons when we can.
2313    if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2314        (VT == N0.getValueType() ||
2315         (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
2316        N0.getOpcode() == ISD::AND)
2317      if (ConstantSDNode *AndRHS =
2318                  dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2319        EVT ShiftTy = DCI.isBeforeLegalizeOps() ?
2320          getPointerTy() : getShiftAmountTy(N0.getValueType());
2321        if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
2322          // Perform the xform if the AND RHS is a single bit.
2323          if (AndRHS->getAPIntValue().isPowerOf2()) {
2324            return DAG.getNode(ISD::TRUNCATE, dl, VT,
2325                              DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2326                   DAG.getConstant(AndRHS->getAPIntValue().logBase2(), ShiftTy)));
2327          }
2328        } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
2329          // (X & 8) == 8  -->  (X & 8) >> 3
2330          // Perform the xform if C1 is a single bit.
2331          if (C1.isPowerOf2()) {
2332            return DAG.getNode(ISD::TRUNCATE, dl, VT,
2333                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2334                                      DAG.getConstant(C1.logBase2(), ShiftTy)));
2335          }
2336        }
2337      }
2338
2339    if (C1.getMinSignedBits() <= 64 &&
2340        !isLegalICmpImmediate(C1.getSExtValue())) {
2341      // (X & -256) == 256 -> (X >> 8) == 1
2342      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2343          N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
2344        if (ConstantSDNode *AndRHS =
2345            dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2346          const APInt &AndRHSC = AndRHS->getAPIntValue();
2347          if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
2348            unsigned ShiftBits = AndRHSC.countTrailingZeros();
2349            EVT ShiftTy = DCI.isBeforeLegalizeOps() ?
2350              getPointerTy() : getShiftAmountTy(N0.getValueType());
2351            EVT CmpTy = N0.getValueType();
2352            SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
2353                                        DAG.getConstant(ShiftBits, ShiftTy));
2354            SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), CmpTy);
2355            return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
2356          }
2357        }
2358      } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
2359                 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
2360        bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
2361        // X <  0x100000000 -> (X >> 32) <  1
2362        // X >= 0x100000000 -> (X >> 32) >= 1
2363        // X <= 0x0ffffffff -> (X >> 32) <  1
2364        // X >  0x0ffffffff -> (X >> 32) >= 1
2365        unsigned ShiftBits;
2366        APInt NewC = C1;
2367        ISD::CondCode NewCond = Cond;
2368        if (AdjOne) {
2369          ShiftBits = C1.countTrailingOnes();
2370          NewC = NewC + 1;
2371          NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2372        } else {
2373          ShiftBits = C1.countTrailingZeros();
2374        }
2375        NewC = NewC.lshr(ShiftBits);
2376        if (ShiftBits && isLegalICmpImmediate(NewC.getSExtValue())) {
2377          EVT ShiftTy = DCI.isBeforeLegalizeOps() ?
2378            getPointerTy() : getShiftAmountTy(N0.getValueType());
2379          EVT CmpTy = N0.getValueType();
2380          SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
2381                                      DAG.getConstant(ShiftBits, ShiftTy));
2382          SDValue CmpRHS = DAG.getConstant(NewC, CmpTy);
2383          return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
2384        }
2385      }
2386    }
2387  }
2388
2389  if (isa<ConstantFPSDNode>(N0.getNode())) {
2390    // Constant fold or commute setcc.
2391    SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
2392    if (O.getNode()) return O;
2393  } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
2394    // If the RHS of an FP comparison is a constant, simplify it away in
2395    // some cases.
2396    if (CFP->getValueAPF().isNaN()) {
2397      // If an operand is known to be a nan, we can fold it.
2398      switch (ISD::getUnorderedFlavor(Cond)) {
2399      default: llvm_unreachable("Unknown flavor!");
2400      case 0:  // Known false.
2401        return DAG.getConstant(0, VT);
2402      case 1:  // Known true.
2403        return DAG.getConstant(1, VT);
2404      case 2:  // Undefined.
2405        return DAG.getUNDEF(VT);
2406      }
2407    }
2408
2409    // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
2410    // constant if knowing that the operand is non-nan is enough.  We prefer to
2411    // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
2412    // materialize 0.0.
2413    if (Cond == ISD::SETO || Cond == ISD::SETUO)
2414      return DAG.getSetCC(dl, VT, N0, N0, Cond);
2415
2416    // If the condition is not legal, see if we can find an equivalent one
2417    // which is legal.
2418    if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
2419      // If the comparison was an awkward floating-point == or != and one of
2420      // the comparison operands is infinity or negative infinity, convert the
2421      // condition to a less-awkward <= or >=.
2422      if (CFP->getValueAPF().isInfinity()) {
2423        if (CFP->getValueAPF().isNegative()) {
2424          if (Cond == ISD::SETOEQ &&
2425              isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2426            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
2427          if (Cond == ISD::SETUEQ &&
2428              isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2429            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
2430          if (Cond == ISD::SETUNE &&
2431              isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2432            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
2433          if (Cond == ISD::SETONE &&
2434              isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2435            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
2436        } else {
2437          if (Cond == ISD::SETOEQ &&
2438              isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2439            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
2440          if (Cond == ISD::SETUEQ &&
2441              isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2442            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
2443          if (Cond == ISD::SETUNE &&
2444              isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2445            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
2446          if (Cond == ISD::SETONE &&
2447              isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2448            return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
2449        }
2450      }
2451    }
2452  }
2453
2454  if (N0 == N1) {
2455    // The sext(setcc()) => setcc() optimization relies on the appropriate
2456    // constant being emitted.
2457    uint64_t EqVal = 0;
2458    switch (getBooleanContents(N0.getValueType().isVector())) {
2459    case UndefinedBooleanContent:
2460    case ZeroOrOneBooleanContent:
2461      EqVal = ISD::isTrueWhenEqual(Cond);
2462      break;
2463    case ZeroOrNegativeOneBooleanContent:
2464      EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
2465      break;
2466    }
2467
2468    // We can always fold X == X for integer setcc's.
2469    if (N0.getValueType().isInteger()) {
2470      return DAG.getConstant(EqVal, VT);
2471    }
2472    unsigned UOF = ISD::getUnorderedFlavor(Cond);
2473    if (UOF == 2)   // FP operators that are undefined on NaNs.
2474      return DAG.getConstant(EqVal, VT);
2475    if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
2476      return DAG.getConstant(EqVal, VT);
2477    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
2478    // if it is not already.
2479    ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
2480    if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
2481          getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
2482      return DAG.getSetCC(dl, VT, N0, N1, NewCond);
2483  }
2484
2485  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2486      N0.getValueType().isInteger()) {
2487    if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2488        N0.getOpcode() == ISD::XOR) {
2489      // Simplify (X+Y) == (X+Z) -->  Y == Z
2490      if (N0.getOpcode() == N1.getOpcode()) {
2491        if (N0.getOperand(0) == N1.getOperand(0))
2492          return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
2493        if (N0.getOperand(1) == N1.getOperand(1))
2494          return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
2495        if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2496          // If X op Y == Y op X, try other combinations.
2497          if (N0.getOperand(0) == N1.getOperand(1))
2498            return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
2499                                Cond);
2500          if (N0.getOperand(1) == N1.getOperand(0))
2501            return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
2502                                Cond);
2503        }
2504      }
2505
2506      // If RHS is a legal immediate value for a compare instruction, we need
2507      // to be careful about increasing register pressure needlessly.
2508      bool LegalRHSImm = false;
2509
2510      if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2511        if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2512          // Turn (X+C1) == C2 --> X == C2-C1
2513          if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
2514            return DAG.getSetCC(dl, VT, N0.getOperand(0),
2515                                DAG.getConstant(RHSC->getAPIntValue()-
2516                                                LHSR->getAPIntValue(),
2517                                N0.getValueType()), Cond);
2518          }
2519
2520          // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
2521          if (N0.getOpcode() == ISD::XOR)
2522            // If we know that all of the inverted bits are zero, don't bother
2523            // performing the inversion.
2524            if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2525              return
2526                DAG.getSetCC(dl, VT, N0.getOperand(0),
2527                             DAG.getConstant(LHSR->getAPIntValue() ^
2528                                               RHSC->getAPIntValue(),
2529                                             N0.getValueType()),
2530                             Cond);
2531        }
2532
2533        // Turn (C1-X) == C2 --> X == C1-C2
2534        if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
2535          if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
2536            return
2537              DAG.getSetCC(dl, VT, N0.getOperand(1),
2538                           DAG.getConstant(SUBC->getAPIntValue() -
2539                                             RHSC->getAPIntValue(),
2540                                           N0.getValueType()),
2541                           Cond);
2542          }
2543        }
2544
2545        // Could RHSC fold directly into a compare?
2546        if (RHSC->getValueType(0).getSizeInBits() <= 64)
2547          LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
2548      }
2549
2550      // Simplify (X+Z) == X -->  Z == 0
2551      // Don't do this if X is an immediate that can fold into a cmp
2552      // instruction and X+Z has other uses. It could be an induction variable
2553      // chain, and the transform would increase register pressure.
2554      if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
2555        if (N0.getOperand(0) == N1)
2556          return DAG.getSetCC(dl, VT, N0.getOperand(1),
2557                              DAG.getConstant(0, N0.getValueType()), Cond);
2558        if (N0.getOperand(1) == N1) {
2559          if (DAG.isCommutativeBinOp(N0.getOpcode()))
2560            return DAG.getSetCC(dl, VT, N0.getOperand(0),
2561                                DAG.getConstant(0, N0.getValueType()), Cond);
2562          if (N0.getNode()->hasOneUse()) {
2563            assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2564            // (Z-X) == X  --> Z == X<<1
2565            SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N1,
2566                       DAG.getConstant(1, getShiftAmountTy(N1.getValueType())));
2567            if (!DCI.isCalledByLegalizer())
2568              DCI.AddToWorklist(SH.getNode());
2569            return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2570          }
2571        }
2572      }
2573    }
2574
2575    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2576        N1.getOpcode() == ISD::XOR) {
2577      // Simplify  X == (X+Z) -->  Z == 0
2578      if (N1.getOperand(0) == N0)
2579        return DAG.getSetCC(dl, VT, N1.getOperand(1),
2580                        DAG.getConstant(0, N1.getValueType()), Cond);
2581      if (N1.getOperand(1) == N0) {
2582        if (DAG.isCommutativeBinOp(N1.getOpcode()))
2583          return DAG.getSetCC(dl, VT, N1.getOperand(0),
2584                          DAG.getConstant(0, N1.getValueType()), Cond);
2585        if (N1.getNode()->hasOneUse()) {
2586          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2587          // X == (Z-X)  --> X<<1 == Z
2588          SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N0,
2589                       DAG.getConstant(1, getShiftAmountTy(N0.getValueType())));
2590          if (!DCI.isCalledByLegalizer())
2591            DCI.AddToWorklist(SH.getNode());
2592          return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
2593        }
2594      }
2595    }
2596
2597    // Simplify x&y == y to x&y != 0 if y has exactly one bit set.
2598    // Note that where y is variable and is known to have at most
2599    // one bit set (for example, if it is z&1) we cannot do this;
2600    // the expressions are not equivalent when y==0.
2601    if (N0.getOpcode() == ISD::AND)
2602      if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) {
2603        if (ValueHasExactlyOneBitSet(N1, DAG)) {
2604          Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2605          SDValue Zero = DAG.getConstant(0, N1.getValueType());
2606          return DAG.getSetCC(dl, VT, N0, Zero, Cond);
2607        }
2608      }
2609    if (N1.getOpcode() == ISD::AND)
2610      if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) {
2611        if (ValueHasExactlyOneBitSet(N0, DAG)) {
2612          Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2613          SDValue Zero = DAG.getConstant(0, N0.getValueType());
2614          return DAG.getSetCC(dl, VT, N1, Zero, Cond);
2615        }
2616      }
2617  }
2618
2619  // Fold away ALL boolean setcc's.
2620  SDValue Temp;
2621  if (N0.getValueType() == MVT::i1 && foldBooleans) {
2622    switch (Cond) {
2623    default: llvm_unreachable("Unknown integer setcc!");
2624    case ISD::SETEQ:  // X == Y  -> ~(X^Y)
2625      Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2626      N0 = DAG.getNOT(dl, Temp, MVT::i1);
2627      if (!DCI.isCalledByLegalizer())
2628        DCI.AddToWorklist(Temp.getNode());
2629      break;
2630    case ISD::SETNE:  // X != Y   -->  (X^Y)
2631      N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2632      break;
2633    case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
2634    case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
2635      Temp = DAG.getNOT(dl, N0, MVT::i1);
2636      N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
2637      if (!DCI.isCalledByLegalizer())
2638        DCI.AddToWorklist(Temp.getNode());
2639      break;
2640    case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
2641    case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
2642      Temp = DAG.getNOT(dl, N1, MVT::i1);
2643      N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
2644      if (!DCI.isCalledByLegalizer())
2645        DCI.AddToWorklist(Temp.getNode());
2646      break;
2647    case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
2648    case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
2649      Temp = DAG.getNOT(dl, N0, MVT::i1);
2650      N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
2651      if (!DCI.isCalledByLegalizer())
2652        DCI.AddToWorklist(Temp.getNode());
2653      break;
2654    case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
2655    case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
2656      Temp = DAG.getNOT(dl, N1, MVT::i1);
2657      N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
2658      break;
2659    }
2660    if (VT != MVT::i1) {
2661      if (!DCI.isCalledByLegalizer())
2662        DCI.AddToWorklist(N0.getNode());
2663      // FIXME: If running after legalize, we probably can't do this.
2664      N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
2665    }
2666    return N0;
2667  }
2668
2669  // Could not fold it.
2670  return SDValue();
2671}
2672
2673/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
2674/// node is a GlobalAddress + offset.
2675bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
2676                                    int64_t &Offset) const {
2677  if (isa<GlobalAddressSDNode>(N)) {
2678    GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N);
2679    GA = GASD->getGlobal();
2680    Offset += GASD->getOffset();
2681    return true;
2682  }
2683
2684  if (N->getOpcode() == ISD::ADD) {
2685    SDValue N1 = N->getOperand(0);
2686    SDValue N2 = N->getOperand(1);
2687    if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
2688      ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
2689      if (V) {
2690        Offset += V->getSExtValue();
2691        return true;
2692      }
2693    } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
2694      ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
2695      if (V) {
2696        Offset += V->getSExtValue();
2697        return true;
2698      }
2699    }
2700  }
2701
2702  return false;
2703}
2704
2705
2706SDValue TargetLowering::
2707PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
2708  // Default implementation: no optimization.
2709  return SDValue();
2710}
2711
2712//===----------------------------------------------------------------------===//
2713//  Inline Assembler Implementation Methods
2714//===----------------------------------------------------------------------===//
2715
2716
2717TargetLowering::ConstraintType
2718TargetLowering::getConstraintType(const std::string &Constraint) const {
2719  if (Constraint.size() == 1) {
2720    switch (Constraint[0]) {
2721    default: break;
2722    case 'r': return C_RegisterClass;
2723    case 'm':    // memory
2724    case 'o':    // offsetable
2725    case 'V':    // not offsetable
2726      return C_Memory;
2727    case 'i':    // Simple Integer or Relocatable Constant
2728    case 'n':    // Simple Integer
2729    case 'E':    // Floating Point Constant
2730    case 'F':    // Floating Point Constant
2731    case 's':    // Relocatable Constant
2732    case 'p':    // Address.
2733    case 'X':    // Allow ANY value.
2734    case 'I':    // Target registers.
2735    case 'J':
2736    case 'K':
2737    case 'L':
2738    case 'M':
2739    case 'N':
2740    case 'O':
2741    case 'P':
2742    case '<':
2743    case '>':
2744      return C_Other;
2745    }
2746  }
2747
2748  if (Constraint.size() > 1 && Constraint[0] == '{' &&
2749      Constraint[Constraint.size()-1] == '}')
2750    return C_Register;
2751  return C_Unknown;
2752}
2753
2754/// LowerXConstraint - try to replace an X constraint, which matches anything,
2755/// with another that has more specific requirements based on the type of the
2756/// corresponding operand.
2757const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
2758  if (ConstraintVT.isInteger())
2759    return "r";
2760  if (ConstraintVT.isFloatingPoint())
2761    return "f";      // works for many targets
2762  return 0;
2763}
2764
2765/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2766/// vector.  If it is invalid, don't add anything to Ops.
2767void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2768                                                  std::string &Constraint,
2769                                                  std::vector<SDValue> &Ops,
2770                                                  SelectionDAG &DAG) const {
2771
2772  if (Constraint.length() > 1) return;
2773
2774  char ConstraintLetter = Constraint[0];
2775  switch (ConstraintLetter) {
2776  default: break;
2777  case 'X':     // Allows any operand; labels (basic block) use this.
2778    if (Op.getOpcode() == ISD::BasicBlock) {
2779      Ops.push_back(Op);
2780      return;
2781    }
2782    // fall through
2783  case 'i':    // Simple Integer or Relocatable Constant
2784  case 'n':    // Simple Integer
2785  case 's': {  // Relocatable Constant
2786    // These operands are interested in values of the form (GV+C), where C may
2787    // be folded in as an offset of GV, or it may be explicitly added.  Also, it
2788    // is possible and fine if either GV or C are missing.
2789    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2790    GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2791
2792    // If we have "(add GV, C)", pull out GV/C
2793    if (Op.getOpcode() == ISD::ADD) {
2794      C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2795      GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2796      if (C == 0 || GA == 0) {
2797        C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2798        GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2799      }
2800      if (C == 0 || GA == 0)
2801        C = 0, GA = 0;
2802    }
2803
2804    // If we find a valid operand, map to the TargetXXX version so that the
2805    // value itself doesn't get selected.
2806    if (GA) {   // Either &GV   or   &GV+C
2807      if (ConstraintLetter != 'n') {
2808        int64_t Offs = GA->getOffset();
2809        if (C) Offs += C->getZExtValue();
2810        Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2811                                                 C ? C->getDebugLoc() : DebugLoc(),
2812                                                 Op.getValueType(), Offs));
2813        return;
2814      }
2815    }
2816    if (C) {   // just C, no GV.
2817      // Simple constants are not allowed for 's'.
2818      if (ConstraintLetter != 's') {
2819        // gcc prints these as sign extended.  Sign extend value to 64 bits
2820        // now; without this it would get ZExt'd later in
2821        // ScheduleDAGSDNodes::EmitNode, which is very generic.
2822        Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
2823                                            MVT::i64));
2824        return;
2825      }
2826    }
2827    break;
2828  }
2829  }
2830}
2831
2832std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
2833getRegForInlineAsmConstraint(const std::string &Constraint,
2834                             EVT VT) const {
2835  if (Constraint[0] != '{')
2836    return std::make_pair(0u, static_cast<TargetRegisterClass*>(0));
2837  assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2838
2839  // Remove the braces from around the name.
2840  StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2841
2842  std::pair<unsigned, const TargetRegisterClass*> R =
2843    std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2844
2845  // Figure out which register class contains this reg.
2846  const TargetRegisterInfo *RI = TM.getRegisterInfo();
2847  for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
2848       E = RI->regclass_end(); RCI != E; ++RCI) {
2849    const TargetRegisterClass *RC = *RCI;
2850
2851    // If none of the value types for this register class are valid, we
2852    // can't use it.  For example, 64-bit reg classes on 32-bit targets.
2853    if (!isLegalRC(RC))
2854      continue;
2855
2856    for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2857         I != E; ++I) {
2858      if (RegName.equals_lower(RI->getName(*I))) {
2859        std::pair<unsigned, const TargetRegisterClass*> S =
2860          std::make_pair(*I, RC);
2861
2862        // If this register class has the requested value type, return it,
2863        // otherwise keep searching and return the first class found
2864        // if no other is found which explicitly has the requested type.
2865        if (RC->hasType(VT))
2866          return S;
2867        else if (!R.second)
2868          R = S;
2869      }
2870    }
2871  }
2872
2873  return R;
2874}
2875
2876//===----------------------------------------------------------------------===//
2877// Constraint Selection.
2878
2879/// isMatchingInputConstraint - Return true of this is an input operand that is
2880/// a matching constraint like "4".
2881bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2882  assert(!ConstraintCode.empty() && "No known constraint!");
2883  return isdigit(ConstraintCode[0]);
2884}
2885
2886/// getMatchedOperand - If this is an input matching constraint, this method
2887/// returns the output operand it matches.
2888unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2889  assert(!ConstraintCode.empty() && "No known constraint!");
2890  return atoi(ConstraintCode.c_str());
2891}
2892
2893
2894/// ParseConstraints - Split up the constraint string from the inline
2895/// assembly value into the specific constraints and their prefixes,
2896/// and also tie in the associated operand values.
2897/// If this returns an empty vector, and if the constraint string itself
2898/// isn't empty, there was an error parsing.
2899TargetLowering::AsmOperandInfoVector TargetLowering::ParseConstraints(
2900    ImmutableCallSite CS) const {
2901  /// ConstraintOperands - Information about all of the constraints.
2902  AsmOperandInfoVector ConstraintOperands;
2903  const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
2904  unsigned maCount = 0; // Largest number of multiple alternative constraints.
2905
2906  // Do a prepass over the constraints, canonicalizing them, and building up the
2907  // ConstraintOperands list.
2908  InlineAsm::ConstraintInfoVector
2909    ConstraintInfos = IA->ParseConstraints();
2910
2911  unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
2912  unsigned ResNo = 0;   // ResNo - The result number of the next output.
2913
2914  for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
2915    ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
2916    AsmOperandInfo &OpInfo = ConstraintOperands.back();
2917
2918    // Update multiple alternative constraint count.
2919    if (OpInfo.multipleAlternatives.size() > maCount)
2920      maCount = OpInfo.multipleAlternatives.size();
2921
2922    OpInfo.ConstraintVT = MVT::Other;
2923
2924    // Compute the value type for each operand.
2925    switch (OpInfo.Type) {
2926    case InlineAsm::isOutput:
2927      // Indirect outputs just consume an argument.
2928      if (OpInfo.isIndirect) {
2929        OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2930        break;
2931      }
2932
2933      // The return value of the call is this value.  As such, there is no
2934      // corresponding argument.
2935      assert(!CS.getType()->isVoidTy() &&
2936             "Bad inline asm!");
2937      if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
2938        OpInfo.ConstraintVT = getSimpleValueType(STy->getElementType(ResNo));
2939      } else {
2940        assert(ResNo == 0 && "Asm only has one result!");
2941        OpInfo.ConstraintVT = getSimpleValueType(CS.getType());
2942      }
2943      ++ResNo;
2944      break;
2945    case InlineAsm::isInput:
2946      OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2947      break;
2948    case InlineAsm::isClobber:
2949      // Nothing to do.
2950      break;
2951    }
2952
2953    if (OpInfo.CallOperandVal) {
2954      llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
2955      if (OpInfo.isIndirect) {
2956        llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
2957        if (!PtrTy)
2958          report_fatal_error("Indirect operand for inline asm not a pointer!");
2959        OpTy = PtrTy->getElementType();
2960      }
2961
2962      // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
2963      if (StructType *STy = dyn_cast<StructType>(OpTy))
2964        if (STy->getNumElements() == 1)
2965          OpTy = STy->getElementType(0);
2966
2967      // If OpTy is not a single value, it may be a struct/union that we
2968      // can tile with integers.
2969      if (!OpTy->isSingleValueType() && OpTy->isSized()) {
2970        unsigned BitSize = TD->getTypeSizeInBits(OpTy);
2971        switch (BitSize) {
2972        default: break;
2973        case 1:
2974        case 8:
2975        case 16:
2976        case 32:
2977        case 64:
2978        case 128:
2979          OpInfo.ConstraintVT =
2980            MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
2981          break;
2982        }
2983      } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
2984        OpInfo.ConstraintVT = MVT::getIntegerVT(
2985            8*TD->getPointerSize(PT->getAddressSpace()));
2986      } else {
2987        OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
2988      }
2989    }
2990  }
2991
2992  // If we have multiple alternative constraints, select the best alternative.
2993  if (ConstraintInfos.size()) {
2994    if (maCount) {
2995      unsigned bestMAIndex = 0;
2996      int bestWeight = -1;
2997      // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
2998      int weight = -1;
2999      unsigned maIndex;
3000      // Compute the sums of the weights for each alternative, keeping track
3001      // of the best (highest weight) one so far.
3002      for (maIndex = 0; maIndex < maCount; ++maIndex) {
3003        int weightSum = 0;
3004        for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3005            cIndex != eIndex; ++cIndex) {
3006          AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
3007          if (OpInfo.Type == InlineAsm::isClobber)
3008            continue;
3009
3010          // If this is an output operand with a matching input operand,
3011          // look up the matching input. If their types mismatch, e.g. one
3012          // is an integer, the other is floating point, or their sizes are
3013          // different, flag it as an maCantMatch.
3014          if (OpInfo.hasMatchingInput()) {
3015            AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
3016            if (OpInfo.ConstraintVT != Input.ConstraintVT) {
3017              if ((OpInfo.ConstraintVT.isInteger() !=
3018                   Input.ConstraintVT.isInteger()) ||
3019                  (OpInfo.ConstraintVT.getSizeInBits() !=
3020                   Input.ConstraintVT.getSizeInBits())) {
3021                weightSum = -1;  // Can't match.
3022                break;
3023              }
3024            }
3025          }
3026          weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
3027          if (weight == -1) {
3028            weightSum = -1;
3029            break;
3030          }
3031          weightSum += weight;
3032        }
3033        // Update best.
3034        if (weightSum > bestWeight) {
3035          bestWeight = weightSum;
3036          bestMAIndex = maIndex;
3037        }
3038      }
3039
3040      // Now select chosen alternative in each constraint.
3041      for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3042          cIndex != eIndex; ++cIndex) {
3043        AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
3044        if (cInfo.Type == InlineAsm::isClobber)
3045          continue;
3046        cInfo.selectAlternative(bestMAIndex);
3047      }
3048    }
3049  }
3050
3051  // Check and hook up tied operands, choose constraint code to use.
3052  for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3053      cIndex != eIndex; ++cIndex) {
3054    AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
3055
3056    // If this is an output operand with a matching input operand, look up the
3057    // matching input. If their types mismatch, e.g. one is an integer, the
3058    // other is floating point, or their sizes are different, flag it as an
3059    // error.
3060    if (OpInfo.hasMatchingInput()) {
3061      AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
3062
3063      if (OpInfo.ConstraintVT != Input.ConstraintVT) {
3064        std::pair<unsigned, const TargetRegisterClass*> MatchRC =
3065          getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3066                                       OpInfo.ConstraintVT);
3067        std::pair<unsigned, const TargetRegisterClass*> InputRC =
3068          getRegForInlineAsmConstraint(Input.ConstraintCode,
3069                                       Input.ConstraintVT);
3070        if ((OpInfo.ConstraintVT.isInteger() !=
3071             Input.ConstraintVT.isInteger()) ||
3072            (MatchRC.second != InputRC.second)) {
3073          report_fatal_error("Unsupported asm: input constraint"
3074                             " with a matching output constraint of"
3075                             " incompatible type!");
3076        }
3077      }
3078
3079    }
3080  }
3081
3082  return ConstraintOperands;
3083}
3084
3085
3086/// getConstraintGenerality - Return an integer indicating how general CT
3087/// is.
3088static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3089  switch (CT) {
3090  case TargetLowering::C_Other:
3091  case TargetLowering::C_Unknown:
3092    return 0;
3093  case TargetLowering::C_Register:
3094    return 1;
3095  case TargetLowering::C_RegisterClass:
3096    return 2;
3097  case TargetLowering::C_Memory:
3098    return 3;
3099  }
3100  llvm_unreachable("Invalid constraint type");
3101}
3102
3103/// Examine constraint type and operand type and determine a weight value.
3104/// This object must already have been set up with the operand type
3105/// and the current alternative constraint selected.
3106TargetLowering::ConstraintWeight
3107  TargetLowering::getMultipleConstraintMatchWeight(
3108    AsmOperandInfo &info, int maIndex) const {
3109  InlineAsm::ConstraintCodeVector *rCodes;
3110  if (maIndex >= (int)info.multipleAlternatives.size())
3111    rCodes = &info.Codes;
3112  else
3113    rCodes = &info.multipleAlternatives[maIndex].Codes;
3114  ConstraintWeight BestWeight = CW_Invalid;
3115
3116  // Loop over the options, keeping track of the most general one.
3117  for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
3118    ConstraintWeight weight =
3119      getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
3120    if (weight > BestWeight)
3121      BestWeight = weight;
3122  }
3123
3124  return BestWeight;
3125}
3126
3127/// Examine constraint type and operand type and determine a weight value.
3128/// This object must already have been set up with the operand type
3129/// and the current alternative constraint selected.
3130TargetLowering::ConstraintWeight
3131  TargetLowering::getSingleConstraintMatchWeight(
3132    AsmOperandInfo &info, const char *constraint) const {
3133  ConstraintWeight weight = CW_Invalid;
3134  Value *CallOperandVal = info.CallOperandVal;
3135    // If we don't have a value, we can't do a match,
3136    // but allow it at the lowest weight.
3137  if (CallOperandVal == NULL)
3138    return CW_Default;
3139  // Look at the constraint type.
3140  switch (*constraint) {
3141    case 'i': // immediate integer.
3142    case 'n': // immediate integer with a known value.
3143      if (isa<ConstantInt>(CallOperandVal))
3144        weight = CW_Constant;
3145      break;
3146    case 's': // non-explicit intregal immediate.
3147      if (isa<GlobalValue>(CallOperandVal))
3148        weight = CW_Constant;
3149      break;
3150    case 'E': // immediate float if host format.
3151    case 'F': // immediate float.
3152      if (isa<ConstantFP>(CallOperandVal))
3153        weight = CW_Constant;
3154      break;
3155    case '<': // memory operand with autodecrement.
3156    case '>': // memory operand with autoincrement.
3157    case 'm': // memory operand.
3158    case 'o': // offsettable memory operand
3159    case 'V': // non-offsettable memory operand
3160      weight = CW_Memory;
3161      break;
3162    case 'r': // general register.
3163    case 'g': // general register, memory operand or immediate integer.
3164              // note: Clang converts "g" to "imr".
3165      if (CallOperandVal->getType()->isIntegerTy())
3166        weight = CW_Register;
3167      break;
3168    case 'X': // any operand.
3169    default:
3170      weight = CW_Default;
3171      break;
3172  }
3173  return weight;
3174}
3175
3176/// ChooseConstraint - If there are multiple different constraints that we
3177/// could pick for this operand (e.g. "imr") try to pick the 'best' one.
3178/// This is somewhat tricky: constraints fall into four classes:
3179///    Other         -> immediates and magic values
3180///    Register      -> one specific register
3181///    RegisterClass -> a group of regs
3182///    Memory        -> memory
3183/// Ideally, we would pick the most specific constraint possible: if we have
3184/// something that fits into a register, we would pick it.  The problem here
3185/// is that if we have something that could either be in a register or in
3186/// memory that use of the register could cause selection of *other*
3187/// operands to fail: they might only succeed if we pick memory.  Because of
3188/// this the heuristic we use is:
3189///
3190///  1) If there is an 'other' constraint, and if the operand is valid for
3191///     that constraint, use it.  This makes us take advantage of 'i'
3192///     constraints when available.
3193///  2) Otherwise, pick the most general constraint present.  This prefers
3194///     'm' over 'r', for example.
3195///
3196static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
3197                             const TargetLowering &TLI,
3198                             SDValue Op, SelectionDAG *DAG) {
3199  assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
3200  unsigned BestIdx = 0;
3201  TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
3202  int BestGenerality = -1;
3203
3204  // Loop over the options, keeping track of the most general one.
3205  for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
3206    TargetLowering::ConstraintType CType =
3207      TLI.getConstraintType(OpInfo.Codes[i]);
3208
3209    // If this is an 'other' constraint, see if the operand is valid for it.
3210    // For example, on X86 we might have an 'rI' constraint.  If the operand
3211    // is an integer in the range [0..31] we want to use I (saving a load
3212    // of a register), otherwise we must use 'r'.
3213    if (CType == TargetLowering::C_Other && Op.getNode()) {
3214      assert(OpInfo.Codes[i].size() == 1 &&
3215             "Unhandled multi-letter 'other' constraint");
3216      std::vector<SDValue> ResultOps;
3217      TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
3218                                       ResultOps, *DAG);
3219      if (!ResultOps.empty()) {
3220        BestType = CType;
3221        BestIdx = i;
3222        break;
3223      }
3224    }
3225
3226    // Things with matching constraints can only be registers, per gcc
3227    // documentation.  This mainly affects "g" constraints.
3228    if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
3229      continue;
3230
3231    // This constraint letter is more general than the previous one, use it.
3232    int Generality = getConstraintGenerality(CType);
3233    if (Generality > BestGenerality) {
3234      BestType = CType;
3235      BestIdx = i;
3236      BestGenerality = Generality;
3237    }
3238  }
3239
3240  OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
3241  OpInfo.ConstraintType = BestType;
3242}
3243
3244/// ComputeConstraintToUse - Determines the constraint code and constraint
3245/// type to use for the specific AsmOperandInfo, setting
3246/// OpInfo.ConstraintCode and OpInfo.ConstraintType.
3247void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
3248                                            SDValue Op,
3249                                            SelectionDAG *DAG) const {
3250  assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
3251
3252  // Single-letter constraints ('r') are very common.
3253  if (OpInfo.Codes.size() == 1) {
3254    OpInfo.ConstraintCode = OpInfo.Codes[0];
3255    OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
3256  } else {
3257    ChooseConstraint(OpInfo, *this, Op, DAG);
3258  }
3259
3260  // 'X' matches anything.
3261  if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
3262    // Labels and constants are handled elsewhere ('X' is the only thing
3263    // that matches labels).  For Functions, the type here is the type of
3264    // the result, which is not what we want to look at; leave them alone.
3265    Value *v = OpInfo.CallOperandVal;
3266    if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
3267      OpInfo.CallOperandVal = v;
3268      return;
3269    }
3270
3271    // Otherwise, try to resolve it to something we know about by looking at
3272    // the actual operand type.
3273    if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
3274      OpInfo.ConstraintCode = Repl;
3275      OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
3276    }
3277  }
3278}
3279
3280//===----------------------------------------------------------------------===//
3281//  Loop Strength Reduction hooks
3282//===----------------------------------------------------------------------===//
3283
3284/// isLegalAddressingMode - Return true if the addressing mode represented
3285/// by AM is legal for this target, for a load/store of the specified type.
3286bool TargetLowering::isLegalAddressingMode(const AddrMode &AM,
3287                                           Type *Ty) const {
3288  // The default implementation of this implements a conservative RISCy, r+r and
3289  // r+i addr mode.
3290
3291  // Allows a sign-extended 16-bit immediate field.
3292  if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
3293    return false;
3294
3295  // No global is ever allowed as a base.
3296  if (AM.BaseGV)
3297    return false;
3298
3299  // Only support r+r,
3300  switch (AM.Scale) {
3301  case 0:  // "r+i" or just "i", depending on HasBaseReg.
3302    break;
3303  case 1:
3304    if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
3305      return false;
3306    // Otherwise we have r+r or r+i.
3307    break;
3308  case 2:
3309    if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
3310      return false;
3311    // Allow 2*r as r+r.
3312    break;
3313  }
3314
3315  return true;
3316}
3317
3318/// BuildExactDiv - Given an exact SDIV by a constant, create a multiplication
3319/// with the multiplicative inverse of the constant.
3320SDValue TargetLowering::BuildExactSDIV(SDValue Op1, SDValue Op2, DebugLoc dl,
3321                                       SelectionDAG &DAG) const {
3322  ConstantSDNode *C = cast<ConstantSDNode>(Op2);
3323  APInt d = C->getAPIntValue();
3324  assert(d != 0 && "Division by zero!");
3325
3326  // Shift the value upfront if it is even, so the LSB is one.
3327  unsigned ShAmt = d.countTrailingZeros();
3328  if (ShAmt) {
3329    // TODO: For UDIV use SRL instead of SRA.
3330    SDValue Amt = DAG.getConstant(ShAmt, getShiftAmountTy(Op1.getValueType()));
3331    Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt);
3332    d = d.ashr(ShAmt);
3333  }
3334
3335  // Calculate the multiplicative inverse, using Newton's method.
3336  APInt t, xn = d;
3337  while ((t = d*xn) != 1)
3338    xn *= APInt(d.getBitWidth(), 2) - t;
3339
3340  Op2 = DAG.getConstant(xn, Op1.getValueType());
3341  return DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
3342}
3343
3344/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
3345/// return a DAG expression to select that will generate the same value by
3346/// multiplying by a magic number.  See:
3347/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
3348SDValue TargetLowering::
3349BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
3350          std::vector<SDNode*> *Created) const {
3351  EVT VT = N->getValueType(0);
3352  DebugLoc dl= N->getDebugLoc();
3353
3354  // Check to see if we can do this.
3355  // FIXME: We should be more aggressive here.
3356  if (!isTypeLegal(VT))
3357    return SDValue();
3358
3359  APInt d = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
3360  APInt::ms magics = d.magic();
3361
3362  // Multiply the numerator (operand 0) by the magic value
3363  // FIXME: We should support doing a MUL in a wider type
3364  SDValue Q;
3365  if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
3366                            isOperationLegalOrCustom(ISD::MULHS, VT))
3367    Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
3368                    DAG.getConstant(magics.m, VT));
3369  else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
3370                                 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
3371    Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
3372                              N->getOperand(0),
3373                              DAG.getConstant(magics.m, VT)).getNode(), 1);
3374  else
3375    return SDValue();       // No mulhs or equvialent
3376  // If d > 0 and m < 0, add the numerator
3377  if (d.isStrictlyPositive() && magics.m.isNegative()) {
3378    Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
3379    if (Created)
3380      Created->push_back(Q.getNode());
3381  }
3382  // If d < 0 and m > 0, subtract the numerator.
3383  if (d.isNegative() && magics.m.isStrictlyPositive()) {
3384    Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
3385    if (Created)
3386      Created->push_back(Q.getNode());
3387  }
3388  // Shift right algebraic if shift value is nonzero
3389  if (magics.s > 0) {
3390    Q = DAG.getNode(ISD::SRA, dl, VT, Q,
3391                 DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
3392    if (Created)
3393      Created->push_back(Q.getNode());
3394  }
3395  // Extract the sign bit and add it to the quotient
3396  SDValue T =
3397    DAG.getNode(ISD::SRL, dl, VT, Q, DAG.getConstant(VT.getSizeInBits()-1,
3398                                           getShiftAmountTy(Q.getValueType())));
3399  if (Created)
3400    Created->push_back(T.getNode());
3401  return DAG.getNode(ISD::ADD, dl, VT, Q, T);
3402}
3403
3404/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
3405/// return a DAG expression to select that will generate the same value by
3406/// multiplying by a magic number.  See:
3407/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
3408SDValue TargetLowering::
3409BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
3410          std::vector<SDNode*> *Created) const {
3411  EVT VT = N->getValueType(0);
3412  DebugLoc dl = N->getDebugLoc();
3413
3414  // Check to see if we can do this.
3415  // FIXME: We should be more aggressive here.
3416  if (!isTypeLegal(VT))
3417    return SDValue();
3418
3419  // FIXME: We should use a narrower constant when the upper
3420  // bits are known to be zero.
3421  const APInt &N1C = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
3422  APInt::mu magics = N1C.magicu();
3423
3424  SDValue Q = N->getOperand(0);
3425
3426  // If the divisor is even, we can avoid using the expensive fixup by shifting
3427  // the divided value upfront.
3428  if (magics.a != 0 && !N1C[0]) {
3429    unsigned Shift = N1C.countTrailingZeros();
3430    Q = DAG.getNode(ISD::SRL, dl, VT, Q,
3431                    DAG.getConstant(Shift, getShiftAmountTy(Q.getValueType())));
3432    if (Created)
3433      Created->push_back(Q.getNode());
3434
3435    // Get magic number for the shifted divisor.
3436    magics = N1C.lshr(Shift).magicu(Shift);
3437    assert(magics.a == 0 && "Should use cheap fixup now");
3438  }
3439
3440  // Multiply the numerator (operand 0) by the magic value
3441  // FIXME: We should support doing a MUL in a wider type
3442  if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
3443                            isOperationLegalOrCustom(ISD::MULHU, VT))
3444    Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, VT));
3445  else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
3446                                 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
3447    Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
3448                            DAG.getConstant(magics.m, VT)).getNode(), 1);
3449  else
3450    return SDValue();       // No mulhu or equvialent
3451  if (Created)
3452    Created->push_back(Q.getNode());
3453
3454  if (magics.a == 0) {
3455    assert(magics.s < N1C.getBitWidth() &&
3456           "We shouldn't generate an undefined shift!");
3457    return DAG.getNode(ISD::SRL, dl, VT, Q,
3458                 DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
3459  } else {
3460    SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
3461    if (Created)
3462      Created->push_back(NPQ.getNode());
3463    NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ,
3464                      DAG.getConstant(1, getShiftAmountTy(NPQ.getValueType())));
3465    if (Created)
3466      Created->push_back(NPQ.getNode());
3467    NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
3468    if (Created)
3469      Created->push_back(NPQ.getNode());
3470    return DAG.getNode(ISD::SRL, dl, VT, NPQ,
3471             DAG.getConstant(magics.s-1, getShiftAmountTy(NPQ.getValueType())));
3472  }
3473}
3474