blob: 4d528abb6b4b12b0585eed8b59fe84ea9c9782e3 [file] [log] [blame]
Arnold Schwaighofera70fe792007-10-12 21:53:12 +00001//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that X86 uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#include "X86.h"
16#include "X86InstrBuilder.h"
17#include "X86ISelLowering.h"
18#include "X86MachineFunctionInfo.h"
19#include "X86TargetMachine.h"
20#include "llvm/CallingConv.h"
21#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/Function.h"
25#include "llvm/Intrinsics.h"
26#include "llvm/ADT/VectorExtras.h"
27#include "llvm/Analysis/ScalarEvolutionExpressions.h"
28#include "llvm/CodeGen/CallingConvLower.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
32#include "llvm/CodeGen/SelectionDAG.h"
33#include "llvm/CodeGen/SSARegMap.h"
34#include "llvm/Support/MathExtras.h"
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037#include "llvm/Target/TargetOptions.h"
38#include "llvm/ADT/StringExtras.h"
Duncan Sandsd8455ca2007-07-27 20:02:49 +000039#include "llvm/ParameterAttributes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040using namespace llvm;
41
42X86TargetLowering::X86TargetLowering(TargetMachine &TM)
43 : TargetLowering(TM) {
44 Subtarget = &TM.getSubtarget<X86Subtarget>();
Dale Johannesene0e0fd02007-09-23 14:52:20 +000045 X86ScalarSSEf64 = Subtarget->hasSSE2();
46 X86ScalarSSEf32 = Subtarget->hasSSE1();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +000048
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049
50 RegInfo = TM.getRegisterInfo();
51
52 // Set up the TargetLowering object.
53
54 // X86 is weird, it always uses i8 for shift amounts and setcc results.
55 setShiftAmountType(MVT::i8);
56 setSetCCResultType(MVT::i8);
57 setSetCCResultContents(ZeroOrOneSetCCResult);
58 setSchedulingPreference(SchedulingForRegPressure);
59 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
60 setStackPointerRegisterToSaveRestore(X86StackPtr);
61
62 if (Subtarget->isTargetDarwin()) {
63 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
64 setUseUnderscoreSetJmp(false);
65 setUseUnderscoreLongJmp(false);
66 } else if (Subtarget->isTargetMingw()) {
67 // MS runtime is weird: it exports _setjmp, but longjmp!
68 setUseUnderscoreSetJmp(true);
69 setUseUnderscoreLongJmp(false);
70 } else {
71 setUseUnderscoreSetJmp(true);
72 setUseUnderscoreLongJmp(true);
73 }
74
75 // Set up the register classes.
76 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
77 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
78 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
79 if (Subtarget->is64Bit())
80 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
81
82 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
83
84 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
85 // operation.
86 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
87 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
88 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
89
90 if (Subtarget->is64Bit()) {
91 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
92 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
93 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +000094 if (X86ScalarSSEf64)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
96 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
97 else
98 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
99 }
100
101 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
102 // this operation.
103 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
104 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
105 // SSE has no i16 to fp conversion, only i32
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000106 if (X86ScalarSSEf32) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000108 // f32 and f64 cases are Legal, f80 case is not
109 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
110 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000111 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
112 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
113 }
114
Dale Johannesen958b08b2007-09-19 23:55:34 +0000115 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
116 // are Legal, f80 is custom lowered.
117 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
118 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119
120 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
121 // this operation.
122 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
123 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
124
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000125 if (X86ScalarSSEf32) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000126 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000127 // f32 and f64 cases are Legal, f80 case is not
128 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129 } else {
130 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
131 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
132 }
133
134 // Handle FP_TO_UINT by promoting the destination to a larger signed
135 // conversion.
136 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
137 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
138 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
139
140 if (Subtarget->is64Bit()) {
141 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
142 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
143 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000144 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 // Expand FP_TO_UINT into a select.
146 // FIXME: We would like to use a Custom expander here eventually to do
147 // the optimal thing for SSE vs. the default expansion in the legalizer.
148 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
149 else
150 // With SSE3 we can use fisttpll to convert to a signed i64.
151 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
152 }
153
154 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000155 if (!X86ScalarSSEf64) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
157 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
158 }
159
Dan Gohman5a199552007-10-08 18:33:35 +0000160 // Scalar integer multiply, multiply-high, divide, and remainder are
161 // lowered to use operations that produce two results, to match the
162 // available instructions. This exposes the two-result form to trivial
163 // CSE, which is able to combine x/y and x%y into a single instruction,
164 // for example. The single-result multiply instructions are introduced
165 // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
166 // is not needed.
167 setOperationAction(ISD::MUL , MVT::i8 , Expand);
168 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
169 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
170 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
171 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
172 setOperationAction(ISD::SREM , MVT::i8 , Expand);
173 setOperationAction(ISD::UREM , MVT::i8 , Expand);
174 setOperationAction(ISD::MUL , MVT::i16 , Expand);
175 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
176 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
177 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
178 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
179 setOperationAction(ISD::SREM , MVT::i16 , Expand);
180 setOperationAction(ISD::UREM , MVT::i16 , Expand);
181 setOperationAction(ISD::MUL , MVT::i32 , Expand);
182 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
183 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
184 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
185 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
186 setOperationAction(ISD::SREM , MVT::i32 , Expand);
187 setOperationAction(ISD::UREM , MVT::i32 , Expand);
188 setOperationAction(ISD::MUL , MVT::i64 , Expand);
189 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
190 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
191 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
192 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
193 setOperationAction(ISD::SREM , MVT::i64 , Expand);
194 setOperationAction(ISD::UREM , MVT::i64 , Expand);
Dan Gohman242a5ba2007-09-25 18:23:27 +0000195
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
197 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
198 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
199 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
200 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
201 if (Subtarget->is64Bit())
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
206 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
207 setOperationAction(ISD::FREM , MVT::f64 , Expand);
208
209 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i8 , Expand);
211 setOperationAction(ISD::CTLZ , MVT::i8 , Expand);
212 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
213 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
214 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
215 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
216 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
217 setOperationAction(ISD::CTLZ , MVT::i32 , Expand);
218 if (Subtarget->is64Bit()) {
219 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
220 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
221 setOperationAction(ISD::CTLZ , MVT::i64 , Expand);
222 }
223
224 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
225 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
226
227 // These should be promoted to a larger select which is supported.
228 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
229 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
230 // X86 wants to expand cmov itself.
231 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
232 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
233 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
234 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000235 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
237 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
238 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
239 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
240 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000241 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 if (Subtarget->is64Bit()) {
243 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
244 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
245 }
246 // X86 ret instruction may pop stack.
247 setOperationAction(ISD::RET , MVT::Other, Custom);
248 if (!Subtarget->is64Bit())
249 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
250
251 // Darwin ABI issue.
252 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
253 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
254 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
255 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
256 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
257 if (Subtarget->is64Bit()) {
258 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
259 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
260 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
261 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
262 }
263 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
264 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
265 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
266 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
267 // X86 wants to expand memset / memcpy itself.
268 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
269 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
270
Dan Gohman21442852007-09-25 15:10:49 +0000271 // Use the default ISD::LOCATION expansion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 // FIXME - use subtarget debug flags
274 if (!Subtarget->isTargetDarwin() &&
275 !Subtarget->isTargetELF() &&
276 !Subtarget->isTargetCygMing())
277 setOperationAction(ISD::LABEL, MVT::Other, Expand);
278
279 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
280 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
281 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
282 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
283 if (Subtarget->is64Bit()) {
284 // FIXME: Verify
285 setExceptionPointerRegister(X86::RAX);
286 setExceptionSelectorRegister(X86::RDX);
287 } else {
288 setExceptionPointerRegister(X86::EAX);
289 setExceptionSelectorRegister(X86::EDX);
290 }
Anton Korobeynikov23ca9c52007-09-03 00:36:06 +0000291 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292
Duncan Sands7407a9f2007-09-11 14:10:23 +0000293 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
Duncan Sandsd8455ca2007-07-27 20:02:49 +0000294
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
296 setOperationAction(ISD::VASTART , MVT::Other, Custom);
297 setOperationAction(ISD::VAARG , MVT::Other, Expand);
298 setOperationAction(ISD::VAEND , MVT::Other, Expand);
299 if (Subtarget->is64Bit())
300 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
301 else
302 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
303
304 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
305 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
306 if (Subtarget->is64Bit())
307 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
308 if (Subtarget->isTargetCygMing())
309 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
310 else
311 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
312
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000313 if (X86ScalarSSEf64) {
314 // f32 and f64 use SSE.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 // Set up the FP register classes.
316 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
317 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
318
319 // Use ANDPD to simulate FABS.
320 setOperationAction(ISD::FABS , MVT::f64, Custom);
321 setOperationAction(ISD::FABS , MVT::f32, Custom);
322
323 // Use XORP to simulate FNEG.
324 setOperationAction(ISD::FNEG , MVT::f64, Custom);
325 setOperationAction(ISD::FNEG , MVT::f32, Custom);
326
327 // Use ANDPD and ORPD to simulate FCOPYSIGN.
328 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
329 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
330
331 // We don't support sin/cos/fmod
332 setOperationAction(ISD::FSIN , MVT::f64, Expand);
333 setOperationAction(ISD::FCOS , MVT::f64, Expand);
334 setOperationAction(ISD::FREM , MVT::f64, Expand);
335 setOperationAction(ISD::FSIN , MVT::f32, Expand);
336 setOperationAction(ISD::FCOS , MVT::f32, Expand);
337 setOperationAction(ISD::FREM , MVT::f32, Expand);
338
339 // Expand FP immediates into loads from the stack, except for the special
340 // cases we handle.
341 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
342 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000343 addLegalFPImmediate(APFloat(+0.0)); // xorpd
344 addLegalFPImmediate(APFloat(+0.0f)); // xorps
Dale Johannesen8f83a6b2007-08-09 01:04:01 +0000345
346 // Conversions to long double (in X87) go through memory.
347 setConvertAction(MVT::f32, MVT::f80, Expand);
348 setConvertAction(MVT::f64, MVT::f80, Expand);
349
350 // Conversions from long double (in X87) go through memory.
351 setConvertAction(MVT::f80, MVT::f32, Expand);
352 setConvertAction(MVT::f80, MVT::f64, Expand);
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000353 } else if (X86ScalarSSEf32) {
354 // Use SSE for f32, x87 for f64.
355 // Set up the FP register classes.
356 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
357 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
358
359 // Use ANDPS to simulate FABS.
360 setOperationAction(ISD::FABS , MVT::f32, Custom);
361
362 // Use XORP to simulate FNEG.
363 setOperationAction(ISD::FNEG , MVT::f32, Custom);
364
365 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
366
367 // Use ANDPS and ORPS to simulate FCOPYSIGN.
368 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
369 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
370
371 // We don't support sin/cos/fmod
372 setOperationAction(ISD::FSIN , MVT::f32, Expand);
373 setOperationAction(ISD::FCOS , MVT::f32, Expand);
374 setOperationAction(ISD::FREM , MVT::f32, Expand);
375
376 // Expand FP immediates into loads from the stack, except for the special
377 // cases we handle.
378 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
379 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
380 addLegalFPImmediate(APFloat(+0.0f)); // xorps
381 addLegalFPImmediate(APFloat(+0.0)); // FLD0
382 addLegalFPImmediate(APFloat(+1.0)); // FLD1
383 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
384 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
385
386 // SSE->x87 conversions go through memory.
387 setConvertAction(MVT::f32, MVT::f64, Expand);
388 setConvertAction(MVT::f32, MVT::f80, Expand);
389
390 // x87->SSE truncations need to go through memory.
391 setConvertAction(MVT::f80, MVT::f32, Expand);
392 setConvertAction(MVT::f64, MVT::f32, Expand);
393 // And x87->x87 truncations also.
394 setConvertAction(MVT::f80, MVT::f64, Expand);
395
396 if (!UnsafeFPMath) {
397 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
398 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
399 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000400 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000401 // f32 and f64 in x87.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 // Set up the FP register classes.
403 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
404 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
405
406 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
407 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
408 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
409 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
Dale Johannesen8f83a6b2007-08-09 01:04:01 +0000410
411 // Floating truncations need to go through memory.
412 setConvertAction(MVT::f80, MVT::f32, Expand);
413 setConvertAction(MVT::f64, MVT::f32, Expand);
414 setConvertAction(MVT::f80, MVT::f64, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415
416 if (!UnsafeFPMath) {
417 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
418 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
419 }
420
421 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
422 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
Dale Johannesenbbe2b702007-08-30 00:23:21 +0000423 addLegalFPImmediate(APFloat(+0.0)); // FLD0
424 addLegalFPImmediate(APFloat(+1.0)); // FLD1
425 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
426 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000427 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
428 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
429 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
430 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431 }
432
Dale Johannesen4ab00bd2007-08-05 18:49:15 +0000433 // Long double always uses X87.
434 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000435 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
436 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
437 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
Dale Johannesen7f1076b2007-09-26 21:10:55 +0000438 if (!UnsafeFPMath) {
439 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
440 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
441 }
Dale Johannesen4ab00bd2007-08-05 18:49:15 +0000442
Dan Gohman2f7b1982007-10-11 23:21:31 +0000443 // Always use a library call for pow.
444 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
445 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
446 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
447
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448 // First set operation action for all vector types to expand. Then we
449 // will selectively turn on ones that can be effectively codegen'd.
450 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
451 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
452 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
453 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
454 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
455 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
456 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
457 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
458 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
459 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
460 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
461 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
462 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
463 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
464 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
465 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
466 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
467 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
468 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
469 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
470 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
471 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
472 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
473 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
474 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
Dan Gohman5a199552007-10-08 18:33:35 +0000475 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
476 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
477 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
478 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
Dan Gohman2f7b1982007-10-11 23:21:31 +0000479 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
Dan Gohman1d2dc2c2007-10-12 14:09:42 +0000480 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
481 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
482 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483 }
484
485 if (Subtarget->hasMMX()) {
486 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
487 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
488 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
489 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
490
491 // FIXME: add MMX packed arithmetics
492
493 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
494 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
495 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
496 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
497
498 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
499 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
500 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
501
502 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
503 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
504
505 setOperationAction(ISD::AND, MVT::v8i8, Promote);
506 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
507 setOperationAction(ISD::AND, MVT::v4i16, Promote);
508 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
509 setOperationAction(ISD::AND, MVT::v2i32, Promote);
510 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
511 setOperationAction(ISD::AND, MVT::v1i64, Legal);
512
513 setOperationAction(ISD::OR, MVT::v8i8, Promote);
514 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
515 setOperationAction(ISD::OR, MVT::v4i16, Promote);
516 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
517 setOperationAction(ISD::OR, MVT::v2i32, Promote);
518 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
519 setOperationAction(ISD::OR, MVT::v1i64, Legal);
520
521 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
522 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
523 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
524 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
525 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
526 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
527 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
528
529 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
530 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
531 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
532 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
533 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
534 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
535 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
536
537 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
538 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
539 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
540 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
541
542 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
543 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
544 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
545 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
546
547 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
548 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
549 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
550 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
551 }
552
553 if (Subtarget->hasSSE1()) {
554 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
555
556 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
557 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
558 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
559 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
560 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
561 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000562 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
563 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
564 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
565 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
566 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
567 }
568
569 if (Subtarget->hasSSE2()) {
570 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
571 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
572 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
573 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
574 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
575
576 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
577 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
578 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
579 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
580 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
581 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
582 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
583 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
584 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
585 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
586 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
587 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
588 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
589 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
590 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000591
592 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
593 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
594 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
595 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
596 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
597 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
598
599 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
600 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
601 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
602 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
603 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
604 }
605 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
606 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
607 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
608 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
609 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
610 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
611
612 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
613 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
614 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
615 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
616 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
617 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
618 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
619 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
620 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
621 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
622 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
623 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
624 }
625
626 // Custom lower v2i64 and v2f64 selects.
627 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
628 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
629 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
630 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
631 }
632
633 // We want to custom lower some of our intrinsics.
634 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
635
636 // We have target-specific dag combine patterns for the following nodes:
637 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
638 setTargetDAGCombine(ISD::SELECT);
639
640 computeRegisterProperties();
641
642 // FIXME: These should be based on subtarget info. Plus, the values should
643 // be smaller when we are in optimizing for size mode.
644 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
645 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
646 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
647 allowUnalignedMemoryAccesses = true; // x86 supports it!
648}
649
650
651//===----------------------------------------------------------------------===//
652// Return Value Calling Convention Implementation
653//===----------------------------------------------------------------------===//
654
655#include "X86GenCallingConv.inc"
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000656
657/// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
658/// exists skip possible ISD:TokenFactor.
659static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
660 if (Chain.getOpcode()==X86ISD::TAILCALL) {
661 return Chain;
662 } else if (Chain.getOpcode()==ISD::TokenFactor) {
663 if (Chain.getNumOperands() &&
664 Chain.getOperand(0).getOpcode()==X86ISD::TAILCALL)
665 return Chain.getOperand(0);
666 }
667 return Chain;
668}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669
670/// LowerRET - Lower an ISD::RET node.
671SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
672 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
673
674 SmallVector<CCValAssign, 16> RVLocs;
675 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
676 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
677 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
678 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000679
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000680 // If this is the first return lowered for this function, add the regs to the
681 // liveout set for the function.
682 if (DAG.getMachineFunction().liveout_empty()) {
683 for (unsigned i = 0; i != RVLocs.size(); ++i)
684 if (RVLocs[i].isRegLoc())
685 DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
686 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687 SDOperand Chain = Op.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000689 // Handle tail call return.
690 Chain = GetPossiblePreceedingTailCall(Chain);
691 if (Chain.getOpcode() == X86ISD::TAILCALL) {
692 SDOperand TailCall = Chain;
693 SDOperand TargetAddress = TailCall.getOperand(1);
694 SDOperand StackAdjustment = TailCall.getOperand(2);
695 assert ( ((TargetAddress.getOpcode() == ISD::Register &&
696 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
697 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
698 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
699 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
700 "Expecting an global address, external symbol, or register");
701 assert( StackAdjustment.getOpcode() == ISD::Constant &&
702 "Expecting a const value");
703
704 SmallVector<SDOperand,8> Operands;
705 Operands.push_back(Chain.getOperand(0));
706 Operands.push_back(TargetAddress);
707 Operands.push_back(StackAdjustment);
708 // Copy registers used by the call. Last operand is a flag so it is not
709 // copied.
Arnold Schwaighofer10202b32007-10-16 09:05:00 +0000710 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000711 Operands.push_back(Chain.getOperand(i));
712 }
Arnold Schwaighofer10202b32007-10-16 09:05:00 +0000713 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
714 Operands.size());
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000715 }
716
717 // Regular return.
718 SDOperand Flag;
719
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720 // Copy the result values into the output registers.
721 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
722 RVLocs[0].getLocReg() != X86::ST0) {
723 for (unsigned i = 0; i != RVLocs.size(); ++i) {
724 CCValAssign &VA = RVLocs[i];
725 assert(VA.isRegLoc() && "Can only return in registers!");
726 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
727 Flag);
728 Flag = Chain.getValue(1);
729 }
730 } else {
731 // We need to handle a destination of ST0 specially, because it isn't really
732 // a register.
733 SDOperand Value = Op.getOperand(1);
734
735 // If this is an FP return with ScalarSSE, we need to move the value from
736 // an XMM register onto the fp-stack.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000737 if ((X86ScalarSSEf32 && RVLocs[0].getValVT()==MVT::f32) ||
738 (X86ScalarSSEf64 && RVLocs[0].getValVT()==MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 SDOperand MemLoc;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000740
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 // If this is a load into a scalarsse value, don't store the loaded value
742 // back to the stack, only to reload it: just replace the scalar-sse load.
743 if (ISD::isNON_EXTLoad(Value.Val) &&
744 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
745 Chain = Value.getOperand(0);
746 MemLoc = Value.getOperand(1);
747 } else {
748 // Spill the value to memory and reload it into top of stack.
749 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
750 MachineFunction &MF = DAG.getMachineFunction();
751 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
752 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
753 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
754 }
755 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
756 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
757 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
758 Chain = Value.getValue(1);
759 }
760
761 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
762 SDOperand Ops[] = { Chain, Value };
763 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
764 Flag = Chain.getValue(1);
765 }
766
767 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
768 if (Flag.Val)
769 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
770 else
771 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
772}
773
774
775/// LowerCallResult - Lower the result values of an ISD::CALL into the
776/// appropriate copies out of appropriate physical registers. This assumes that
777/// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
778/// being lowered. The returns a SDNode with the same number of values as the
779/// ISD::CALL.
780SDNode *X86TargetLowering::
781LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
782 unsigned CallingConv, SelectionDAG &DAG) {
783
784 // Assign locations to each value returned by this call.
785 SmallVector<CCValAssign, 16> RVLocs;
786 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
787 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
788 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
789
790
791 SmallVector<SDOperand, 8> ResultVals;
792
793 // Copy all of the result registers out of their specified physreg.
794 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
795 for (unsigned i = 0; i != RVLocs.size(); ++i) {
796 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
797 RVLocs[i].getValVT(), InFlag).getValue(1);
798 InFlag = Chain.getValue(2);
799 ResultVals.push_back(Chain.getValue(0));
800 }
801 } else {
802 // Copies from the FP stack are special, as ST0 isn't a valid register
803 // before the fp stackifier runs.
804
805 // Copy ST0 into an RFP register with FP_GET_RESULT.
806 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
807 SDOperand GROps[] = { Chain, InFlag };
808 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
809 Chain = RetVal.getValue(1);
810 InFlag = RetVal.getValue(2);
811
812 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
813 // an XMM register.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000814 if ((X86ScalarSSEf32 && RVLocs[0].getValVT() == MVT::f32) ||
815 (X86ScalarSSEf64 && RVLocs[0].getValVT() == MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
817 // shouldn't be necessary except that RFP cannot be live across
818 // multiple blocks. When stackifier is fixed, they can be uncoupled.
819 MachineFunction &MF = DAG.getMachineFunction();
820 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
821 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
822 SDOperand Ops[] = {
823 Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
824 };
825 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
826 RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
827 Chain = RetVal.getValue(1);
828 }
829 ResultVals.push_back(RetVal);
830 }
831
832 // Merge everything together with a MERGE_VALUES node.
833 ResultVals.push_back(Chain);
834 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
835 &ResultVals[0], ResultVals.size()).Val;
836}
837
838
839//===----------------------------------------------------------------------===//
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000840// C & StdCall & Fast Calling Convention implementation
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841//===----------------------------------------------------------------------===//
842// StdCall calling convention seems to be standard for many Windows' API
843// routines and around. It differs from C calling convention just a little:
844// callee should clean up the stack, not caller. Symbols should be also
845// decorated in some fancy way :) It doesn't support any vector arguments.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000846// For info on fast calling convention see Fast Calling Convention (tail call)
847// implementation LowerX86_32FastCCCallTo.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000848
849/// AddLiveIn - This helper function adds the specified physical register to the
850/// MachineFunction as a live in value. It also creates a corresponding virtual
851/// register for it.
852static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
853 const TargetRegisterClass *RC) {
854 assert(RC->contains(PReg) && "Not the correct regclass!");
855 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
856 MF.addLiveIn(PReg, VReg);
857 return VReg;
858}
859
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000860// align stack arguments according to platform alignment needed for tail calls
861unsigned GetAlignedArgumentStackSize(unsigned StackSize, SelectionDAG& DAG);
862
Rafael Espindola03cbeb72007-09-14 15:48:13 +0000863SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
864 const CCValAssign &VA,
865 MachineFrameInfo *MFI,
866 SDOperand Root, unsigned i) {
867 // Create the nodes corresponding to a load from this parameter slot.
868 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
869 VA.getLocMemOffset());
870 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
871
872 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
873
874 if (Flags & ISD::ParamFlags::ByVal)
875 return FIN;
876 else
877 return DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0);
878}
879
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
881 bool isStdCall) {
882 unsigned NumArgs = Op.Val->getNumValues() - 1;
883 MachineFunction &MF = DAG.getMachineFunction();
884 MachineFrameInfo *MFI = MF.getFrameInfo();
885 SDOperand Root = Op.getOperand(0);
886 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000887 unsigned CC = MF.getFunction()->getCallingConv();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000888 // Assign locations to all of the incoming arguments.
889 SmallVector<CCValAssign, 16> ArgLocs;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000890 CCState CCInfo(CC, isVarArg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000891 getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000892 // Check for possible tail call calling convention.
893 if (CC == CallingConv::Fast && PerformTailCallOpt)
894 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_TailCall);
895 else
896 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
897
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000898 SmallVector<SDOperand, 8> ArgValues;
899 unsigned LastVal = ~0U;
900 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
901 CCValAssign &VA = ArgLocs[i];
902 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
903 // places.
904 assert(VA.getValNo() != LastVal &&
905 "Don't support value assigned to multiple locs yet");
906 LastVal = VA.getValNo();
907
908 if (VA.isRegLoc()) {
909 MVT::ValueType RegVT = VA.getLocVT();
910 TargetRegisterClass *RC;
911 if (RegVT == MVT::i32)
912 RC = X86::GR32RegisterClass;
913 else {
914 assert(MVT::isVector(RegVT));
915 RC = X86::VR128RegisterClass;
916 }
917
918 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
919 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
920
921 // If this is an 8 or 16-bit value, it is really passed promoted to 32
922 // bits. Insert an assert[sz]ext to capture this, then truncate to the
923 // right size.
924 if (VA.getLocInfo() == CCValAssign::SExt)
925 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
926 DAG.getValueType(VA.getValVT()));
927 else if (VA.getLocInfo() == CCValAssign::ZExt)
928 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
929 DAG.getValueType(VA.getValVT()));
930
931 if (VA.getLocInfo() != CCValAssign::Full)
932 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
933
934 ArgValues.push_back(ArgValue);
935 } else {
936 assert(VA.isMemLoc());
Rafael Espindola03cbeb72007-09-14 15:48:13 +0000937 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938 }
939 }
940
941 unsigned StackSize = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000942 // align stack specially for tail calls
943 if (CC==CallingConv::Fast)
944 StackSize = GetAlignedArgumentStackSize(StackSize,DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945
946 ArgValues.push_back(Root);
947
948 // If the function takes variable number of arguments, make a frame index for
949 // the start of the first vararg value... for expansion of llvm.va_start.
950 if (isVarArg)
951 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
952
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000953 // Tail call calling convention (CallingConv::Fast) does not support varargs.
954 assert( !(isVarArg && CC == CallingConv::Fast) &&
955 "CallingConv::Fast does not support varargs.");
956
957 if (isStdCall && !isVarArg &&
958 (CC==CallingConv::Fast && PerformTailCallOpt || CC!=CallingConv::Fast)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000959 BytesToPopOnReturn = StackSize; // Callee pops everything..
960 BytesCallerReserves = 0;
961 } else {
962 BytesToPopOnReturn = 0; // Callee pops nothing.
963
964 // If this is an sret function, the return should pop the hidden pointer.
965 if (NumArgs &&
966 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
967 ISD::ParamFlags::StructReturn))
968 BytesToPopOnReturn = 4;
969
970 BytesCallerReserves = StackSize;
971 }
Anton Korobeynikove844e472007-08-15 17:12:32 +0000972
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974
Anton Korobeynikove844e472007-08-15 17:12:32 +0000975 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
976 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000977
978 // Return the new list of results.
979 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
980 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
981}
982
983SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
984 unsigned CC) {
985 SDOperand Chain = Op.getOperand(0);
986 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000987 SDOperand Callee = Op.getOperand(4);
988 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000989
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990 // Analyze operands of the call, assigning locations to each operand.
991 SmallVector<CCValAssign, 16> ArgLocs;
992 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000993 if(CC==CallingConv::Fast && PerformTailCallOpt)
994 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
995 else
996 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000997
998 // Get a count of how many bytes are to be pushed on the stack.
999 unsigned NumBytes = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001000 if (CC==CallingConv::Fast)
1001 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002
1003 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1004
1005 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1006 SmallVector<SDOperand, 8> MemOpChains;
1007
1008 SDOperand StackPtr;
1009
1010 // Walk the register/memloc assignments, inserting copies/loads.
1011 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1012 CCValAssign &VA = ArgLocs[i];
1013 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1014
1015 // Promote the value if needed.
1016 switch (VA.getLocInfo()) {
1017 default: assert(0 && "Unknown loc info!");
1018 case CCValAssign::Full: break;
1019 case CCValAssign::SExt:
1020 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1021 break;
1022 case CCValAssign::ZExt:
1023 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1024 break;
1025 case CCValAssign::AExt:
1026 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1027 break;
1028 }
1029
1030 if (VA.isRegLoc()) {
1031 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1032 } else {
1033 assert(VA.isMemLoc());
1034 if (StackPtr.Val == 0)
1035 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindola007b7142007-09-21 15:50:22 +00001036
1037 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1038 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001039 }
1040 }
1041
1042 // If the first argument is an sret pointer, remember it.
1043 bool isSRet = NumOps &&
1044 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
1045 ISD::ParamFlags::StructReturn);
1046
1047 if (!MemOpChains.empty())
1048 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1049 &MemOpChains[0], MemOpChains.size());
1050
1051 // Build a sequence of copy-to-reg nodes chained together with token chain
1052 // and flag operands which copy the outgoing args into registers.
1053 SDOperand InFlag;
1054 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1055 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1056 InFlag);
1057 InFlag = Chain.getValue(1);
1058 }
1059
1060 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1061 // GOT pointer.
1062 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1063 Subtarget->isPICStyleGOT()) {
1064 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1065 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1066 InFlag);
1067 InFlag = Chain.getValue(1);
1068 }
1069
1070 // If the callee is a GlobalAddress node (quite common, every direct call is)
1071 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1072 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1073 // We should use extra load for direct calls to dllimported functions in
1074 // non-JIT mode.
1075 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1076 getTargetMachine(), true))
1077 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1078 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1079 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1080
1081 // Returns a chain & a flag for retval copy to use.
1082 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1083 SmallVector<SDOperand, 8> Ops;
1084 Ops.push_back(Chain);
1085 Ops.push_back(Callee);
1086
1087 // Add argument registers to the end of the list so that they are known live
1088 // into the call.
1089 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1090 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1091 RegsToPass[i].second.getValueType()));
1092
1093 // Add an implicit use GOT pointer in EBX.
1094 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1095 Subtarget->isPICStyleGOT())
1096 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1097
1098 if (InFlag.Val)
1099 Ops.push_back(InFlag);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001100
1101 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102 InFlag = Chain.getValue(1);
1103
1104 // Create the CALLSEQ_END node.
1105 unsigned NumBytesForCalleeToPush = 0;
1106
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001107 if (CC == CallingConv::X86_StdCall ||
1108 (CC == CallingConv::Fast && PerformTailCallOpt)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001109 if (isVarArg)
1110 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1111 else
1112 NumBytesForCalleeToPush = NumBytes;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001113 assert(!(isVarArg && CC==CallingConv::Fast) &&
1114 "CallingConv::Fast does not support varargs.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001115 } else {
1116 // If this is is a call to a struct-return function, the callee
1117 // pops the hidden struct pointer, so we have to push it back.
1118 // This is common for Darwin/X86, Linux & Mingw32 targets.
1119 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1120 }
1121
1122 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1123 Ops.clear();
1124 Ops.push_back(Chain);
1125 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1126 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
1127 Ops.push_back(InFlag);
1128 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1129 InFlag = Chain.getValue(1);
1130
1131 // Handle result values, copying them out of physregs into vregs that we
1132 // return.
1133 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1134}
1135
1136
1137//===----------------------------------------------------------------------===//
1138// FastCall Calling Convention implementation
1139//===----------------------------------------------------------------------===//
1140//
1141// The X86 'fastcall' calling convention passes up to two integer arguments in
1142// registers (an appropriate portion of ECX/EDX), passes arguments in C order,
1143// and requires that the callee pop its arguments off the stack (allowing proper
1144// tail calls), and has the same return value conventions as C calling convs.
1145//
1146// This calling convention always arranges for the callee pop value to be 8n+4
1147// bytes, which is needed for tail recursion elimination and stack alignment
1148// reasons.
1149SDOperand
1150X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
1151 MachineFunction &MF = DAG.getMachineFunction();
1152 MachineFrameInfo *MFI = MF.getFrameInfo();
1153 SDOperand Root = Op.getOperand(0);
1154 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1155
1156 // Assign locations to all of the incoming arguments.
1157 SmallVector<CCValAssign, 16> ArgLocs;
1158 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
1159 getTargetMachine(), ArgLocs);
1160 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
1161
1162 SmallVector<SDOperand, 8> ArgValues;
1163 unsigned LastVal = ~0U;
1164 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1165 CCValAssign &VA = ArgLocs[i];
1166 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1167 // places.
1168 assert(VA.getValNo() != LastVal &&
1169 "Don't support value assigned to multiple locs yet");
1170 LastVal = VA.getValNo();
1171
1172 if (VA.isRegLoc()) {
1173 MVT::ValueType RegVT = VA.getLocVT();
1174 TargetRegisterClass *RC;
1175 if (RegVT == MVT::i32)
1176 RC = X86::GR32RegisterClass;
1177 else {
1178 assert(MVT::isVector(RegVT));
1179 RC = X86::VR128RegisterClass;
1180 }
1181
1182 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1183 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1184
1185 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1186 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1187 // right size.
1188 if (VA.getLocInfo() == CCValAssign::SExt)
1189 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1190 DAG.getValueType(VA.getValVT()));
1191 else if (VA.getLocInfo() == CCValAssign::ZExt)
1192 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1193 DAG.getValueType(VA.getValVT()));
1194
1195 if (VA.getLocInfo() != CCValAssign::Full)
1196 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1197
1198 ArgValues.push_back(ArgValue);
1199 } else {
1200 assert(VA.isMemLoc());
Rafael Espindolab53ef122007-09-21 14:55:38 +00001201 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001202 }
1203 }
1204
1205 ArgValues.push_back(Root);
1206
1207 unsigned StackSize = CCInfo.getNextStackOffset();
1208
1209 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1210 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001211 // arguments and the arguments after the retaddr has been pushed are
1212 // aligned.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001213 if ((StackSize & 7) == 0)
1214 StackSize += 4;
1215 }
1216
1217 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1218 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
1220 BytesCallerReserves = 0;
1221
Anton Korobeynikove844e472007-08-15 17:12:32 +00001222 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1223 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224
1225 // Return the new list of results.
1226 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1227 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1228}
1229
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001230SDOperand
1231X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1232 const SDOperand &StackPtr,
1233 const CCValAssign &VA,
1234 SDOperand Chain,
1235 SDOperand Arg) {
1236 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1237 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1238 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1239 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1240 if (Flags & ISD::ParamFlags::ByVal) {
1241 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1242 ISD::ParamFlags::ByValAlignOffs);
1243
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001244 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1245 ISD::ParamFlags::ByValSizeOffs;
1246
1247 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1248 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
Rafael Espindola80825902007-10-19 10:41:11 +00001249 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i1);
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001250
Rafael Espindola80825902007-10-19 10:41:11 +00001251 return DAG.getMemcpy(Chain, PtrOff, Arg, SizeNode, AlignNode,
1252 AlwaysInline);
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001253 } else {
1254 return DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1255 }
1256}
1257
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1259 unsigned CC) {
1260 SDOperand Chain = Op.getOperand(0);
1261 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1262 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1263 SDOperand Callee = Op.getOperand(4);
1264
1265 // Analyze operands of the call, assigning locations to each operand.
1266 SmallVector<CCValAssign, 16> ArgLocs;
1267 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1268 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1269
1270 // Get a count of how many bytes are to be pushed on the stack.
1271 unsigned NumBytes = CCInfo.getNextStackOffset();
1272
1273 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1274 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001275 // arguments and the arguments after the retaddr has been pushed are
1276 // aligned.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277 if ((NumBytes & 7) == 0)
1278 NumBytes += 4;
1279 }
1280
1281 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1282
1283 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1284 SmallVector<SDOperand, 8> MemOpChains;
1285
1286 SDOperand StackPtr;
1287
1288 // Walk the register/memloc assignments, inserting copies/loads.
1289 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1290 CCValAssign &VA = ArgLocs[i];
1291 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1292
1293 // Promote the value if needed.
1294 switch (VA.getLocInfo()) {
1295 default: assert(0 && "Unknown loc info!");
1296 case CCValAssign::Full: break;
1297 case CCValAssign::SExt:
1298 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1299 break;
1300 case CCValAssign::ZExt:
1301 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1302 break;
1303 case CCValAssign::AExt:
1304 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1305 break;
1306 }
1307
1308 if (VA.isRegLoc()) {
1309 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1310 } else {
1311 assert(VA.isMemLoc());
1312 if (StackPtr.Val == 0)
1313 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindola007b7142007-09-21 15:50:22 +00001314
1315 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1316 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001317 }
1318 }
1319
1320 if (!MemOpChains.empty())
1321 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1322 &MemOpChains[0], MemOpChains.size());
1323
1324 // Build a sequence of copy-to-reg nodes chained together with token chain
1325 // and flag operands which copy the outgoing args into registers.
1326 SDOperand InFlag;
1327 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1328 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1329 InFlag);
1330 InFlag = Chain.getValue(1);
1331 }
1332
1333 // If the callee is a GlobalAddress node (quite common, every direct call is)
1334 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1335 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1336 // We should use extra load for direct calls to dllimported functions in
1337 // non-JIT mode.
1338 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1339 getTargetMachine(), true))
1340 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1341 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1342 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1343
1344 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1345 // GOT pointer.
1346 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1347 Subtarget->isPICStyleGOT()) {
1348 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1349 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1350 InFlag);
1351 InFlag = Chain.getValue(1);
1352 }
1353
1354 // Returns a chain & a flag for retval copy to use.
1355 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1356 SmallVector<SDOperand, 8> Ops;
1357 Ops.push_back(Chain);
1358 Ops.push_back(Callee);
1359
1360 // Add argument registers to the end of the list so that they are known live
1361 // into the call.
1362 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1363 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1364 RegsToPass[i].second.getValueType()));
1365
1366 // Add an implicit use GOT pointer in EBX.
1367 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1368 Subtarget->isPICStyleGOT())
1369 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1370
1371 if (InFlag.Val)
1372 Ops.push_back(InFlag);
1373
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001374 assert(isTailCall==false && "no tail call here");
1375 Chain = DAG.getNode(X86ISD::CALL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001376 NodeTys, &Ops[0], Ops.size());
1377 InFlag = Chain.getValue(1);
1378
1379 // Returns a flag for retval copy to use.
1380 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1381 Ops.clear();
1382 Ops.push_back(Chain);
1383 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1384 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1385 Ops.push_back(InFlag);
1386 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1387 InFlag = Chain.getValue(1);
1388
1389 // Handle result values, copying them out of physregs into vregs that we
1390 // return.
1391 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1392}
1393
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001394//===----------------------------------------------------------------------===//
1395// Fast Calling Convention (tail call) implementation
1396//===----------------------------------------------------------------------===//
1397
1398// Like std call, callee cleans arguments, convention except that ECX is
1399// reserved for storing the tail called function address. Only 2 registers are
1400// free for argument passing (inreg). Tail call optimization is performed
1401// provided:
1402// * tailcallopt is enabled
1403// * caller/callee are fastcc
1404// * elf/pic is disabled OR
1405// * elf/pic enabled + callee is in module + callee has
1406// visibility protected or hidden
Arnold Schwaighofer373e8652007-10-12 21:30:57 +00001407// To keep the stack aligned according to platform abi the function
1408// GetAlignedArgumentStackSize ensures that argument delta is always multiples
1409// of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001410// If a tail called function callee has more arguments than the caller the
1411// caller needs to make sure that there is room to move the RETADDR to. This is
Arnold Schwaighofer373e8652007-10-12 21:30:57 +00001412// achieved by reserving an area the size of the argument delta right after the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001413// original REtADDR, but before the saved framepointer or the spilled registers
1414// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1415// stack layout:
1416// arg1
1417// arg2
1418// RETADDR
1419// [ new RETADDR
1420// move area ]
1421// (possible EBP)
1422// ESI
1423// EDI
1424// local1 ..
1425
1426/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1427/// for a 16 byte align requirement.
1428unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1429 SelectionDAG& DAG) {
1430 if (PerformTailCallOpt) {
1431 MachineFunction &MF = DAG.getMachineFunction();
1432 const TargetMachine &TM = MF.getTarget();
1433 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1434 unsigned StackAlignment = TFI.getStackAlignment();
1435 uint64_t AlignMask = StackAlignment - 1;
1436 int64_t Offset = StackSize;
1437 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1438 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1439 // Number smaller than 12 so just add the difference.
1440 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1441 } else {
1442 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1443 Offset = ((~AlignMask) & Offset) + StackAlignment +
1444 (StackAlignment-SlotSize);
1445 }
1446 StackSize = Offset;
1447 }
1448 return StackSize;
1449}
1450
1451/// IsEligibleForTailCallElimination - Check to see whether the next instruction
1452// following the call is a return. A function is eligible if caller/callee
1453// calling conventions match, currently only fastcc supports tail calls, and the
1454// function CALL is immediatly followed by a RET.
1455bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1456 SDOperand Ret,
1457 SelectionDAG& DAG) const {
1458 bool IsEligible = false;
1459
1460 // Check whether CALL node immediatly preceeds the RET node and whether the
1461 // return uses the result of the node or is a void return.
1462 if ((Ret.getNumOperands() == 1 &&
1463 (Ret.getOperand(0)== SDOperand(Call.Val,1) ||
1464 Ret.getOperand(0)== SDOperand(Call.Val,0))) ||
1465 (Ret.getOperand(0)== SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1466 Ret.getOperand(1)== SDOperand(Call.Val,0))) {
1467 MachineFunction &MF = DAG.getMachineFunction();
1468 unsigned CallerCC = MF.getFunction()->getCallingConv();
1469 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1470 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1471 SDOperand Callee = Call.getOperand(4);
1472 // On elf/pic %ebx needs to be livein.
1473 if(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1474 Subtarget->isPICStyleGOT()) {
1475 // Can only do local tail calls with PIC.
1476 GlobalValue * GV = 0;
1477 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1478 if(G != 0 &&
1479 (GV = G->getGlobal()) &&
1480 (GV->hasHiddenVisibility() || GV->hasProtectedVisibility()))
1481 IsEligible=true;
1482 } else {
1483 IsEligible=true;
1484 }
1485 }
1486 }
1487 return IsEligible;
1488}
1489
1490SDOperand X86TargetLowering::LowerX86_TailCallTo(SDOperand Op,
1491 SelectionDAG &DAG,
1492 unsigned CC) {
1493 SDOperand Chain = Op.getOperand(0);
1494 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1495 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1496 SDOperand Callee = Op.getOperand(4);
1497 bool is64Bit = Subtarget->is64Bit();
1498
1499 assert(isTailCall && PerformTailCallOpt && "Should only emit tail calls.");
1500
1501 // Analyze operands of the call, assigning locations to each operand.
1502 SmallVector<CCValAssign, 16> ArgLocs;
1503 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1504 if (is64Bit)
1505 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1506 else
1507 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1508
1509
1510 // Lower arguments at fp - stackoffset + fpdiff.
1511 MachineFunction &MF = DAG.getMachineFunction();
1512
1513 unsigned NumBytesToBePushed =
1514 GetAlignedArgumentStackSize(CCInfo.getNextStackOffset(), DAG);
1515
1516 unsigned NumBytesCallerPushed =
1517 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1518 int FPDiff = NumBytesCallerPushed - NumBytesToBePushed;
1519
1520 // Set the delta of movement of the returnaddr stackslot.
1521 // But only set if delta is greater than previous delta.
1522 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1523 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1524
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001525 Chain = DAG.
1526 getCALLSEQ_START(Chain, DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1527
1528 // Adjust the Return address stack slot.
1529 SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001530 if (FPDiff) {
1531 MVT::ValueType VT = is64Bit ? MVT::i64 : MVT::i32;
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001532 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1533 // Load the "old" Return address.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001534 RetAddrFrIdx =
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001535 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1536 // Calculate the new stack slot for the return address.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001537 int SlotSize = is64Bit ? 8 : 4;
1538 int NewReturnAddrFI =
1539 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001540 NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1541 Chain = SDOperand(RetAddrFrIdx.Val, 1);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001542 }
1543
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001544 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1545 SmallVector<SDOperand, 8> MemOpChains;
1546 SmallVector<SDOperand, 8> MemOpChains2;
1547 SDOperand FramePtr, StackPtr;
1548 SDOperand PtrOff;
1549 SDOperand FIN;
1550 int FI = 0;
1551
1552 // Walk the register/memloc assignments, inserting copies/loads. Lower
1553 // arguments first to the stack slot where they would normally - in case of a
1554 // normal function call - be.
1555 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1556 CCValAssign &VA = ArgLocs[i];
1557 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1558
1559 // Promote the value if needed.
1560 switch (VA.getLocInfo()) {
1561 default: assert(0 && "Unknown loc info!");
1562 case CCValAssign::Full: break;
1563 case CCValAssign::SExt:
1564 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1565 break;
1566 case CCValAssign::ZExt:
1567 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1568 break;
1569 case CCValAssign::AExt:
1570 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1571 break;
1572 }
1573
1574 if (VA.isRegLoc()) {
1575 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1576 } else {
1577 assert(VA.isMemLoc());
1578 if (StackPtr.Val == 0)
1579 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1580
1581 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1582 Arg));
1583 }
1584 }
1585
1586 if (!MemOpChains.empty())
1587 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1588 &MemOpChains[0], MemOpChains.size());
1589
1590 // Build a sequence of copy-to-reg nodes chained together with token chain
1591 // and flag operands which copy the outgoing args into registers.
1592 SDOperand InFlag;
1593 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1594 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1595 InFlag);
1596 InFlag = Chain.getValue(1);
1597 }
1598 InFlag = SDOperand();
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001599
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001600 // Copy from stack slots to stack slot of a tail called function. This needs
1601 // to be done because if we would lower the arguments directly to their real
1602 // stack slot we might end up overwriting each other.
1603 // TODO: To make this more efficient (sometimes saving a store/load) we could
1604 // analyse the arguments and emit this store/load/store sequence only for
1605 // arguments which would be overwritten otherwise.
1606 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1607 CCValAssign &VA = ArgLocs[i];
1608 if (!VA.isRegLoc()) {
1609 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1610 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1611
1612 // Get source stack slot.
1613 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1614 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1615 // Create frame index.
1616 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1617 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1618 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1619 FIN = DAG.getFrameIndex(FI, MVT::i32);
1620 if (Flags & ISD::ParamFlags::ByVal) {
1621 // Copy relative to framepointer.
1622 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1623 ISD::ParamFlags::ByValAlignOffs);
1624
1625 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1626 ISD::ParamFlags::ByValSizeOffs;
1627
1628 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1629 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1630 // Copy relative to framepointer.
1631 MemOpChains2.push_back(DAG.getNode(ISD::MEMCPY, MVT::Other, Chain, FIN,
1632 PtrOff, SizeNode, AlignNode));
1633 } else {
1634 SDOperand LoadedArg = DAG.getLoad(VA.getValVT(), Chain, PtrOff, NULL,0);
1635 // Store relative to framepointer.
1636 MemOpChains2.push_back(DAG.getStore(Chain, LoadedArg, FIN, NULL, 0));
1637 }
1638 }
1639 }
1640
1641 if (!MemOpChains2.empty())
1642 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1643 &MemOpChains2[0], MemOpChains.size());
1644
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001645 // Store the return address to the appropriate stack slot.
1646 if (FPDiff)
1647 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1648
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001649 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1650 // GOT pointer.
1651 // Does not work with tail call since ebx is not restored correctly by
1652 // tailcaller. TODO: at least for x86 - verify for x86-64
1653
1654 // If the callee is a GlobalAddress node (quite common, every direct call is)
1655 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1656 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1657 // We should use extra load for direct calls to dllimported functions in
1658 // non-JIT mode.
1659 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1660 getTargetMachine(), true))
1661 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1662 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1663 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1664 else {
1665 assert(Callee.getOpcode() == ISD::LOAD &&
1666 "Function destination must be loaded into virtual register");
1667 unsigned Opc = is64Bit ? X86::R9 : X86::ECX;
1668
1669 Chain = DAG.getCopyToReg(Chain,
1670 DAG.getRegister(Opc, getPointerTy()) ,
1671 Callee,InFlag);
1672 Callee = DAG.getRegister(Opc, getPointerTy());
1673 // Add register as live out.
1674 DAG.getMachineFunction().addLiveOut(Opc);
1675 }
1676
1677 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1678 SmallVector<SDOperand, 8> Ops;
1679
1680 Ops.push_back(Chain);
1681 Ops.push_back(DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1682 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1683 if (InFlag.Val)
1684 Ops.push_back(InFlag);
1685 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1686 InFlag = Chain.getValue(1);
1687
1688 // Returns a chain & a flag for retval copy to use.
1689 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1690 Ops.clear();
1691 Ops.push_back(Chain);
1692 Ops.push_back(Callee);
1693 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1694 // Add argument registers to the end of the list so that they are known live
1695 // into the call.
1696 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1697 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1698 RegsToPass[i].second.getValueType()));
1699 if (InFlag.Val)
1700 Ops.push_back(InFlag);
1701 assert(InFlag.Val &&
1702 "Flag must be set. Depend on flag being set in LowerRET");
1703 Chain = DAG.getNode(X86ISD::TAILCALL,
1704 Op.Val->getVTList(), &Ops[0], Ops.size());
1705
1706 return SDOperand(Chain.Val, Op.ResNo);
1707}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001708
1709//===----------------------------------------------------------------------===//
1710// X86-64 C Calling Convention implementation
1711//===----------------------------------------------------------------------===//
1712
1713SDOperand
1714X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1715 MachineFunction &MF = DAG.getMachineFunction();
1716 MachineFrameInfo *MFI = MF.getFrameInfo();
1717 SDOperand Root = Op.getOperand(0);
1718 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001719 unsigned CC= MF.getFunction()->getCallingConv();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001720
1721 static const unsigned GPR64ArgRegs[] = {
1722 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1723 };
1724 static const unsigned XMMArgRegs[] = {
1725 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1726 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1727 };
1728
1729
1730 // Assign locations to all of the incoming arguments.
1731 SmallVector<CCValAssign, 16> ArgLocs;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001732 CCState CCInfo(CC, isVarArg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001733 getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001734 if (CC == CallingConv::Fast && PerformTailCallOpt)
1735 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_TailCall);
1736 else
1737 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738
1739 SmallVector<SDOperand, 8> ArgValues;
1740 unsigned LastVal = ~0U;
1741 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1742 CCValAssign &VA = ArgLocs[i];
1743 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1744 // places.
1745 assert(VA.getValNo() != LastVal &&
1746 "Don't support value assigned to multiple locs yet");
1747 LastVal = VA.getValNo();
1748
1749 if (VA.isRegLoc()) {
1750 MVT::ValueType RegVT = VA.getLocVT();
1751 TargetRegisterClass *RC;
1752 if (RegVT == MVT::i32)
1753 RC = X86::GR32RegisterClass;
1754 else if (RegVT == MVT::i64)
1755 RC = X86::GR64RegisterClass;
1756 else if (RegVT == MVT::f32)
1757 RC = X86::FR32RegisterClass;
1758 else if (RegVT == MVT::f64)
1759 RC = X86::FR64RegisterClass;
1760 else {
1761 assert(MVT::isVector(RegVT));
1762 if (MVT::getSizeInBits(RegVT) == 64) {
1763 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1764 RegVT = MVT::i64;
1765 } else
1766 RC = X86::VR128RegisterClass;
1767 }
1768
1769 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1770 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1771
1772 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1773 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1774 // right size.
1775 if (VA.getLocInfo() == CCValAssign::SExt)
1776 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1777 DAG.getValueType(VA.getValVT()));
1778 else if (VA.getLocInfo() == CCValAssign::ZExt)
1779 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1780 DAG.getValueType(VA.getValVT()));
1781
1782 if (VA.getLocInfo() != CCValAssign::Full)
1783 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1784
1785 // Handle MMX values passed in GPRs.
1786 if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1787 MVT::getSizeInBits(RegVT) == 64)
1788 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1789
1790 ArgValues.push_back(ArgValue);
1791 } else {
1792 assert(VA.isMemLoc());
Rafael Espindola03cbeb72007-09-14 15:48:13 +00001793 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001794 }
1795 }
1796
1797 unsigned StackSize = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001798 if (CC==CallingConv::Fast)
1799 StackSize =GetAlignedArgumentStackSize(StackSize, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001800
1801 // If the function takes variable number of arguments, make a frame index for
1802 // the start of the first vararg value... for expansion of llvm.va_start.
1803 if (isVarArg) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001804 assert(CC!=CallingConv::Fast
1805 && "Var arg not supported with calling convention fastcc");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001806 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1807 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1808
1809 // For X86-64, if there are vararg parameters that are passed via
1810 // registers, then we must store them to their spots on the stack so they
1811 // may be loaded by deferencing the result of va_next.
1812 VarArgsGPOffset = NumIntRegs * 8;
1813 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1814 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1815 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1816
1817 // Store the integer parameter registers.
1818 SmallVector<SDOperand, 8> MemOps;
1819 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1820 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1821 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1822 for (; NumIntRegs != 6; ++NumIntRegs) {
1823 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1824 X86::GR64RegisterClass);
1825 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1826 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1827 MemOps.push_back(Store);
1828 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1829 DAG.getConstant(8, getPointerTy()));
1830 }
1831
1832 // Now store the XMM (fp + vector) parameter registers.
1833 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1834 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1835 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1836 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1837 X86::VR128RegisterClass);
1838 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1839 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1840 MemOps.push_back(Store);
1841 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1842 DAG.getConstant(16, getPointerTy()));
1843 }
1844 if (!MemOps.empty())
1845 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1846 &MemOps[0], MemOps.size());
1847 }
1848
1849 ArgValues.push_back(Root);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001850 // Tail call convention (fastcc) needs callee pop.
Evan Cheng778fa0f2007-10-14 10:09:39 +00001851 if (CC == CallingConv::Fast && PerformTailCallOpt) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001852 BytesToPopOnReturn = StackSize; // Callee pops everything.
1853 BytesCallerReserves = 0;
1854 } else {
1855 BytesToPopOnReturn = 0; // Callee pops nothing.
1856 BytesCallerReserves = StackSize;
1857 }
Anton Korobeynikove844e472007-08-15 17:12:32 +00001858 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1859 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1860
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001861 // Return the new list of results.
1862 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1863 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1864}
1865
1866SDOperand
1867X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1868 unsigned CC) {
1869 SDOperand Chain = Op.getOperand(0);
1870 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001871 SDOperand Callee = Op.getOperand(4);
1872
1873 // Analyze operands of the call, assigning locations to each operand.
1874 SmallVector<CCValAssign, 16> ArgLocs;
1875 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Evan Cheng778fa0f2007-10-14 10:09:39 +00001876 if (CC==CallingConv::Fast && PerformTailCallOpt)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001877 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1878 else
1879 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001880
1881 // Get a count of how many bytes are to be pushed on the stack.
1882 unsigned NumBytes = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001883 if (CC == CallingConv::Fast)
1884 NumBytes = GetAlignedArgumentStackSize(NumBytes,DAG);
1885
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001886 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1887
1888 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1889 SmallVector<SDOperand, 8> MemOpChains;
1890
1891 SDOperand StackPtr;
1892
1893 // Walk the register/memloc assignments, inserting copies/loads.
1894 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1895 CCValAssign &VA = ArgLocs[i];
1896 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1897
1898 // Promote the value if needed.
1899 switch (VA.getLocInfo()) {
1900 default: assert(0 && "Unknown loc info!");
1901 case CCValAssign::Full: break;
1902 case CCValAssign::SExt:
1903 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1904 break;
1905 case CCValAssign::ZExt:
1906 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1907 break;
1908 case CCValAssign::AExt:
1909 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1910 break;
1911 }
1912
1913 if (VA.isRegLoc()) {
1914 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1915 } else {
1916 assert(VA.isMemLoc());
1917 if (StackPtr.Val == 0)
1918 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindolab8bcfcd2007-08-20 15:18:24 +00001919
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001920 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1921 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001922 }
1923 }
1924
1925 if (!MemOpChains.empty())
1926 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1927 &MemOpChains[0], MemOpChains.size());
1928
1929 // Build a sequence of copy-to-reg nodes chained together with token chain
1930 // and flag operands which copy the outgoing args into registers.
1931 SDOperand InFlag;
1932 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1933 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1934 InFlag);
1935 InFlag = Chain.getValue(1);
1936 }
1937
1938 if (isVarArg) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001939 assert ( CallingConv::Fast != CC &&
1940 "Var args not supported with calling convention fastcc");
1941
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001942 // From AMD64 ABI document:
1943 // For calls that may call functions that use varargs or stdargs
1944 // (prototype-less calls or calls to functions containing ellipsis (...) in
1945 // the declaration) %al is used as hidden argument to specify the number
1946 // of SSE registers used. The contents of %al do not need to match exactly
1947 // the number of registers, but must be an ubound on the number of SSE
1948 // registers used and is in the range 0 - 8 inclusive.
1949
1950 // Count the number of XMM registers allocated.
1951 static const unsigned XMMArgRegs[] = {
1952 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1953 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1954 };
1955 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1956
1957 Chain = DAG.getCopyToReg(Chain, X86::AL,
1958 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1959 InFlag = Chain.getValue(1);
1960 }
1961
1962 // If the callee is a GlobalAddress node (quite common, every direct call is)
1963 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1964 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1965 // We should use extra load for direct calls to dllimported functions in
1966 // non-JIT mode.
1967 if (getTargetMachine().getCodeModel() != CodeModel::Large
1968 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1969 getTargetMachine(), true))
1970 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1971 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1972 if (getTargetMachine().getCodeModel() != CodeModel::Large)
1973 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1974
1975 // Returns a chain & a flag for retval copy to use.
1976 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1977 SmallVector<SDOperand, 8> Ops;
1978 Ops.push_back(Chain);
1979 Ops.push_back(Callee);
1980
1981 // Add argument registers to the end of the list so that they are known live
1982 // into the call.
1983 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1984 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1985 RegsToPass[i].second.getValueType()));
1986
1987 if (InFlag.Val)
1988 Ops.push_back(InFlag);
1989
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001990 Chain = DAG.getNode(X86ISD::CALL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001991 NodeTys, &Ops[0], Ops.size());
1992 InFlag = Chain.getValue(1);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001993 int NumBytesForCalleeToPush = 0;
Evan Cheng778fa0f2007-10-14 10:09:39 +00001994 if (CC==CallingConv::Fast && PerformTailCallOpt) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001995 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001996 } else {
1997 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1998 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001999 // Returns a flag for retval copy to use.
2000 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2001 Ops.clear();
2002 Ops.push_back(Chain);
2003 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002004 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002005 Ops.push_back(InFlag);
2006 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
2007 InFlag = Chain.getValue(1);
2008
2009 // Handle result values, copying them out of physregs into vregs that we
2010 // return.
2011 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
2012}
2013
2014
2015//===----------------------------------------------------------------------===//
2016// Other Lowering Hooks
2017//===----------------------------------------------------------------------===//
2018
2019
2020SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
Anton Korobeynikove844e472007-08-15 17:12:32 +00002021 MachineFunction &MF = DAG.getMachineFunction();
2022 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2023 int ReturnAddrIndex = FuncInfo->getRAIndex();
2024
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002025 if (ReturnAddrIndex == 0) {
2026 // Set up a frame object for the return address.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002027 if (Subtarget->is64Bit())
2028 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
2029 else
2030 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
Anton Korobeynikove844e472007-08-15 17:12:32 +00002031
2032 FuncInfo->setRAIndex(ReturnAddrIndex);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002033 }
2034
2035 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2036}
2037
2038
2039
2040/// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
2041/// specific condition code. It returns a false if it cannot do a direct
2042/// translation. X86CC is the translated CondCode. LHS/RHS are modified as
2043/// needed.
2044static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2045 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
2046 SelectionDAG &DAG) {
2047 X86CC = X86::COND_INVALID;
2048 if (!isFP) {
2049 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2050 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2051 // X > -1 -> X == 0, jump !sign.
2052 RHS = DAG.getConstant(0, RHS.getValueType());
2053 X86CC = X86::COND_NS;
2054 return true;
2055 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2056 // X < 0 -> X == 0, jump on sign.
2057 X86CC = X86::COND_S;
2058 return true;
Dan Gohman37b34262007-09-17 14:49:27 +00002059 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
2060 // X < 1 -> X <= 0
2061 RHS = DAG.getConstant(0, RHS.getValueType());
2062 X86CC = X86::COND_LE;
2063 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002064 }
2065 }
2066
2067 switch (SetCCOpcode) {
2068 default: break;
2069 case ISD::SETEQ: X86CC = X86::COND_E; break;
2070 case ISD::SETGT: X86CC = X86::COND_G; break;
2071 case ISD::SETGE: X86CC = X86::COND_GE; break;
2072 case ISD::SETLT: X86CC = X86::COND_L; break;
2073 case ISD::SETLE: X86CC = X86::COND_LE; break;
2074 case ISD::SETNE: X86CC = X86::COND_NE; break;
2075 case ISD::SETULT: X86CC = X86::COND_B; break;
2076 case ISD::SETUGT: X86CC = X86::COND_A; break;
2077 case ISD::SETULE: X86CC = X86::COND_BE; break;
2078 case ISD::SETUGE: X86CC = X86::COND_AE; break;
2079 }
2080 } else {
2081 // On a floating point condition, the flags are set as follows:
2082 // ZF PF CF op
2083 // 0 | 0 | 0 | X > Y
2084 // 0 | 0 | 1 | X < Y
2085 // 1 | 0 | 0 | X == Y
2086 // 1 | 1 | 1 | unordered
2087 bool Flip = false;
2088 switch (SetCCOpcode) {
2089 default: break;
2090 case ISD::SETUEQ:
2091 case ISD::SETEQ: X86CC = X86::COND_E; break;
2092 case ISD::SETOLT: Flip = true; // Fallthrough
2093 case ISD::SETOGT:
2094 case ISD::SETGT: X86CC = X86::COND_A; break;
2095 case ISD::SETOLE: Flip = true; // Fallthrough
2096 case ISD::SETOGE:
2097 case ISD::SETGE: X86CC = X86::COND_AE; break;
2098 case ISD::SETUGT: Flip = true; // Fallthrough
2099 case ISD::SETULT:
2100 case ISD::SETLT: X86CC = X86::COND_B; break;
2101 case ISD::SETUGE: Flip = true; // Fallthrough
2102 case ISD::SETULE:
2103 case ISD::SETLE: X86CC = X86::COND_BE; break;
2104 case ISD::SETONE:
2105 case ISD::SETNE: X86CC = X86::COND_NE; break;
2106 case ISD::SETUO: X86CC = X86::COND_P; break;
2107 case ISD::SETO: X86CC = X86::COND_NP; break;
2108 }
2109 if (Flip)
2110 std::swap(LHS, RHS);
2111 }
2112
2113 return X86CC != X86::COND_INVALID;
2114}
2115
2116/// hasFPCMov - is there a floating point cmov for the specific X86 condition
2117/// code. Current x86 isa includes the following FP cmov instructions:
2118/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2119static bool hasFPCMov(unsigned X86CC) {
2120 switch (X86CC) {
2121 default:
2122 return false;
2123 case X86::COND_B:
2124 case X86::COND_BE:
2125 case X86::COND_E:
2126 case X86::COND_P:
2127 case X86::COND_A:
2128 case X86::COND_AE:
2129 case X86::COND_NE:
2130 case X86::COND_NP:
2131 return true;
2132 }
2133}
2134
2135/// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2136/// true if Op is undef or if its value falls within the specified range (L, H].
2137static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2138 if (Op.getOpcode() == ISD::UNDEF)
2139 return true;
2140
2141 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2142 return (Val >= Low && Val < Hi);
2143}
2144
2145/// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2146/// true if Op is undef or if its value equal to the specified value.
2147static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2148 if (Op.getOpcode() == ISD::UNDEF)
2149 return true;
2150 return cast<ConstantSDNode>(Op)->getValue() == Val;
2151}
2152
2153/// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2154/// specifies a shuffle of elements that is suitable for input to PSHUFD.
2155bool X86::isPSHUFDMask(SDNode *N) {
2156 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2157
Dan Gohman7dc19012007-08-02 21:17:01 +00002158 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002159 return false;
2160
2161 // Check if the value doesn't reference the second vector.
2162 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2163 SDOperand Arg = N->getOperand(i);
2164 if (Arg.getOpcode() == ISD::UNDEF) continue;
2165 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Dan Gohman7dc19012007-08-02 21:17:01 +00002166 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002167 return false;
2168 }
2169
2170 return true;
2171}
2172
2173/// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2174/// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2175bool X86::isPSHUFHWMask(SDNode *N) {
2176 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2177
2178 if (N->getNumOperands() != 8)
2179 return false;
2180
2181 // Lower quadword copied in order.
2182 for (unsigned i = 0; i != 4; ++i) {
2183 SDOperand Arg = N->getOperand(i);
2184 if (Arg.getOpcode() == ISD::UNDEF) continue;
2185 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2186 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2187 return false;
2188 }
2189
2190 // Upper quadword shuffled.
2191 for (unsigned i = 4; i != 8; ++i) {
2192 SDOperand Arg = N->getOperand(i);
2193 if (Arg.getOpcode() == ISD::UNDEF) continue;
2194 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2195 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2196 if (Val < 4 || Val > 7)
2197 return false;
2198 }
2199
2200 return true;
2201}
2202
2203/// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2204/// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2205bool X86::isPSHUFLWMask(SDNode *N) {
2206 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2207
2208 if (N->getNumOperands() != 8)
2209 return false;
2210
2211 // Upper quadword copied in order.
2212 for (unsigned i = 4; i != 8; ++i)
2213 if (!isUndefOrEqual(N->getOperand(i), i))
2214 return false;
2215
2216 // Lower quadword shuffled.
2217 for (unsigned i = 0; i != 4; ++i)
2218 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2219 return false;
2220
2221 return true;
2222}
2223
2224/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2225/// specifies a shuffle of elements that is suitable for input to SHUFP*.
2226static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2227 if (NumElems != 2 && NumElems != 4) return false;
2228
2229 unsigned Half = NumElems / 2;
2230 for (unsigned i = 0; i < Half; ++i)
2231 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2232 return false;
2233 for (unsigned i = Half; i < NumElems; ++i)
2234 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2235 return false;
2236
2237 return true;
2238}
2239
2240bool X86::isSHUFPMask(SDNode *N) {
2241 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2242 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2243}
2244
2245/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2246/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2247/// half elements to come from vector 1 (which would equal the dest.) and
2248/// the upper half to come from vector 2.
2249static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2250 if (NumOps != 2 && NumOps != 4) return false;
2251
2252 unsigned Half = NumOps / 2;
2253 for (unsigned i = 0; i < Half; ++i)
2254 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2255 return false;
2256 for (unsigned i = Half; i < NumOps; ++i)
2257 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2258 return false;
2259 return true;
2260}
2261
2262static bool isCommutedSHUFP(SDNode *N) {
2263 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2264 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2265}
2266
2267/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2268/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2269bool X86::isMOVHLPSMask(SDNode *N) {
2270 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2271
2272 if (N->getNumOperands() != 4)
2273 return false;
2274
2275 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2276 return isUndefOrEqual(N->getOperand(0), 6) &&
2277 isUndefOrEqual(N->getOperand(1), 7) &&
2278 isUndefOrEqual(N->getOperand(2), 2) &&
2279 isUndefOrEqual(N->getOperand(3), 3);
2280}
2281
2282/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2283/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2284/// <2, 3, 2, 3>
2285bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2286 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2287
2288 if (N->getNumOperands() != 4)
2289 return false;
2290
2291 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2292 return isUndefOrEqual(N->getOperand(0), 2) &&
2293 isUndefOrEqual(N->getOperand(1), 3) &&
2294 isUndefOrEqual(N->getOperand(2), 2) &&
2295 isUndefOrEqual(N->getOperand(3), 3);
2296}
2297
2298/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2299/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2300bool X86::isMOVLPMask(SDNode *N) {
2301 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2302
2303 unsigned NumElems = N->getNumOperands();
2304 if (NumElems != 2 && NumElems != 4)
2305 return false;
2306
2307 for (unsigned i = 0; i < NumElems/2; ++i)
2308 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2309 return false;
2310
2311 for (unsigned i = NumElems/2; i < NumElems; ++i)
2312 if (!isUndefOrEqual(N->getOperand(i), i))
2313 return false;
2314
2315 return true;
2316}
2317
2318/// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2319/// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2320/// and MOVLHPS.
2321bool X86::isMOVHPMask(SDNode *N) {
2322 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2323
2324 unsigned NumElems = N->getNumOperands();
2325 if (NumElems != 2 && NumElems != 4)
2326 return false;
2327
2328 for (unsigned i = 0; i < NumElems/2; ++i)
2329 if (!isUndefOrEqual(N->getOperand(i), i))
2330 return false;
2331
2332 for (unsigned i = 0; i < NumElems/2; ++i) {
2333 SDOperand Arg = N->getOperand(i + NumElems/2);
2334 if (!isUndefOrEqual(Arg, i + NumElems))
2335 return false;
2336 }
2337
2338 return true;
2339}
2340
2341/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2342/// specifies a shuffle of elements that is suitable for input to UNPCKL.
2343bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2344 bool V2IsSplat = false) {
2345 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2346 return false;
2347
2348 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2349 SDOperand BitI = Elts[i];
2350 SDOperand BitI1 = Elts[i+1];
2351 if (!isUndefOrEqual(BitI, j))
2352 return false;
2353 if (V2IsSplat) {
2354 if (isUndefOrEqual(BitI1, NumElts))
2355 return false;
2356 } else {
2357 if (!isUndefOrEqual(BitI1, j + NumElts))
2358 return false;
2359 }
2360 }
2361
2362 return true;
2363}
2364
2365bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2366 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2367 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2368}
2369
2370/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2371/// specifies a shuffle of elements that is suitable for input to UNPCKH.
2372bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2373 bool V2IsSplat = false) {
2374 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2375 return false;
2376
2377 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2378 SDOperand BitI = Elts[i];
2379 SDOperand BitI1 = Elts[i+1];
2380 if (!isUndefOrEqual(BitI, j + NumElts/2))
2381 return false;
2382 if (V2IsSplat) {
2383 if (isUndefOrEqual(BitI1, NumElts))
2384 return false;
2385 } else {
2386 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2387 return false;
2388 }
2389 }
2390
2391 return true;
2392}
2393
2394bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2395 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2396 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2397}
2398
2399/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2400/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2401/// <0, 0, 1, 1>
2402bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2403 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2404
2405 unsigned NumElems = N->getNumOperands();
2406 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2407 return false;
2408
2409 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2410 SDOperand BitI = N->getOperand(i);
2411 SDOperand BitI1 = N->getOperand(i+1);
2412
2413 if (!isUndefOrEqual(BitI, j))
2414 return false;
2415 if (!isUndefOrEqual(BitI1, j))
2416 return false;
2417 }
2418
2419 return true;
2420}
2421
2422/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2423/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2424/// <2, 2, 3, 3>
2425bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2426 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2427
2428 unsigned NumElems = N->getNumOperands();
2429 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2430 return false;
2431
2432 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2433 SDOperand BitI = N->getOperand(i);
2434 SDOperand BitI1 = N->getOperand(i + 1);
2435
2436 if (!isUndefOrEqual(BitI, j))
2437 return false;
2438 if (!isUndefOrEqual(BitI1, j))
2439 return false;
2440 }
2441
2442 return true;
2443}
2444
2445/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2446/// specifies a shuffle of elements that is suitable for input to MOVSS,
2447/// MOVSD, and MOVD, i.e. setting the lowest element.
2448static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2449 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2450 return false;
2451
2452 if (!isUndefOrEqual(Elts[0], NumElts))
2453 return false;
2454
2455 for (unsigned i = 1; i < NumElts; ++i) {
2456 if (!isUndefOrEqual(Elts[i], i))
2457 return false;
2458 }
2459
2460 return true;
2461}
2462
2463bool X86::isMOVLMask(SDNode *N) {
2464 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2465 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2466}
2467
2468/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2469/// of what x86 movss want. X86 movs requires the lowest element to be lowest
2470/// element of vector 2 and the other elements to come from vector 1 in order.
2471static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2472 bool V2IsSplat = false,
2473 bool V2IsUndef = false) {
2474 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2475 return false;
2476
2477 if (!isUndefOrEqual(Ops[0], 0))
2478 return false;
2479
2480 for (unsigned i = 1; i < NumOps; ++i) {
2481 SDOperand Arg = Ops[i];
2482 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2483 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2484 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2485 return false;
2486 }
2487
2488 return true;
2489}
2490
2491static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2492 bool V2IsUndef = false) {
2493 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2494 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2495 V2IsSplat, V2IsUndef);
2496}
2497
2498/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2499/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2500bool X86::isMOVSHDUPMask(SDNode *N) {
2501 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2502
2503 if (N->getNumOperands() != 4)
2504 return false;
2505
2506 // Expect 1, 1, 3, 3
2507 for (unsigned i = 0; i < 2; ++i) {
2508 SDOperand Arg = N->getOperand(i);
2509 if (Arg.getOpcode() == ISD::UNDEF) continue;
2510 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2511 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2512 if (Val != 1) return false;
2513 }
2514
2515 bool HasHi = false;
2516 for (unsigned i = 2; i < 4; ++i) {
2517 SDOperand Arg = N->getOperand(i);
2518 if (Arg.getOpcode() == ISD::UNDEF) continue;
2519 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2520 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2521 if (Val != 3) return false;
2522 HasHi = true;
2523 }
2524
2525 // Don't use movshdup if it can be done with a shufps.
2526 return HasHi;
2527}
2528
2529/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2530/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2531bool X86::isMOVSLDUPMask(SDNode *N) {
2532 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2533
2534 if (N->getNumOperands() != 4)
2535 return false;
2536
2537 // Expect 0, 0, 2, 2
2538 for (unsigned i = 0; i < 2; ++i) {
2539 SDOperand Arg = N->getOperand(i);
2540 if (Arg.getOpcode() == ISD::UNDEF) continue;
2541 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2542 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2543 if (Val != 0) return false;
2544 }
2545
2546 bool HasHi = false;
2547 for (unsigned i = 2; i < 4; ++i) {
2548 SDOperand Arg = N->getOperand(i);
2549 if (Arg.getOpcode() == ISD::UNDEF) continue;
2550 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2551 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2552 if (Val != 2) return false;
2553 HasHi = true;
2554 }
2555
2556 // Don't use movshdup if it can be done with a shufps.
2557 return HasHi;
2558}
2559
2560/// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2561/// specifies a identity operation on the LHS or RHS.
2562static bool isIdentityMask(SDNode *N, bool RHS = false) {
2563 unsigned NumElems = N->getNumOperands();
2564 for (unsigned i = 0; i < NumElems; ++i)
2565 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2566 return false;
2567 return true;
2568}
2569
2570/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2571/// a splat of a single element.
2572static bool isSplatMask(SDNode *N) {
2573 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2574
2575 // This is a splat operation if each element of the permute is the same, and
2576 // if the value doesn't reference the second vector.
2577 unsigned NumElems = N->getNumOperands();
2578 SDOperand ElementBase;
2579 unsigned i = 0;
2580 for (; i != NumElems; ++i) {
2581 SDOperand Elt = N->getOperand(i);
2582 if (isa<ConstantSDNode>(Elt)) {
2583 ElementBase = Elt;
2584 break;
2585 }
2586 }
2587
2588 if (!ElementBase.Val)
2589 return false;
2590
2591 for (; i != NumElems; ++i) {
2592 SDOperand Arg = N->getOperand(i);
2593 if (Arg.getOpcode() == ISD::UNDEF) continue;
2594 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2595 if (Arg != ElementBase) return false;
2596 }
2597
2598 // Make sure it is a splat of the first vector operand.
2599 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2600}
2601
2602/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2603/// a splat of a single element and it's a 2 or 4 element mask.
2604bool X86::isSplatMask(SDNode *N) {
2605 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2606
2607 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2608 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2609 return false;
2610 return ::isSplatMask(N);
2611}
2612
2613/// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2614/// specifies a splat of zero element.
2615bool X86::isSplatLoMask(SDNode *N) {
2616 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2617
2618 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2619 if (!isUndefOrEqual(N->getOperand(i), 0))
2620 return false;
2621 return true;
2622}
2623
2624/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2625/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2626/// instructions.
2627unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2628 unsigned NumOperands = N->getNumOperands();
2629 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2630 unsigned Mask = 0;
2631 for (unsigned i = 0; i < NumOperands; ++i) {
2632 unsigned Val = 0;
2633 SDOperand Arg = N->getOperand(NumOperands-i-1);
2634 if (Arg.getOpcode() != ISD::UNDEF)
2635 Val = cast<ConstantSDNode>(Arg)->getValue();
2636 if (Val >= NumOperands) Val -= NumOperands;
2637 Mask |= Val;
2638 if (i != NumOperands - 1)
2639 Mask <<= Shift;
2640 }
2641
2642 return Mask;
2643}
2644
2645/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2646/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2647/// instructions.
2648unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2649 unsigned Mask = 0;
2650 // 8 nodes, but we only care about the last 4.
2651 for (unsigned i = 7; i >= 4; --i) {
2652 unsigned Val = 0;
2653 SDOperand Arg = N->getOperand(i);
2654 if (Arg.getOpcode() != ISD::UNDEF)
2655 Val = cast<ConstantSDNode>(Arg)->getValue();
2656 Mask |= (Val - 4);
2657 if (i != 4)
2658 Mask <<= 2;
2659 }
2660
2661 return Mask;
2662}
2663
2664/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2665/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2666/// instructions.
2667unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2668 unsigned Mask = 0;
2669 // 8 nodes, but we only care about the first 4.
2670 for (int i = 3; i >= 0; --i) {
2671 unsigned Val = 0;
2672 SDOperand Arg = N->getOperand(i);
2673 if (Arg.getOpcode() != ISD::UNDEF)
2674 Val = cast<ConstantSDNode>(Arg)->getValue();
2675 Mask |= Val;
2676 if (i != 0)
2677 Mask <<= 2;
2678 }
2679
2680 return Mask;
2681}
2682
2683/// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2684/// specifies a 8 element shuffle that can be broken into a pair of
2685/// PSHUFHW and PSHUFLW.
2686static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2687 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2688
2689 if (N->getNumOperands() != 8)
2690 return false;
2691
2692 // Lower quadword shuffled.
2693 for (unsigned i = 0; i != 4; ++i) {
2694 SDOperand Arg = N->getOperand(i);
2695 if (Arg.getOpcode() == ISD::UNDEF) continue;
2696 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2697 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2698 if (Val > 4)
2699 return false;
2700 }
2701
2702 // Upper quadword shuffled.
2703 for (unsigned i = 4; i != 8; ++i) {
2704 SDOperand Arg = N->getOperand(i);
2705 if (Arg.getOpcode() == ISD::UNDEF) continue;
2706 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2707 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2708 if (Val < 4 || Val > 7)
2709 return false;
2710 }
2711
2712 return true;
2713}
2714
2715/// CommuteVectorShuffle - Swap vector_shuffle operandsas well as
2716/// values in ther permute mask.
2717static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2718 SDOperand &V2, SDOperand &Mask,
2719 SelectionDAG &DAG) {
2720 MVT::ValueType VT = Op.getValueType();
2721 MVT::ValueType MaskVT = Mask.getValueType();
2722 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2723 unsigned NumElems = Mask.getNumOperands();
2724 SmallVector<SDOperand, 8> MaskVec;
2725
2726 for (unsigned i = 0; i != NumElems; ++i) {
2727 SDOperand Arg = Mask.getOperand(i);
2728 if (Arg.getOpcode() == ISD::UNDEF) {
2729 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2730 continue;
2731 }
2732 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2733 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2734 if (Val < NumElems)
2735 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2736 else
2737 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2738 }
2739
2740 std::swap(V1, V2);
2741 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2742 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2743}
2744
2745/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2746/// match movhlps. The lower half elements should come from upper half of
2747/// V1 (and in order), and the upper half elements should come from the upper
2748/// half of V2 (and in order).
2749static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2750 unsigned NumElems = Mask->getNumOperands();
2751 if (NumElems != 4)
2752 return false;
2753 for (unsigned i = 0, e = 2; i != e; ++i)
2754 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2755 return false;
2756 for (unsigned i = 2; i != 4; ++i)
2757 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2758 return false;
2759 return true;
2760}
2761
2762/// isScalarLoadToVector - Returns true if the node is a scalar load that
2763/// is promoted to a vector.
2764static inline bool isScalarLoadToVector(SDNode *N) {
2765 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2766 N = N->getOperand(0).Val;
2767 return ISD::isNON_EXTLoad(N);
2768 }
2769 return false;
2770}
2771
2772/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2773/// match movlp{s|d}. The lower half elements should come from lower half of
2774/// V1 (and in order), and the upper half elements should come from the upper
2775/// half of V2 (and in order). And since V1 will become the source of the
2776/// MOVLP, it must be either a vector load or a scalar load to vector.
2777static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2778 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2779 return false;
2780 // Is V2 is a vector load, don't do this transformation. We will try to use
2781 // load folding shufps op.
2782 if (ISD::isNON_EXTLoad(V2))
2783 return false;
2784
2785 unsigned NumElems = Mask->getNumOperands();
2786 if (NumElems != 2 && NumElems != 4)
2787 return false;
2788 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2789 if (!isUndefOrEqual(Mask->getOperand(i), i))
2790 return false;
2791 for (unsigned i = NumElems/2; i != NumElems; ++i)
2792 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2793 return false;
2794 return true;
2795}
2796
2797/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2798/// all the same.
2799static bool isSplatVector(SDNode *N) {
2800 if (N->getOpcode() != ISD::BUILD_VECTOR)
2801 return false;
2802
2803 SDOperand SplatValue = N->getOperand(0);
2804 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2805 if (N->getOperand(i) != SplatValue)
2806 return false;
2807 return true;
2808}
2809
2810/// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2811/// to an undef.
2812static bool isUndefShuffle(SDNode *N) {
2813 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2814 return false;
2815
2816 SDOperand V1 = N->getOperand(0);
2817 SDOperand V2 = N->getOperand(1);
2818 SDOperand Mask = N->getOperand(2);
2819 unsigned NumElems = Mask.getNumOperands();
2820 for (unsigned i = 0; i != NumElems; ++i) {
2821 SDOperand Arg = Mask.getOperand(i);
2822 if (Arg.getOpcode() != ISD::UNDEF) {
2823 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2824 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2825 return false;
2826 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2827 return false;
2828 }
2829 }
2830 return true;
2831}
2832
2833/// isZeroNode - Returns true if Elt is a constant zero or a floating point
2834/// constant +0.0.
2835static inline bool isZeroNode(SDOperand Elt) {
2836 return ((isa<ConstantSDNode>(Elt) &&
2837 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2838 (isa<ConstantFPSDNode>(Elt) &&
Dale Johannesendf8a8312007-08-31 04:03:46 +00002839 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002840}
2841
2842/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2843/// to an zero vector.
2844static bool isZeroShuffle(SDNode *N) {
2845 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2846 return false;
2847
2848 SDOperand V1 = N->getOperand(0);
2849 SDOperand V2 = N->getOperand(1);
2850 SDOperand Mask = N->getOperand(2);
2851 unsigned NumElems = Mask.getNumOperands();
2852 for (unsigned i = 0; i != NumElems; ++i) {
2853 SDOperand Arg = Mask.getOperand(i);
2854 if (Arg.getOpcode() != ISD::UNDEF) {
2855 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2856 if (Idx < NumElems) {
2857 unsigned Opc = V1.Val->getOpcode();
2858 if (Opc == ISD::UNDEF)
2859 continue;
2860 if (Opc != ISD::BUILD_VECTOR ||
2861 !isZeroNode(V1.Val->getOperand(Idx)))
2862 return false;
2863 } else if (Idx >= NumElems) {
2864 unsigned Opc = V2.Val->getOpcode();
2865 if (Opc == ISD::UNDEF)
2866 continue;
2867 if (Opc != ISD::BUILD_VECTOR ||
2868 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2869 return false;
2870 }
2871 }
2872 }
2873 return true;
2874}
2875
2876/// getZeroVector - Returns a vector of specified type with all zero elements.
2877///
2878static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2879 assert(MVT::isVector(VT) && "Expected a vector type");
2880 unsigned NumElems = MVT::getVectorNumElements(VT);
2881 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2882 bool isFP = MVT::isFloatingPoint(EVT);
2883 SDOperand Zero = isFP ? DAG.getConstantFP(0.0, EVT) : DAG.getConstant(0, EVT);
2884 SmallVector<SDOperand, 8> ZeroVec(NumElems, Zero);
2885 return DAG.getNode(ISD::BUILD_VECTOR, VT, &ZeroVec[0], ZeroVec.size());
2886}
2887
2888/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2889/// that point to V2 points to its first element.
2890static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2891 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2892
2893 bool Changed = false;
2894 SmallVector<SDOperand, 8> MaskVec;
2895 unsigned NumElems = Mask.getNumOperands();
2896 for (unsigned i = 0; i != NumElems; ++i) {
2897 SDOperand Arg = Mask.getOperand(i);
2898 if (Arg.getOpcode() != ISD::UNDEF) {
2899 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2900 if (Val > NumElems) {
2901 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2902 Changed = true;
2903 }
2904 }
2905 MaskVec.push_back(Arg);
2906 }
2907
2908 if (Changed)
2909 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2910 &MaskVec[0], MaskVec.size());
2911 return Mask;
2912}
2913
2914/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2915/// operation of specified width.
2916static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2917 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2918 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2919
2920 SmallVector<SDOperand, 8> MaskVec;
2921 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2922 for (unsigned i = 1; i != NumElems; ++i)
2923 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2924 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2925}
2926
2927/// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2928/// of specified width.
2929static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2930 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2931 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2932 SmallVector<SDOperand, 8> MaskVec;
2933 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2934 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2935 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2936 }
2937 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2938}
2939
2940/// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2941/// of specified width.
2942static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2943 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2944 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2945 unsigned Half = NumElems/2;
2946 SmallVector<SDOperand, 8> MaskVec;
2947 for (unsigned i = 0; i != Half; ++i) {
2948 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2949 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2950 }
2951 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2952}
2953
2954/// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2955///
2956static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2957 SDOperand V1 = Op.getOperand(0);
2958 SDOperand Mask = Op.getOperand(2);
2959 MVT::ValueType VT = Op.getValueType();
2960 unsigned NumElems = Mask.getNumOperands();
2961 Mask = getUnpacklMask(NumElems, DAG);
2962 while (NumElems != 4) {
2963 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2964 NumElems >>= 1;
2965 }
2966 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2967
2968 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2969 Mask = getZeroVector(MaskVT, DAG);
2970 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2971 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2972 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2973}
2974
2975/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2976/// vector of zero or undef vector.
2977static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2978 unsigned NumElems, unsigned Idx,
2979 bool isZero, SelectionDAG &DAG) {
2980 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2981 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2982 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2983 SDOperand Zero = DAG.getConstant(0, EVT);
2984 SmallVector<SDOperand, 8> MaskVec(NumElems, Zero);
2985 MaskVec[Idx] = DAG.getConstant(NumElems, EVT);
2986 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2987 &MaskVec[0], MaskVec.size());
2988 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2989}
2990
2991/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2992///
2993static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2994 unsigned NumNonZero, unsigned NumZero,
2995 SelectionDAG &DAG, TargetLowering &TLI) {
2996 if (NumNonZero > 8)
2997 return SDOperand();
2998
2999 SDOperand V(0, 0);
3000 bool First = true;
3001 for (unsigned i = 0; i < 16; ++i) {
3002 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3003 if (ThisIsNonZero && First) {
3004 if (NumZero)
3005 V = getZeroVector(MVT::v8i16, DAG);
3006 else
3007 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3008 First = false;
3009 }
3010
3011 if ((i & 1) != 0) {
3012 SDOperand ThisElt(0, 0), LastElt(0, 0);
3013 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3014 if (LastIsNonZero) {
3015 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3016 }
3017 if (ThisIsNonZero) {
3018 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3019 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3020 ThisElt, DAG.getConstant(8, MVT::i8));
3021 if (LastIsNonZero)
3022 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3023 } else
3024 ThisElt = LastElt;
3025
3026 if (ThisElt.Val)
3027 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3028 DAG.getConstant(i/2, TLI.getPointerTy()));
3029 }
3030 }
3031
3032 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3033}
3034
3035/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3036///
3037static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3038 unsigned NumNonZero, unsigned NumZero,
3039 SelectionDAG &DAG, TargetLowering &TLI) {
3040 if (NumNonZero > 4)
3041 return SDOperand();
3042
3043 SDOperand V(0, 0);
3044 bool First = true;
3045 for (unsigned i = 0; i < 8; ++i) {
3046 bool isNonZero = (NonZeros & (1 << i)) != 0;
3047 if (isNonZero) {
3048 if (First) {
3049 if (NumZero)
3050 V = getZeroVector(MVT::v8i16, DAG);
3051 else
3052 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3053 First = false;
3054 }
3055 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3056 DAG.getConstant(i, TLI.getPointerTy()));
3057 }
3058 }
3059
3060 return V;
3061}
3062
3063SDOperand
3064X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3065 // All zero's are handled with pxor.
3066 if (ISD::isBuildVectorAllZeros(Op.Val))
3067 return Op;
3068
3069 // All one's are handled with pcmpeqd.
3070 if (ISD::isBuildVectorAllOnes(Op.Val))
3071 return Op;
3072
3073 MVT::ValueType VT = Op.getValueType();
3074 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3075 unsigned EVTBits = MVT::getSizeInBits(EVT);
3076
3077 unsigned NumElems = Op.getNumOperands();
3078 unsigned NumZero = 0;
3079 unsigned NumNonZero = 0;
3080 unsigned NonZeros = 0;
Dan Gohman21463242007-07-24 22:55:08 +00003081 unsigned NumNonZeroImms = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003082 std::set<SDOperand> Values;
3083 for (unsigned i = 0; i < NumElems; ++i) {
3084 SDOperand Elt = Op.getOperand(i);
3085 if (Elt.getOpcode() != ISD::UNDEF) {
3086 Values.insert(Elt);
3087 if (isZeroNode(Elt))
3088 NumZero++;
3089 else {
3090 NonZeros |= (1 << i);
3091 NumNonZero++;
Dan Gohman21463242007-07-24 22:55:08 +00003092 if (Elt.getOpcode() == ISD::Constant ||
3093 Elt.getOpcode() == ISD::ConstantFP)
3094 NumNonZeroImms++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003095 }
3096 }
3097 }
3098
3099 if (NumNonZero == 0) {
3100 if (NumZero == 0)
3101 // All undef vector. Return an UNDEF.
3102 return DAG.getNode(ISD::UNDEF, VT);
3103 else
3104 // A mix of zero and undef. Return a zero vector.
3105 return getZeroVector(VT, DAG);
3106 }
3107
3108 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3109 if (Values.size() == 1)
3110 return SDOperand();
3111
3112 // Special case for single non-zero element.
3113 if (NumNonZero == 1) {
3114 unsigned Idx = CountTrailingZeros_32(NonZeros);
3115 SDOperand Item = Op.getOperand(Idx);
3116 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3117 if (Idx == 0)
3118 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3119 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
3120 NumZero > 0, DAG);
3121
3122 if (EVTBits == 32) {
3123 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3124 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
3125 DAG);
3126 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3127 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3128 SmallVector<SDOperand, 8> MaskVec;
3129 for (unsigned i = 0; i < NumElems; i++)
3130 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3131 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3132 &MaskVec[0], MaskVec.size());
3133 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3134 DAG.getNode(ISD::UNDEF, VT), Mask);
3135 }
3136 }
3137
Dan Gohman21463242007-07-24 22:55:08 +00003138 // A vector full of immediates; various special cases are already
3139 // handled, so this is best done with a single constant-pool load.
3140 if (NumNonZero == NumNonZeroImms)
3141 return SDOperand();
3142
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003143 // Let legalizer expand 2-wide build_vectors.
3144 if (EVTBits == 64)
3145 return SDOperand();
3146
3147 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3148 if (EVTBits == 8 && NumElems == 16) {
3149 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3150 *this);
3151 if (V.Val) return V;
3152 }
3153
3154 if (EVTBits == 16 && NumElems == 8) {
3155 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3156 *this);
3157 if (V.Val) return V;
3158 }
3159
3160 // If element VT is == 32 bits, turn it into a number of shuffles.
3161 SmallVector<SDOperand, 8> V;
3162 V.resize(NumElems);
3163 if (NumElems == 4 && NumZero > 0) {
3164 for (unsigned i = 0; i < 4; ++i) {
3165 bool isZero = !(NonZeros & (1 << i));
3166 if (isZero)
3167 V[i] = getZeroVector(VT, DAG);
3168 else
3169 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3170 }
3171
3172 for (unsigned i = 0; i < 2; ++i) {
3173 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3174 default: break;
3175 case 0:
3176 V[i] = V[i*2]; // Must be a zero vector.
3177 break;
3178 case 1:
3179 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3180 getMOVLMask(NumElems, DAG));
3181 break;
3182 case 2:
3183 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3184 getMOVLMask(NumElems, DAG));
3185 break;
3186 case 3:
3187 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3188 getUnpacklMask(NumElems, DAG));
3189 break;
3190 }
3191 }
3192
3193 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3194 // clears the upper bits.
3195 // FIXME: we can do the same for v4f32 case when we know both parts of
3196 // the lower half come from scalar_to_vector (loadf32). We should do
3197 // that in post legalizer dag combiner with target specific hooks.
3198 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3199 return V[0];
3200 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3201 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3202 SmallVector<SDOperand, 8> MaskVec;
3203 bool Reverse = (NonZeros & 0x3) == 2;
3204 for (unsigned i = 0; i < 2; ++i)
3205 if (Reverse)
3206 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3207 else
3208 MaskVec.push_back(DAG.getConstant(i, EVT));
3209 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3210 for (unsigned i = 0; i < 2; ++i)
3211 if (Reverse)
3212 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3213 else
3214 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3215 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3216 &MaskVec[0], MaskVec.size());
3217 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3218 }
3219
3220 if (Values.size() > 2) {
3221 // Expand into a number of unpckl*.
3222 // e.g. for v4f32
3223 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3224 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3225 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3226 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3227 for (unsigned i = 0; i < NumElems; ++i)
3228 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3229 NumElems >>= 1;
3230 while (NumElems != 0) {
3231 for (unsigned i = 0; i < NumElems; ++i)
3232 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3233 UnpckMask);
3234 NumElems >>= 1;
3235 }
3236 return V[0];
3237 }
3238
3239 return SDOperand();
3240}
3241
3242SDOperand
3243X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3244 SDOperand V1 = Op.getOperand(0);
3245 SDOperand V2 = Op.getOperand(1);
3246 SDOperand PermMask = Op.getOperand(2);
3247 MVT::ValueType VT = Op.getValueType();
3248 unsigned NumElems = PermMask.getNumOperands();
3249 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3250 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3251 bool V1IsSplat = false;
3252 bool V2IsSplat = false;
3253
3254 if (isUndefShuffle(Op.Val))
3255 return DAG.getNode(ISD::UNDEF, VT);
3256
3257 if (isZeroShuffle(Op.Val))
3258 return getZeroVector(VT, DAG);
3259
3260 if (isIdentityMask(PermMask.Val))
3261 return V1;
3262 else if (isIdentityMask(PermMask.Val, true))
3263 return V2;
3264
3265 if (isSplatMask(PermMask.Val)) {
3266 if (NumElems <= 4) return Op;
3267 // Promote it to a v4i32 splat.
3268 return PromoteSplat(Op, DAG);
3269 }
3270
3271 if (X86::isMOVLMask(PermMask.Val))
3272 return (V1IsUndef) ? V2 : Op;
3273
3274 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3275 X86::isMOVSLDUPMask(PermMask.Val) ||
3276 X86::isMOVHLPSMask(PermMask.Val) ||
3277 X86::isMOVHPMask(PermMask.Val) ||
3278 X86::isMOVLPMask(PermMask.Val))
3279 return Op;
3280
3281 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3282 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3283 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3284
3285 bool Commuted = false;
3286 V1IsSplat = isSplatVector(V1.Val);
3287 V2IsSplat = isSplatVector(V2.Val);
3288 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3289 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3290 std::swap(V1IsSplat, V2IsSplat);
3291 std::swap(V1IsUndef, V2IsUndef);
3292 Commuted = true;
3293 }
3294
3295 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3296 if (V2IsUndef) return V1;
3297 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3298 if (V2IsSplat) {
3299 // V2 is a splat, so the mask may be malformed. That is, it may point
3300 // to any V2 element. The instruction selectior won't like this. Get
3301 // a corrected mask and commute to form a proper MOVS{S|D}.
3302 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3303 if (NewMask.Val != PermMask.Val)
3304 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3305 }
3306 return Op;
3307 }
3308
3309 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3310 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3311 X86::isUNPCKLMask(PermMask.Val) ||
3312 X86::isUNPCKHMask(PermMask.Val))
3313 return Op;
3314
3315 if (V2IsSplat) {
3316 // Normalize mask so all entries that point to V2 points to its first
3317 // element then try to match unpck{h|l} again. If match, return a
3318 // new vector_shuffle with the corrected mask.
3319 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3320 if (NewMask.Val != PermMask.Val) {
3321 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3322 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3323 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3324 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3325 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3326 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3327 }
3328 }
3329 }
3330
3331 // Normalize the node to match x86 shuffle ops if needed
3332 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3333 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3334
3335 if (Commuted) {
3336 // Commute is back and try unpck* again.
3337 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3338 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3339 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3340 X86::isUNPCKLMask(PermMask.Val) ||
3341 X86::isUNPCKHMask(PermMask.Val))
3342 return Op;
3343 }
3344
3345 // If VT is integer, try PSHUF* first, then SHUFP*.
3346 if (MVT::isInteger(VT)) {
Dan Gohman7dc19012007-08-02 21:17:01 +00003347 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3348 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3349 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3350 X86::isPSHUFDMask(PermMask.Val)) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003351 X86::isPSHUFHWMask(PermMask.Val) ||
3352 X86::isPSHUFLWMask(PermMask.Val)) {
3353 if (V2.getOpcode() != ISD::UNDEF)
3354 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3355 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3356 return Op;
3357 }
3358
3359 if (X86::isSHUFPMask(PermMask.Val) &&
3360 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3361 return Op;
3362
3363 // Handle v8i16 shuffle high / low shuffle node pair.
3364 if (VT == MVT::v8i16 && isPSHUFHW_PSHUFLWMask(PermMask.Val)) {
3365 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3366 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3367 SmallVector<SDOperand, 8> MaskVec;
3368 for (unsigned i = 0; i != 4; ++i)
3369 MaskVec.push_back(PermMask.getOperand(i));
3370 for (unsigned i = 4; i != 8; ++i)
3371 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3372 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3373 &MaskVec[0], MaskVec.size());
3374 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3375 MaskVec.clear();
3376 for (unsigned i = 0; i != 4; ++i)
3377 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3378 for (unsigned i = 4; i != 8; ++i)
3379 MaskVec.push_back(PermMask.getOperand(i));
3380 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0],MaskVec.size());
3381 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3382 }
3383 } else {
3384 // Floating point cases in the other order.
3385 if (X86::isSHUFPMask(PermMask.Val))
3386 return Op;
3387 if (X86::isPSHUFDMask(PermMask.Val) ||
3388 X86::isPSHUFHWMask(PermMask.Val) ||
3389 X86::isPSHUFLWMask(PermMask.Val)) {
3390 if (V2.getOpcode() != ISD::UNDEF)
3391 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3392 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3393 return Op;
3394 }
3395 }
3396
3397 if (NumElems == 4 &&
3398 // Don't do this for MMX.
3399 MVT::getSizeInBits(VT) != 64) {
3400 MVT::ValueType MaskVT = PermMask.getValueType();
3401 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3402 SmallVector<std::pair<int, int>, 8> Locs;
3403 Locs.reserve(NumElems);
3404 SmallVector<SDOperand, 8> Mask1(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3405 SmallVector<SDOperand, 8> Mask2(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3406 unsigned NumHi = 0;
3407 unsigned NumLo = 0;
3408 // If no more than two elements come from either vector. This can be
3409 // implemented with two shuffles. First shuffle gather the elements.
3410 // The second shuffle, which takes the first shuffle as both of its
3411 // vector operands, put the elements into the right order.
3412 for (unsigned i = 0; i != NumElems; ++i) {
3413 SDOperand Elt = PermMask.getOperand(i);
3414 if (Elt.getOpcode() == ISD::UNDEF) {
3415 Locs[i] = std::make_pair(-1, -1);
3416 } else {
3417 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3418 if (Val < NumElems) {
3419 Locs[i] = std::make_pair(0, NumLo);
3420 Mask1[NumLo] = Elt;
3421 NumLo++;
3422 } else {
3423 Locs[i] = std::make_pair(1, NumHi);
3424 if (2+NumHi < NumElems)
3425 Mask1[2+NumHi] = Elt;
3426 NumHi++;
3427 }
3428 }
3429 }
3430 if (NumLo <= 2 && NumHi <= 2) {
3431 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3432 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3433 &Mask1[0], Mask1.size()));
3434 for (unsigned i = 0; i != NumElems; ++i) {
3435 if (Locs[i].first == -1)
3436 continue;
3437 else {
3438 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3439 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3440 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3441 }
3442 }
3443
3444 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3445 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3446 &Mask2[0], Mask2.size()));
3447 }
3448
3449 // Break it into (shuffle shuffle_hi, shuffle_lo).
3450 Locs.clear();
3451 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3452 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3453 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3454 unsigned MaskIdx = 0;
3455 unsigned LoIdx = 0;
3456 unsigned HiIdx = NumElems/2;
3457 for (unsigned i = 0; i != NumElems; ++i) {
3458 if (i == NumElems/2) {
3459 MaskPtr = &HiMask;
3460 MaskIdx = 1;
3461 LoIdx = 0;
3462 HiIdx = NumElems/2;
3463 }
3464 SDOperand Elt = PermMask.getOperand(i);
3465 if (Elt.getOpcode() == ISD::UNDEF) {
3466 Locs[i] = std::make_pair(-1, -1);
3467 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3468 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3469 (*MaskPtr)[LoIdx] = Elt;
3470 LoIdx++;
3471 } else {
3472 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3473 (*MaskPtr)[HiIdx] = Elt;
3474 HiIdx++;
3475 }
3476 }
3477
3478 SDOperand LoShuffle =
3479 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3480 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3481 &LoMask[0], LoMask.size()));
3482 SDOperand HiShuffle =
3483 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3484 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3485 &HiMask[0], HiMask.size()));
3486 SmallVector<SDOperand, 8> MaskOps;
3487 for (unsigned i = 0; i != NumElems; ++i) {
3488 if (Locs[i].first == -1) {
3489 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3490 } else {
3491 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3492 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3493 }
3494 }
3495 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3496 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3497 &MaskOps[0], MaskOps.size()));
3498 }
3499
3500 return SDOperand();
3501}
3502
3503SDOperand
3504X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3505 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3506 return SDOperand();
3507
3508 MVT::ValueType VT = Op.getValueType();
3509 // TODO: handle v16i8.
3510 if (MVT::getSizeInBits(VT) == 16) {
3511 // Transform it so it match pextrw which produces a 32-bit result.
3512 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3513 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3514 Op.getOperand(0), Op.getOperand(1));
3515 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3516 DAG.getValueType(VT));
3517 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3518 } else if (MVT::getSizeInBits(VT) == 32) {
3519 SDOperand Vec = Op.getOperand(0);
3520 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3521 if (Idx == 0)
3522 return Op;
3523 // SHUFPS the element to the lowest double word, then movss.
3524 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3525 SmallVector<SDOperand, 8> IdxVec;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00003526 IdxVec.
3527 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3528 IdxVec.
3529 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3530 IdxVec.
3531 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3532 IdxVec.
3533 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003534 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3535 &IdxVec[0], IdxVec.size());
3536 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3537 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3538 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3539 DAG.getConstant(0, getPointerTy()));
3540 } else if (MVT::getSizeInBits(VT) == 64) {
3541 SDOperand Vec = Op.getOperand(0);
3542 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3543 if (Idx == 0)
3544 return Op;
3545
3546 // UNPCKHPD the element to the lowest double word, then movsd.
3547 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3548 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3549 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3550 SmallVector<SDOperand, 8> IdxVec;
3551 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00003552 IdxVec.
3553 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003554 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3555 &IdxVec[0], IdxVec.size());
3556 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3557 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3558 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3559 DAG.getConstant(0, getPointerTy()));
3560 }
3561
3562 return SDOperand();
3563}
3564
3565SDOperand
3566X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3567 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3568 // as its second argument.
3569 MVT::ValueType VT = Op.getValueType();
3570 MVT::ValueType BaseVT = MVT::getVectorElementType(VT);
3571 SDOperand N0 = Op.getOperand(0);
3572 SDOperand N1 = Op.getOperand(1);
3573 SDOperand N2 = Op.getOperand(2);
3574 if (MVT::getSizeInBits(BaseVT) == 16) {
3575 if (N1.getValueType() != MVT::i32)
3576 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3577 if (N2.getValueType() != MVT::i32)
3578 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
3579 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3580 } else if (MVT::getSizeInBits(BaseVT) == 32) {
3581 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
3582 if (Idx == 0) {
3583 // Use a movss.
3584 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
3585 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3586 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3587 SmallVector<SDOperand, 8> MaskVec;
3588 MaskVec.push_back(DAG.getConstant(4, BaseVT));
3589 for (unsigned i = 1; i <= 3; ++i)
3590 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3591 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
3592 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3593 &MaskVec[0], MaskVec.size()));
3594 } else {
3595 // Use two pinsrw instructions to insert a 32 bit value.
3596 Idx <<= 1;
3597 if (MVT::isFloatingPoint(N1.getValueType())) {
Evan Cheng1eea6752007-07-31 06:21:44 +00003598 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
3599 N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
3600 N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
3601 DAG.getConstant(0, getPointerTy()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003602 }
3603 N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
3604 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3605 DAG.getConstant(Idx, getPointerTy()));
3606 N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
3607 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3608 DAG.getConstant(Idx+1, getPointerTy()));
3609 return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3610 }
3611 }
3612
3613 return SDOperand();
3614}
3615
3616SDOperand
3617X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3618 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3619 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3620}
3621
3622// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3623// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3624// one of the above mentioned nodes. It has to be wrapped because otherwise
3625// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3626// be used to form addressing mode. These wrapped nodes will be selected
3627// into MOV32ri.
3628SDOperand
3629X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3630 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3631 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3632 getPointerTy(),
3633 CP->getAlignment());
3634 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3635 // With PIC, the address is actually $g + Offset.
3636 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3637 !Subtarget->isPICStyleRIPRel()) {
3638 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3639 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3640 Result);
3641 }
3642
3643 return Result;
3644}
3645
3646SDOperand
3647X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3648 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3649 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3650 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3651 // With PIC, the address is actually $g + Offset.
3652 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3653 !Subtarget->isPICStyleRIPRel()) {
3654 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3655 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3656 Result);
3657 }
3658
3659 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3660 // load the value at address GV, not the value of GV itself. This means that
3661 // the GlobalAddress must be in the base or index register of the address, not
3662 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3663 // The same applies for external symbols during PIC codegen
3664 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3665 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
3666
3667 return Result;
3668}
3669
3670// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3671static SDOperand
3672LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3673 const MVT::ValueType PtrVT) {
3674 SDOperand InFlag;
3675 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3676 DAG.getNode(X86ISD::GlobalBaseReg,
3677 PtrVT), InFlag);
3678 InFlag = Chain.getValue(1);
3679
3680 // emit leal symbol@TLSGD(,%ebx,1), %eax
3681 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3682 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3683 GA->getValueType(0),
3684 GA->getOffset());
3685 SDOperand Ops[] = { Chain, TGA, InFlag };
3686 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3687 InFlag = Result.getValue(2);
3688 Chain = Result.getValue(1);
3689
3690 // call ___tls_get_addr. This function receives its argument in
3691 // the register EAX.
3692 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3693 InFlag = Chain.getValue(1);
3694
3695 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3696 SDOperand Ops1[] = { Chain,
3697 DAG.getTargetExternalSymbol("___tls_get_addr",
3698 PtrVT),
3699 DAG.getRegister(X86::EAX, PtrVT),
3700 DAG.getRegister(X86::EBX, PtrVT),
3701 InFlag };
3702 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3703 InFlag = Chain.getValue(1);
3704
3705 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3706}
3707
3708// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3709// "local exec" model.
3710static SDOperand
3711LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3712 const MVT::ValueType PtrVT) {
3713 // Get the Thread Pointer
3714 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3715 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3716 // exec)
3717 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3718 GA->getValueType(0),
3719 GA->getOffset());
3720 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3721
3722 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3723 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
3724
3725 // The address of the thread local variable is the add of the thread
3726 // pointer with the offset of the variable.
3727 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3728}
3729
3730SDOperand
3731X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3732 // TODO: implement the "local dynamic" model
3733 // TODO: implement the "initial exec"model for pic executables
3734 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3735 "TLS not implemented for non-ELF and 64-bit targets");
3736 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3737 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3738 // otherwise use the "Local Exec"TLS Model
3739 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3740 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3741 else
3742 return LowerToTLSExecModel(GA, DAG, getPointerTy());
3743}
3744
3745SDOperand
3746X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3747 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3748 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3749 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3750 // With PIC, the address is actually $g + Offset.
3751 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3752 !Subtarget->isPICStyleRIPRel()) {
3753 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3754 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3755 Result);
3756 }
3757
3758 return Result;
3759}
3760
3761SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3762 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3763 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3764 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3765 // With PIC, the address is actually $g + Offset.
3766 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3767 !Subtarget->isPICStyleRIPRel()) {
3768 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3769 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3770 Result);
3771 }
3772
3773 return Result;
3774}
3775
Chris Lattner62814a32007-10-17 06:02:13 +00003776/// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
3777/// take a 2 x i32 value to shift plus a shift amount.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003778SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner62814a32007-10-17 06:02:13 +00003779 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
3780 "Not an i64 shift!");
3781 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
3782 SDOperand ShOpLo = Op.getOperand(0);
3783 SDOperand ShOpHi = Op.getOperand(1);
3784 SDOperand ShAmt = Op.getOperand(2);
3785 SDOperand Tmp1 = isSRA ?
3786 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
3787 DAG.getConstant(0, MVT::i32);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003788
Chris Lattner62814a32007-10-17 06:02:13 +00003789 SDOperand Tmp2, Tmp3;
3790 if (Op.getOpcode() == ISD::SHL_PARTS) {
3791 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
3792 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
3793 } else {
3794 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
3795 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
3796 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003797
Chris Lattner62814a32007-10-17 06:02:13 +00003798 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3799 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
3800 DAG.getConstant(32, MVT::i8));
3801 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
3802 AndNode, DAG.getConstant(0, MVT::i8));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003803
Chris Lattner62814a32007-10-17 06:02:13 +00003804 SDOperand Hi, Lo;
3805 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3806 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
3807 SmallVector<SDOperand, 4> Ops;
3808 if (Op.getOpcode() == ISD::SHL_PARTS) {
3809 Ops.push_back(Tmp2);
3810 Ops.push_back(Tmp3);
3811 Ops.push_back(CC);
3812 Ops.push_back(Cond);
3813 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003814
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003815 Ops.clear();
Chris Lattner62814a32007-10-17 06:02:13 +00003816 Ops.push_back(Tmp3);
3817 Ops.push_back(Tmp1);
3818 Ops.push_back(CC);
3819 Ops.push_back(Cond);
3820 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3821 } else {
3822 Ops.push_back(Tmp2);
3823 Ops.push_back(Tmp3);
3824 Ops.push_back(CC);
3825 Ops.push_back(Cond);
3826 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3827
3828 Ops.clear();
3829 Ops.push_back(Tmp3);
3830 Ops.push_back(Tmp1);
3831 Ops.push_back(CC);
3832 Ops.push_back(Cond);
3833 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3834 }
3835
3836 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
3837 Ops.clear();
3838 Ops.push_back(Lo);
3839 Ops.push_back(Hi);
3840 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003841}
3842
3843SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
3844 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
3845 Op.getOperand(0).getValueType() >= MVT::i16 &&
3846 "Unknown SINT_TO_FP to lower!");
3847
3848 SDOperand Result;
3849 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
3850 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
3851 MachineFunction &MF = DAG.getMachineFunction();
3852 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
3853 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3854 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
3855 StackSlot, NULL, 0);
3856
Dale Johannesen2fc20782007-09-14 22:26:36 +00003857 // These are really Legal; caller falls through into that case.
Dale Johannesene0e0fd02007-09-23 14:52:20 +00003858 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f32 && X86ScalarSSEf32)
3859 return Result;
3860 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f64 && X86ScalarSSEf64)
Dale Johannesen2fc20782007-09-14 22:26:36 +00003861 return Result;
Dale Johannesen958b08b2007-09-19 23:55:34 +00003862 if (SrcVT==MVT::i64 && Op.getValueType() != MVT::f80 &&
3863 Subtarget->is64Bit())
3864 return Result;
Dale Johannesen2fc20782007-09-14 22:26:36 +00003865
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003866 // Build the FILD
3867 SDVTList Tys;
Dale Johannesene0e0fd02007-09-23 14:52:20 +00003868 bool useSSE = (X86ScalarSSEf32 && Op.getValueType() == MVT::f32) ||
3869 (X86ScalarSSEf64 && Op.getValueType() == MVT::f64);
Dale Johannesen2fc20782007-09-14 22:26:36 +00003870 if (useSSE)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003871 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
3872 else
3873 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
3874 SmallVector<SDOperand, 8> Ops;
3875 Ops.push_back(Chain);
3876 Ops.push_back(StackSlot);
3877 Ops.push_back(DAG.getValueType(SrcVT));
Dale Johannesen2fc20782007-09-14 22:26:36 +00003878 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003879 Tys, &Ops[0], Ops.size());
3880
Dale Johannesen2fc20782007-09-14 22:26:36 +00003881 if (useSSE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003882 Chain = Result.getValue(1);
3883 SDOperand InFlag = Result.getValue(2);
3884
3885 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
3886 // shouldn't be necessary except that RFP cannot be live across
3887 // multiple blocks. When stackifier is fixed, they can be uncoupled.
3888 MachineFunction &MF = DAG.getMachineFunction();
3889 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3890 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3891 Tys = DAG.getVTList(MVT::Other);
3892 SmallVector<SDOperand, 8> Ops;
3893 Ops.push_back(Chain);
3894 Ops.push_back(Result);
3895 Ops.push_back(StackSlot);
3896 Ops.push_back(DAG.getValueType(Op.getValueType()));
3897 Ops.push_back(InFlag);
3898 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
3899 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
3900 }
3901
3902 return Result;
3903}
3904
3905SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
3906 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
3907 "Unknown FP_TO_SINT to lower!");
Dale Johannesen2fc20782007-09-14 22:26:36 +00003908 SDOperand Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003909
Dale Johannesen2fc20782007-09-14 22:26:36 +00003910 // These are really Legal.
Dale Johannesene0e0fd02007-09-23 14:52:20 +00003911 if (Op.getValueType() == MVT::i32 &&
3912 X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32)
3913 return Result;
3914 if (Op.getValueType() == MVT::i32 &&
3915 X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)
Dale Johannesen2fc20782007-09-14 22:26:36 +00003916 return Result;
Dale Johannesen958b08b2007-09-19 23:55:34 +00003917 if (Subtarget->is64Bit() &&
3918 Op.getValueType() == MVT::i64 &&
3919 Op.getOperand(0).getValueType() != MVT::f80)
3920 return Result;
Dale Johannesen2fc20782007-09-14 22:26:36 +00003921
Evan Cheng05441e62007-10-15 20:11:21 +00003922 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
3923 // stack slot.
3924 MachineFunction &MF = DAG.getMachineFunction();
3925 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
3926 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3927 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003928 unsigned Opc;
3929 switch (Op.getValueType()) {
3930 default: assert(0 && "Invalid FP_TO_SINT to lower!");
3931 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
3932 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
3933 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
3934 }
3935
3936 SDOperand Chain = DAG.getEntryNode();
3937 SDOperand Value = Op.getOperand(0);
Dale Johannesene0e0fd02007-09-23 14:52:20 +00003938 if ((X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32) ||
3939 (X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003940 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
3941 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
3942 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
3943 SDOperand Ops[] = {
3944 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
3945 };
3946 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
3947 Chain = Value.getValue(1);
3948 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3949 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3950 }
3951
3952 // Build the FP_TO_INT*_IN_MEM
3953 SDOperand Ops[] = { Chain, Value, StackSlot };
3954 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
3955
Chris Lattner79b8afe2007-10-17 06:17:29 +00003956 // Load the result. If this is an i64 load on an x86-32 host, expand the
3957 // load.
3958 if (Op.getValueType() != MVT::i64 || Subtarget->is64Bit())
3959 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
3960
3961 SDOperand Lo = DAG.getLoad(MVT::i32, FIST, StackSlot, NULL, 0);
3962 StackSlot = DAG.getNode(ISD::ADD, StackSlot.getValueType(), StackSlot,
3963 DAG.getConstant(StackSlot.getValueType(), 4));
3964 SDOperand Hi = DAG.getLoad(MVT::i32, FIST, StackSlot, NULL, 0);
3965
3966
3967 return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003968}
3969
3970SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
3971 MVT::ValueType VT = Op.getValueType();
3972 MVT::ValueType EltVT = VT;
3973 if (MVT::isVector(VT))
3974 EltVT = MVT::getVectorElementType(VT);
3975 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
3976 std::vector<Constant*> CV;
3977 if (EltVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00003978 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003979 CV.push_back(C);
3980 CV.push_back(C);
3981 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00003982 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003983 CV.push_back(C);
3984 CV.push_back(C);
3985 CV.push_back(C);
3986 CV.push_back(C);
3987 }
Dan Gohman11821702007-07-27 17:16:43 +00003988 Constant *C = ConstantVector::get(CV);
3989 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
3990 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
3991 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003992 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
3993}
3994
3995SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
3996 MVT::ValueType VT = Op.getValueType();
3997 MVT::ValueType EltVT = VT;
Evan Cheng92b8f782007-07-19 23:36:01 +00003998 unsigned EltNum = 1;
3999 if (MVT::isVector(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004000 EltVT = MVT::getVectorElementType(VT);
Evan Cheng92b8f782007-07-19 23:36:01 +00004001 EltNum = MVT::getVectorNumElements(VT);
4002 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004003 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4004 std::vector<Constant*> CV;
4005 if (EltVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004006 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004007 CV.push_back(C);
4008 CV.push_back(C);
4009 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004010 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004011 CV.push_back(C);
4012 CV.push_back(C);
4013 CV.push_back(C);
4014 CV.push_back(C);
4015 }
Dan Gohman11821702007-07-27 17:16:43 +00004016 Constant *C = ConstantVector::get(CV);
4017 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4018 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4019 false, 16);
Evan Cheng92b8f782007-07-19 23:36:01 +00004020 if (MVT::isVector(VT)) {
Evan Cheng92b8f782007-07-19 23:36:01 +00004021 return DAG.getNode(ISD::BIT_CONVERT, VT,
4022 DAG.getNode(ISD::XOR, MVT::v2i64,
4023 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4024 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4025 } else {
Evan Cheng92b8f782007-07-19 23:36:01 +00004026 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4027 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004028}
4029
4030SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4031 SDOperand Op0 = Op.getOperand(0);
4032 SDOperand Op1 = Op.getOperand(1);
4033 MVT::ValueType VT = Op.getValueType();
4034 MVT::ValueType SrcVT = Op1.getValueType();
4035 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4036
4037 // If second operand is smaller, extend it first.
4038 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4039 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4040 SrcVT = VT;
Dale Johannesenb9de9f02007-09-06 18:13:44 +00004041 SrcTy = MVT::getTypeForValueType(SrcVT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004042 }
Dale Johannesenfb0fa912007-10-21 01:07:44 +00004043 // And if it is bigger, shrink it first.
4044 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4045 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1);
4046 SrcVT = VT;
4047 SrcTy = MVT::getTypeForValueType(SrcVT);
4048 }
4049
4050 // At this point the operands and the result should have the same
4051 // type, and that won't be f80 since that is not custom lowered.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004052
4053 // First get the sign bit of second operand.
4054 std::vector<Constant*> CV;
4055 if (SrcVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004056 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4057 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004058 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004059 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4060 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4061 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4062 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004063 }
Dan Gohman11821702007-07-27 17:16:43 +00004064 Constant *C = ConstantVector::get(CV);
4065 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4066 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx, NULL, 0,
4067 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004068 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4069
4070 // Shift sign bit right or left if the two operands have different types.
4071 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4072 // Op0 is MVT::f32, Op1 is MVT::f64.
4073 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4074 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4075 DAG.getConstant(32, MVT::i32));
4076 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4077 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4078 DAG.getConstant(0, getPointerTy()));
4079 }
4080
4081 // Clear first operand sign bit.
4082 CV.clear();
4083 if (VT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004084 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4085 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004086 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004087 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4088 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4089 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4090 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004091 }
Dan Gohman11821702007-07-27 17:16:43 +00004092 C = ConstantVector::get(CV);
4093 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4094 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4095 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004096 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4097
4098 // Or the value with the sign bit.
4099 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4100}
4101
Evan Cheng621216e2007-09-29 00:00:36 +00004102SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
Evan Cheng950aac02007-09-25 01:57:46 +00004103 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
Evan Cheng6afec3d2007-09-26 00:45:55 +00004104 SDOperand Cond;
Evan Cheng950aac02007-09-25 01:57:46 +00004105 SDOperand Op0 = Op.getOperand(0);
4106 SDOperand Op1 = Op.getOperand(1);
4107 SDOperand CC = Op.getOperand(2);
4108 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4109 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4110 unsigned X86CC;
4111
Evan Cheng950aac02007-09-25 01:57:46 +00004112 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
Evan Cheng6afec3d2007-09-26 00:45:55 +00004113 Op0, Op1, DAG)) {
Evan Cheng621216e2007-09-29 00:00:36 +00004114 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4115 return DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004116 DAG.getConstant(X86CC, MVT::i8), Cond);
Evan Cheng6afec3d2007-09-26 00:45:55 +00004117 }
Evan Cheng950aac02007-09-25 01:57:46 +00004118
4119 assert(isFP && "Illegal integer SetCC!");
4120
Evan Cheng621216e2007-09-29 00:00:36 +00004121 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
Evan Cheng950aac02007-09-25 01:57:46 +00004122 switch (SetCCOpcode) {
4123 default: assert(false && "Illegal floating point SetCC!");
4124 case ISD::SETOEQ: { // !PF & ZF
Evan Cheng621216e2007-09-29 00:00:36 +00004125 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004126 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004127 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004128 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4129 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4130 }
4131 case ISD::SETUNE: { // PF | !ZF
Evan Cheng621216e2007-09-29 00:00:36 +00004132 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004133 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004134 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004135 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4136 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4137 }
4138 }
4139}
4140
4141
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004142SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4143 bool addTest = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004144 SDOperand Cond = Op.getOperand(0);
4145 SDOperand CC;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004146
4147 if (Cond.getOpcode() == ISD::SETCC)
Evan Cheng621216e2007-09-29 00:00:36 +00004148 Cond = LowerSETCC(Cond, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004149
Evan Cheng50d37ab2007-10-08 22:16:29 +00004150 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4151 // setting operand in place of the X86ISD::SETCC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004152 if (Cond.getOpcode() == X86ISD::SETCC) {
4153 CC = Cond.getOperand(0);
4154
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004155 SDOperand Cmp = Cond.getOperand(1);
4156 unsigned Opc = Cmp.getOpcode();
Evan Cheng50d37ab2007-10-08 22:16:29 +00004157 MVT::ValueType VT = Op.getValueType();
4158 bool IllegalFPCMov = false;
4159 if (VT == MVT::f32 && !X86ScalarSSEf32)
4160 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4161 else if (VT == MVT::f64 && !X86ScalarSSEf64)
4162 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
Dale Johannesen3b955db2007-10-16 18:09:08 +00004163 else if (VT == MVT::f80)
4164 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
Evan Cheng621216e2007-09-29 00:00:36 +00004165 if ((Opc == X86ISD::CMP ||
4166 Opc == X86ISD::COMI ||
4167 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
Evan Cheng50d37ab2007-10-08 22:16:29 +00004168 Cond = Cmp;
Evan Cheng950aac02007-09-25 01:57:46 +00004169 addTest = false;
4170 }
4171 }
4172
4173 if (addTest) {
4174 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
Evan Cheng50d37ab2007-10-08 22:16:29 +00004175 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
Evan Cheng950aac02007-09-25 01:57:46 +00004176 }
4177
4178 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4179 MVT::Flag);
4180 SmallVector<SDOperand, 4> Ops;
4181 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4182 // condition is true.
4183 Ops.push_back(Op.getOperand(2));
4184 Ops.push_back(Op.getOperand(1));
4185 Ops.push_back(CC);
4186 Ops.push_back(Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004187 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
Evan Cheng950aac02007-09-25 01:57:46 +00004188}
4189
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004190SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4191 bool addTest = true;
4192 SDOperand Chain = Op.getOperand(0);
4193 SDOperand Cond = Op.getOperand(1);
4194 SDOperand Dest = Op.getOperand(2);
4195 SDOperand CC;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004196
4197 if (Cond.getOpcode() == ISD::SETCC)
Evan Cheng621216e2007-09-29 00:00:36 +00004198 Cond = LowerSETCC(Cond, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004199
Evan Cheng50d37ab2007-10-08 22:16:29 +00004200 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4201 // setting operand in place of the X86ISD::SETCC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004202 if (Cond.getOpcode() == X86ISD::SETCC) {
4203 CC = Cond.getOperand(0);
4204
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004205 SDOperand Cmp = Cond.getOperand(1);
4206 unsigned Opc = Cmp.getOpcode();
Evan Cheng621216e2007-09-29 00:00:36 +00004207 if (Opc == X86ISD::CMP ||
4208 Opc == X86ISD::COMI ||
4209 Opc == X86ISD::UCOMI) {
Evan Cheng50d37ab2007-10-08 22:16:29 +00004210 Cond = Cmp;
Evan Cheng950aac02007-09-25 01:57:46 +00004211 addTest = false;
4212 }
4213 }
4214
4215 if (addTest) {
4216 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
Evan Cheng621216e2007-09-29 00:00:36 +00004217 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
Evan Cheng950aac02007-09-25 01:57:46 +00004218 }
Evan Cheng621216e2007-09-29 00:00:36 +00004219 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
Evan Cheng950aac02007-09-25 01:57:46 +00004220 Chain, Op.getOperand(2), CC, Cond);
4221}
4222
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004223SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004224 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4225 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004226
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004227 if (Subtarget->is64Bit())
4228 if(CallingConv==CallingConv::Fast && isTailCall && PerformTailCallOpt)
4229 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4230 else
4231 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004232 else
4233 switch (CallingConv) {
4234 default:
4235 assert(0 && "Unsupported calling convention");
4236 case CallingConv::Fast:
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004237 if (isTailCall && PerformTailCallOpt)
4238 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4239 else
4240 return LowerCCCCallTo(Op,DAG, CallingConv);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004241 case CallingConv::C:
4242 case CallingConv::X86_StdCall:
4243 return LowerCCCCallTo(Op, DAG, CallingConv);
4244 case CallingConv::X86_FastCall:
4245 return LowerFastCCCallTo(Op, DAG, CallingConv);
4246 }
4247}
4248
4249
4250// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4251// Calls to _alloca is needed to probe the stack when allocating more than 4k
4252// bytes in one go. Touching the stack at 4K increments is necessary to ensure
4253// that the guard pages used by the OS virtual memory manager are allocated in
4254// correct sequence.
4255SDOperand
4256X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4257 SelectionDAG &DAG) {
4258 assert(Subtarget->isTargetCygMing() &&
4259 "This should be used only on Cygwin/Mingw targets");
4260
4261 // Get the inputs.
4262 SDOperand Chain = Op.getOperand(0);
4263 SDOperand Size = Op.getOperand(1);
4264 // FIXME: Ensure alignment here
4265
4266 SDOperand Flag;
4267
4268 MVT::ValueType IntPtr = getPointerTy();
4269 MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
4270
4271 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4272 Flag = Chain.getValue(1);
4273
4274 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4275 SDOperand Ops[] = { Chain,
4276 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4277 DAG.getRegister(X86::EAX, IntPtr),
4278 Flag };
4279 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4280 Flag = Chain.getValue(1);
4281
4282 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4283
4284 std::vector<MVT::ValueType> Tys;
4285 Tys.push_back(SPTy);
4286 Tys.push_back(MVT::Other);
4287 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4288 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4289}
4290
4291SDOperand
4292X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
4293 MachineFunction &MF = DAG.getMachineFunction();
4294 const Function* Fn = MF.getFunction();
4295 if (Fn->hasExternalLinkage() &&
4296 Subtarget->isTargetCygMing() &&
4297 Fn->getName() == "main")
4298 MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
4299
4300 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4301 if (Subtarget->is64Bit())
4302 return LowerX86_64CCCArguments(Op, DAG);
4303 else
4304 switch(CC) {
4305 default:
4306 assert(0 && "Unsupported calling convention");
4307 case CallingConv::Fast:
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004308 return LowerCCCArguments(Op,DAG, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004309 // Falls through
4310 case CallingConv::C:
4311 return LowerCCCArguments(Op, DAG);
4312 case CallingConv::X86_StdCall:
4313 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
4314 return LowerCCCArguments(Op, DAG, true);
4315 case CallingConv::X86_FastCall:
4316 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
4317 return LowerFastCCArguments(Op, DAG);
4318 }
4319}
4320
4321SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4322 SDOperand InFlag(0, 0);
4323 SDOperand Chain = Op.getOperand(0);
4324 unsigned Align =
4325 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4326 if (Align == 0) Align = 1;
4327
4328 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
Rafael Espindola5d3e7622007-08-27 10:18:20 +00004329 // If not DWORD aligned or size is more than the threshold, call memset.
Rafael Espindolab2e7a6b2007-08-27 17:48:26 +00004330 // The libc version is likely to be faster for these cases. It can use the
4331 // address value and run time information about the CPU.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004332 if ((Align & 3) != 0 ||
Rafael Espindola5d3e7622007-08-27 10:18:20 +00004333 (I && I->getValue() > Subtarget->getMinRepStrSizeThreshold())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004334 MVT::ValueType IntPtr = getPointerTy();
4335 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4336 TargetLowering::ArgListTy Args;
4337 TargetLowering::ArgListEntry Entry;
4338 Entry.Node = Op.getOperand(1);
4339 Entry.Ty = IntPtrTy;
4340 Args.push_back(Entry);
4341 // Extend the unsigned i8 argument to be an int value for the call.
4342 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4343 Entry.Ty = IntPtrTy;
4344 Args.push_back(Entry);
4345 Entry.Node = Op.getOperand(3);
4346 Args.push_back(Entry);
4347 std::pair<SDOperand,SDOperand> CallResult =
4348 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4349 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4350 return CallResult.second;
4351 }
4352
4353 MVT::ValueType AVT;
4354 SDOperand Count;
4355 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4356 unsigned BytesLeft = 0;
4357 bool TwoRepStos = false;
4358 if (ValC) {
4359 unsigned ValReg;
4360 uint64_t Val = ValC->getValue() & 255;
4361
4362 // If the value is a constant, then we can potentially use larger sets.
4363 switch (Align & 3) {
4364 case 2: // WORD aligned
4365 AVT = MVT::i16;
4366 ValReg = X86::AX;
4367 Val = (Val << 8) | Val;
4368 break;
4369 case 0: // DWORD aligned
4370 AVT = MVT::i32;
4371 ValReg = X86::EAX;
4372 Val = (Val << 8) | Val;
4373 Val = (Val << 16) | Val;
4374 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4375 AVT = MVT::i64;
4376 ValReg = X86::RAX;
4377 Val = (Val << 32) | Val;
4378 }
4379 break;
4380 default: // Byte aligned
4381 AVT = MVT::i8;
4382 ValReg = X86::AL;
4383 Count = Op.getOperand(3);
4384 break;
4385 }
4386
4387 if (AVT > MVT::i8) {
4388 if (I) {
4389 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4390 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
4391 BytesLeft = I->getValue() % UBytes;
4392 } else {
4393 assert(AVT >= MVT::i32 &&
4394 "Do not use rep;stos if not at least DWORD aligned");
4395 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4396 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4397 TwoRepStos = true;
4398 }
4399 }
4400
4401 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4402 InFlag);
4403 InFlag = Chain.getValue(1);
4404 } else {
4405 AVT = MVT::i8;
4406 Count = Op.getOperand(3);
4407 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4408 InFlag = Chain.getValue(1);
4409 }
4410
4411 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4412 Count, InFlag);
4413 InFlag = Chain.getValue(1);
4414 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4415 Op.getOperand(1), InFlag);
4416 InFlag = Chain.getValue(1);
4417
4418 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4419 SmallVector<SDOperand, 8> Ops;
4420 Ops.push_back(Chain);
4421 Ops.push_back(DAG.getValueType(AVT));
4422 Ops.push_back(InFlag);
4423 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4424
4425 if (TwoRepStos) {
4426 InFlag = Chain.getValue(1);
4427 Count = Op.getOperand(3);
4428 MVT::ValueType CVT = Count.getValueType();
4429 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4430 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4431 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4432 Left, InFlag);
4433 InFlag = Chain.getValue(1);
4434 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4435 Ops.clear();
4436 Ops.push_back(Chain);
4437 Ops.push_back(DAG.getValueType(MVT::i8));
4438 Ops.push_back(InFlag);
4439 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4440 } else if (BytesLeft) {
4441 // Issue stores for the last 1 - 7 bytes.
4442 SDOperand Value;
4443 unsigned Val = ValC->getValue() & 255;
4444 unsigned Offset = I->getValue() - BytesLeft;
4445 SDOperand DstAddr = Op.getOperand(1);
4446 MVT::ValueType AddrVT = DstAddr.getValueType();
4447 if (BytesLeft >= 4) {
4448 Val = (Val << 8) | Val;
4449 Val = (Val << 16) | Val;
4450 Value = DAG.getConstant(Val, MVT::i32);
4451 Chain = DAG.getStore(Chain, Value,
4452 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4453 DAG.getConstant(Offset, AddrVT)),
4454 NULL, 0);
4455 BytesLeft -= 4;
4456 Offset += 4;
4457 }
4458 if (BytesLeft >= 2) {
4459 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4460 Chain = DAG.getStore(Chain, Value,
4461 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4462 DAG.getConstant(Offset, AddrVT)),
4463 NULL, 0);
4464 BytesLeft -= 2;
4465 Offset += 2;
4466 }
4467 if (BytesLeft == 1) {
4468 Value = DAG.getConstant(Val, MVT::i8);
4469 Chain = DAG.getStore(Chain, Value,
4470 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4471 DAG.getConstant(Offset, AddrVT)),
4472 NULL, 0);
4473 }
4474 }
4475
4476 return Chain;
4477}
4478
4479SDOperand X86TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004480 SDOperand ChainOp = Op.getOperand(0);
4481 SDOperand DestOp = Op.getOperand(1);
4482 SDOperand SourceOp = Op.getOperand(2);
4483 SDOperand CountOp = Op.getOperand(3);
4484 SDOperand AlignOp = Op.getOperand(4);
Rafael Espindola80825902007-10-19 10:41:11 +00004485 SDOperand AlwaysInlineOp = Op.getOperand(5);
4486
4487 bool AlwaysInline = (bool)cast<ConstantSDNode>(AlwaysInlineOp)->getValue();
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004488 unsigned Align = (unsigned)cast<ConstantSDNode>(AlignOp)->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004489 if (Align == 0) Align = 1;
4490
Rafael Espindola80825902007-10-19 10:41:11 +00004491 // If size is unknown, call memcpy.
4492 ConstantSDNode *I = dyn_cast<ConstantSDNode>(CountOp);
4493 if (!I) {
4494 assert(!AlwaysInline && "Cannot inline copy of unknown size");
4495 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
4496 }
4497 unsigned Size = I->getValue();
4498
4499 if (AlwaysInline)
4500 return LowerMEMCPYInline(ChainOp, DestOp, SourceOp, Size, Align, DAG);
4501
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004502 // The libc version is likely to be faster for the following cases. It can
4503 // use the address value and run time information about the CPU.
Rafael Espindolab2e7a6b2007-08-27 17:48:26 +00004504 // With glibc 2.6.1 on a core 2, coping an array of 100M longs was 30% faster
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004505
4506 // If not DWORD aligned, call memcpy.
4507 if ((Align & 3) != 0)
4508 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
4509
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004510 // If size is more than the threshold, call memcpy.
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004511 if (Size > Subtarget->getMinRepStrSizeThreshold())
4512 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
4513
4514 return LowerMEMCPYInline(ChainOp, DestOp, SourceOp, Size, Align, DAG);
4515}
4516
4517SDOperand X86TargetLowering::LowerMEMCPYCall(SDOperand Chain,
4518 SDOperand Dest,
4519 SDOperand Source,
4520 SDOperand Count,
4521 SelectionDAG &DAG) {
4522 MVT::ValueType IntPtr = getPointerTy();
4523 TargetLowering::ArgListTy Args;
4524 TargetLowering::ArgListEntry Entry;
4525 Entry.Ty = getTargetData()->getIntPtrType();
4526 Entry.Node = Dest; Args.push_back(Entry);
4527 Entry.Node = Source; Args.push_back(Entry);
4528 Entry.Node = Count; Args.push_back(Entry);
4529 std::pair<SDOperand,SDOperand> CallResult =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004530 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4531 DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004532 return CallResult.second;
4533}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004534
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004535SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4536 SDOperand Dest,
4537 SDOperand Source,
4538 unsigned Size,
4539 unsigned Align,
4540 SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004541 MVT::ValueType AVT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004542 unsigned BytesLeft = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004543 switch (Align & 3) {
4544 case 2: // WORD aligned
4545 AVT = MVT::i16;
4546 break;
4547 case 0: // DWORD aligned
4548 AVT = MVT::i32;
4549 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4550 AVT = MVT::i64;
4551 break;
4552 default: // Byte aligned
4553 AVT = MVT::i8;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004554 break;
4555 }
4556
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004557 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4558 SDOperand Count = DAG.getConstant(Size / UBytes, getPointerTy());
4559 BytesLeft = Size % UBytes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004560
4561 SDOperand InFlag(0, 0);
4562 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4563 Count, InFlag);
4564 InFlag = Chain.getValue(1);
4565 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004566 Dest, InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004567 InFlag = Chain.getValue(1);
4568 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004569 Source, InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004570 InFlag = Chain.getValue(1);
4571
4572 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4573 SmallVector<SDOperand, 8> Ops;
4574 Ops.push_back(Chain);
4575 Ops.push_back(DAG.getValueType(AVT));
4576 Ops.push_back(InFlag);
4577 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4578
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004579 if (BytesLeft) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004580 // Issue loads and stores for the last 1 - 7 bytes.
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004581 unsigned Offset = Size - BytesLeft;
4582 SDOperand DstAddr = Dest;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004583 MVT::ValueType DstVT = DstAddr.getValueType();
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004584 SDOperand SrcAddr = Source;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004585 MVT::ValueType SrcVT = SrcAddr.getValueType();
4586 SDOperand Value;
4587 if (BytesLeft >= 4) {
4588 Value = DAG.getLoad(MVT::i32, Chain,
4589 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4590 DAG.getConstant(Offset, SrcVT)),
4591 NULL, 0);
4592 Chain = Value.getValue(1);
4593 Chain = DAG.getStore(Chain, Value,
4594 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4595 DAG.getConstant(Offset, DstVT)),
4596 NULL, 0);
4597 BytesLeft -= 4;
4598 Offset += 4;
4599 }
4600 if (BytesLeft >= 2) {
4601 Value = DAG.getLoad(MVT::i16, Chain,
4602 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4603 DAG.getConstant(Offset, SrcVT)),
4604 NULL, 0);
4605 Chain = Value.getValue(1);
4606 Chain = DAG.getStore(Chain, Value,
4607 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4608 DAG.getConstant(Offset, DstVT)),
4609 NULL, 0);
4610 BytesLeft -= 2;
4611 Offset += 2;
4612 }
4613
4614 if (BytesLeft == 1) {
4615 Value = DAG.getLoad(MVT::i8, Chain,
4616 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4617 DAG.getConstant(Offset, SrcVT)),
4618 NULL, 0);
4619 Chain = Value.getValue(1);
4620 Chain = DAG.getStore(Chain, Value,
4621 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4622 DAG.getConstant(Offset, DstVT)),
4623 NULL, 0);
4624 }
4625 }
4626
4627 return Chain;
4628}
4629
4630SDOperand
4631X86TargetLowering::LowerREADCYCLCECOUNTER(SDOperand Op, SelectionDAG &DAG) {
4632 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4633 SDOperand TheOp = Op.getOperand(0);
4634 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheOp, 1);
4635 if (Subtarget->is64Bit()) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004636 SDOperand Copy1 =
4637 DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004638 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::RDX,
4639 MVT::i64, Copy1.getValue(2));
4640 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, Copy2,
4641 DAG.getConstant(32, MVT::i8));
4642 SDOperand Ops[] = {
4643 DAG.getNode(ISD::OR, MVT::i64, Copy1, Tmp), Copy2.getValue(1)
4644 };
4645
4646 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4647 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2);
4648 }
4649
4650 SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4651 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::EDX,
4652 MVT::i32, Copy1.getValue(2));
4653 SDOperand Ops[] = { Copy1, Copy2, Copy2.getValue(1) };
4654 Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
4655 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 3);
4656}
4657
4658SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4659 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
4660
4661 if (!Subtarget->is64Bit()) {
4662 // vastart just stores the address of the VarArgsFrameIndex slot into the
4663 // memory location argument.
4664 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4665 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
4666 SV->getOffset());
4667 }
4668
4669 // __va_list_tag:
4670 // gp_offset (0 - 6 * 8)
4671 // fp_offset (48 - 48 + 8 * 16)
4672 // overflow_arg_area (point to parameters coming in memory).
4673 // reg_save_area
4674 SmallVector<SDOperand, 8> MemOps;
4675 SDOperand FIN = Op.getOperand(1);
4676 // Store gp_offset
4677 SDOperand Store = DAG.getStore(Op.getOperand(0),
4678 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4679 FIN, SV->getValue(), SV->getOffset());
4680 MemOps.push_back(Store);
4681
4682 // Store fp_offset
4683 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4684 DAG.getConstant(4, getPointerTy()));
4685 Store = DAG.getStore(Op.getOperand(0),
4686 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4687 FIN, SV->getValue(), SV->getOffset());
4688 MemOps.push_back(Store);
4689
4690 // Store ptr to overflow_arg_area
4691 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4692 DAG.getConstant(4, getPointerTy()));
4693 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4694 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
4695 SV->getOffset());
4696 MemOps.push_back(Store);
4697
4698 // Store ptr to reg_save_area.
4699 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4700 DAG.getConstant(8, getPointerTy()));
4701 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4702 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
4703 SV->getOffset());
4704 MemOps.push_back(Store);
4705 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4706}
4707
4708SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4709 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4710 SDOperand Chain = Op.getOperand(0);
4711 SDOperand DstPtr = Op.getOperand(1);
4712 SDOperand SrcPtr = Op.getOperand(2);
4713 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
4714 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
4715
4716 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
4717 SrcSV->getValue(), SrcSV->getOffset());
4718 Chain = SrcPtr.getValue(1);
4719 for (unsigned i = 0; i < 3; ++i) {
4720 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
4721 SrcSV->getValue(), SrcSV->getOffset());
4722 Chain = Val.getValue(1);
4723 Chain = DAG.getStore(Chain, Val, DstPtr,
4724 DstSV->getValue(), DstSV->getOffset());
4725 if (i == 2)
4726 break;
4727 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
4728 DAG.getConstant(8, getPointerTy()));
4729 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
4730 DAG.getConstant(8, getPointerTy()));
4731 }
4732 return Chain;
4733}
4734
4735SDOperand
4736X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4737 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4738 switch (IntNo) {
4739 default: return SDOperand(); // Don't custom lower most intrinsics.
4740 // Comparison intrinsics.
4741 case Intrinsic::x86_sse_comieq_ss:
4742 case Intrinsic::x86_sse_comilt_ss:
4743 case Intrinsic::x86_sse_comile_ss:
4744 case Intrinsic::x86_sse_comigt_ss:
4745 case Intrinsic::x86_sse_comige_ss:
4746 case Intrinsic::x86_sse_comineq_ss:
4747 case Intrinsic::x86_sse_ucomieq_ss:
4748 case Intrinsic::x86_sse_ucomilt_ss:
4749 case Intrinsic::x86_sse_ucomile_ss:
4750 case Intrinsic::x86_sse_ucomigt_ss:
4751 case Intrinsic::x86_sse_ucomige_ss:
4752 case Intrinsic::x86_sse_ucomineq_ss:
4753 case Intrinsic::x86_sse2_comieq_sd:
4754 case Intrinsic::x86_sse2_comilt_sd:
4755 case Intrinsic::x86_sse2_comile_sd:
4756 case Intrinsic::x86_sse2_comigt_sd:
4757 case Intrinsic::x86_sse2_comige_sd:
4758 case Intrinsic::x86_sse2_comineq_sd:
4759 case Intrinsic::x86_sse2_ucomieq_sd:
4760 case Intrinsic::x86_sse2_ucomilt_sd:
4761 case Intrinsic::x86_sse2_ucomile_sd:
4762 case Intrinsic::x86_sse2_ucomigt_sd:
4763 case Intrinsic::x86_sse2_ucomige_sd:
4764 case Intrinsic::x86_sse2_ucomineq_sd: {
4765 unsigned Opc = 0;
4766 ISD::CondCode CC = ISD::SETCC_INVALID;
4767 switch (IntNo) {
4768 default: break;
4769 case Intrinsic::x86_sse_comieq_ss:
4770 case Intrinsic::x86_sse2_comieq_sd:
4771 Opc = X86ISD::COMI;
4772 CC = ISD::SETEQ;
4773 break;
4774 case Intrinsic::x86_sse_comilt_ss:
4775 case Intrinsic::x86_sse2_comilt_sd:
4776 Opc = X86ISD::COMI;
4777 CC = ISD::SETLT;
4778 break;
4779 case Intrinsic::x86_sse_comile_ss:
4780 case Intrinsic::x86_sse2_comile_sd:
4781 Opc = X86ISD::COMI;
4782 CC = ISD::SETLE;
4783 break;
4784 case Intrinsic::x86_sse_comigt_ss:
4785 case Intrinsic::x86_sse2_comigt_sd:
4786 Opc = X86ISD::COMI;
4787 CC = ISD::SETGT;
4788 break;
4789 case Intrinsic::x86_sse_comige_ss:
4790 case Intrinsic::x86_sse2_comige_sd:
4791 Opc = X86ISD::COMI;
4792 CC = ISD::SETGE;
4793 break;
4794 case Intrinsic::x86_sse_comineq_ss:
4795 case Intrinsic::x86_sse2_comineq_sd:
4796 Opc = X86ISD::COMI;
4797 CC = ISD::SETNE;
4798 break;
4799 case Intrinsic::x86_sse_ucomieq_ss:
4800 case Intrinsic::x86_sse2_ucomieq_sd:
4801 Opc = X86ISD::UCOMI;
4802 CC = ISD::SETEQ;
4803 break;
4804 case Intrinsic::x86_sse_ucomilt_ss:
4805 case Intrinsic::x86_sse2_ucomilt_sd:
4806 Opc = X86ISD::UCOMI;
4807 CC = ISD::SETLT;
4808 break;
4809 case Intrinsic::x86_sse_ucomile_ss:
4810 case Intrinsic::x86_sse2_ucomile_sd:
4811 Opc = X86ISD::UCOMI;
4812 CC = ISD::SETLE;
4813 break;
4814 case Intrinsic::x86_sse_ucomigt_ss:
4815 case Intrinsic::x86_sse2_ucomigt_sd:
4816 Opc = X86ISD::UCOMI;
4817 CC = ISD::SETGT;
4818 break;
4819 case Intrinsic::x86_sse_ucomige_ss:
4820 case Intrinsic::x86_sse2_ucomige_sd:
4821 Opc = X86ISD::UCOMI;
4822 CC = ISD::SETGE;
4823 break;
4824 case Intrinsic::x86_sse_ucomineq_ss:
4825 case Intrinsic::x86_sse2_ucomineq_sd:
4826 Opc = X86ISD::UCOMI;
4827 CC = ISD::SETNE;
4828 break;
4829 }
4830
4831 unsigned X86CC;
4832 SDOperand LHS = Op.getOperand(1);
4833 SDOperand RHS = Op.getOperand(2);
4834 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4835
Evan Cheng621216e2007-09-29 00:00:36 +00004836 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
4837 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
4838 DAG.getConstant(X86CC, MVT::i8), Cond);
4839 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004840 }
4841 }
4842}
4843
4844SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4845 // Depths > 0 not supported yet!
4846 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4847 return SDOperand();
4848
4849 // Just load the return address
4850 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4851 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4852}
4853
4854SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4855 // Depths > 0 not supported yet!
4856 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4857 return SDOperand();
4858
4859 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4860 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
4861 DAG.getConstant(4, getPointerTy()));
4862}
4863
4864SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
4865 SelectionDAG &DAG) {
4866 // Is not yet supported on x86-64
4867 if (Subtarget->is64Bit())
4868 return SDOperand();
4869
4870 return DAG.getConstant(8, getPointerTy());
4871}
4872
4873SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
4874{
4875 assert(!Subtarget->is64Bit() &&
4876 "Lowering of eh_return builtin is not supported yet on x86-64");
4877
4878 MachineFunction &MF = DAG.getMachineFunction();
4879 SDOperand Chain = Op.getOperand(0);
4880 SDOperand Offset = Op.getOperand(1);
4881 SDOperand Handler = Op.getOperand(2);
4882
4883 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
4884 getPointerTy());
4885
4886 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
4887 DAG.getConstant(-4UL, getPointerTy()));
4888 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
4889 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
4890 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
4891 MF.addLiveOut(X86::ECX);
4892
4893 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
4894 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
4895}
4896
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004897SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
4898 SelectionDAG &DAG) {
4899 SDOperand Root = Op.getOperand(0);
4900 SDOperand Trmp = Op.getOperand(1); // trampoline
4901 SDOperand FPtr = Op.getOperand(2); // nested function
4902 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
4903
4904 SrcValueSDNode *TrmpSV = cast<SrcValueSDNode>(Op.getOperand(4));
4905
4906 if (Subtarget->is64Bit()) {
4907 return SDOperand(); // not yet supported
4908 } else {
4909 Function *Func = (Function *)
4910 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
4911 unsigned CC = Func->getCallingConv();
Duncan Sands466eadd2007-08-29 19:01:20 +00004912 unsigned NestReg;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004913
4914 switch (CC) {
4915 default:
4916 assert(0 && "Unsupported calling convention");
4917 case CallingConv::C:
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004918 case CallingConv::X86_StdCall: {
4919 // Pass 'nest' parameter in ECX.
4920 // Must be kept in sync with X86CallingConv.td
Duncan Sands466eadd2007-08-29 19:01:20 +00004921 NestReg = X86::ECX;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004922
4923 // Check that ECX wasn't needed by an 'inreg' parameter.
4924 const FunctionType *FTy = Func->getFunctionType();
4925 const ParamAttrsList *Attrs = FTy->getParamAttrs();
4926
4927 if (Attrs && !Func->isVarArg()) {
4928 unsigned InRegCount = 0;
4929 unsigned Idx = 1;
4930
4931 for (FunctionType::param_iterator I = FTy->param_begin(),
4932 E = FTy->param_end(); I != E; ++I, ++Idx)
4933 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
4934 // FIXME: should only count parameters that are lowered to integers.
4935 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
4936
4937 if (InRegCount > 2) {
4938 cerr << "Nest register in use - reduce number of inreg parameters!\n";
4939 abort();
4940 }
4941 }
4942 break;
4943 }
4944 case CallingConv::X86_FastCall:
4945 // Pass 'nest' parameter in EAX.
4946 // Must be kept in sync with X86CallingConv.td
Duncan Sands466eadd2007-08-29 19:01:20 +00004947 NestReg = X86::EAX;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004948 break;
4949 }
4950
Duncan Sands466eadd2007-08-29 19:01:20 +00004951 const X86InstrInfo *TII =
4952 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
4953
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004954 SDOperand OutChains[4];
4955 SDOperand Addr, Disp;
4956
4957 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
4958 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
4959
Duncan Sands466eadd2007-08-29 19:01:20 +00004960 unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
4961 unsigned char N86Reg = ((X86RegisterInfo&)RegInfo).getX86RegNum(NestReg);
4962 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004963 Trmp, TrmpSV->getValue(), TrmpSV->getOffset());
4964
4965 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
4966 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpSV->getValue(),
4967 TrmpSV->getOffset() + 1, false, 1);
4968
Duncan Sands466eadd2007-08-29 19:01:20 +00004969 unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004970 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
4971 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
4972 TrmpSV->getValue() + 5, TrmpSV->getOffset());
4973
4974 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
4975 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpSV->getValue(),
4976 TrmpSV->getOffset() + 6, false, 1);
4977
Duncan Sands7407a9f2007-09-11 14:10:23 +00004978 SDOperand Ops[] =
4979 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
4980 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004981 }
4982}
4983
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004984/// LowerOperation - Provide custom lowering hooks for some operations.
4985///
4986SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4987 switch (Op.getOpcode()) {
4988 default: assert(0 && "Should not custom lower this!");
4989 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
4990 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
4991 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4992 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
4993 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
4994 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
4995 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
4996 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
4997 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
4998 case ISD::SHL_PARTS:
4999 case ISD::SRA_PARTS:
5000 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5001 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5002 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5003 case ISD::FABS: return LowerFABS(Op, DAG);
5004 case ISD::FNEG: return LowerFNEG(Op, DAG);
5005 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
Evan Cheng621216e2007-09-29 00:00:36 +00005006 case ISD::SETCC: return LowerSETCC(Op, DAG);
5007 case ISD::SELECT: return LowerSELECT(Op, DAG);
5008 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005009 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5010 case ISD::CALL: return LowerCALL(Op, DAG);
5011 case ISD::RET: return LowerRET(Op, DAG);
5012 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5013 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5014 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
5015 case ISD::READCYCLECOUNTER: return LowerREADCYCLCECOUNTER(Op, DAG);
5016 case ISD::VASTART: return LowerVASTART(Op, DAG);
5017 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5018 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5019 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5020 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5021 case ISD::FRAME_TO_ARGS_OFFSET:
5022 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5023 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5024 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005025 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005026 }
5027 return SDOperand();
5028}
5029
5030const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5031 switch (Opcode) {
5032 default: return NULL;
5033 case X86ISD::SHLD: return "X86ISD::SHLD";
5034 case X86ISD::SHRD: return "X86ISD::SHRD";
5035 case X86ISD::FAND: return "X86ISD::FAND";
5036 case X86ISD::FOR: return "X86ISD::FOR";
5037 case X86ISD::FXOR: return "X86ISD::FXOR";
5038 case X86ISD::FSRL: return "X86ISD::FSRL";
5039 case X86ISD::FILD: return "X86ISD::FILD";
5040 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5041 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5042 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5043 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5044 case X86ISD::FLD: return "X86ISD::FLD";
5045 case X86ISD::FST: return "X86ISD::FST";
5046 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5047 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5048 case X86ISD::CALL: return "X86ISD::CALL";
5049 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5050 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5051 case X86ISD::CMP: return "X86ISD::CMP";
5052 case X86ISD::COMI: return "X86ISD::COMI";
5053 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5054 case X86ISD::SETCC: return "X86ISD::SETCC";
5055 case X86ISD::CMOV: return "X86ISD::CMOV";
5056 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5057 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5058 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5059 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005060 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5061 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5062 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5063 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5064 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5065 case X86ISD::FMAX: return "X86ISD::FMAX";
5066 case X86ISD::FMIN: return "X86ISD::FMIN";
5067 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5068 case X86ISD::FRCP: return "X86ISD::FRCP";
5069 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5070 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5071 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00005072 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005073 }
5074}
5075
5076// isLegalAddressingMode - Return true if the addressing mode represented
5077// by AM is legal for this target, for a load/store of the specified type.
5078bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5079 const Type *Ty) const {
5080 // X86 supports extremely general addressing modes.
5081
5082 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5083 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5084 return false;
5085
5086 if (AM.BaseGV) {
Evan Cheng6a1f3f12007-08-01 23:46:47 +00005087 // We can only fold this if we don't need an extra load.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005088 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5089 return false;
Evan Cheng6a1f3f12007-08-01 23:46:47 +00005090
5091 // X86-64 only supports addr of globals in small code model.
5092 if (Subtarget->is64Bit()) {
5093 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5094 return false;
5095 // If lower 4G is not available, then we must use rip-relative addressing.
5096 if (AM.BaseOffs || AM.Scale > 1)
5097 return false;
5098 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005099 }
5100
5101 switch (AM.Scale) {
5102 case 0:
5103 case 1:
5104 case 2:
5105 case 4:
5106 case 8:
5107 // These scales always work.
5108 break;
5109 case 3:
5110 case 5:
5111 case 9:
5112 // These scales are formed with basereg+scalereg. Only accept if there is
5113 // no basereg yet.
5114 if (AM.HasBaseReg)
5115 return false;
5116 break;
5117 default: // Other stuff never works.
5118 return false;
5119 }
5120
5121 return true;
5122}
5123
5124
5125/// isShuffleMaskLegal - Targets can use this to indicate that they only
5126/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5127/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5128/// are assumed to be legal.
5129bool
5130X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5131 // Only do shuffles on 128-bit vector types for now.
5132 if (MVT::getSizeInBits(VT) == 64) return false;
5133 return (Mask.Val->getNumOperands() <= 4 ||
5134 isIdentityMask(Mask.Val) ||
5135 isIdentityMask(Mask.Val, true) ||
5136 isSplatMask(Mask.Val) ||
5137 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5138 X86::isUNPCKLMask(Mask.Val) ||
5139 X86::isUNPCKHMask(Mask.Val) ||
5140 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5141 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5142}
5143
5144bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5145 MVT::ValueType EVT,
5146 SelectionDAG &DAG) const {
5147 unsigned NumElts = BVOps.size();
5148 // Only do shuffles on 128-bit vector types for now.
5149 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5150 if (NumElts == 2) return true;
5151 if (NumElts == 4) {
5152 return (isMOVLMask(&BVOps[0], 4) ||
5153 isCommutedMOVL(&BVOps[0], 4, true) ||
5154 isSHUFPMask(&BVOps[0], 4) ||
5155 isCommutedSHUFP(&BVOps[0], 4));
5156 }
5157 return false;
5158}
5159
5160//===----------------------------------------------------------------------===//
5161// X86 Scheduler Hooks
5162//===----------------------------------------------------------------------===//
5163
5164MachineBasicBlock *
5165X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
5166 MachineBasicBlock *BB) {
5167 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5168 switch (MI->getOpcode()) {
5169 default: assert(false && "Unexpected instr type to insert");
5170 case X86::CMOV_FR32:
5171 case X86::CMOV_FR64:
5172 case X86::CMOV_V4F32:
5173 case X86::CMOV_V2F64:
Evan Cheng621216e2007-09-29 00:00:36 +00005174 case X86::CMOV_V2I64: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005175 // To "insert" a SELECT_CC instruction, we actually have to insert the
5176 // diamond control-flow pattern. The incoming instruction knows the
5177 // destination vreg to set, the condition code register to branch on, the
5178 // true/false values to select between, and a branch opcode to use.
5179 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5180 ilist<MachineBasicBlock>::iterator It = BB;
5181 ++It;
5182
5183 // thisMBB:
5184 // ...
5185 // TrueVal = ...
5186 // cmpTY ccX, r1, r2
5187 // bCC copy1MBB
5188 // fallthrough --> copy0MBB
5189 MachineBasicBlock *thisMBB = BB;
5190 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5191 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5192 unsigned Opc =
5193 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5194 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5195 MachineFunction *F = BB->getParent();
5196 F->getBasicBlockList().insert(It, copy0MBB);
5197 F->getBasicBlockList().insert(It, sinkMBB);
5198 // Update machine-CFG edges by first adding all successors of the current
5199 // block to the new block which will contain the Phi node for the select.
5200 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5201 e = BB->succ_end(); i != e; ++i)
5202 sinkMBB->addSuccessor(*i);
5203 // Next, remove all successors of the current block, and add the true
5204 // and fallthrough blocks as its successors.
5205 while(!BB->succ_empty())
5206 BB->removeSuccessor(BB->succ_begin());
5207 BB->addSuccessor(copy0MBB);
5208 BB->addSuccessor(sinkMBB);
5209
5210 // copy0MBB:
5211 // %FalseValue = ...
5212 // # fallthrough to sinkMBB
5213 BB = copy0MBB;
5214
5215 // Update machine-CFG edges
5216 BB->addSuccessor(sinkMBB);
5217
5218 // sinkMBB:
5219 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5220 // ...
5221 BB = sinkMBB;
5222 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5223 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5224 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5225
5226 delete MI; // The pseudo instruction is gone now.
5227 return BB;
5228 }
5229
5230 case X86::FP32_TO_INT16_IN_MEM:
5231 case X86::FP32_TO_INT32_IN_MEM:
5232 case X86::FP32_TO_INT64_IN_MEM:
5233 case X86::FP64_TO_INT16_IN_MEM:
5234 case X86::FP64_TO_INT32_IN_MEM:
Dale Johannesen6d0e36a2007-08-07 01:17:37 +00005235 case X86::FP64_TO_INT64_IN_MEM:
5236 case X86::FP80_TO_INT16_IN_MEM:
5237 case X86::FP80_TO_INT32_IN_MEM:
5238 case X86::FP80_TO_INT64_IN_MEM: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005239 // Change the floating point control register to use "round towards zero"
5240 // mode when truncating to an integer value.
5241 MachineFunction *F = BB->getParent();
5242 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5243 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5244
5245 // Load the old value of the high byte of the control word...
5246 unsigned OldCW =
5247 F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
5248 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5249
5250 // Set the high part to be round to zero...
5251 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5252 .addImm(0xC7F);
5253
5254 // Reload the modified control word now...
5255 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5256
5257 // Restore the memory image of control word to original value
5258 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5259 .addReg(OldCW);
5260
5261 // Get the X86 opcode to use.
5262 unsigned Opc;
5263 switch (MI->getOpcode()) {
5264 default: assert(0 && "illegal opcode!");
5265 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5266 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5267 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5268 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5269 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5270 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
Dale Johannesen6d0e36a2007-08-07 01:17:37 +00005271 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5272 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5273 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005274 }
5275
5276 X86AddressMode AM;
5277 MachineOperand &Op = MI->getOperand(0);
5278 if (Op.isRegister()) {
5279 AM.BaseType = X86AddressMode::RegBase;
5280 AM.Base.Reg = Op.getReg();
5281 } else {
5282 AM.BaseType = X86AddressMode::FrameIndexBase;
5283 AM.Base.FrameIndex = Op.getFrameIndex();
5284 }
5285 Op = MI->getOperand(1);
5286 if (Op.isImmediate())
5287 AM.Scale = Op.getImm();
5288 Op = MI->getOperand(2);
5289 if (Op.isImmediate())
5290 AM.IndexReg = Op.getImm();
5291 Op = MI->getOperand(3);
5292 if (Op.isGlobalAddress()) {
5293 AM.GV = Op.getGlobal();
5294 } else {
5295 AM.Disp = Op.getImm();
5296 }
5297 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5298 .addReg(MI->getOperand(4).getReg());
5299
5300 // Reload the original control word now.
5301 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5302
5303 delete MI; // The pseudo instruction is gone now.
5304 return BB;
5305 }
5306 }
5307}
5308
5309//===----------------------------------------------------------------------===//
5310// X86 Optimization Hooks
5311//===----------------------------------------------------------------------===//
5312
5313void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5314 uint64_t Mask,
5315 uint64_t &KnownZero,
5316 uint64_t &KnownOne,
5317 const SelectionDAG &DAG,
5318 unsigned Depth) const {
5319 unsigned Opc = Op.getOpcode();
5320 assert((Opc >= ISD::BUILTIN_OP_END ||
5321 Opc == ISD::INTRINSIC_WO_CHAIN ||
5322 Opc == ISD::INTRINSIC_W_CHAIN ||
5323 Opc == ISD::INTRINSIC_VOID) &&
5324 "Should use MaskedValueIsZero if you don't know whether Op"
5325 " is a target node!");
5326
5327 KnownZero = KnownOne = 0; // Don't know anything.
5328 switch (Opc) {
5329 default: break;
5330 case X86ISD::SETCC:
5331 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5332 break;
5333 }
5334}
5335
5336/// getShuffleScalarElt - Returns the scalar element that will make up the ith
5337/// element of the result of the vector shuffle.
5338static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5339 MVT::ValueType VT = N->getValueType(0);
5340 SDOperand PermMask = N->getOperand(2);
5341 unsigned NumElems = PermMask.getNumOperands();
5342 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5343 i %= NumElems;
5344 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5345 return (i == 0)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00005346 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005347 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5348 SDOperand Idx = PermMask.getOperand(i);
5349 if (Idx.getOpcode() == ISD::UNDEF)
5350 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5351 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5352 }
5353 return SDOperand();
5354}
5355
5356/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5357/// node is a GlobalAddress + an offset.
5358static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5359 unsigned Opc = N->getOpcode();
5360 if (Opc == X86ISD::Wrapper) {
5361 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5362 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5363 return true;
5364 }
5365 } else if (Opc == ISD::ADD) {
5366 SDOperand N1 = N->getOperand(0);
5367 SDOperand N2 = N->getOperand(1);
5368 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5369 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5370 if (V) {
5371 Offset += V->getSignExtended();
5372 return true;
5373 }
5374 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5375 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5376 if (V) {
5377 Offset += V->getSignExtended();
5378 return true;
5379 }
5380 }
5381 }
5382 return false;
5383}
5384
5385/// isConsecutiveLoad - Returns true if N is loading from an address of Base
5386/// + Dist * Size.
5387static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5388 MachineFrameInfo *MFI) {
5389 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5390 return false;
5391
5392 SDOperand Loc = N->getOperand(1);
5393 SDOperand BaseLoc = Base->getOperand(1);
5394 if (Loc.getOpcode() == ISD::FrameIndex) {
5395 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5396 return false;
Dan Gohman53491e92007-07-23 20:24:29 +00005397 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5398 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005399 int FS = MFI->getObjectSize(FI);
5400 int BFS = MFI->getObjectSize(BFI);
5401 if (FS != BFS || FS != Size) return false;
5402 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5403 } else {
5404 GlobalValue *GV1 = NULL;
5405 GlobalValue *GV2 = NULL;
5406 int64_t Offset1 = 0;
5407 int64_t Offset2 = 0;
5408 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5409 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5410 if (isGA1 && isGA2 && GV1 == GV2)
5411 return Offset1 == (Offset2 + Dist*Size);
5412 }
5413
5414 return false;
5415}
5416
5417static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5418 const X86Subtarget *Subtarget) {
5419 GlobalValue *GV;
5420 int64_t Offset;
5421 if (isGAPlusOffset(Base, GV, Offset))
5422 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5423 else {
5424 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
Dan Gohman53491e92007-07-23 20:24:29 +00005425 int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005426 if (BFI < 0)
5427 // Fixed objects do not specify alignment, however the offsets are known.
5428 return ((Subtarget->getStackAlignment() % 16) == 0 &&
5429 (MFI->getObjectOffset(BFI) % 16) == 0);
5430 else
5431 return MFI->getObjectAlignment(BFI) >= 16;
5432 }
5433 return false;
5434}
5435
5436
5437/// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5438/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5439/// if the load addresses are consecutive, non-overlapping, and in the right
5440/// order.
5441static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5442 const X86Subtarget *Subtarget) {
5443 MachineFunction &MF = DAG.getMachineFunction();
5444 MachineFrameInfo *MFI = MF.getFrameInfo();
5445 MVT::ValueType VT = N->getValueType(0);
5446 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5447 SDOperand PermMask = N->getOperand(2);
5448 int NumElems = (int)PermMask.getNumOperands();
5449 SDNode *Base = NULL;
5450 for (int i = 0; i < NumElems; ++i) {
5451 SDOperand Idx = PermMask.getOperand(i);
5452 if (Idx.getOpcode() == ISD::UNDEF) {
5453 if (!Base) return SDOperand();
5454 } else {
5455 SDOperand Arg =
5456 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5457 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5458 return SDOperand();
5459 if (!Base)
5460 Base = Arg.Val;
5461 else if (!isConsecutiveLoad(Arg.Val, Base,
5462 i, MVT::getSizeInBits(EVT)/8,MFI))
5463 return SDOperand();
5464 }
5465 }
5466
5467 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
Dan Gohman11821702007-07-27 17:16:43 +00005468 LoadSDNode *LD = cast<LoadSDNode>(Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005469 if (isAlign16) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005470 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
Dan Gohman11821702007-07-27 17:16:43 +00005471 LD->getSrcValueOffset(), LD->isVolatile());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005472 } else {
Dan Gohman11821702007-07-27 17:16:43 +00005473 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5474 LD->getSrcValueOffset(), LD->isVolatile(),
5475 LD->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005476 }
5477}
5478
5479/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5480static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5481 const X86Subtarget *Subtarget) {
5482 SDOperand Cond = N->getOperand(0);
5483
5484 // If we have SSE[12] support, try to form min/max nodes.
5485 if (Subtarget->hasSSE2() &&
5486 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5487 if (Cond.getOpcode() == ISD::SETCC) {
5488 // Get the LHS/RHS of the select.
5489 SDOperand LHS = N->getOperand(1);
5490 SDOperand RHS = N->getOperand(2);
5491 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5492
5493 unsigned Opcode = 0;
5494 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5495 switch (CC) {
5496 default: break;
5497 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5498 case ISD::SETULE:
5499 case ISD::SETLE:
5500 if (!UnsafeFPMath) break;
5501 // FALL THROUGH.
5502 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
5503 case ISD::SETLT:
5504 Opcode = X86ISD::FMIN;
5505 break;
5506
5507 case ISD::SETOGT: // (X > Y) ? X : Y -> max
5508 case ISD::SETUGT:
5509 case ISD::SETGT:
5510 if (!UnsafeFPMath) break;
5511 // FALL THROUGH.
5512 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
5513 case ISD::SETGE:
5514 Opcode = X86ISD::FMAX;
5515 break;
5516 }
5517 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5518 switch (CC) {
5519 default: break;
5520 case ISD::SETOGT: // (X > Y) ? Y : X -> min
5521 case ISD::SETUGT:
5522 case ISD::SETGT:
5523 if (!UnsafeFPMath) break;
5524 // FALL THROUGH.
5525 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
5526 case ISD::SETGE:
5527 Opcode = X86ISD::FMIN;
5528 break;
5529
5530 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
5531 case ISD::SETULE:
5532 case ISD::SETLE:
5533 if (!UnsafeFPMath) break;
5534 // FALL THROUGH.
5535 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
5536 case ISD::SETLT:
5537 Opcode = X86ISD::FMAX;
5538 break;
5539 }
5540 }
5541
5542 if (Opcode)
5543 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5544 }
5545
5546 }
5547
5548 return SDOperand();
5549}
5550
5551
5552SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5553 DAGCombinerInfo &DCI) const {
5554 SelectionDAG &DAG = DCI.DAG;
5555 switch (N->getOpcode()) {
5556 default: break;
5557 case ISD::VECTOR_SHUFFLE:
5558 return PerformShuffleCombine(N, DAG, Subtarget);
5559 case ISD::SELECT:
5560 return PerformSELECTCombine(N, DAG, Subtarget);
5561 }
5562
5563 return SDOperand();
5564}
5565
5566//===----------------------------------------------------------------------===//
5567// X86 Inline Assembly Support
5568//===----------------------------------------------------------------------===//
5569
5570/// getConstraintType - Given a constraint letter, return the type of
5571/// constraint it is for this target.
5572X86TargetLowering::ConstraintType
5573X86TargetLowering::getConstraintType(const std::string &Constraint) const {
5574 if (Constraint.size() == 1) {
5575 switch (Constraint[0]) {
5576 case 'A':
5577 case 'r':
5578 case 'R':
5579 case 'l':
5580 case 'q':
5581 case 'Q':
5582 case 'x':
5583 case 'Y':
5584 return C_RegisterClass;
5585 default:
5586 break;
5587 }
5588 }
5589 return TargetLowering::getConstraintType(Constraint);
5590}
5591
Chris Lattnera531abc2007-08-25 00:47:38 +00005592/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5593/// vector. If it is invalid, don't add anything to Ops.
5594void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
5595 char Constraint,
5596 std::vector<SDOperand>&Ops,
5597 SelectionDAG &DAG) {
5598 SDOperand Result(0, 0);
5599
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005600 switch (Constraint) {
5601 default: break;
5602 case 'I':
5603 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
Chris Lattnera531abc2007-08-25 00:47:38 +00005604 if (C->getValue() <= 31) {
5605 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5606 break;
5607 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005608 }
Chris Lattnera531abc2007-08-25 00:47:38 +00005609 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005610 case 'N':
5611 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
Chris Lattnera531abc2007-08-25 00:47:38 +00005612 if (C->getValue() <= 255) {
5613 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5614 break;
5615 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005616 }
Chris Lattnera531abc2007-08-25 00:47:38 +00005617 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005618 case 'i': {
5619 // Literal immediates are always ok.
Chris Lattnera531abc2007-08-25 00:47:38 +00005620 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
5621 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
5622 break;
5623 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005624
5625 // If we are in non-pic codegen mode, we allow the address of a global (with
5626 // an optional displacement) to be used with 'i'.
5627 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
5628 int64_t Offset = 0;
5629
5630 // Match either (GA) or (GA+C)
5631 if (GA) {
5632 Offset = GA->getOffset();
5633 } else if (Op.getOpcode() == ISD::ADD) {
5634 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5635 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5636 if (C && GA) {
5637 Offset = GA->getOffset()+C->getValue();
5638 } else {
5639 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5640 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5641 if (C && GA)
5642 Offset = GA->getOffset()+C->getValue();
5643 else
5644 C = 0, GA = 0;
5645 }
5646 }
5647
5648 if (GA) {
5649 // If addressing this global requires a load (e.g. in PIC mode), we can't
5650 // match.
5651 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
5652 false))
Chris Lattnera531abc2007-08-25 00:47:38 +00005653 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005654
5655 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5656 Offset);
Chris Lattnera531abc2007-08-25 00:47:38 +00005657 Result = Op;
5658 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005659 }
5660
5661 // Otherwise, not valid for this mode.
Chris Lattnera531abc2007-08-25 00:47:38 +00005662 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005663 }
5664 }
Chris Lattnera531abc2007-08-25 00:47:38 +00005665
5666 if (Result.Val) {
5667 Ops.push_back(Result);
5668 return;
5669 }
5670 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005671}
5672
5673std::vector<unsigned> X86TargetLowering::
5674getRegClassForInlineAsmConstraint(const std::string &Constraint,
5675 MVT::ValueType VT) const {
5676 if (Constraint.size() == 1) {
5677 // FIXME: not handling fp-stack yet!
5678 switch (Constraint[0]) { // GCC X86 Constraint Letters
5679 default: break; // Unknown constraint letter
5680 case 'A': // EAX/EDX
5681 if (VT == MVT::i32 || VT == MVT::i64)
5682 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
5683 break;
5684 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
5685 case 'Q': // Q_REGS
5686 if (VT == MVT::i32)
5687 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
5688 else if (VT == MVT::i16)
5689 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
5690 else if (VT == MVT::i8)
Evan Chengf85c10f2007-08-13 23:27:11 +00005691 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005692 break;
5693 }
5694 }
5695
5696 return std::vector<unsigned>();
5697}
5698
5699std::pair<unsigned, const TargetRegisterClass*>
5700X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
5701 MVT::ValueType VT) const {
5702 // First, see if this is a constraint that directly corresponds to an LLVM
5703 // register class.
5704 if (Constraint.size() == 1) {
5705 // GCC Constraint Letters
5706 switch (Constraint[0]) {
5707 default: break;
5708 case 'r': // GENERAL_REGS
5709 case 'R': // LEGACY_REGS
5710 case 'l': // INDEX_REGS
5711 if (VT == MVT::i64 && Subtarget->is64Bit())
5712 return std::make_pair(0U, X86::GR64RegisterClass);
5713 if (VT == MVT::i32)
5714 return std::make_pair(0U, X86::GR32RegisterClass);
5715 else if (VT == MVT::i16)
5716 return std::make_pair(0U, X86::GR16RegisterClass);
5717 else if (VT == MVT::i8)
5718 return std::make_pair(0U, X86::GR8RegisterClass);
5719 break;
5720 case 'y': // MMX_REGS if MMX allowed.
5721 if (!Subtarget->hasMMX()) break;
5722 return std::make_pair(0U, X86::VR64RegisterClass);
5723 break;
5724 case 'Y': // SSE_REGS if SSE2 allowed
5725 if (!Subtarget->hasSSE2()) break;
5726 // FALL THROUGH.
5727 case 'x': // SSE_REGS if SSE1 allowed
5728 if (!Subtarget->hasSSE1()) break;
5729
5730 switch (VT) {
5731 default: break;
5732 // Scalar SSE types.
5733 case MVT::f32:
5734 case MVT::i32:
5735 return std::make_pair(0U, X86::FR32RegisterClass);
5736 case MVT::f64:
5737 case MVT::i64:
5738 return std::make_pair(0U, X86::FR64RegisterClass);
5739 // Vector types.
5740 case MVT::v16i8:
5741 case MVT::v8i16:
5742 case MVT::v4i32:
5743 case MVT::v2i64:
5744 case MVT::v4f32:
5745 case MVT::v2f64:
5746 return std::make_pair(0U, X86::VR128RegisterClass);
5747 }
5748 break;
5749 }
5750 }
5751
5752 // Use the default implementation in TargetLowering to convert the register
5753 // constraint into a member of a register class.
5754 std::pair<unsigned, const TargetRegisterClass*> Res;
5755 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
5756
5757 // Not found as a standard register?
5758 if (Res.second == 0) {
5759 // GCC calls "st(0)" just plain "st".
5760 if (StringsEqualNoCase("{st}", Constraint)) {
5761 Res.first = X86::ST0;
Chris Lattner3cfe51b2007-09-24 05:27:37 +00005762 Res.second = X86::RFP80RegisterClass;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005763 }
5764
5765 return Res;
5766 }
5767
5768 // Otherwise, check to see if this is a register class of the wrong value
5769 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
5770 // turn into {ax},{dx}.
5771 if (Res.second->hasType(VT))
5772 return Res; // Correct type already, nothing to do.
5773
5774 // All of the single-register GCC register classes map their values onto
5775 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
5776 // really want an 8-bit or 32-bit register, map to the appropriate register
5777 // class and return the appropriate register.
5778 if (Res.second != X86::GR16RegisterClass)
5779 return Res;
5780
5781 if (VT == MVT::i8) {
5782 unsigned DestReg = 0;
5783 switch (Res.first) {
5784 default: break;
5785 case X86::AX: DestReg = X86::AL; break;
5786 case X86::DX: DestReg = X86::DL; break;
5787 case X86::CX: DestReg = X86::CL; break;
5788 case X86::BX: DestReg = X86::BL; break;
5789 }
5790 if (DestReg) {
5791 Res.first = DestReg;
5792 Res.second = Res.second = X86::GR8RegisterClass;
5793 }
5794 } else if (VT == MVT::i32) {
5795 unsigned DestReg = 0;
5796 switch (Res.first) {
5797 default: break;
5798 case X86::AX: DestReg = X86::EAX; break;
5799 case X86::DX: DestReg = X86::EDX; break;
5800 case X86::CX: DestReg = X86::ECX; break;
5801 case X86::BX: DestReg = X86::EBX; break;
5802 case X86::SI: DestReg = X86::ESI; break;
5803 case X86::DI: DestReg = X86::EDI; break;
5804 case X86::BP: DestReg = X86::EBP; break;
5805 case X86::SP: DestReg = X86::ESP; break;
5806 }
5807 if (DestReg) {
5808 Res.first = DestReg;
5809 Res.second = Res.second = X86::GR32RegisterClass;
5810 }
5811 } else if (VT == MVT::i64) {
5812 unsigned DestReg = 0;
5813 switch (Res.first) {
5814 default: break;
5815 case X86::AX: DestReg = X86::RAX; break;
5816 case X86::DX: DestReg = X86::RDX; break;
5817 case X86::CX: DestReg = X86::RCX; break;
5818 case X86::BX: DestReg = X86::RBX; break;
5819 case X86::SI: DestReg = X86::RSI; break;
5820 case X86::DI: DestReg = X86::RDI; break;
5821 case X86::BP: DestReg = X86::RBP; break;
5822 case X86::SP: DestReg = X86::RSP; break;
5823 }
5824 if (DestReg) {
5825 Res.first = DestReg;
5826 Res.second = Res.second = X86::GR64RegisterClass;
5827 }
5828 }
5829
5830 return Res;
5831}