blob: f59f8510c76ec1bbb59c7542fdbf98685cc7bf8c [file] [log] [blame]
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001//===-- 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/MC/MCAsmInfo.h"
16#include "llvm/MC/MCExpr.h"
17#include "llvm/Target/TargetData.h"
18#include "llvm/Target/TargetLoweringObjectFile.h"
19#include "llvm/Target/TargetMachine.h"
20#include "llvm/Target/TargetRegisterInfo.h"
21#include "llvm/Target/TargetSubtarget.h"
22#include "llvm/GlobalVariable.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineJumpTableInfo.h"
26#include "llvm/CodeGen/MachineFunction.h"
27#include "llvm/CodeGen/SelectionDAG.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/MathExtras.h"
Shih-wei Liaoe4454322010-04-07 12:21:42 -070031#include <ctype.h>
Shih-wei Liaoe264f622010-02-10 11:10:31 -080032using namespace llvm;
33
34namespace llvm {
35TLSModel::Model getTLSModel(const GlobalValue *GV, Reloc::Model reloc) {
36 bool isLocal = GV->hasLocalLinkage();
37 bool isDeclaration = GV->isDeclaration();
38 // FIXME: what should we do for protected and internal visibility?
39 // For variables, is internal different from hidden?
40 bool isHidden = GV->hasHiddenVisibility();
41
42 if (reloc == Reloc::PIC_) {
43 if (isLocal || isHidden)
44 return TLSModel::LocalDynamic;
45 else
46 return TLSModel::GeneralDynamic;
47 } else {
48 if (!isDeclaration || isHidden)
49 return TLSModel::LocalExec;
50 else
51 return TLSModel::InitialExec;
52 }
53}
54}
55
56/// InitLibcallNames - Set default libcall names.
57///
58static void InitLibcallNames(const char **Names) {
59 Names[RTLIB::SHL_I16] = "__ashlhi3";
60 Names[RTLIB::SHL_I32] = "__ashlsi3";
61 Names[RTLIB::SHL_I64] = "__ashldi3";
62 Names[RTLIB::SHL_I128] = "__ashlti3";
63 Names[RTLIB::SRL_I16] = "__lshrhi3";
64 Names[RTLIB::SRL_I32] = "__lshrsi3";
65 Names[RTLIB::SRL_I64] = "__lshrdi3";
66 Names[RTLIB::SRL_I128] = "__lshrti3";
67 Names[RTLIB::SRA_I16] = "__ashrhi3";
68 Names[RTLIB::SRA_I32] = "__ashrsi3";
69 Names[RTLIB::SRA_I64] = "__ashrdi3";
70 Names[RTLIB::SRA_I128] = "__ashrti3";
71 Names[RTLIB::MUL_I8] = "__mulqi3";
72 Names[RTLIB::MUL_I16] = "__mulhi3";
73 Names[RTLIB::MUL_I32] = "__mulsi3";
74 Names[RTLIB::MUL_I64] = "__muldi3";
75 Names[RTLIB::MUL_I128] = "__multi3";
76 Names[RTLIB::SDIV_I8] = "__divqi3";
77 Names[RTLIB::SDIV_I16] = "__divhi3";
78 Names[RTLIB::SDIV_I32] = "__divsi3";
79 Names[RTLIB::SDIV_I64] = "__divdi3";
80 Names[RTLIB::SDIV_I128] = "__divti3";
81 Names[RTLIB::UDIV_I8] = "__udivqi3";
82 Names[RTLIB::UDIV_I16] = "__udivhi3";
83 Names[RTLIB::UDIV_I32] = "__udivsi3";
84 Names[RTLIB::UDIV_I64] = "__udivdi3";
85 Names[RTLIB::UDIV_I128] = "__udivti3";
86 Names[RTLIB::SREM_I8] = "__modqi3";
87 Names[RTLIB::SREM_I16] = "__modhi3";
88 Names[RTLIB::SREM_I32] = "__modsi3";
89 Names[RTLIB::SREM_I64] = "__moddi3";
90 Names[RTLIB::SREM_I128] = "__modti3";
91 Names[RTLIB::UREM_I8] = "__umodqi3";
92 Names[RTLIB::UREM_I16] = "__umodhi3";
93 Names[RTLIB::UREM_I32] = "__umodsi3";
94 Names[RTLIB::UREM_I64] = "__umoddi3";
95 Names[RTLIB::UREM_I128] = "__umodti3";
96 Names[RTLIB::NEG_I32] = "__negsi2";
97 Names[RTLIB::NEG_I64] = "__negdi2";
98 Names[RTLIB::ADD_F32] = "__addsf3";
99 Names[RTLIB::ADD_F64] = "__adddf3";
100 Names[RTLIB::ADD_F80] = "__addxf3";
101 Names[RTLIB::ADD_PPCF128] = "__gcc_qadd";
102 Names[RTLIB::SUB_F32] = "__subsf3";
103 Names[RTLIB::SUB_F64] = "__subdf3";
104 Names[RTLIB::SUB_F80] = "__subxf3";
105 Names[RTLIB::SUB_PPCF128] = "__gcc_qsub";
106 Names[RTLIB::MUL_F32] = "__mulsf3";
107 Names[RTLIB::MUL_F64] = "__muldf3";
108 Names[RTLIB::MUL_F80] = "__mulxf3";
109 Names[RTLIB::MUL_PPCF128] = "__gcc_qmul";
110 Names[RTLIB::DIV_F32] = "__divsf3";
111 Names[RTLIB::DIV_F64] = "__divdf3";
112 Names[RTLIB::DIV_F80] = "__divxf3";
113 Names[RTLIB::DIV_PPCF128] = "__gcc_qdiv";
114 Names[RTLIB::REM_F32] = "fmodf";
115 Names[RTLIB::REM_F64] = "fmod";
116 Names[RTLIB::REM_F80] = "fmodl";
117 Names[RTLIB::REM_PPCF128] = "fmodl";
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";
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700178 Names[RTLIB::COPYSIGN_F32] = "copysignf";
179 Names[RTLIB::COPYSIGN_F64] = "copysign";
180 Names[RTLIB::COPYSIGN_F80] = "copysignl";
181 Names[RTLIB::COPYSIGN_PPCF128] = "copysignl";
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800182 Names[RTLIB::FPEXT_F32_F64] = "__extendsfdf2";
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700183 Names[RTLIB::FPEXT_F16_F32] = "__gnu_h2f_ieee";
184 Names[RTLIB::FPROUND_F32_F16] = "__gnu_f2h_ieee";
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800185 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";
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700190 Names[RTLIB::FPTOSINT_F32_I8] = "__fixsfqi";
191 Names[RTLIB::FPTOSINT_F32_I16] = "__fixsfhi";
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800192 Names[RTLIB::FPTOSINT_F32_I32] = "__fixsfsi";
193 Names[RTLIB::FPTOSINT_F32_I64] = "__fixsfdi";
194 Names[RTLIB::FPTOSINT_F32_I128] = "__fixsfti";
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700195 Names[RTLIB::FPTOSINT_F64_I8] = "__fixdfqi";
196 Names[RTLIB::FPTOSINT_F64_I16] = "__fixdfhi";
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800197 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";
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700206 Names[RTLIB::FPTOUINT_F32_I8] = "__fixunssfqi";
207 Names[RTLIB::FPTOUINT_F32_I16] = "__fixunssfhi";
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800208 Names[RTLIB::FPTOUINT_F32_I32] = "__fixunssfsi";
209 Names[RTLIB::FPTOUINT_F32_I64] = "__fixunssfdi";
210 Names[RTLIB::FPTOUINT_F32_I128] = "__fixunssfti";
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700211 Names[RTLIB::FPTOUINT_F64_I8] = "__fixunsdfqi";
212 Names[RTLIB::FPTOUINT_F64_I16] = "__fixunsdfhi";
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800213 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}
267
268/// InitLibcallCallingConvs - Set default libcall CallingConvs.
269///
270static void InitLibcallCallingConvs(CallingConv::ID *CCs) {
271 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) {
272 CCs[i] = CallingConv::C;
273 }
274}
275
276/// getFPEXT - Return the FPEXT_*_* value for the given types, or
277/// UNKNOWN_LIBCALL if there is none.
278RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) {
279 if (OpVT == MVT::f32) {
280 if (RetVT == MVT::f64)
281 return FPEXT_F32_F64;
282 }
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700283
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800284 return UNKNOWN_LIBCALL;
285}
286
287/// getFPROUND - Return the FPROUND_*_* value for the given types, or
288/// UNKNOWN_LIBCALL if there is none.
289RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) {
290 if (RetVT == MVT::f32) {
291 if (OpVT == MVT::f64)
292 return FPROUND_F64_F32;
293 if (OpVT == MVT::f80)
294 return FPROUND_F80_F32;
295 if (OpVT == MVT::ppcf128)
296 return FPROUND_PPCF128_F32;
297 } else if (RetVT == MVT::f64) {
298 if (OpVT == MVT::f80)
299 return FPROUND_F80_F64;
300 if (OpVT == MVT::ppcf128)
301 return FPROUND_PPCF128_F64;
302 }
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700303
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800304 return UNKNOWN_LIBCALL;
305}
306
307/// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or
308/// UNKNOWN_LIBCALL if there is none.
309RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) {
310 if (OpVT == MVT::f32) {
311 if (RetVT == MVT::i8)
312 return FPTOSINT_F32_I8;
313 if (RetVT == MVT::i16)
314 return FPTOSINT_F32_I16;
315 if (RetVT == MVT::i32)
316 return FPTOSINT_F32_I32;
317 if (RetVT == MVT::i64)
318 return FPTOSINT_F32_I64;
319 if (RetVT == MVT::i128)
320 return FPTOSINT_F32_I128;
321 } else if (OpVT == MVT::f64) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700322 if (RetVT == MVT::i8)
323 return FPTOSINT_F64_I8;
324 if (RetVT == MVT::i16)
325 return FPTOSINT_F64_I16;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800326 if (RetVT == MVT::i32)
327 return FPTOSINT_F64_I32;
328 if (RetVT == MVT::i64)
329 return FPTOSINT_F64_I64;
330 if (RetVT == MVT::i128)
331 return FPTOSINT_F64_I128;
332 } else if (OpVT == MVT::f80) {
333 if (RetVT == MVT::i32)
334 return FPTOSINT_F80_I32;
335 if (RetVT == MVT::i64)
336 return FPTOSINT_F80_I64;
337 if (RetVT == MVT::i128)
338 return FPTOSINT_F80_I128;
339 } else if (OpVT == MVT::ppcf128) {
340 if (RetVT == MVT::i32)
341 return FPTOSINT_PPCF128_I32;
342 if (RetVT == MVT::i64)
343 return FPTOSINT_PPCF128_I64;
344 if (RetVT == MVT::i128)
345 return FPTOSINT_PPCF128_I128;
346 }
347 return UNKNOWN_LIBCALL;
348}
349
350/// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or
351/// UNKNOWN_LIBCALL if there is none.
352RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) {
353 if (OpVT == MVT::f32) {
354 if (RetVT == MVT::i8)
355 return FPTOUINT_F32_I8;
356 if (RetVT == MVT::i16)
357 return FPTOUINT_F32_I16;
358 if (RetVT == MVT::i32)
359 return FPTOUINT_F32_I32;
360 if (RetVT == MVT::i64)
361 return FPTOUINT_F32_I64;
362 if (RetVT == MVT::i128)
363 return FPTOUINT_F32_I128;
364 } else if (OpVT == MVT::f64) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700365 if (RetVT == MVT::i8)
366 return FPTOUINT_F64_I8;
367 if (RetVT == MVT::i16)
368 return FPTOUINT_F64_I16;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800369 if (RetVT == MVT::i32)
370 return FPTOUINT_F64_I32;
371 if (RetVT == MVT::i64)
372 return FPTOUINT_F64_I64;
373 if (RetVT == MVT::i128)
374 return FPTOUINT_F64_I128;
375 } else if (OpVT == MVT::f80) {
376 if (RetVT == MVT::i32)
377 return FPTOUINT_F80_I32;
378 if (RetVT == MVT::i64)
379 return FPTOUINT_F80_I64;
380 if (RetVT == MVT::i128)
381 return FPTOUINT_F80_I128;
382 } else if (OpVT == MVT::ppcf128) {
383 if (RetVT == MVT::i32)
384 return FPTOUINT_PPCF128_I32;
385 if (RetVT == MVT::i64)
386 return FPTOUINT_PPCF128_I64;
387 if (RetVT == MVT::i128)
388 return FPTOUINT_PPCF128_I128;
389 }
390 return UNKNOWN_LIBCALL;
391}
392
393/// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or
394/// UNKNOWN_LIBCALL if there is none.
395RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) {
396 if (OpVT == MVT::i32) {
397 if (RetVT == MVT::f32)
398 return SINTTOFP_I32_F32;
399 else if (RetVT == MVT::f64)
400 return SINTTOFP_I32_F64;
401 else if (RetVT == MVT::f80)
402 return SINTTOFP_I32_F80;
403 else if (RetVT == MVT::ppcf128)
404 return SINTTOFP_I32_PPCF128;
405 } else if (OpVT == MVT::i64) {
406 if (RetVT == MVT::f32)
407 return SINTTOFP_I64_F32;
408 else if (RetVT == MVT::f64)
409 return SINTTOFP_I64_F64;
410 else if (RetVT == MVT::f80)
411 return SINTTOFP_I64_F80;
412 else if (RetVT == MVT::ppcf128)
413 return SINTTOFP_I64_PPCF128;
414 } else if (OpVT == MVT::i128) {
415 if (RetVT == MVT::f32)
416 return SINTTOFP_I128_F32;
417 else if (RetVT == MVT::f64)
418 return SINTTOFP_I128_F64;
419 else if (RetVT == MVT::f80)
420 return SINTTOFP_I128_F80;
421 else if (RetVT == MVT::ppcf128)
422 return SINTTOFP_I128_PPCF128;
423 }
424 return UNKNOWN_LIBCALL;
425}
426
427/// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or
428/// UNKNOWN_LIBCALL if there is none.
429RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) {
430 if (OpVT == MVT::i32) {
431 if (RetVT == MVT::f32)
432 return UINTTOFP_I32_F32;
433 else if (RetVT == MVT::f64)
434 return UINTTOFP_I32_F64;
435 else if (RetVT == MVT::f80)
436 return UINTTOFP_I32_F80;
437 else if (RetVT == MVT::ppcf128)
438 return UINTTOFP_I32_PPCF128;
439 } else if (OpVT == MVT::i64) {
440 if (RetVT == MVT::f32)
441 return UINTTOFP_I64_F32;
442 else if (RetVT == MVT::f64)
443 return UINTTOFP_I64_F64;
444 else if (RetVT == MVT::f80)
445 return UINTTOFP_I64_F80;
446 else if (RetVT == MVT::ppcf128)
447 return UINTTOFP_I64_PPCF128;
448 } else if (OpVT == MVT::i128) {
449 if (RetVT == MVT::f32)
450 return UINTTOFP_I128_F32;
451 else if (RetVT == MVT::f64)
452 return UINTTOFP_I128_F64;
453 else if (RetVT == MVT::f80)
454 return UINTTOFP_I128_F80;
455 else if (RetVT == MVT::ppcf128)
456 return UINTTOFP_I128_PPCF128;
457 }
458 return UNKNOWN_LIBCALL;
459}
460
461/// InitCmpLibcallCCs - Set default comparison libcall CC.
462///
463static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
464 memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
465 CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
466 CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
467 CCs[RTLIB::UNE_F32] = ISD::SETNE;
468 CCs[RTLIB::UNE_F64] = ISD::SETNE;
469 CCs[RTLIB::OGE_F32] = ISD::SETGE;
470 CCs[RTLIB::OGE_F64] = ISD::SETGE;
471 CCs[RTLIB::OLT_F32] = ISD::SETLT;
472 CCs[RTLIB::OLT_F64] = ISD::SETLT;
473 CCs[RTLIB::OLE_F32] = ISD::SETLE;
474 CCs[RTLIB::OLE_F64] = ISD::SETLE;
475 CCs[RTLIB::OGT_F32] = ISD::SETGT;
476 CCs[RTLIB::OGT_F64] = ISD::SETGT;
477 CCs[RTLIB::UO_F32] = ISD::SETNE;
478 CCs[RTLIB::UO_F64] = ISD::SETNE;
479 CCs[RTLIB::O_F32] = ISD::SETEQ;
480 CCs[RTLIB::O_F64] = ISD::SETEQ;
481}
482
483/// NOTE: The constructor takes ownership of TLOF.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700484TargetLowering::TargetLowering(const TargetMachine &tm,
485 const TargetLoweringObjectFile *tlof)
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800486 : TM(tm), TD(TM.getTargetData()), TLOF(*tlof) {
487 // All operations default to being supported.
488 memset(OpActions, 0, sizeof(OpActions));
489 memset(LoadExtActions, 0, sizeof(LoadExtActions));
490 memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
491 memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800492 memset(CondCodeActions, 0, sizeof(CondCodeActions));
493
494 // Set default actions for various operations.
495 for (unsigned VT = 0; VT != (unsigned)MVT::LAST_VALUETYPE; ++VT) {
496 // Default all indexed load / store to expand.
497 for (unsigned IM = (unsigned)ISD::PRE_INC;
498 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
499 setIndexedLoadAction(IM, (MVT::SimpleValueType)VT, Expand);
500 setIndexedStoreAction(IM, (MVT::SimpleValueType)VT, Expand);
501 }
502
503 // These operations default to expand.
504 setOperationAction(ISD::FGETSIGN, (MVT::SimpleValueType)VT, Expand);
505 setOperationAction(ISD::CONCAT_VECTORS, (MVT::SimpleValueType)VT, Expand);
506 }
507
508 // Most targets ignore the @llvm.prefetch intrinsic.
509 setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
510
511 // ConstantFP nodes default to expand. Targets can either change this to
512 // Legal, in which case all fp constants are legal, or use isFPImmLegal()
513 // to optimize expansions for certain constants.
514 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
515 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
516 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
517
518 // These library functions default to expand.
519 setOperationAction(ISD::FLOG , MVT::f64, Expand);
520 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
521 setOperationAction(ISD::FLOG10,MVT::f64, Expand);
522 setOperationAction(ISD::FEXP , MVT::f64, Expand);
523 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
524 setOperationAction(ISD::FLOG , MVT::f32, Expand);
525 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
526 setOperationAction(ISD::FLOG10,MVT::f32, Expand);
527 setOperationAction(ISD::FEXP , MVT::f32, Expand);
528 setOperationAction(ISD::FEXP2, MVT::f32, Expand);
529
530 // Default ISD::TRAP to expand (which turns it into abort).
531 setOperationAction(ISD::TRAP, MVT::Other, Expand);
532
533 IsLittleEndian = TD->isLittleEndian();
534 ShiftAmountTy = PointerTy = MVT::getIntegerVT(8*TD->getPointerSize());
535 memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*));
536 memset(TargetDAGCombineArray, 0, array_lengthof(TargetDAGCombineArray));
537 maxStoresPerMemset = maxStoresPerMemcpy = maxStoresPerMemmove = 8;
538 benefitFromCodePlacementOpt = false;
539 UseUnderscoreSetJmp = false;
540 UseUnderscoreLongJmp = false;
541 SelectIsExpensive = false;
542 IntDivIsCheap = false;
543 Pow2DivIsCheap = false;
544 StackPointerRegisterToSaveRestore = 0;
545 ExceptionPointerRegister = 0;
546 ExceptionSelectorRegister = 0;
547 BooleanContents = UndefinedBooleanContent;
548 SchedPreferenceInfo = SchedulingForLatency;
549 JumpBufSize = 0;
550 JumpBufAlignment = 0;
551 IfCvtBlockSizeLimit = 2;
552 IfCvtDupBlockSizeLimit = 0;
553 PrefLoopAlignment = 0;
554
555 InitLibcallNames(LibcallRoutineNames);
556 InitCmpLibcallCCs(CmpLibcallCCs);
557 InitLibcallCallingConvs(LibcallCallingConvs);
558}
559
560TargetLowering::~TargetLowering() {
561 delete &TLOF;
562}
563
Shih-wei Liaoe4454322010-04-07 12:21:42 -0700564/// canOpTrap - Returns true if the operation can trap for the value type.
565/// VT must be a legal type.
566bool TargetLowering::canOpTrap(unsigned Op, EVT VT) const {
567 assert(isTypeLegal(VT));
568 switch (Op) {
569 default:
570 return false;
571 case ISD::FDIV:
572 case ISD::FREM:
573 case ISD::SDIV:
574 case ISD::UDIV:
575 case ISD::SREM:
576 case ISD::UREM:
577 return true;
578 }
579}
580
581
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800582static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
583 unsigned &NumIntermediates,
584 EVT &RegisterVT,
585 TargetLowering* TLI) {
586 // Figure out the right, legal destination reg to copy into.
587 unsigned NumElts = VT.getVectorNumElements();
588 MVT EltTy = VT.getVectorElementType();
589
590 unsigned NumVectorRegs = 1;
591
592 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
593 // could break down into LHS/RHS like LegalizeDAG does.
594 if (!isPowerOf2_32(NumElts)) {
595 NumVectorRegs = NumElts;
596 NumElts = 1;
597 }
598
599 // Divide the input until we get to a supported size. This will always
600 // end with a scalar if the target doesn't support vectors.
601 while (NumElts > 1 && !TLI->isTypeLegal(MVT::getVectorVT(EltTy, NumElts))) {
602 NumElts >>= 1;
603 NumVectorRegs <<= 1;
604 }
605
606 NumIntermediates = NumVectorRegs;
607
608 MVT NewVT = MVT::getVectorVT(EltTy, NumElts);
609 if (!TLI->isTypeLegal(NewVT))
610 NewVT = EltTy;
611 IntermediateVT = NewVT;
612
613 EVT DestVT = TLI->getRegisterType(NewVT);
614 RegisterVT = DestVT;
615 if (EVT(DestVT).bitsLT(NewVT)) {
616 // Value is expanded, e.g. i64 -> i16.
617 return NumVectorRegs*(NewVT.getSizeInBits()/DestVT.getSizeInBits());
618 } else {
619 // Otherwise, promotion or legal types use the same number of registers as
620 // the vector decimated to the appropriate level.
621 return NumVectorRegs;
622 }
623
624 return 1;
625}
626
627/// computeRegisterProperties - Once all of the register classes are added,
628/// this allows us to compute derived properties we expose.
629void TargetLowering::computeRegisterProperties() {
630 assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE &&
631 "Too many value types for ValueTypeActions to hold!");
632
633 // Everything defaults to needing one register.
634 for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
635 NumRegistersForVT[i] = 1;
636 RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
637 }
638 // ...except isVoid, which doesn't need any registers.
639 NumRegistersForVT[MVT::isVoid] = 0;
640
641 // Find the largest integer register class.
642 unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
643 for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg)
644 assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
645
646 // Every integer value type larger than this largest register takes twice as
647 // many registers to represent as the previous ValueType.
648 for (unsigned ExpandedReg = LargestIntReg + 1; ; ++ExpandedReg) {
649 EVT ExpandedVT = (MVT::SimpleValueType)ExpandedReg;
650 if (!ExpandedVT.isInteger())
651 break;
652 NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
653 RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
654 TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
655 ValueTypeActions.setTypeAction(ExpandedVT, Expand);
656 }
657
658 // Inspect all of the ValueType's smaller than the largest integer
659 // register to see which ones need promotion.
660 unsigned LegalIntReg = LargestIntReg;
661 for (unsigned IntReg = LargestIntReg - 1;
662 IntReg >= (unsigned)MVT::i1; --IntReg) {
663 EVT IVT = (MVT::SimpleValueType)IntReg;
664 if (isTypeLegal(IVT)) {
665 LegalIntReg = IntReg;
666 } else {
667 RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
668 (MVT::SimpleValueType)LegalIntReg;
669 ValueTypeActions.setTypeAction(IVT, Promote);
670 }
671 }
672
673 // ppcf128 type is really two f64's.
674 if (!isTypeLegal(MVT::ppcf128)) {
675 NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
676 RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
677 TransformToType[MVT::ppcf128] = MVT::f64;
678 ValueTypeActions.setTypeAction(MVT::ppcf128, Expand);
679 }
680
681 // Decide how to handle f64. If the target does not have native f64 support,
682 // expand it to i64 and we will be generating soft float library calls.
683 if (!isTypeLegal(MVT::f64)) {
684 NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
685 RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
686 TransformToType[MVT::f64] = MVT::i64;
687 ValueTypeActions.setTypeAction(MVT::f64, Expand);
688 }
689
690 // Decide how to handle f32. If the target does not have native support for
691 // f32, promote it to f64 if it is legal. Otherwise, expand it to i32.
692 if (!isTypeLegal(MVT::f32)) {
693 if (isTypeLegal(MVT::f64)) {
694 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::f64];
695 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::f64];
696 TransformToType[MVT::f32] = MVT::f64;
697 ValueTypeActions.setTypeAction(MVT::f32, Promote);
698 } else {
699 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
700 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
701 TransformToType[MVT::f32] = MVT::i32;
702 ValueTypeActions.setTypeAction(MVT::f32, Expand);
703 }
704 }
705
706 // Loop over all of the vector value types to see which need transformations.
707 for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
708 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
709 MVT VT = (MVT::SimpleValueType)i;
710 if (!isTypeLegal(VT)) {
711 MVT IntermediateVT;
712 EVT RegisterVT;
713 unsigned NumIntermediates;
714 NumRegistersForVT[i] =
715 getVectorTypeBreakdownMVT(VT, IntermediateVT, NumIntermediates,
716 RegisterVT, this);
717 RegisterTypeForVT[i] = RegisterVT;
718
719 // Determine if there is a legal wider type.
720 bool IsLegalWiderType = false;
721 EVT EltVT = VT.getVectorElementType();
722 unsigned NElts = VT.getVectorNumElements();
723 for (unsigned nVT = i+1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
724 EVT SVT = (MVT::SimpleValueType)nVT;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700725 if (isTypeSynthesizable(SVT) && SVT.getVectorElementType() == EltVT &&
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800726 SVT.getVectorNumElements() > NElts && NElts != 1) {
727 TransformToType[i] = SVT;
728 ValueTypeActions.setTypeAction(VT, Promote);
729 IsLegalWiderType = true;
730 break;
731 }
732 }
733 if (!IsLegalWiderType) {
734 EVT NVT = VT.getPow2VectorType();
735 if (NVT == VT) {
736 // Type is already a power of 2. The default action is to split.
737 TransformToType[i] = MVT::Other;
738 ValueTypeActions.setTypeAction(VT, Expand);
739 } else {
740 TransformToType[i] = NVT;
741 ValueTypeActions.setTypeAction(VT, Promote);
742 }
743 }
744 }
745 }
746}
747
748const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
749 return NULL;
750}
751
752
753MVT::SimpleValueType TargetLowering::getSetCCResultType(EVT VT) const {
754 return PointerTy.SimpleTy;
755}
756
757MVT::SimpleValueType TargetLowering::getCmpLibcallReturnType() const {
758 return MVT::i32; // return the default value
759}
760
761/// getVectorTypeBreakdown - Vector types are broken down into some number of
762/// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
763/// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
764/// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
765///
766/// This method returns the number of registers needed, and the VT for each
767/// register. It also returns the VT and quantity of the intermediate values
768/// before they are promoted/expanded.
769///
770unsigned TargetLowering::getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
771 EVT &IntermediateVT,
772 unsigned &NumIntermediates,
773 EVT &RegisterVT) const {
774 // Figure out the right, legal destination reg to copy into.
775 unsigned NumElts = VT.getVectorNumElements();
776 EVT EltTy = VT.getVectorElementType();
777
778 unsigned NumVectorRegs = 1;
779
780 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
781 // could break down into LHS/RHS like LegalizeDAG does.
782 if (!isPowerOf2_32(NumElts)) {
783 NumVectorRegs = NumElts;
784 NumElts = 1;
785 }
786
787 // Divide the input until we get to a supported size. This will always
788 // end with a scalar if the target doesn't support vectors.
789 while (NumElts > 1 && !isTypeLegal(
790 EVT::getVectorVT(Context, EltTy, NumElts))) {
791 NumElts >>= 1;
792 NumVectorRegs <<= 1;
793 }
794
795 NumIntermediates = NumVectorRegs;
796
797 EVT NewVT = EVT::getVectorVT(Context, EltTy, NumElts);
798 if (!isTypeLegal(NewVT))
799 NewVT = EltTy;
800 IntermediateVT = NewVT;
801
802 EVT DestVT = getRegisterType(Context, NewVT);
803 RegisterVT = DestVT;
804 if (DestVT.bitsLT(NewVT)) {
805 // Value is expanded, e.g. i64 -> i16.
806 return NumVectorRegs*(NewVT.getSizeInBits()/DestVT.getSizeInBits());
807 } else {
808 // Otherwise, promotion or legal types use the same number of registers as
809 // the vector decimated to the appropriate level.
810 return NumVectorRegs;
811 }
812
813 return 1;
814}
815
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800816/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
817/// function arguments in the caller parameter area. This is the actual
818/// alignment, not its logarithm.
819unsigned TargetLowering::getByValTypeAlignment(const Type *Ty) const {
820 return TD->getCallFrameTypeAlignment(Ty);
821}
822
823/// getJumpTableEncoding - Return the entry encoding for a jump table in the
824/// current function. The returned value is a member of the
825/// MachineJumpTableInfo::JTEntryKind enum.
826unsigned TargetLowering::getJumpTableEncoding() const {
827 // In non-pic modes, just use the address of a block.
828 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
829 return MachineJumpTableInfo::EK_BlockAddress;
830
831 // In PIC mode, if the target supports a GPRel32 directive, use it.
832 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != 0)
833 return MachineJumpTableInfo::EK_GPRel32BlockAddress;
834
835 // Otherwise, use a label difference.
836 return MachineJumpTableInfo::EK_LabelDifference32;
837}
838
839SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
840 SelectionDAG &DAG) const {
841 // If our PIC model is GP relative, use the global offset table as the base.
842 if (getJumpTableEncoding() == MachineJumpTableInfo::EK_GPRel32BlockAddress)
843 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
844 return Table;
845}
846
847/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
848/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
849/// MCExpr.
850const MCExpr *
851TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
852 unsigned JTI,MCContext &Ctx) const{
853 // The normal PIC reloc base is the label at the start of the jump table.
854 return MCSymbolRefExpr::Create(MF->getJTISymbol(JTI, Ctx), Ctx);
855}
856
857bool
858TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
859 // Assume that everything is safe in static mode.
860 if (getTargetMachine().getRelocationModel() == Reloc::Static)
861 return true;
862
863 // In dynamic-no-pic mode, assume that known defined values are safe.
864 if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC &&
865 GA &&
866 !GA->getGlobal()->isDeclaration() &&
867 !GA->getGlobal()->isWeakForLinker())
868 return true;
869
870 // Otherwise assume nothing is safe.
871 return false;
872}
873
874//===----------------------------------------------------------------------===//
875// Optimization Methods
876//===----------------------------------------------------------------------===//
877
878/// ShrinkDemandedConstant - Check to see if the specified operand of the
879/// specified instruction is a constant integer. If so, check to see if there
880/// are any bits set in the constant that are not demanded. If so, shrink the
881/// constant and return true.
882bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
883 const APInt &Demanded) {
884 DebugLoc dl = Op.getDebugLoc();
885
886 // FIXME: ISD::SELECT, ISD::SELECT_CC
887 switch (Op.getOpcode()) {
888 default: break;
889 case ISD::XOR:
890 case ISD::AND:
891 case ISD::OR: {
892 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
893 if (!C) return false;
894
895 if (Op.getOpcode() == ISD::XOR &&
896 (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
897 return false;
898
899 // if we can expand it to have all bits set, do it
900 if (C->getAPIntValue().intersects(~Demanded)) {
901 EVT VT = Op.getValueType();
902 SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
903 DAG.getConstant(Demanded &
904 C->getAPIntValue(),
905 VT));
906 return CombineTo(Op, New);
907 }
908
909 break;
910 }
911 }
912
913 return false;
914}
915
916/// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
917/// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
918/// cast, but it could be generalized for targets with other types of
919/// implicit widening casts.
920bool
921TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
922 unsigned BitWidth,
923 const APInt &Demanded,
924 DebugLoc dl) {
925 assert(Op.getNumOperands() == 2 &&
926 "ShrinkDemandedOp only supports binary operators!");
927 assert(Op.getNode()->getNumValues() == 1 &&
928 "ShrinkDemandedOp only supports nodes with one result!");
929
930 // Don't do this if the node has another user, which may require the
931 // full value.
932 if (!Op.getNode()->hasOneUse())
933 return false;
934
935 // Search for the smallest integer type with free casts to and from
936 // Op's type. For expedience, just check power-of-2 integer types.
937 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
938 unsigned SmallVTBits = BitWidth - Demanded.countLeadingZeros();
939 if (!isPowerOf2_32(SmallVTBits))
940 SmallVTBits = NextPowerOf2(SmallVTBits);
941 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
942 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
943 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
944 TLI.isZExtFree(SmallVT, Op.getValueType())) {
945 // We found a type with free casts.
946 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
947 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
948 Op.getNode()->getOperand(0)),
949 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
950 Op.getNode()->getOperand(1)));
951 SDValue Z = DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), X);
952 return CombineTo(Op, Z);
953 }
954 }
955 return false;
956}
957
958/// SimplifyDemandedBits - Look at Op. At this point, we know that only the
959/// DemandedMask bits of the result of Op are ever used downstream. If we can
960/// use this information to simplify Op, create a new simplified DAG node and
961/// return true, returning the original and new nodes in Old and New. Otherwise,
962/// analyze the expression and return a mask of KnownOne and KnownZero bits for
963/// the expression (used to simplify the caller). The KnownZero/One bits may
964/// only be accurate for those bits in the DemandedMask.
965bool TargetLowering::SimplifyDemandedBits(SDValue Op,
966 const APInt &DemandedMask,
967 APInt &KnownZero,
968 APInt &KnownOne,
969 TargetLoweringOpt &TLO,
970 unsigned Depth) const {
971 unsigned BitWidth = DemandedMask.getBitWidth();
972 assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
973 "Mask size mismatches value type size!");
974 APInt NewMask = DemandedMask;
975 DebugLoc dl = Op.getDebugLoc();
976
977 // Don't know anything.
978 KnownZero = KnownOne = APInt(BitWidth, 0);
979
980 // Other users may use these bits.
981 if (!Op.getNode()->hasOneUse()) {
982 if (Depth != 0) {
983 // If not at the root, Just compute the KnownZero/KnownOne bits to
984 // simplify things downstream.
985 TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
986 return false;
987 }
988 // If this is the root being simplified, allow it to have multiple uses,
989 // just set the NewMask to all bits.
990 NewMask = APInt::getAllOnesValue(BitWidth);
991 } else if (DemandedMask == 0) {
992 // Not demanding any bits from Op.
993 if (Op.getOpcode() != ISD::UNDEF)
994 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
995 return false;
996 } else if (Depth == 6) { // Limit search depth.
997 return false;
998 }
999
1000 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
1001 switch (Op.getOpcode()) {
1002 case ISD::Constant:
1003 // We know all of the bits for a constant!
1004 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & NewMask;
1005 KnownZero = ~KnownOne & NewMask;
1006 return false; // Don't fall through, will infinitely loop.
1007 case ISD::AND:
1008 // If the RHS is a constant, check to see if the LHS would be zero without
1009 // using the bits from the RHS. Below, we use knowledge about the RHS to
1010 // simplify the LHS, here we're using information from the LHS to simplify
1011 // the RHS.
1012 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1013 APInt LHSZero, LHSOne;
1014 TLO.DAG.ComputeMaskedBits(Op.getOperand(0), NewMask,
1015 LHSZero, LHSOne, Depth+1);
1016 // If the LHS already has zeros where RHSC does, this and is dead.
1017 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
1018 return TLO.CombineTo(Op, Op.getOperand(0));
1019 // If any of the set bits in the RHS are known zero on the LHS, shrink
1020 // the constant.
1021 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
1022 return true;
1023 }
1024
1025 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
1026 KnownOne, TLO, Depth+1))
1027 return true;
1028 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1029 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
1030 KnownZero2, KnownOne2, TLO, Depth+1))
1031 return true;
1032 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1033
1034 // If all of the demanded bits are known one on one side, return the other.
1035 // These bits cannot contribute to the result of the 'and'.
1036 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
1037 return TLO.CombineTo(Op, Op.getOperand(0));
1038 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
1039 return TLO.CombineTo(Op, Op.getOperand(1));
1040 // If all of the demanded bits in the inputs are known zeros, return zero.
1041 if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
1042 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
1043 // If the RHS is a constant, see if we can simplify it.
1044 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
1045 return true;
1046 // If the operation can be done in a smaller type, do so.
1047 if (TLO.ShrinkOps && TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1048 return true;
1049
1050 // Output known-1 bits are only known if set in both the LHS & RHS.
1051 KnownOne &= KnownOne2;
1052 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1053 KnownZero |= KnownZero2;
1054 break;
1055 case ISD::OR:
1056 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
1057 KnownOne, TLO, Depth+1))
1058 return true;
1059 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1060 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
1061 KnownZero2, KnownOne2, TLO, Depth+1))
1062 return true;
1063 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1064
1065 // If all of the demanded bits are known zero on one side, return the other.
1066 // These bits cannot contribute to the result of the 'or'.
1067 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
1068 return TLO.CombineTo(Op, Op.getOperand(0));
1069 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
1070 return TLO.CombineTo(Op, Op.getOperand(1));
1071 // If all of the potentially set bits on one side are known to be set on
1072 // the other side, just use the 'other' side.
1073 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
1074 return TLO.CombineTo(Op, Op.getOperand(0));
1075 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
1076 return TLO.CombineTo(Op, Op.getOperand(1));
1077 // If the RHS is a constant, see if we can simplify it.
1078 if (TLO.ShrinkDemandedConstant(Op, NewMask))
1079 return true;
1080 // If the operation can be done in a smaller type, do so.
1081 if (TLO.ShrinkOps && TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1082 return true;
1083
1084 // Output known-0 bits are only known if clear in both the LHS & RHS.
1085 KnownZero &= KnownZero2;
1086 // Output known-1 are known to be set if set in either the LHS | RHS.
1087 KnownOne |= KnownOne2;
1088 break;
1089 case ISD::XOR:
1090 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
1091 KnownOne, TLO, Depth+1))
1092 return true;
1093 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1094 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
1095 KnownOne2, TLO, Depth+1))
1096 return true;
1097 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1098
1099 // If all of the demanded bits are known zero on one side, return the other.
1100 // These bits cannot contribute to the result of the 'xor'.
1101 if ((KnownZero & NewMask) == NewMask)
1102 return TLO.CombineTo(Op, Op.getOperand(0));
1103 if ((KnownZero2 & NewMask) == NewMask)
1104 return TLO.CombineTo(Op, Op.getOperand(1));
1105 // If the operation can be done in a smaller type, do so.
1106 if (TLO.ShrinkOps && TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1107 return true;
1108
1109 // If all of the unknown bits are known to be zero on one side or the other
1110 // (but not both) turn this into an *inclusive* or.
1111 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1112 if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
1113 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
1114 Op.getOperand(0),
1115 Op.getOperand(1)));
1116
1117 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1118 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1119 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1120 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1121
1122 // If all of the demanded bits on one side are known, and all of the set
1123 // bits on that side are also known to be set on the other side, turn this
1124 // into an AND, as we know the bits will be cleared.
1125 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1126 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known
1127 if ((KnownOne & KnownOne2) == KnownOne) {
1128 EVT VT = Op.getValueType();
1129 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT);
1130 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
1131 Op.getOperand(0), ANDC));
1132 }
1133 }
1134
1135 // If the RHS is a constant, see if we can simplify it.
1136 // for XOR, we prefer to force bits to 1 if they will make a -1.
1137 // if we can't force bits, try to shrink constant
1138 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1139 APInt Expanded = C->getAPIntValue() | (~NewMask);
1140 // if we can expand it to have all bits set, do it
1141 if (Expanded.isAllOnesValue()) {
1142 if (Expanded != C->getAPIntValue()) {
1143 EVT VT = Op.getValueType();
1144 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
1145 TLO.DAG.getConstant(Expanded, VT));
1146 return TLO.CombineTo(Op, New);
1147 }
1148 // if it already has all the bits set, nothing to change
1149 // but don't shrink either!
1150 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
1151 return true;
1152 }
1153 }
1154
1155 KnownZero = KnownZeroOut;
1156 KnownOne = KnownOneOut;
1157 break;
1158 case ISD::SELECT:
1159 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
1160 KnownOne, TLO, Depth+1))
1161 return true;
1162 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
1163 KnownOne2, TLO, Depth+1))
1164 return true;
1165 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1166 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1167
1168 // If the operands are constants, see if we can simplify them.
1169 if (TLO.ShrinkDemandedConstant(Op, NewMask))
1170 return true;
1171
1172 // Only known if known in both the LHS and RHS.
1173 KnownOne &= KnownOne2;
1174 KnownZero &= KnownZero2;
1175 break;
1176 case ISD::SELECT_CC:
1177 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
1178 KnownOne, TLO, Depth+1))
1179 return true;
1180 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
1181 KnownOne2, TLO, Depth+1))
1182 return true;
1183 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1184 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1185
1186 // If the operands are constants, see if we can simplify them.
1187 if (TLO.ShrinkDemandedConstant(Op, NewMask))
1188 return true;
1189
1190 // Only known if known in both the LHS and RHS.
1191 KnownOne &= KnownOne2;
1192 KnownZero &= KnownZero2;
1193 break;
1194 case ISD::SHL:
1195 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1196 unsigned ShAmt = SA->getZExtValue();
1197 SDValue InOp = Op.getOperand(0);
1198
1199 // If the shift count is an invalid immediate, don't do anything.
1200 if (ShAmt >= BitWidth)
1201 break;
1202
1203 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1204 // single shift. We can do this if the bottom bits (which are shifted
1205 // out) are never demanded.
1206 if (InOp.getOpcode() == ISD::SRL &&
1207 isa<ConstantSDNode>(InOp.getOperand(1))) {
1208 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
1209 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
1210 unsigned Opc = ISD::SHL;
1211 int Diff = ShAmt-C1;
1212 if (Diff < 0) {
1213 Diff = -Diff;
1214 Opc = ISD::SRL;
1215 }
1216
1217 SDValue NewSA =
1218 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
1219 EVT VT = Op.getValueType();
1220 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
1221 InOp.getOperand(0), NewSA));
1222 }
1223 }
1224
1225 if (SimplifyDemandedBits(Op.getOperand(0), NewMask.lshr(ShAmt),
1226 KnownZero, KnownOne, TLO, Depth+1))
1227 return true;
1228 KnownZero <<= SA->getZExtValue();
1229 KnownOne <<= SA->getZExtValue();
1230 // low bits known zero.
1231 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
1232 }
1233 break;
1234 case ISD::SRL:
1235 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1236 EVT VT = Op.getValueType();
1237 unsigned ShAmt = SA->getZExtValue();
1238 unsigned VTSize = VT.getSizeInBits();
1239 SDValue InOp = Op.getOperand(0);
1240
1241 // If the shift count is an invalid immediate, don't do anything.
1242 if (ShAmt >= BitWidth)
1243 break;
1244
1245 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1246 // single shift. We can do this if the top bits (which are shifted out)
1247 // are never demanded.
1248 if (InOp.getOpcode() == ISD::SHL &&
1249 isa<ConstantSDNode>(InOp.getOperand(1))) {
1250 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
1251 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
1252 unsigned Opc = ISD::SRL;
1253 int Diff = ShAmt-C1;
1254 if (Diff < 0) {
1255 Diff = -Diff;
1256 Opc = ISD::SHL;
1257 }
1258
1259 SDValue NewSA =
1260 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
1261 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
1262 InOp.getOperand(0), NewSA));
1263 }
1264 }
1265
1266 // Compute the new bits that are at the top now.
1267 if (SimplifyDemandedBits(InOp, (NewMask << ShAmt),
1268 KnownZero, KnownOne, TLO, Depth+1))
1269 return true;
1270 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1271 KnownZero = KnownZero.lshr(ShAmt);
1272 KnownOne = KnownOne.lshr(ShAmt);
1273
1274 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1275 KnownZero |= HighBits; // High bits known zero.
1276 }
1277 break;
1278 case ISD::SRA:
1279 // If this is an arithmetic shift right and only the low-bit is set, we can
1280 // always convert this into a logical shr, even if the shift amount is
1281 // variable. The low bit of the shift cannot be an input sign bit unless
1282 // the shift amount is >= the size of the datatype, which is undefined.
1283 if (DemandedMask == 1)
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001284 return TLO.CombineTo(Op,
1285 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
1286 Op.getOperand(0), Op.getOperand(1)));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001287
1288 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1289 EVT VT = Op.getValueType();
1290 unsigned ShAmt = SA->getZExtValue();
1291
1292 // If the shift count is an invalid immediate, don't do anything.
1293 if (ShAmt >= BitWidth)
1294 break;
1295
1296 APInt InDemandedMask = (NewMask << ShAmt);
1297
1298 // If any of the demanded bits are produced by the sign extension, we also
1299 // demand the input sign bit.
1300 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1301 if (HighBits.intersects(NewMask))
1302 InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
1303
1304 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
1305 KnownZero, KnownOne, TLO, Depth+1))
1306 return true;
1307 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1308 KnownZero = KnownZero.lshr(ShAmt);
1309 KnownOne = KnownOne.lshr(ShAmt);
1310
1311 // Handle the sign bit, adjusted to where it is now in the mask.
1312 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
1313
1314 // If the input sign bit is known to be zero, or if none of the top bits
1315 // are demanded, turn this into an unsigned shift right.
1316 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
1317 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
1318 Op.getOperand(0),
1319 Op.getOperand(1)));
1320 } else if (KnownOne.intersects(SignBit)) { // New bits are known one.
1321 KnownOne |= HighBits;
1322 }
1323 }
1324 break;
1325 case ISD::SIGN_EXTEND_INREG: {
1326 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1327
1328 // Sign extension. Compute the demanded bits in the result that are not
1329 // present in the input.
1330 APInt NewBits =
1331 APInt::getHighBitsSet(BitWidth,
1332 BitWidth - EVT.getScalarType().getSizeInBits()) &
1333 NewMask;
1334
1335 // If none of the extended bits are demanded, eliminate the sextinreg.
1336 if (NewBits == 0)
1337 return TLO.CombineTo(Op, Op.getOperand(0));
1338
1339 APInt InSignBit = APInt::getSignBit(EVT.getScalarType().getSizeInBits());
1340 InSignBit.zext(BitWidth);
1341 APInt InputDemandedBits =
1342 APInt::getLowBitsSet(BitWidth,
1343 EVT.getScalarType().getSizeInBits()) &
1344 NewMask;
1345
1346 // Since the sign extended bits are demanded, we know that the sign
1347 // bit is demanded.
1348 InputDemandedBits |= InSignBit;
1349
1350 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
1351 KnownZero, KnownOne, TLO, Depth+1))
1352 return true;
1353 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1354
1355 // If the sign bit of the input is known set or clear, then we know the
1356 // top bits of the result.
1357
1358 // If the input sign bit is known zero, convert this into a zero extension.
1359 if (KnownZero.intersects(InSignBit))
1360 return TLO.CombineTo(Op,
1361 TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,EVT));
1362
1363 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1364 KnownOne |= NewBits;
1365 KnownZero &= ~NewBits;
1366 } else { // Input sign bit unknown
1367 KnownZero &= ~NewBits;
1368 KnownOne &= ~NewBits;
1369 }
1370 break;
1371 }
1372 case ISD::ZERO_EXTEND: {
1373 unsigned OperandBitWidth =
1374 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1375 APInt InMask = NewMask;
1376 InMask.trunc(OperandBitWidth);
1377
1378 // If none of the top bits are demanded, convert this into an any_extend.
1379 APInt NewBits =
1380 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
1381 if (!NewBits.intersects(NewMask))
1382 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1383 Op.getValueType(),
1384 Op.getOperand(0)));
1385
1386 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1387 KnownZero, KnownOne, TLO, Depth+1))
1388 return true;
1389 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1390 KnownZero.zext(BitWidth);
1391 KnownOne.zext(BitWidth);
1392 KnownZero |= NewBits;
1393 break;
1394 }
1395 case ISD::SIGN_EXTEND: {
1396 EVT InVT = Op.getOperand(0).getValueType();
1397 unsigned InBits = InVT.getScalarType().getSizeInBits();
1398 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits);
1399 APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
1400 APInt NewBits = ~InMask & NewMask;
1401
1402 // If none of the top bits are demanded, convert this into an any_extend.
1403 if (NewBits == 0)
1404 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1405 Op.getValueType(),
1406 Op.getOperand(0)));
1407
1408 // Since some of the sign extended bits are demanded, we know that the sign
1409 // bit is demanded.
1410 APInt InDemandedBits = InMask & NewMask;
1411 InDemandedBits |= InSignBit;
1412 InDemandedBits.trunc(InBits);
1413
1414 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1415 KnownOne, TLO, Depth+1))
1416 return true;
1417 KnownZero.zext(BitWidth);
1418 KnownOne.zext(BitWidth);
1419
1420 // If the sign bit is known zero, convert this to a zero extend.
1421 if (KnownZero.intersects(InSignBit))
1422 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
1423 Op.getValueType(),
1424 Op.getOperand(0)));
1425
1426 // If the sign bit is known one, the top bits match.
1427 if (KnownOne.intersects(InSignBit)) {
1428 KnownOne |= NewBits;
1429 KnownZero &= ~NewBits;
1430 } else { // Otherwise, top bits aren't known.
1431 KnownOne &= ~NewBits;
1432 KnownZero &= ~NewBits;
1433 }
1434 break;
1435 }
1436 case ISD::ANY_EXTEND: {
1437 unsigned OperandBitWidth =
1438 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1439 APInt InMask = NewMask;
1440 InMask.trunc(OperandBitWidth);
1441 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1442 KnownZero, KnownOne, TLO, Depth+1))
1443 return true;
1444 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1445 KnownZero.zext(BitWidth);
1446 KnownOne.zext(BitWidth);
1447 break;
1448 }
1449 case ISD::TRUNCATE: {
1450 // Simplify the input, using demanded bit information, and compute the known
1451 // zero/one bits live out.
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001452 unsigned OperandBitWidth =
1453 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001454 APInt TruncMask = NewMask;
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001455 TruncMask.zext(OperandBitWidth);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001456 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
1457 KnownZero, KnownOne, TLO, Depth+1))
1458 return true;
1459 KnownZero.trunc(BitWidth);
1460 KnownOne.trunc(BitWidth);
1461
1462 // If the input is only used by this truncate, see if we can shrink it based
1463 // on the known demanded bits.
1464 if (Op.getOperand(0).getNode()->hasOneUse()) {
1465 SDValue In = Op.getOperand(0);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001466 switch (In.getOpcode()) {
1467 default: break;
1468 case ISD::SRL:
1469 // Shrink SRL by a constant if none of the high bits shifted in are
1470 // demanded.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001471 if (TLO.LegalTypes() &&
1472 !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1473 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1474 // undesirable.
1475 break;
1476 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1477 if (!ShAmt)
1478 break;
1479 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1480 OperandBitWidth - BitWidth);
1481 HighBits = HighBits.lshr(ShAmt->getZExtValue());
1482 HighBits.trunc(BitWidth);
1483
1484 if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
1485 // None of the shifted in bits are needed. Add a truncate of the
1486 // shift input, then shift it.
1487 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
1488 Op.getValueType(),
1489 In.getOperand(0));
1490 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1491 Op.getValueType(),
1492 NewTrunc,
1493 In.getOperand(1)));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001494 }
1495 break;
1496 }
1497 }
1498
1499 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1500 break;
1501 }
1502 case ISD::AssertZext: {
1503 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1504 APInt InMask = APInt::getLowBitsSet(BitWidth,
1505 VT.getSizeInBits());
1506 if (SimplifyDemandedBits(Op.getOperand(0), InMask & NewMask,
1507 KnownZero, KnownOne, TLO, Depth+1))
1508 return true;
1509 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1510 KnownZero |= ~InMask & NewMask;
1511 break;
1512 }
1513 case ISD::BIT_CONVERT:
1514#if 0
1515 // If this is an FP->Int bitcast and if the sign bit is the only thing that
1516 // is demanded, turn this into a FGETSIGN.
1517 if (NewMask == EVT::getIntegerVTSignBit(Op.getValueType()) &&
1518 MVT::isFloatingPoint(Op.getOperand(0).getValueType()) &&
1519 !MVT::isVector(Op.getOperand(0).getValueType())) {
1520 // Only do this xform if FGETSIGN is valid or if before legalize.
1521 if (!TLO.AfterLegalize ||
1522 isOperationLegal(ISD::FGETSIGN, Op.getValueType())) {
1523 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1524 // place. We expect the SHL to be eliminated by other optimizations.
1525 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, Op.getValueType(),
1526 Op.getOperand(0));
1527 unsigned ShVal = Op.getValueType().getSizeInBits()-1;
1528 SDValue ShAmt = TLO.DAG.getConstant(ShVal, getShiftAmountTy());
1529 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, Op.getValueType(),
1530 Sign, ShAmt));
1531 }
1532 }
1533#endif
1534 break;
1535 case ISD::ADD:
1536 case ISD::MUL:
1537 case ISD::SUB: {
1538 // Add, Sub, and Mul don't demand any bits in positions beyond that
1539 // of the highest bit demanded of them.
1540 APInt LoMask = APInt::getLowBitsSet(BitWidth,
1541 BitWidth - NewMask.countLeadingZeros());
1542 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1543 KnownOne2, TLO, Depth+1))
1544 return true;
1545 if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1546 KnownOne2, TLO, Depth+1))
1547 return true;
1548 // See if the operation should be performed at a smaller bit width.
1549 if (TLO.ShrinkOps && TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1550 return true;
1551 }
1552 // FALL THROUGH
1553 default:
1554 // Just use ComputeMaskedBits to compute output bits.
1555 TLO.DAG.ComputeMaskedBits(Op, NewMask, KnownZero, KnownOne, Depth);
1556 break;
1557 }
1558
1559 // If we know the value of all of the demanded bits, return this as a
1560 // constant.
1561 if ((NewMask & (KnownZero|KnownOne)) == NewMask)
1562 return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
1563
1564 return false;
1565}
1566
1567/// computeMaskedBitsForTargetNode - Determine which of the bits specified
1568/// in Mask are known to be either zero or one and return them in the
1569/// KnownZero/KnownOne bitsets.
1570void TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1571 const APInt &Mask,
1572 APInt &KnownZero,
1573 APInt &KnownOne,
1574 const SelectionDAG &DAG,
1575 unsigned Depth) const {
1576 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1577 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1578 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1579 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1580 "Should use MaskedValueIsZero if you don't know whether Op"
1581 " is a target node!");
1582 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1583}
1584
1585/// ComputeNumSignBitsForTargetNode - This method can be implemented by
1586/// targets that want to expose additional information about sign bits to the
1587/// DAG Combiner.
1588unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1589 unsigned Depth) const {
1590 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1591 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1592 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1593 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1594 "Should use ComputeNumSignBits if you don't know whether Op"
1595 " is a target node!");
1596 return 1;
1597}
1598
1599/// ValueHasExactlyOneBitSet - Test if the given value is known to have exactly
1600/// one bit set. This differs from ComputeMaskedBits in that it doesn't need to
1601/// determine which bit is set.
1602///
1603static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
1604 // A left-shift of a constant one will have exactly one bit set, because
1605 // shifting the bit off the end is undefined.
1606 if (Val.getOpcode() == ISD::SHL)
1607 if (ConstantSDNode *C =
1608 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1609 if (C->getAPIntValue() == 1)
1610 return true;
1611
1612 // Similarly, a right-shift of a constant sign-bit will have exactly
1613 // one bit set.
1614 if (Val.getOpcode() == ISD::SRL)
1615 if (ConstantSDNode *C =
1616 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1617 if (C->getAPIntValue().isSignBit())
1618 return true;
1619
1620 // More could be done here, though the above checks are enough
1621 // to handle some common cases.
1622
1623 // Fall back to ComputeMaskedBits to catch other known cases.
1624 EVT OpVT = Val.getValueType();
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001625 unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001626 APInt Mask = APInt::getAllOnesValue(BitWidth);
1627 APInt KnownZero, KnownOne;
1628 DAG.ComputeMaskedBits(Val, Mask, KnownZero, KnownOne);
1629 return (KnownZero.countPopulation() == BitWidth - 1) &&
1630 (KnownOne.countPopulation() == 1);
1631}
1632
1633/// SimplifySetCC - Try to simplify a setcc built with the specified operands
1634/// and cc. If it is unable to simplify it, return a null SDValue.
1635SDValue
1636TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1637 ISD::CondCode Cond, bool foldBooleans,
1638 DAGCombinerInfo &DCI, DebugLoc dl) const {
1639 SelectionDAG &DAG = DCI.DAG;
1640 LLVMContext &Context = *DAG.getContext();
1641
1642 // These setcc operations always fold.
1643 switch (Cond) {
1644 default: break;
1645 case ISD::SETFALSE:
1646 case ISD::SETFALSE2: return DAG.getConstant(0, VT);
1647 case ISD::SETTRUE:
1648 case ISD::SETTRUE2: return DAG.getConstant(1, VT);
1649 }
1650
1651 if (isa<ConstantSDNode>(N0.getNode())) {
1652 // Ensure that the constant occurs on the RHS, and fold constant
1653 // comparisons.
1654 return DAG.getSetCC(dl, VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
1655 }
1656
1657 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1658 const APInt &C1 = N1C->getAPIntValue();
1659
1660 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1661 // equality comparison, then we're just comparing whether X itself is
1662 // zero.
1663 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1664 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1665 N0.getOperand(1).getOpcode() == ISD::Constant) {
1666 const APInt &ShAmt
1667 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1668 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1669 ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1670 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1671 // (srl (ctlz x), 5) == 0 -> X != 0
1672 // (srl (ctlz x), 5) != 1 -> X != 0
1673 Cond = ISD::SETNE;
1674 } else {
1675 // (srl (ctlz x), 5) != 0 -> X == 0
1676 // (srl (ctlz x), 5) == 1 -> X == 0
1677 Cond = ISD::SETEQ;
1678 }
1679 SDValue Zero = DAG.getConstant(0, N0.getValueType());
1680 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1681 Zero, Cond);
1682 }
1683 }
1684
1685 // If the LHS is '(and load, const)', the RHS is 0,
1686 // the test is for equality or unsigned, and all 1 bits of the const are
1687 // in the same partial word, see if we can shorten the load.
1688 if (DCI.isBeforeLegalize() &&
1689 N0.getOpcode() == ISD::AND && C1 == 0 &&
1690 N0.getNode()->hasOneUse() &&
1691 isa<LoadSDNode>(N0.getOperand(0)) &&
1692 N0.getOperand(0).getNode()->hasOneUse() &&
1693 isa<ConstantSDNode>(N0.getOperand(1))) {
1694 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
1695 APInt bestMask;
1696 unsigned bestWidth = 0, bestOffset = 0;
1697 if (!Lod->isVolatile() && Lod->isUnindexed()) {
1698 unsigned origWidth = N0.getValueType().getSizeInBits();
1699 unsigned maskWidth = origWidth;
1700 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
1701 // 8 bits, but have to be careful...
1702 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1703 origWidth = Lod->getMemoryVT().getSizeInBits();
1704 const APInt &Mask =
1705 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1706 for (unsigned width = origWidth / 2; width>=8; width /= 2) {
1707 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
1708 for (unsigned offset=0; offset<origWidth/width; offset++) {
1709 if ((newMask & Mask) == Mask) {
1710 if (!TD->isLittleEndian())
1711 bestOffset = (origWidth/width - offset - 1) * (width/8);
1712 else
1713 bestOffset = (uint64_t)offset * (width/8);
1714 bestMask = Mask.lshr(offset * (width/8) * 8);
1715 bestWidth = width;
1716 break;
1717 }
1718 newMask = newMask << width;
1719 }
1720 }
1721 }
1722 if (bestWidth) {
1723 EVT newVT = EVT::getIntegerVT(Context, bestWidth);
1724 if (newVT.isRound()) {
1725 EVT PtrType = Lod->getOperand(1).getValueType();
1726 SDValue Ptr = Lod->getBasePtr();
1727 if (bestOffset != 0)
1728 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
1729 DAG.getConstant(bestOffset, PtrType));
1730 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1731 SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
1732 Lod->getSrcValue(),
1733 Lod->getSrcValueOffset() + bestOffset,
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001734 false, false, NewAlign);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001735 return DAG.getSetCC(dl, VT,
1736 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
1737 DAG.getConstant(bestMask.trunc(bestWidth),
1738 newVT)),
1739 DAG.getConstant(0LL, newVT), Cond);
1740 }
1741 }
1742 }
1743
1744 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1745 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1746 unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
1747
1748 // If the comparison constant has bits in the upper part, the
1749 // zero-extended value could never match.
1750 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1751 C1.getBitWidth() - InSize))) {
1752 switch (Cond) {
1753 case ISD::SETUGT:
1754 case ISD::SETUGE:
1755 case ISD::SETEQ: return DAG.getConstant(0, VT);
1756 case ISD::SETULT:
1757 case ISD::SETULE:
1758 case ISD::SETNE: return DAG.getConstant(1, VT);
1759 case ISD::SETGT:
1760 case ISD::SETGE:
1761 // True if the sign bit of C1 is set.
1762 return DAG.getConstant(C1.isNegative(), VT);
1763 case ISD::SETLT:
1764 case ISD::SETLE:
1765 // True if the sign bit of C1 isn't set.
1766 return DAG.getConstant(C1.isNonNegative(), VT);
1767 default:
1768 break;
1769 }
1770 }
1771
1772 // Otherwise, we can perform the comparison with the low bits.
1773 switch (Cond) {
1774 case ISD::SETEQ:
1775 case ISD::SETNE:
1776 case ISD::SETUGT:
1777 case ISD::SETUGE:
1778 case ISD::SETULT:
1779 case ISD::SETULE: {
1780 EVT newVT = N0.getOperand(0).getValueType();
1781 if (DCI.isBeforeLegalizeOps() ||
1782 (isOperationLegal(ISD::SETCC, newVT) &&
1783 getCondCodeAction(Cond, newVT)==Legal))
1784 return DAG.getSetCC(dl, VT, N0.getOperand(0),
1785 DAG.getConstant(APInt(C1).trunc(InSize), newVT),
1786 Cond);
1787 break;
1788 }
1789 default:
1790 break; // todo, be more careful with signed comparisons
1791 }
1792 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001793 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001794 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1795 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
1796 EVT ExtDstTy = N0.getValueType();
1797 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1798
1799 // If the extended part has any inconsistent bits, it cannot ever
1800 // compare equal. In other words, they have to be all ones or all
1801 // zeros.
1802 APInt ExtBits =
1803 APInt::getHighBitsSet(ExtDstTyBits, ExtDstTyBits - ExtSrcTyBits);
1804 if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
1805 return DAG.getConstant(Cond == ISD::SETNE, VT);
1806
1807 SDValue ZextOp;
1808 EVT Op0Ty = N0.getOperand(0).getValueType();
1809 if (Op0Ty == ExtSrcTy) {
1810 ZextOp = N0.getOperand(0);
1811 } else {
1812 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1813 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
1814 DAG.getConstant(Imm, Op0Ty));
1815 }
1816 if (!DCI.isCalledByLegalizer())
1817 DCI.AddToWorklist(ZextOp.getNode());
1818 // Otherwise, make this a use of a zext.
1819 return DAG.getSetCC(dl, VT, ZextOp,
1820 DAG.getConstant(C1 & APInt::getLowBitsSet(
1821 ExtDstTyBits,
1822 ExtSrcTyBits),
1823 ExtDstTy),
1824 Cond);
1825 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1826 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001827 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001828 if (N0.getOpcode() == ISD::SETCC &&
1829 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001830 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
1831 if (TrueWhenTrue)
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001832 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001833 // Invert the condition.
1834 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1835 CC = ISD::getSetCCInverse(CC,
1836 N0.getOperand(0).getValueType().isInteger());
1837 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
1838 }
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001839
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001840 if ((N0.getOpcode() == ISD::XOR ||
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001841 (N0.getOpcode() == ISD::AND &&
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001842 N0.getOperand(0).getOpcode() == ISD::XOR &&
1843 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1844 isa<ConstantSDNode>(N0.getOperand(1)) &&
1845 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1846 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1847 // can only do this if the top bits are known zero.
1848 unsigned BitWidth = N0.getValueSizeInBits();
1849 if (DAG.MaskedValueIsZero(N0,
1850 APInt::getHighBitsSet(BitWidth,
1851 BitWidth-1))) {
1852 // Okay, get the un-inverted input value.
1853 SDValue Val;
1854 if (N0.getOpcode() == ISD::XOR)
1855 Val = N0.getOperand(0);
1856 else {
1857 assert(N0.getOpcode() == ISD::AND &&
1858 N0.getOperand(0).getOpcode() == ISD::XOR);
1859 // ((X^1)&1)^1 -> X & 1
1860 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1861 N0.getOperand(0).getOperand(0),
1862 N0.getOperand(1));
1863 }
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001864
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001865 return DAG.getSetCC(dl, VT, Val, N1,
1866 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1867 }
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001868 } else if (N1C->getAPIntValue() == 1 &&
1869 (VT == MVT::i1 ||
1870 getBooleanContents() == ZeroOrOneBooleanContent)) {
1871 SDValue Op0 = N0;
1872 if (Op0.getOpcode() == ISD::TRUNCATE)
1873 Op0 = Op0.getOperand(0);
1874
1875 if ((Op0.getOpcode() == ISD::XOR) &&
1876 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1877 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1878 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1879 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1880 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1881 Cond);
1882 } else if (Op0.getOpcode() == ISD::AND &&
1883 isa<ConstantSDNode>(Op0.getOperand(1)) &&
1884 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
1885 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
1886 if (Op0.getValueType() != VT)
1887 Op0 = DAG.getNode(ISD::AND, dl, VT,
1888 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
1889 DAG.getConstant(1, VT));
1890 return DAG.getSetCC(dl, VT, Op0,
1891 DAG.getConstant(0, Op0.getValueType()),
1892 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1893 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001894 }
1895 }
1896
1897 APInt MinVal, MaxVal;
1898 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1899 if (ISD::isSignedIntSetCC(Cond)) {
1900 MinVal = APInt::getSignedMinValue(OperandBitSize);
1901 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1902 } else {
1903 MinVal = APInt::getMinValue(OperandBitSize);
1904 MaxVal = APInt::getMaxValue(OperandBitSize);
1905 }
1906
1907 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1908 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1909 if (C1 == MinVal) return DAG.getConstant(1, VT); // X >= MIN --> true
1910 // X >= C0 --> X > (C0-1)
1911 return DAG.getSetCC(dl, VT, N0,
1912 DAG.getConstant(C1-1, N1.getValueType()),
1913 (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
1914 }
1915
1916 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1917 if (C1 == MaxVal) return DAG.getConstant(1, VT); // X <= MAX --> true
1918 // X <= C0 --> X < (C0+1)
1919 return DAG.getSetCC(dl, VT, N0,
1920 DAG.getConstant(C1+1, N1.getValueType()),
1921 (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
1922 }
1923
1924 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1925 return DAG.getConstant(0, VT); // X < MIN --> false
1926 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1927 return DAG.getConstant(1, VT); // X >= MIN --> true
1928 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1929 return DAG.getConstant(0, VT); // X > MAX --> false
1930 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1931 return DAG.getConstant(1, VT); // X <= MAX --> true
1932
1933 // Canonicalize setgt X, Min --> setne X, Min
1934 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1935 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1936 // Canonicalize setlt X, Max --> setne X, Max
1937 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1938 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1939
1940 // If we have setult X, 1, turn it into seteq X, 0
1941 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1942 return DAG.getSetCC(dl, VT, N0,
1943 DAG.getConstant(MinVal, N0.getValueType()),
1944 ISD::SETEQ);
1945 // If we have setugt X, Max-1, turn it into seteq X, Max
1946 else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1947 return DAG.getSetCC(dl, VT, N0,
1948 DAG.getConstant(MaxVal, N0.getValueType()),
1949 ISD::SETEQ);
1950
1951 // If we have "setcc X, C0", check to see if we can shrink the immediate
1952 // by changing cc.
1953
1954 // SETUGT X, SINTMAX -> SETLT X, 0
1955 if (Cond == ISD::SETUGT &&
1956 C1 == APInt::getSignedMaxValue(OperandBitSize))
1957 return DAG.getSetCC(dl, VT, N0,
1958 DAG.getConstant(0, N1.getValueType()),
1959 ISD::SETLT);
1960
1961 // SETULT X, SINTMIN -> SETGT X, -1
1962 if (Cond == ISD::SETULT &&
1963 C1 == APInt::getSignedMinValue(OperandBitSize)) {
1964 SDValue ConstMinusOne =
1965 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize),
1966 N1.getValueType());
1967 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1968 }
1969
1970 // Fold bit comparisons when we can.
1971 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1972 (VT == N0.getValueType() ||
1973 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
1974 N0.getOpcode() == ISD::AND)
1975 if (ConstantSDNode *AndRHS =
1976 dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1977 EVT ShiftTy = DCI.isBeforeLegalize() ?
1978 getPointerTy() : getShiftAmountTy();
1979 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
1980 // Perform the xform if the AND RHS is a single bit.
1981 if (AndRHS->getAPIntValue().isPowerOf2()) {
1982 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1983 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1984 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), ShiftTy)));
1985 }
1986 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
1987 // (X & 8) == 8 --> (X & 8) >> 3
1988 // Perform the xform if C1 is a single bit.
1989 if (C1.isPowerOf2()) {
1990 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1991 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1992 DAG.getConstant(C1.logBase2(), ShiftTy)));
1993 }
1994 }
1995 }
1996 }
1997
1998 if (isa<ConstantFPSDNode>(N0.getNode())) {
1999 // Constant fold or commute setcc.
2000 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
2001 if (O.getNode()) return O;
2002 } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
2003 // If the RHS of an FP comparison is a constant, simplify it away in
2004 // some cases.
2005 if (CFP->getValueAPF().isNaN()) {
2006 // If an operand is known to be a nan, we can fold it.
2007 switch (ISD::getUnorderedFlavor(Cond)) {
2008 default: llvm_unreachable("Unknown flavor!");
2009 case 0: // Known false.
2010 return DAG.getConstant(0, VT);
2011 case 1: // Known true.
2012 return DAG.getConstant(1, VT);
2013 case 2: // Undefined.
2014 return DAG.getUNDEF(VT);
2015 }
2016 }
2017
2018 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
2019 // constant if knowing that the operand is non-nan is enough. We prefer to
2020 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
2021 // materialize 0.0.
2022 if (Cond == ISD::SETO || Cond == ISD::SETUO)
2023 return DAG.getSetCC(dl, VT, N0, N0, Cond);
2024
2025 // If the condition is not legal, see if we can find an equivalent one
2026 // which is legal.
2027 if (!isCondCodeLegal(Cond, N0.getValueType())) {
2028 // If the comparison was an awkward floating-point == or != and one of
2029 // the comparison operands is infinity or negative infinity, convert the
2030 // condition to a less-awkward <= or >=.
2031 if (CFP->getValueAPF().isInfinity()) {
2032 if (CFP->getValueAPF().isNegative()) {
2033 if (Cond == ISD::SETOEQ &&
2034 isCondCodeLegal(ISD::SETOLE, N0.getValueType()))
2035 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
2036 if (Cond == ISD::SETUEQ &&
2037 isCondCodeLegal(ISD::SETOLE, N0.getValueType()))
2038 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
2039 if (Cond == ISD::SETUNE &&
2040 isCondCodeLegal(ISD::SETUGT, N0.getValueType()))
2041 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
2042 if (Cond == ISD::SETONE &&
2043 isCondCodeLegal(ISD::SETUGT, N0.getValueType()))
2044 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
2045 } else {
2046 if (Cond == ISD::SETOEQ &&
2047 isCondCodeLegal(ISD::SETOGE, N0.getValueType()))
2048 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
2049 if (Cond == ISD::SETUEQ &&
2050 isCondCodeLegal(ISD::SETOGE, N0.getValueType()))
2051 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
2052 if (Cond == ISD::SETUNE &&
2053 isCondCodeLegal(ISD::SETULT, N0.getValueType()))
2054 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
2055 if (Cond == ISD::SETONE &&
2056 isCondCodeLegal(ISD::SETULT, N0.getValueType()))
2057 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
2058 }
2059 }
2060 }
2061 }
2062
2063 if (N0 == N1) {
2064 // We can always fold X == X for integer setcc's.
2065 if (N0.getValueType().isInteger())
2066 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
2067 unsigned UOF = ISD::getUnorderedFlavor(Cond);
2068 if (UOF == 2) // FP operators that are undefined on NaNs.
2069 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
2070 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
2071 return DAG.getConstant(UOF, VT);
2072 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
2073 // if it is not already.
2074 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
2075 if (NewCond != Cond)
2076 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
2077 }
2078
2079 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2080 N0.getValueType().isInteger()) {
2081 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2082 N0.getOpcode() == ISD::XOR) {
2083 // Simplify (X+Y) == (X+Z) --> Y == Z
2084 if (N0.getOpcode() == N1.getOpcode()) {
2085 if (N0.getOperand(0) == N1.getOperand(0))
2086 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
2087 if (N0.getOperand(1) == N1.getOperand(1))
2088 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
2089 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2090 // If X op Y == Y op X, try other combinations.
2091 if (N0.getOperand(0) == N1.getOperand(1))
2092 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
2093 Cond);
2094 if (N0.getOperand(1) == N1.getOperand(0))
2095 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
2096 Cond);
2097 }
2098 }
2099
2100 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2101 if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2102 // Turn (X+C1) == C2 --> X == C2-C1
2103 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
2104 return DAG.getSetCC(dl, VT, N0.getOperand(0),
2105 DAG.getConstant(RHSC->getAPIntValue()-
2106 LHSR->getAPIntValue(),
2107 N0.getValueType()), Cond);
2108 }
2109
2110 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
2111 if (N0.getOpcode() == ISD::XOR)
2112 // If we know that all of the inverted bits are zero, don't bother
2113 // performing the inversion.
2114 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2115 return
2116 DAG.getSetCC(dl, VT, N0.getOperand(0),
2117 DAG.getConstant(LHSR->getAPIntValue() ^
2118 RHSC->getAPIntValue(),
2119 N0.getValueType()),
2120 Cond);
2121 }
2122
2123 // Turn (C1-X) == C2 --> X == C1-C2
2124 if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
2125 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
2126 return
2127 DAG.getSetCC(dl, VT, N0.getOperand(1),
2128 DAG.getConstant(SUBC->getAPIntValue() -
2129 RHSC->getAPIntValue(),
2130 N0.getValueType()),
2131 Cond);
2132 }
2133 }
2134 }
2135
2136 // Simplify (X+Z) == X --> Z == 0
2137 if (N0.getOperand(0) == N1)
2138 return DAG.getSetCC(dl, VT, N0.getOperand(1),
2139 DAG.getConstant(0, N0.getValueType()), Cond);
2140 if (N0.getOperand(1) == N1) {
2141 if (DAG.isCommutativeBinOp(N0.getOpcode()))
2142 return DAG.getSetCC(dl, VT, N0.getOperand(0),
2143 DAG.getConstant(0, N0.getValueType()), Cond);
2144 else if (N0.getNode()->hasOneUse()) {
2145 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2146 // (Z-X) == X --> Z == X<<1
2147 SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(),
2148 N1,
2149 DAG.getConstant(1, getShiftAmountTy()));
2150 if (!DCI.isCalledByLegalizer())
2151 DCI.AddToWorklist(SH.getNode());
2152 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2153 }
2154 }
2155 }
2156
2157 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2158 N1.getOpcode() == ISD::XOR) {
2159 // Simplify X == (X+Z) --> Z == 0
2160 if (N1.getOperand(0) == N0) {
2161 return DAG.getSetCC(dl, VT, N1.getOperand(1),
2162 DAG.getConstant(0, N1.getValueType()), Cond);
2163 } else if (N1.getOperand(1) == N0) {
2164 if (DAG.isCommutativeBinOp(N1.getOpcode())) {
2165 return DAG.getSetCC(dl, VT, N1.getOperand(0),
2166 DAG.getConstant(0, N1.getValueType()), Cond);
2167 } else if (N1.getNode()->hasOneUse()) {
2168 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2169 // X == (Z-X) --> X<<1 == Z
2170 SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N0,
2171 DAG.getConstant(1, getShiftAmountTy()));
2172 if (!DCI.isCalledByLegalizer())
2173 DCI.AddToWorklist(SH.getNode());
2174 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
2175 }
2176 }
2177 }
2178
2179 // Simplify x&y == y to x&y != 0 if y has exactly one bit set.
2180 // Note that where y is variable and is known to have at most
2181 // one bit set (for example, if it is z&1) we cannot do this;
2182 // the expressions are not equivalent when y==0.
2183 if (N0.getOpcode() == ISD::AND)
2184 if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) {
2185 if (ValueHasExactlyOneBitSet(N1, DAG)) {
2186 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2187 SDValue Zero = DAG.getConstant(0, N1.getValueType());
2188 return DAG.getSetCC(dl, VT, N0, Zero, Cond);
2189 }
2190 }
2191 if (N1.getOpcode() == ISD::AND)
2192 if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) {
2193 if (ValueHasExactlyOneBitSet(N0, DAG)) {
2194 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2195 SDValue Zero = DAG.getConstant(0, N0.getValueType());
2196 return DAG.getSetCC(dl, VT, N1, Zero, Cond);
2197 }
2198 }
2199 }
2200
2201 // Fold away ALL boolean setcc's.
2202 SDValue Temp;
2203 if (N0.getValueType() == MVT::i1 && foldBooleans) {
2204 switch (Cond) {
2205 default: llvm_unreachable("Unknown integer setcc!");
2206 case ISD::SETEQ: // X == Y -> ~(X^Y)
2207 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2208 N0 = DAG.getNOT(dl, Temp, MVT::i1);
2209 if (!DCI.isCalledByLegalizer())
2210 DCI.AddToWorklist(Temp.getNode());
2211 break;
2212 case ISD::SETNE: // X != Y --> (X^Y)
2213 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2214 break;
2215 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
2216 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
2217 Temp = DAG.getNOT(dl, N0, MVT::i1);
2218 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
2219 if (!DCI.isCalledByLegalizer())
2220 DCI.AddToWorklist(Temp.getNode());
2221 break;
2222 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
2223 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
2224 Temp = DAG.getNOT(dl, N1, MVT::i1);
2225 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
2226 if (!DCI.isCalledByLegalizer())
2227 DCI.AddToWorklist(Temp.getNode());
2228 break;
2229 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
2230 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
2231 Temp = DAG.getNOT(dl, N0, MVT::i1);
2232 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
2233 if (!DCI.isCalledByLegalizer())
2234 DCI.AddToWorklist(Temp.getNode());
2235 break;
2236 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
2237 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
2238 Temp = DAG.getNOT(dl, N1, MVT::i1);
2239 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
2240 break;
2241 }
2242 if (VT != MVT::i1) {
2243 if (!DCI.isCalledByLegalizer())
2244 DCI.AddToWorklist(N0.getNode());
2245 // FIXME: If running after legalize, we probably can't do this.
2246 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
2247 }
2248 return N0;
2249 }
2250
2251 // Could not fold it.
2252 return SDValue();
2253}
2254
2255/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
2256/// node is a GlobalAddress + offset.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07002257bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue* &GA,
Shih-wei Liaoe264f622010-02-10 11:10:31 -08002258 int64_t &Offset) const {
2259 if (isa<GlobalAddressSDNode>(N)) {
2260 GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N);
2261 GA = GASD->getGlobal();
2262 Offset += GASD->getOffset();
2263 return true;
2264 }
2265
2266 if (N->getOpcode() == ISD::ADD) {
2267 SDValue N1 = N->getOperand(0);
2268 SDValue N2 = N->getOperand(1);
2269 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
2270 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
2271 if (V) {
2272 Offset += V->getSExtValue();
2273 return true;
2274 }
2275 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
2276 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
2277 if (V) {
2278 Offset += V->getSExtValue();
2279 return true;
2280 }
2281 }
2282 }
2283 return false;
2284}
2285
2286
2287SDValue TargetLowering::
2288PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
2289 // Default implementation: no optimization.
2290 return SDValue();
2291}
2292
2293//===----------------------------------------------------------------------===//
2294// Inline Assembler Implementation Methods
2295//===----------------------------------------------------------------------===//
2296
2297
2298TargetLowering::ConstraintType
2299TargetLowering::getConstraintType(const std::string &Constraint) const {
2300 // FIXME: lots more standard ones to handle.
2301 if (Constraint.size() == 1) {
2302 switch (Constraint[0]) {
2303 default: break;
2304 case 'r': return C_RegisterClass;
2305 case 'm': // memory
2306 case 'o': // offsetable
2307 case 'V': // not offsetable
2308 return C_Memory;
2309 case 'i': // Simple Integer or Relocatable Constant
2310 case 'n': // Simple Integer
2311 case 's': // Relocatable Constant
2312 case 'X': // Allow ANY value.
2313 case 'I': // Target registers.
2314 case 'J':
2315 case 'K':
2316 case 'L':
2317 case 'M':
2318 case 'N':
2319 case 'O':
2320 case 'P':
2321 return C_Other;
2322 }
2323 }
2324
2325 if (Constraint.size() > 1 && Constraint[0] == '{' &&
2326 Constraint[Constraint.size()-1] == '}')
2327 return C_Register;
2328 return C_Unknown;
2329}
2330
2331/// LowerXConstraint - try to replace an X constraint, which matches anything,
2332/// with another that has more specific requirements based on the type of the
2333/// corresponding operand.
2334const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
2335 if (ConstraintVT.isInteger())
2336 return "r";
2337 if (ConstraintVT.isFloatingPoint())
2338 return "f"; // works for many targets
2339 return 0;
2340}
2341
2342/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2343/// vector. If it is invalid, don't add anything to Ops.
2344void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2345 char ConstraintLetter,
2346 bool hasMemory,
2347 std::vector<SDValue> &Ops,
2348 SelectionDAG &DAG) const {
2349 switch (ConstraintLetter) {
2350 default: break;
2351 case 'X': // Allows any operand; labels (basic block) use this.
2352 if (Op.getOpcode() == ISD::BasicBlock) {
2353 Ops.push_back(Op);
2354 return;
2355 }
2356 // fall through
2357 case 'i': // Simple Integer or Relocatable Constant
2358 case 'n': // Simple Integer
2359 case 's': { // Relocatable Constant
2360 // These operands are interested in values of the form (GV+C), where C may
2361 // be folded in as an offset of GV, or it may be explicitly added. Also, it
2362 // is possible and fine if either GV or C are missing.
2363 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2364 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2365
2366 // If we have "(add GV, C)", pull out GV/C
2367 if (Op.getOpcode() == ISD::ADD) {
2368 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2369 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2370 if (C == 0 || GA == 0) {
2371 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2372 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2373 }
2374 if (C == 0 || GA == 0)
2375 C = 0, GA = 0;
2376 }
2377
2378 // If we find a valid operand, map to the TargetXXX version so that the
2379 // value itself doesn't get selected.
2380 if (GA) { // Either &GV or &GV+C
2381 if (ConstraintLetter != 'n') {
2382 int64_t Offs = GA->getOffset();
2383 if (C) Offs += C->getZExtValue();
2384 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2385 Op.getValueType(), Offs));
2386 return;
2387 }
2388 }
2389 if (C) { // just C, no GV.
2390 // Simple constants are not allowed for 's'.
2391 if (ConstraintLetter != 's') {
2392 // gcc prints these as sign extended. Sign extend value to 64 bits
2393 // now; without this it would get ZExt'd later in
2394 // ScheduleDAGSDNodes::EmitNode, which is very generic.
2395 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
2396 MVT::i64));
2397 return;
2398 }
2399 }
2400 break;
2401 }
2402 }
2403}
2404
2405std::vector<unsigned> TargetLowering::
2406getRegClassForInlineAsmConstraint(const std::string &Constraint,
2407 EVT VT) const {
2408 return std::vector<unsigned>();
2409}
2410
2411
2412std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
2413getRegForInlineAsmConstraint(const std::string &Constraint,
2414 EVT VT) const {
2415 if (Constraint[0] != '{')
2416 return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
2417 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2418
2419 // Remove the braces from around the name.
2420 StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2421
2422 // Figure out which register class contains this reg.
2423 const TargetRegisterInfo *RI = TM.getRegisterInfo();
2424 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
2425 E = RI->regclass_end(); RCI != E; ++RCI) {
2426 const TargetRegisterClass *RC = *RCI;
2427
2428 // If none of the value types for this register class are valid, we
2429 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2430 bool isLegal = false;
2431 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2432 I != E; ++I) {
2433 if (isTypeLegal(*I)) {
2434 isLegal = true;
2435 break;
2436 }
2437 }
2438
2439 if (!isLegal) continue;
2440
2441 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2442 I != E; ++I) {
2443 if (RegName.equals_lower(RI->getName(*I)))
2444 return std::make_pair(*I, RC);
2445 }
2446 }
2447
2448 return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
2449}
2450
2451//===----------------------------------------------------------------------===//
2452// Constraint Selection.
2453
2454/// isMatchingInputConstraint - Return true of this is an input operand that is
2455/// a matching constraint like "4".
2456bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2457 assert(!ConstraintCode.empty() && "No known constraint!");
2458 return isdigit(ConstraintCode[0]);
2459}
2460
2461/// getMatchedOperand - If this is an input matching constraint, this method
2462/// returns the output operand it matches.
2463unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2464 assert(!ConstraintCode.empty() && "No known constraint!");
2465 return atoi(ConstraintCode.c_str());
2466}
2467
2468
2469/// getConstraintGenerality - Return an integer indicating how general CT
2470/// is.
2471static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2472 switch (CT) {
2473 default: llvm_unreachable("Unknown constraint type!");
2474 case TargetLowering::C_Other:
2475 case TargetLowering::C_Unknown:
2476 return 0;
2477 case TargetLowering::C_Register:
2478 return 1;
2479 case TargetLowering::C_RegisterClass:
2480 return 2;
2481 case TargetLowering::C_Memory:
2482 return 3;
2483 }
2484}
2485
2486/// ChooseConstraint - If there are multiple different constraints that we
2487/// could pick for this operand (e.g. "imr") try to pick the 'best' one.
2488/// This is somewhat tricky: constraints fall into four classes:
2489/// Other -> immediates and magic values
2490/// Register -> one specific register
2491/// RegisterClass -> a group of regs
2492/// Memory -> memory
2493/// Ideally, we would pick the most specific constraint possible: if we have
2494/// something that fits into a register, we would pick it. The problem here
2495/// is that if we have something that could either be in a register or in
2496/// memory that use of the register could cause selection of *other*
2497/// operands to fail: they might only succeed if we pick memory. Because of
2498/// this the heuristic we use is:
2499///
2500/// 1) If there is an 'other' constraint, and if the operand is valid for
2501/// that constraint, use it. This makes us take advantage of 'i'
2502/// constraints when available.
2503/// 2) Otherwise, pick the most general constraint present. This prefers
2504/// 'm' over 'r', for example.
2505///
2506static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
2507 bool hasMemory, const TargetLowering &TLI,
2508 SDValue Op, SelectionDAG *DAG) {
2509 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2510 unsigned BestIdx = 0;
2511 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2512 int BestGenerality = -1;
2513
2514 // Loop over the options, keeping track of the most general one.
2515 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2516 TargetLowering::ConstraintType CType =
2517 TLI.getConstraintType(OpInfo.Codes[i]);
2518
2519 // If this is an 'other' constraint, see if the operand is valid for it.
2520 // For example, on X86 we might have an 'rI' constraint. If the operand
2521 // is an integer in the range [0..31] we want to use I (saving a load
2522 // of a register), otherwise we must use 'r'.
2523 if (CType == TargetLowering::C_Other && Op.getNode()) {
2524 assert(OpInfo.Codes[i].size() == 1 &&
2525 "Unhandled multi-letter 'other' constraint");
2526 std::vector<SDValue> ResultOps;
2527 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i][0], hasMemory,
2528 ResultOps, *DAG);
2529 if (!ResultOps.empty()) {
2530 BestType = CType;
2531 BestIdx = i;
2532 break;
2533 }
2534 }
2535
2536 // This constraint letter is more general than the previous one, use it.
2537 int Generality = getConstraintGenerality(CType);
2538 if (Generality > BestGenerality) {
2539 BestType = CType;
2540 BestIdx = i;
2541 BestGenerality = Generality;
2542 }
2543 }
2544
2545 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2546 OpInfo.ConstraintType = BestType;
2547}
2548
2549/// ComputeConstraintToUse - Determines the constraint code and constraint
2550/// type to use for the specific AsmOperandInfo, setting
2551/// OpInfo.ConstraintCode and OpInfo.ConstraintType.
2552void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2553 SDValue Op,
2554 bool hasMemory,
2555 SelectionDAG *DAG) const {
2556 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
2557
2558 // Single-letter constraints ('r') are very common.
2559 if (OpInfo.Codes.size() == 1) {
2560 OpInfo.ConstraintCode = OpInfo.Codes[0];
2561 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2562 } else {
2563 ChooseConstraint(OpInfo, hasMemory, *this, Op, DAG);
2564 }
2565
2566 // 'X' matches anything.
2567 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2568 // Labels and constants are handled elsewhere ('X' is the only thing
2569 // that matches labels). For Functions, the type here is the type of
2570 // the result, which is not what we want to look at; leave them alone.
2571 Value *v = OpInfo.CallOperandVal;
2572 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2573 OpInfo.CallOperandVal = v;
2574 return;
2575 }
2576
2577 // Otherwise, try to resolve it to something we know about by looking at
2578 // the actual operand type.
2579 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2580 OpInfo.ConstraintCode = Repl;
2581 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2582 }
2583 }
2584}
2585
2586//===----------------------------------------------------------------------===//
2587// Loop Strength Reduction hooks
2588//===----------------------------------------------------------------------===//
2589
2590/// isLegalAddressingMode - Return true if the addressing mode represented
2591/// by AM is legal for this target, for a load/store of the specified type.
2592bool TargetLowering::isLegalAddressingMode(const AddrMode &AM,
2593 const Type *Ty) const {
2594 // The default implementation of this implements a conservative RISCy, r+r and
2595 // r+i addr mode.
2596
2597 // Allows a sign-extended 16-bit immediate field.
2598 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
2599 return false;
2600
2601 // No global is ever allowed as a base.
2602 if (AM.BaseGV)
2603 return false;
2604
2605 // Only support r+r,
2606 switch (AM.Scale) {
2607 case 0: // "r+i" or just "i", depending on HasBaseReg.
2608 break;
2609 case 1:
2610 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
2611 return false;
2612 // Otherwise we have r+r or r+i.
2613 break;
2614 case 2:
2615 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
2616 return false;
2617 // Allow 2*r as r+r.
2618 break;
2619 }
2620
2621 return true;
2622}
2623
2624/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
2625/// return a DAG expression to select that will generate the same value by
2626/// multiplying by a magic number. See:
2627/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2628SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
2629 std::vector<SDNode*>* Created) const {
2630 EVT VT = N->getValueType(0);
2631 DebugLoc dl= N->getDebugLoc();
2632
2633 // Check to see if we can do this.
2634 // FIXME: We should be more aggressive here.
2635 if (!isTypeLegal(VT))
2636 return SDValue();
2637
2638 APInt d = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
2639 APInt::ms magics = d.magic();
2640
2641 // Multiply the numerator (operand 0) by the magic value
2642 // FIXME: We should support doing a MUL in a wider type
2643 SDValue Q;
2644 if (isOperationLegalOrCustom(ISD::MULHS, VT))
2645 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
2646 DAG.getConstant(magics.m, VT));
2647 else if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
2648 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
2649 N->getOperand(0),
2650 DAG.getConstant(magics.m, VT)).getNode(), 1);
2651 else
2652 return SDValue(); // No mulhs or equvialent
2653 // If d > 0 and m < 0, add the numerator
2654 if (d.isStrictlyPositive() && magics.m.isNegative()) {
2655 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
2656 if (Created)
2657 Created->push_back(Q.getNode());
2658 }
2659 // If d < 0 and m > 0, subtract the numerator.
2660 if (d.isNegative() && magics.m.isStrictlyPositive()) {
2661 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
2662 if (Created)
2663 Created->push_back(Q.getNode());
2664 }
2665 // Shift right algebraic if shift value is nonzero
2666 if (magics.s > 0) {
2667 Q = DAG.getNode(ISD::SRA, dl, VT, Q,
2668 DAG.getConstant(magics.s, getShiftAmountTy()));
2669 if (Created)
2670 Created->push_back(Q.getNode());
2671 }
2672 // Extract the sign bit and add it to the quotient
2673 SDValue T =
2674 DAG.getNode(ISD::SRL, dl, VT, Q, DAG.getConstant(VT.getSizeInBits()-1,
2675 getShiftAmountTy()));
2676 if (Created)
2677 Created->push_back(T.getNode());
2678 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
2679}
2680
2681/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
2682/// return a DAG expression to select that will generate the same value by
2683/// multiplying by a magic number. See:
2684/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2685SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
2686 std::vector<SDNode*>* Created) const {
2687 EVT VT = N->getValueType(0);
2688 DebugLoc dl = N->getDebugLoc();
2689
2690 // Check to see if we can do this.
2691 // FIXME: We should be more aggressive here.
2692 if (!isTypeLegal(VT))
2693 return SDValue();
2694
2695 // FIXME: We should use a narrower constant when the upper
2696 // bits are known to be zero.
2697 ConstantSDNode *N1C = cast<ConstantSDNode>(N->getOperand(1));
2698 APInt::mu magics = N1C->getAPIntValue().magicu();
2699
2700 // Multiply the numerator (operand 0) by the magic value
2701 // FIXME: We should support doing a MUL in a wider type
2702 SDValue Q;
2703 if (isOperationLegalOrCustom(ISD::MULHU, VT))
2704 Q = DAG.getNode(ISD::MULHU, dl, VT, N->getOperand(0),
2705 DAG.getConstant(magics.m, VT));
2706 else if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
2707 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT),
2708 N->getOperand(0),
2709 DAG.getConstant(magics.m, VT)).getNode(), 1);
2710 else
2711 return SDValue(); // No mulhu or equvialent
2712 if (Created)
2713 Created->push_back(Q.getNode());
2714
2715 if (magics.a == 0) {
2716 assert(magics.s < N1C->getAPIntValue().getBitWidth() &&
2717 "We shouldn't generate an undefined shift!");
2718 return DAG.getNode(ISD::SRL, dl, VT, Q,
2719 DAG.getConstant(magics.s, getShiftAmountTy()));
2720 } else {
2721 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
2722 if (Created)
2723 Created->push_back(NPQ.getNode());
2724 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ,
2725 DAG.getConstant(1, getShiftAmountTy()));
2726 if (Created)
2727 Created->push_back(NPQ.getNode());
2728 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
2729 if (Created)
2730 Created->push_back(NPQ.getNode());
2731 return DAG.getNode(ISD::SRL, dl, VT, NPQ,
2732 DAG.getConstant(magics.s-1, getShiftAmountTy()));
2733 }
2734}