blob: c0001c0f974f3fa6c275dd7216ca73433663c061 [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);
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +0000208 setOperationAction(ISD::FLT_ROUNDS , MVT::i32 , Custom);
209
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
211 setOperationAction(ISD::CTTZ , MVT::i8 , Expand);
212 setOperationAction(ISD::CTLZ , MVT::i8 , Expand);
213 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
214 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
215 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
216 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
217 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
218 setOperationAction(ISD::CTLZ , MVT::i32 , Expand);
219 if (Subtarget->is64Bit()) {
220 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
221 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
222 setOperationAction(ISD::CTLZ , MVT::i64 , Expand);
223 }
224
225 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
226 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
227
228 // These should be promoted to a larger select which is supported.
229 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
230 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
231 // X86 wants to expand cmov itself.
232 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
233 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
234 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
235 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000236 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
238 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
239 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
240 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
241 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000242 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243 if (Subtarget->is64Bit()) {
244 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
245 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
246 }
247 // X86 ret instruction may pop stack.
248 setOperationAction(ISD::RET , MVT::Other, Custom);
249 if (!Subtarget->is64Bit())
250 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
251
252 // Darwin ABI issue.
253 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
254 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
255 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
256 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
257 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
258 if (Subtarget->is64Bit()) {
259 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
260 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
261 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
262 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
263 }
264 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
265 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
266 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
267 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
268 // X86 wants to expand memset / memcpy itself.
269 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
270 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
271
Dan Gohman21442852007-09-25 15:10:49 +0000272 // Use the default ISD::LOCATION expansion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274 // FIXME - use subtarget debug flags
275 if (!Subtarget->isTargetDarwin() &&
276 !Subtarget->isTargetELF() &&
277 !Subtarget->isTargetCygMing())
278 setOperationAction(ISD::LABEL, MVT::Other, Expand);
279
280 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
281 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
282 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
283 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
284 if (Subtarget->is64Bit()) {
285 // FIXME: Verify
286 setExceptionPointerRegister(X86::RAX);
287 setExceptionSelectorRegister(X86::RDX);
288 } else {
289 setExceptionPointerRegister(X86::EAX);
290 setExceptionSelectorRegister(X86::EDX);
291 }
Anton Korobeynikov23ca9c52007-09-03 00:36:06 +0000292 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293
Duncan Sands7407a9f2007-09-11 14:10:23 +0000294 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
Duncan Sandsd8455ca2007-07-27 20:02:49 +0000295
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297 setOperationAction(ISD::VASTART , MVT::Other, Custom);
298 setOperationAction(ISD::VAARG , MVT::Other, Expand);
299 setOperationAction(ISD::VAEND , MVT::Other, Expand);
300 if (Subtarget->is64Bit())
301 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
302 else
303 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
304
305 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
306 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
307 if (Subtarget->is64Bit())
308 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
309 if (Subtarget->isTargetCygMing())
310 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
311 else
312 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
313
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000314 if (X86ScalarSSEf64) {
315 // f32 and f64 use SSE.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 // Set up the FP register classes.
317 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
318 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
319
320 // Use ANDPD to simulate FABS.
321 setOperationAction(ISD::FABS , MVT::f64, Custom);
322 setOperationAction(ISD::FABS , MVT::f32, Custom);
323
324 // Use XORP to simulate FNEG.
325 setOperationAction(ISD::FNEG , MVT::f64, Custom);
326 setOperationAction(ISD::FNEG , MVT::f32, Custom);
327
328 // Use ANDPD and ORPD to simulate FCOPYSIGN.
329 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
330 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
331
332 // We don't support sin/cos/fmod
333 setOperationAction(ISD::FSIN , MVT::f64, Expand);
334 setOperationAction(ISD::FCOS , MVT::f64, Expand);
335 setOperationAction(ISD::FREM , MVT::f64, Expand);
336 setOperationAction(ISD::FSIN , MVT::f32, Expand);
337 setOperationAction(ISD::FCOS , MVT::f32, Expand);
338 setOperationAction(ISD::FREM , MVT::f32, Expand);
339
340 // Expand FP immediates into loads from the stack, except for the special
341 // cases we handle.
342 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
343 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000344 addLegalFPImmediate(APFloat(+0.0)); // xorpd
345 addLegalFPImmediate(APFloat(+0.0f)); // xorps
Dale Johannesen8f83a6b2007-08-09 01:04:01 +0000346
347 // Conversions to long double (in X87) go through memory.
348 setConvertAction(MVT::f32, MVT::f80, Expand);
349 setConvertAction(MVT::f64, MVT::f80, Expand);
350
351 // Conversions from long double (in X87) go through memory.
352 setConvertAction(MVT::f80, MVT::f32, Expand);
353 setConvertAction(MVT::f80, MVT::f64, Expand);
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000354 } else if (X86ScalarSSEf32) {
355 // Use SSE for f32, x87 for f64.
356 // Set up the FP register classes.
357 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
358 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
359
360 // Use ANDPS to simulate FABS.
361 setOperationAction(ISD::FABS , MVT::f32, Custom);
362
363 // Use XORP to simulate FNEG.
364 setOperationAction(ISD::FNEG , MVT::f32, Custom);
365
366 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
367
368 // Use ANDPS and ORPS to simulate FCOPYSIGN.
369 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
370 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
371
372 // We don't support sin/cos/fmod
373 setOperationAction(ISD::FSIN , MVT::f32, Expand);
374 setOperationAction(ISD::FCOS , MVT::f32, Expand);
375 setOperationAction(ISD::FREM , MVT::f32, Expand);
376
377 // Expand FP immediates into loads from the stack, except for the special
378 // cases we handle.
379 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
380 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
381 addLegalFPImmediate(APFloat(+0.0f)); // xorps
382 addLegalFPImmediate(APFloat(+0.0)); // FLD0
383 addLegalFPImmediate(APFloat(+1.0)); // FLD1
384 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
385 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
386
387 // SSE->x87 conversions go through memory.
388 setConvertAction(MVT::f32, MVT::f64, Expand);
389 setConvertAction(MVT::f32, MVT::f80, Expand);
390
391 // x87->SSE truncations need to go through memory.
392 setConvertAction(MVT::f80, MVT::f32, Expand);
393 setConvertAction(MVT::f64, MVT::f32, Expand);
394 // And x87->x87 truncations also.
395 setConvertAction(MVT::f80, MVT::f64, Expand);
396
397 if (!UnsafeFPMath) {
398 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
399 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
400 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000402 // f32 and f64 in x87.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403 // Set up the FP register classes.
404 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
405 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
406
407 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
408 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
409 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
410 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
Dale Johannesen8f83a6b2007-08-09 01:04:01 +0000411
412 // Floating truncations need to go through memory.
413 setConvertAction(MVT::f80, MVT::f32, Expand);
414 setConvertAction(MVT::f64, MVT::f32, Expand);
415 setConvertAction(MVT::f80, MVT::f64, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000416
417 if (!UnsafeFPMath) {
418 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
419 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
420 }
421
422 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
423 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
Dale Johannesenbbe2b702007-08-30 00:23:21 +0000424 addLegalFPImmediate(APFloat(+0.0)); // FLD0
425 addLegalFPImmediate(APFloat(+1.0)); // FLD1
426 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
427 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000428 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
429 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
430 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
431 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 }
433
Dale Johannesen4ab00bd2007-08-05 18:49:15 +0000434 // Long double always uses X87.
435 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000436 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
437 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
438 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
Dale Johannesen7f1076b2007-09-26 21:10:55 +0000439 if (!UnsafeFPMath) {
440 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
441 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
442 }
Dale Johannesen4ab00bd2007-08-05 18:49:15 +0000443
Dan Gohman2f7b1982007-10-11 23:21:31 +0000444 // Always use a library call for pow.
445 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
446 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
447 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
448
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000449 // First set operation action for all vector types to expand. Then we
450 // will selectively turn on ones that can be effectively codegen'd.
451 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
452 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
453 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
454 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
455 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
456 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
457 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
458 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
459 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
460 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
461 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
462 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
463 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
464 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
465 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
466 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
467 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
468 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
469 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
470 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
471 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
472 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
473 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
474 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
475 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
Dan Gohman5a199552007-10-08 18:33:35 +0000476 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
477 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
478 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
479 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
Dan Gohman2f7b1982007-10-11 23:21:31 +0000480 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
Dan Gohman1d2dc2c2007-10-12 14:09:42 +0000481 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
482 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
483 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000484 }
485
486 if (Subtarget->hasMMX()) {
487 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
488 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
489 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
490 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
491
492 // FIXME: add MMX packed arithmetics
493
494 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
495 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
496 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
497 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
498
499 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
500 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
501 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
Dale Johannesen6b65c332007-10-30 01:18:38 +0000502 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503
504 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
505 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
506
507 setOperationAction(ISD::AND, MVT::v8i8, Promote);
508 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
509 setOperationAction(ISD::AND, MVT::v4i16, Promote);
510 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
511 setOperationAction(ISD::AND, MVT::v2i32, Promote);
512 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
513 setOperationAction(ISD::AND, MVT::v1i64, Legal);
514
515 setOperationAction(ISD::OR, MVT::v8i8, Promote);
516 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
517 setOperationAction(ISD::OR, MVT::v4i16, Promote);
518 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
519 setOperationAction(ISD::OR, MVT::v2i32, Promote);
520 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
521 setOperationAction(ISD::OR, MVT::v1i64, Legal);
522
523 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
524 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
525 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
526 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
527 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
528 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
529 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
530
531 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
532 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
533 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
534 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
535 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
536 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
537 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
538
539 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
540 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
541 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
542 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
543
544 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
545 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
546 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
547 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
548
549 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
550 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
551 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
552 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
553 }
554
555 if (Subtarget->hasSSE1()) {
556 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
557
558 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
559 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
560 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
561 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
562 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
563 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
565 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
566 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
567 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
568 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
569 }
570
571 if (Subtarget->hasSSE2()) {
572 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
573 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
574 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
575 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
576 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
577
578 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
579 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
580 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
581 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
582 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
583 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
584 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
585 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
586 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
587 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
588 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
589 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
590 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
591 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
592 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000593
594 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
595 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
596 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
597 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
598 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
599 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
600
601 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
602 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
603 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
604 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
605 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
606 }
607 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
608 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
609 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
610 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
611 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
Dale Johannesen2ff963d2007-10-31 00:32:36 +0000612 if (Subtarget->is64Bit())
613 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614
615 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
616 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
617 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
618 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
619 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
620 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
621 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
622 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
623 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
624 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
625 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
626 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
627 }
628
629 // Custom lower v2i64 and v2f64 selects.
630 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
631 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
632 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
633 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
634 }
635
636 // We want to custom lower some of our intrinsics.
637 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
638
639 // We have target-specific dag combine patterns for the following nodes:
640 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
641 setTargetDAGCombine(ISD::SELECT);
642
643 computeRegisterProperties();
644
645 // FIXME: These should be based on subtarget info. Plus, the values should
646 // be smaller when we are in optimizing for size mode.
647 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
648 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
649 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
650 allowUnalignedMemoryAccesses = true; // x86 supports it!
651}
652
653
Evan Cheng6fb06762007-11-09 01:32:10 +0000654/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
655/// jumptable.
656SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
657 SelectionDAG &DAG) const {
658 if (usesGlobalOffsetTable())
659 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
660 if (!Subtarget->isPICStyleRIPRel())
661 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
662 return Table;
663}
664
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000665//===----------------------------------------------------------------------===//
666// Return Value Calling Convention Implementation
667//===----------------------------------------------------------------------===//
668
669#include "X86GenCallingConv.inc"
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000670
671/// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
672/// exists skip possible ISD:TokenFactor.
673static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
674 if (Chain.getOpcode()==X86ISD::TAILCALL) {
675 return Chain;
676 } else if (Chain.getOpcode()==ISD::TokenFactor) {
677 if (Chain.getNumOperands() &&
678 Chain.getOperand(0).getOpcode()==X86ISD::TAILCALL)
679 return Chain.getOperand(0);
680 }
681 return Chain;
682}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683
684/// LowerRET - Lower an ISD::RET node.
685SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
686 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
687
688 SmallVector<CCValAssign, 16> RVLocs;
689 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
690 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
691 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
692 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000693
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694 // If this is the first return lowered for this function, add the regs to the
695 // liveout set for the function.
696 if (DAG.getMachineFunction().liveout_empty()) {
697 for (unsigned i = 0; i != RVLocs.size(); ++i)
698 if (RVLocs[i].isRegLoc())
699 DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
700 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701 SDOperand Chain = Op.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000703 // Handle tail call return.
704 Chain = GetPossiblePreceedingTailCall(Chain);
705 if (Chain.getOpcode() == X86ISD::TAILCALL) {
706 SDOperand TailCall = Chain;
707 SDOperand TargetAddress = TailCall.getOperand(1);
708 SDOperand StackAdjustment = TailCall.getOperand(2);
709 assert ( ((TargetAddress.getOpcode() == ISD::Register &&
710 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
711 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
712 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
713 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
714 "Expecting an global address, external symbol, or register");
715 assert( StackAdjustment.getOpcode() == ISD::Constant &&
716 "Expecting a const value");
717
718 SmallVector<SDOperand,8> Operands;
719 Operands.push_back(Chain.getOperand(0));
720 Operands.push_back(TargetAddress);
721 Operands.push_back(StackAdjustment);
722 // Copy registers used by the call. Last operand is a flag so it is not
723 // copied.
Arnold Schwaighofer10202b32007-10-16 09:05:00 +0000724 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000725 Operands.push_back(Chain.getOperand(i));
726 }
Arnold Schwaighofer10202b32007-10-16 09:05:00 +0000727 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
728 Operands.size());
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000729 }
730
731 // Regular return.
732 SDOperand Flag;
733
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 // Copy the result values into the output registers.
735 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
736 RVLocs[0].getLocReg() != X86::ST0) {
737 for (unsigned i = 0; i != RVLocs.size(); ++i) {
738 CCValAssign &VA = RVLocs[i];
739 assert(VA.isRegLoc() && "Can only return in registers!");
740 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
741 Flag);
742 Flag = Chain.getValue(1);
743 }
744 } else {
745 // We need to handle a destination of ST0 specially, because it isn't really
746 // a register.
747 SDOperand Value = Op.getOperand(1);
748
749 // If this is an FP return with ScalarSSE, we need to move the value from
750 // an XMM register onto the fp-stack.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000751 if ((X86ScalarSSEf32 && RVLocs[0].getValVT()==MVT::f32) ||
752 (X86ScalarSSEf64 && RVLocs[0].getValVT()==MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000753 SDOperand MemLoc;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000754
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000755 // If this is a load into a scalarsse value, don't store the loaded value
756 // back to the stack, only to reload it: just replace the scalar-sse load.
757 if (ISD::isNON_EXTLoad(Value.Val) &&
758 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
759 Chain = Value.getOperand(0);
760 MemLoc = Value.getOperand(1);
761 } else {
762 // Spill the value to memory and reload it into top of stack.
763 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
764 MachineFunction &MF = DAG.getMachineFunction();
765 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
766 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
767 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
768 }
769 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
770 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
771 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
772 Chain = Value.getValue(1);
773 }
774
775 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
776 SDOperand Ops[] = { Chain, Value };
777 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
778 Flag = Chain.getValue(1);
779 }
780
781 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
782 if (Flag.Val)
783 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
784 else
785 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
786}
787
788
789/// LowerCallResult - Lower the result values of an ISD::CALL into the
790/// appropriate copies out of appropriate physical registers. This assumes that
791/// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
792/// being lowered. The returns a SDNode with the same number of values as the
793/// ISD::CALL.
794SDNode *X86TargetLowering::
795LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
796 unsigned CallingConv, SelectionDAG &DAG) {
797
798 // Assign locations to each value returned by this call.
799 SmallVector<CCValAssign, 16> RVLocs;
800 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
801 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
802 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
803
804
805 SmallVector<SDOperand, 8> ResultVals;
806
807 // Copy all of the result registers out of their specified physreg.
808 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
809 for (unsigned i = 0; i != RVLocs.size(); ++i) {
810 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
811 RVLocs[i].getValVT(), InFlag).getValue(1);
812 InFlag = Chain.getValue(2);
813 ResultVals.push_back(Chain.getValue(0));
814 }
815 } else {
816 // Copies from the FP stack are special, as ST0 isn't a valid register
817 // before the fp stackifier runs.
818
819 // Copy ST0 into an RFP register with FP_GET_RESULT.
820 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
821 SDOperand GROps[] = { Chain, InFlag };
822 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
823 Chain = RetVal.getValue(1);
824 InFlag = RetVal.getValue(2);
825
826 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
827 // an XMM register.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000828 if ((X86ScalarSSEf32 && RVLocs[0].getValVT() == MVT::f32) ||
829 (X86ScalarSSEf64 && RVLocs[0].getValVT() == MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000830 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
831 // shouldn't be necessary except that RFP cannot be live across
832 // multiple blocks. When stackifier is fixed, they can be uncoupled.
833 MachineFunction &MF = DAG.getMachineFunction();
834 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
835 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
836 SDOperand Ops[] = {
837 Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
838 };
839 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
840 RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
841 Chain = RetVal.getValue(1);
842 }
843 ResultVals.push_back(RetVal);
844 }
845
846 // Merge everything together with a MERGE_VALUES node.
847 ResultVals.push_back(Chain);
848 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
849 &ResultVals[0], ResultVals.size()).Val;
850}
851
852
853//===----------------------------------------------------------------------===//
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000854// C & StdCall & Fast Calling Convention implementation
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855//===----------------------------------------------------------------------===//
856// StdCall calling convention seems to be standard for many Windows' API
857// routines and around. It differs from C calling convention just a little:
858// callee should clean up the stack, not caller. Symbols should be also
859// decorated in some fancy way :) It doesn't support any vector arguments.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000860// For info on fast calling convention see Fast Calling Convention (tail call)
861// implementation LowerX86_32FastCCCallTo.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862
863/// AddLiveIn - This helper function adds the specified physical register to the
864/// MachineFunction as a live in value. It also creates a corresponding virtual
865/// register for it.
866static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
867 const TargetRegisterClass *RC) {
868 assert(RC->contains(PReg) && "Not the correct regclass!");
869 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
870 MF.addLiveIn(PReg, VReg);
871 return VReg;
872}
873
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000874// align stack arguments according to platform alignment needed for tail calls
875unsigned GetAlignedArgumentStackSize(unsigned StackSize, SelectionDAG& DAG);
876
Rafael Espindola03cbeb72007-09-14 15:48:13 +0000877SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
878 const CCValAssign &VA,
879 MachineFrameInfo *MFI,
880 SDOperand Root, unsigned i) {
881 // Create the nodes corresponding to a load from this parameter slot.
882 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
883 VA.getLocMemOffset());
884 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
885
886 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
887
888 if (Flags & ISD::ParamFlags::ByVal)
889 return FIN;
890 else
891 return DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0);
892}
893
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000894SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
895 bool isStdCall) {
896 unsigned NumArgs = Op.Val->getNumValues() - 1;
897 MachineFunction &MF = DAG.getMachineFunction();
898 MachineFrameInfo *MFI = MF.getFrameInfo();
899 SDOperand Root = Op.getOperand(0);
900 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000901 unsigned CC = MF.getFunction()->getCallingConv();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902 // Assign locations to all of the incoming arguments.
903 SmallVector<CCValAssign, 16> ArgLocs;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000904 CCState CCInfo(CC, isVarArg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000905 getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000906 // Check for possible tail call calling convention.
907 if (CC == CallingConv::Fast && PerformTailCallOpt)
908 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_TailCall);
909 else
910 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
911
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 SmallVector<SDOperand, 8> ArgValues;
913 unsigned LastVal = ~0U;
914 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
915 CCValAssign &VA = ArgLocs[i];
916 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
917 // places.
918 assert(VA.getValNo() != LastVal &&
919 "Don't support value assigned to multiple locs yet");
920 LastVal = VA.getValNo();
921
922 if (VA.isRegLoc()) {
923 MVT::ValueType RegVT = VA.getLocVT();
924 TargetRegisterClass *RC;
925 if (RegVT == MVT::i32)
926 RC = X86::GR32RegisterClass;
927 else {
928 assert(MVT::isVector(RegVT));
929 RC = X86::VR128RegisterClass;
930 }
931
932 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
933 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
934
935 // If this is an 8 or 16-bit value, it is really passed promoted to 32
936 // bits. Insert an assert[sz]ext to capture this, then truncate to the
937 // right size.
938 if (VA.getLocInfo() == CCValAssign::SExt)
939 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
940 DAG.getValueType(VA.getValVT()));
941 else if (VA.getLocInfo() == CCValAssign::ZExt)
942 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
943 DAG.getValueType(VA.getValVT()));
944
945 if (VA.getLocInfo() != CCValAssign::Full)
946 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
947
948 ArgValues.push_back(ArgValue);
949 } else {
950 assert(VA.isMemLoc());
Rafael Espindola03cbeb72007-09-14 15:48:13 +0000951 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000952 }
953 }
954
955 unsigned StackSize = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000956 // align stack specially for tail calls
957 if (CC==CallingConv::Fast)
958 StackSize = GetAlignedArgumentStackSize(StackSize,DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000959
960 ArgValues.push_back(Root);
961
962 // If the function takes variable number of arguments, make a frame index for
963 // the start of the first vararg value... for expansion of llvm.va_start.
964 if (isVarArg)
965 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
966
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000967 // Tail call calling convention (CallingConv::Fast) does not support varargs.
968 assert( !(isVarArg && CC == CallingConv::Fast) &&
969 "CallingConv::Fast does not support varargs.");
970
971 if (isStdCall && !isVarArg &&
972 (CC==CallingConv::Fast && PerformTailCallOpt || CC!=CallingConv::Fast)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973 BytesToPopOnReturn = StackSize; // Callee pops everything..
974 BytesCallerReserves = 0;
975 } else {
976 BytesToPopOnReturn = 0; // Callee pops nothing.
977
978 // If this is an sret function, the return should pop the hidden pointer.
979 if (NumArgs &&
980 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
981 ISD::ParamFlags::StructReturn))
982 BytesToPopOnReturn = 4;
983
984 BytesCallerReserves = StackSize;
985 }
Anton Korobeynikove844e472007-08-15 17:12:32 +0000986
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000987 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000988
Anton Korobeynikove844e472007-08-15 17:12:32 +0000989 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
990 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991
992 // Return the new list of results.
993 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
994 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
995}
996
997SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
998 unsigned CC) {
999 SDOperand Chain = Op.getOperand(0);
1000 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001 SDOperand Callee = Op.getOperand(4);
1002 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001003
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001004 // Analyze operands of the call, assigning locations to each operand.
1005 SmallVector<CCValAssign, 16> ArgLocs;
1006 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001007 if(CC==CallingConv::Fast && PerformTailCallOpt)
1008 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1009 else
1010 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001011
1012 // Get a count of how many bytes are to be pushed on the stack.
1013 unsigned NumBytes = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001014 if (CC==CallingConv::Fast)
1015 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001016
1017 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1018
1019 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1020 SmallVector<SDOperand, 8> MemOpChains;
1021
1022 SDOperand StackPtr;
1023
1024 // Walk the register/memloc assignments, inserting copies/loads.
1025 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1026 CCValAssign &VA = ArgLocs[i];
1027 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1028
1029 // Promote the value if needed.
1030 switch (VA.getLocInfo()) {
1031 default: assert(0 && "Unknown loc info!");
1032 case CCValAssign::Full: break;
1033 case CCValAssign::SExt:
1034 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1035 break;
1036 case CCValAssign::ZExt:
1037 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1038 break;
1039 case CCValAssign::AExt:
1040 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1041 break;
1042 }
1043
1044 if (VA.isRegLoc()) {
1045 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1046 } else {
1047 assert(VA.isMemLoc());
1048 if (StackPtr.Val == 0)
1049 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindola007b7142007-09-21 15:50:22 +00001050
1051 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1052 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 }
1054 }
1055
1056 // If the first argument is an sret pointer, remember it.
1057 bool isSRet = NumOps &&
1058 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
1059 ISD::ParamFlags::StructReturn);
1060
1061 if (!MemOpChains.empty())
1062 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1063 &MemOpChains[0], MemOpChains.size());
1064
1065 // Build a sequence of copy-to-reg nodes chained together with token chain
1066 // and flag operands which copy the outgoing args into registers.
1067 SDOperand InFlag;
1068 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1069 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1070 InFlag);
1071 InFlag = Chain.getValue(1);
1072 }
1073
1074 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1075 // GOT pointer.
1076 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1077 Subtarget->isPICStyleGOT()) {
1078 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1079 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1080 InFlag);
1081 InFlag = Chain.getValue(1);
1082 }
1083
1084 // If the callee is a GlobalAddress node (quite common, every direct call is)
1085 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1086 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1087 // We should use extra load for direct calls to dllimported functions in
1088 // non-JIT mode.
1089 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1090 getTargetMachine(), true))
1091 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1092 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1093 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1094
1095 // Returns a chain & a flag for retval copy to use.
1096 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1097 SmallVector<SDOperand, 8> Ops;
1098 Ops.push_back(Chain);
1099 Ops.push_back(Callee);
1100
1101 // Add argument registers to the end of the list so that they are known live
1102 // into the call.
1103 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1104 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1105 RegsToPass[i].second.getValueType()));
1106
1107 // Add an implicit use GOT pointer in EBX.
1108 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1109 Subtarget->isPICStyleGOT())
1110 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1111
1112 if (InFlag.Val)
1113 Ops.push_back(InFlag);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001114
1115 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116 InFlag = Chain.getValue(1);
1117
1118 // Create the CALLSEQ_END node.
1119 unsigned NumBytesForCalleeToPush = 0;
1120
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001121 if (CC == CallingConv::X86_StdCall ||
1122 (CC == CallingConv::Fast && PerformTailCallOpt)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001123 if (isVarArg)
1124 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1125 else
1126 NumBytesForCalleeToPush = NumBytes;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001127 assert(!(isVarArg && CC==CallingConv::Fast) &&
1128 "CallingConv::Fast does not support varargs.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001129 } else {
1130 // If this is is a call to a struct-return function, the callee
1131 // pops the hidden struct pointer, so we have to push it back.
1132 // This is common for Darwin/X86, Linux & Mingw32 targets.
1133 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1134 }
Bill Wendling22f8deb2007-11-13 00:44:25 +00001135
1136 Chain = DAG.getCALLSEQ_END(Chain,
1137 DAG.getConstant(NumBytes, getPointerTy()),
1138 DAG.getConstant(NumBytesForCalleeToPush,
1139 getPointerTy()),
1140 InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 InFlag = Chain.getValue(1);
1142
1143 // Handle result values, copying them out of physregs into vregs that we
1144 // return.
1145 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1146}
1147
1148
1149//===----------------------------------------------------------------------===//
1150// FastCall Calling Convention implementation
1151//===----------------------------------------------------------------------===//
1152//
1153// The X86 'fastcall' calling convention passes up to two integer arguments in
1154// registers (an appropriate portion of ECX/EDX), passes arguments in C order,
1155// and requires that the callee pop its arguments off the stack (allowing proper
1156// tail calls), and has the same return value conventions as C calling convs.
1157//
1158// This calling convention always arranges for the callee pop value to be 8n+4
1159// bytes, which is needed for tail recursion elimination and stack alignment
1160// reasons.
1161SDOperand
1162X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
1163 MachineFunction &MF = DAG.getMachineFunction();
1164 MachineFrameInfo *MFI = MF.getFrameInfo();
1165 SDOperand Root = Op.getOperand(0);
1166 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1167
1168 // Assign locations to all of the incoming arguments.
1169 SmallVector<CCValAssign, 16> ArgLocs;
1170 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
1171 getTargetMachine(), ArgLocs);
1172 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
1173
1174 SmallVector<SDOperand, 8> ArgValues;
1175 unsigned LastVal = ~0U;
1176 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1177 CCValAssign &VA = ArgLocs[i];
1178 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1179 // places.
1180 assert(VA.getValNo() != LastVal &&
1181 "Don't support value assigned to multiple locs yet");
1182 LastVal = VA.getValNo();
1183
1184 if (VA.isRegLoc()) {
1185 MVT::ValueType RegVT = VA.getLocVT();
1186 TargetRegisterClass *RC;
1187 if (RegVT == MVT::i32)
1188 RC = X86::GR32RegisterClass;
1189 else {
1190 assert(MVT::isVector(RegVT));
1191 RC = X86::VR128RegisterClass;
1192 }
1193
1194 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1195 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1196
1197 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1198 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1199 // right size.
1200 if (VA.getLocInfo() == CCValAssign::SExt)
1201 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1202 DAG.getValueType(VA.getValVT()));
1203 else if (VA.getLocInfo() == CCValAssign::ZExt)
1204 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1205 DAG.getValueType(VA.getValVT()));
1206
1207 if (VA.getLocInfo() != CCValAssign::Full)
1208 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1209
1210 ArgValues.push_back(ArgValue);
1211 } else {
1212 assert(VA.isMemLoc());
Rafael Espindolab53ef122007-09-21 14:55:38 +00001213 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 }
1215 }
1216
1217 ArgValues.push_back(Root);
1218
1219 unsigned StackSize = CCInfo.getNextStackOffset();
1220
1221 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1222 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001223 // arguments and the arguments after the retaddr has been pushed are
1224 // aligned.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225 if ((StackSize & 7) == 0)
1226 StackSize += 4;
1227 }
1228
1229 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1230 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001231 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
1232 BytesCallerReserves = 0;
1233
Anton Korobeynikove844e472007-08-15 17:12:32 +00001234 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1235 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001236
1237 // Return the new list of results.
1238 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1239 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1240}
1241
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001242SDOperand
1243X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1244 const SDOperand &StackPtr,
1245 const CCValAssign &VA,
1246 SDOperand Chain,
1247 SDOperand Arg) {
1248 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1249 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1250 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1251 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1252 if (Flags & ISD::ParamFlags::ByVal) {
1253 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1254 ISD::ParamFlags::ByValAlignOffs);
1255
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001256 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1257 ISD::ParamFlags::ByValSizeOffs;
1258
1259 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1260 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00001261 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001262
Rafael Espindola80825902007-10-19 10:41:11 +00001263 return DAG.getMemcpy(Chain, PtrOff, Arg, SizeNode, AlignNode,
1264 AlwaysInline);
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001265 } else {
1266 return DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1267 }
1268}
1269
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1271 unsigned CC) {
1272 SDOperand Chain = Op.getOperand(0);
1273 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1274 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1275 SDOperand Callee = Op.getOperand(4);
1276
1277 // Analyze operands of the call, assigning locations to each operand.
1278 SmallVector<CCValAssign, 16> ArgLocs;
1279 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1280 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1281
1282 // Get a count of how many bytes are to be pushed on the stack.
1283 unsigned NumBytes = CCInfo.getNextStackOffset();
1284
1285 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1286 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001287 // arguments and the arguments after the retaddr has been pushed are
1288 // aligned.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289 if ((NumBytes & 7) == 0)
1290 NumBytes += 4;
1291 }
1292
1293 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1294
1295 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1296 SmallVector<SDOperand, 8> MemOpChains;
1297
1298 SDOperand StackPtr;
1299
1300 // Walk the register/memloc assignments, inserting copies/loads.
1301 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1302 CCValAssign &VA = ArgLocs[i];
1303 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1304
1305 // Promote the value if needed.
1306 switch (VA.getLocInfo()) {
1307 default: assert(0 && "Unknown loc info!");
1308 case CCValAssign::Full: break;
1309 case CCValAssign::SExt:
1310 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1311 break;
1312 case CCValAssign::ZExt:
1313 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1314 break;
1315 case CCValAssign::AExt:
1316 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1317 break;
1318 }
1319
1320 if (VA.isRegLoc()) {
1321 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1322 } else {
1323 assert(VA.isMemLoc());
1324 if (StackPtr.Val == 0)
1325 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindola007b7142007-09-21 15:50:22 +00001326
1327 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1328 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001329 }
1330 }
1331
1332 if (!MemOpChains.empty())
1333 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1334 &MemOpChains[0], MemOpChains.size());
1335
1336 // Build a sequence of copy-to-reg nodes chained together with token chain
1337 // and flag operands which copy the outgoing args into registers.
1338 SDOperand InFlag;
1339 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1340 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1341 InFlag);
1342 InFlag = Chain.getValue(1);
1343 }
1344
1345 // If the callee is a GlobalAddress node (quite common, every direct call is)
1346 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1347 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1348 // We should use extra load for direct calls to dllimported functions in
1349 // non-JIT mode.
1350 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1351 getTargetMachine(), true))
1352 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1353 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1354 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1355
1356 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1357 // GOT pointer.
1358 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1359 Subtarget->isPICStyleGOT()) {
1360 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1361 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1362 InFlag);
1363 InFlag = Chain.getValue(1);
1364 }
1365
1366 // Returns a chain & a flag for retval copy to use.
1367 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1368 SmallVector<SDOperand, 8> Ops;
1369 Ops.push_back(Chain);
1370 Ops.push_back(Callee);
1371
1372 // Add argument registers to the end of the list so that they are known live
1373 // into the call.
1374 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1375 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1376 RegsToPass[i].second.getValueType()));
1377
1378 // Add an implicit use GOT pointer in EBX.
1379 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1380 Subtarget->isPICStyleGOT())
1381 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1382
1383 if (InFlag.Val)
1384 Ops.push_back(InFlag);
1385
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001386 assert(isTailCall==false && "no tail call here");
1387 Chain = DAG.getNode(X86ISD::CALL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388 NodeTys, &Ops[0], Ops.size());
1389 InFlag = Chain.getValue(1);
1390
1391 // Returns a flag for retval copy to use.
1392 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1393 Ops.clear();
1394 Ops.push_back(Chain);
1395 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1396 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1397 Ops.push_back(InFlag);
1398 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1399 InFlag = Chain.getValue(1);
1400
1401 // Handle result values, copying them out of physregs into vregs that we
1402 // return.
1403 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1404}
1405
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001406//===----------------------------------------------------------------------===//
1407// Fast Calling Convention (tail call) implementation
1408//===----------------------------------------------------------------------===//
1409
1410// Like std call, callee cleans arguments, convention except that ECX is
1411// reserved for storing the tail called function address. Only 2 registers are
1412// free for argument passing (inreg). Tail call optimization is performed
1413// provided:
1414// * tailcallopt is enabled
1415// * caller/callee are fastcc
1416// * elf/pic is disabled OR
1417// * elf/pic enabled + callee is in module + callee has
1418// visibility protected or hidden
Arnold Schwaighofer373e8652007-10-12 21:30:57 +00001419// To keep the stack aligned according to platform abi the function
1420// GetAlignedArgumentStackSize ensures that argument delta is always multiples
1421// of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001422// If a tail called function callee has more arguments than the caller the
1423// caller needs to make sure that there is room to move the RETADDR to. This is
Arnold Schwaighofer373e8652007-10-12 21:30:57 +00001424// achieved by reserving an area the size of the argument delta right after the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001425// original REtADDR, but before the saved framepointer or the spilled registers
1426// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1427// stack layout:
1428// arg1
1429// arg2
1430// RETADDR
1431// [ new RETADDR
1432// move area ]
1433// (possible EBP)
1434// ESI
1435// EDI
1436// local1 ..
1437
1438/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1439/// for a 16 byte align requirement.
1440unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1441 SelectionDAG& DAG) {
1442 if (PerformTailCallOpt) {
1443 MachineFunction &MF = DAG.getMachineFunction();
1444 const TargetMachine &TM = MF.getTarget();
1445 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1446 unsigned StackAlignment = TFI.getStackAlignment();
1447 uint64_t AlignMask = StackAlignment - 1;
1448 int64_t Offset = StackSize;
1449 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1450 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1451 // Number smaller than 12 so just add the difference.
1452 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1453 } else {
1454 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1455 Offset = ((~AlignMask) & Offset) + StackAlignment +
1456 (StackAlignment-SlotSize);
1457 }
1458 StackSize = Offset;
1459 }
1460 return StackSize;
1461}
1462
1463/// IsEligibleForTailCallElimination - Check to see whether the next instruction
Evan Chenge7a87392007-11-02 01:26:22 +00001464/// following the call is a return. A function is eligible if caller/callee
1465/// calling conventions match, currently only fastcc supports tail calls, and
1466/// the function CALL is immediatly followed by a RET.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001467bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1468 SDOperand Ret,
1469 SelectionDAG& DAG) const {
Evan Chenge7a87392007-11-02 01:26:22 +00001470 if (!PerformTailCallOpt)
1471 return false;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001472
1473 // Check whether CALL node immediatly preceeds the RET node and whether the
1474 // return uses the result of the node or is a void return.
Evan Chenge7a87392007-11-02 01:26:22 +00001475 unsigned NumOps = Ret.getNumOperands();
1476 if ((NumOps == 1 &&
1477 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1478 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
Evan Cheng26c0e982007-11-02 17:45:40 +00001479 (NumOps > 1 &&
Evan Chenge7a87392007-11-02 01:26:22 +00001480 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1481 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001482 MachineFunction &MF = DAG.getMachineFunction();
1483 unsigned CallerCC = MF.getFunction()->getCallingConv();
1484 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1485 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1486 SDOperand Callee = Call.getOperand(4);
1487 // On elf/pic %ebx needs to be livein.
Evan Chenge7a87392007-11-02 01:26:22 +00001488 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1489 !Subtarget->isPICStyleGOT())
1490 return true;
1491
1492 // Can only do local tail calls with PIC.
1493 GlobalValue * GV = 0;
1494 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1495 if(G != 0 &&
1496 (GV = G->getGlobal()) &&
1497 (GV->hasHiddenVisibility() || GV->hasProtectedVisibility()))
1498 return true;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001499 }
1500 }
Evan Chenge7a87392007-11-02 01:26:22 +00001501
1502 return false;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001503}
1504
1505SDOperand X86TargetLowering::LowerX86_TailCallTo(SDOperand Op,
1506 SelectionDAG &DAG,
1507 unsigned CC) {
1508 SDOperand Chain = Op.getOperand(0);
1509 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1510 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1511 SDOperand Callee = Op.getOperand(4);
1512 bool is64Bit = Subtarget->is64Bit();
1513
1514 assert(isTailCall && PerformTailCallOpt && "Should only emit tail calls.");
1515
1516 // Analyze operands of the call, assigning locations to each operand.
1517 SmallVector<CCValAssign, 16> ArgLocs;
1518 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1519 if (is64Bit)
1520 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1521 else
1522 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1523
1524
1525 // Lower arguments at fp - stackoffset + fpdiff.
1526 MachineFunction &MF = DAG.getMachineFunction();
1527
1528 unsigned NumBytesToBePushed =
1529 GetAlignedArgumentStackSize(CCInfo.getNextStackOffset(), DAG);
1530
1531 unsigned NumBytesCallerPushed =
1532 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1533 int FPDiff = NumBytesCallerPushed - NumBytesToBePushed;
1534
1535 // Set the delta of movement of the returnaddr stackslot.
1536 // But only set if delta is greater than previous delta.
1537 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1538 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1539
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001540 Chain = DAG.
1541 getCALLSEQ_START(Chain, DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1542
1543 // Adjust the Return address stack slot.
1544 SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001545 if (FPDiff) {
1546 MVT::ValueType VT = is64Bit ? MVT::i64 : MVT::i32;
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001547 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1548 // Load the "old" Return address.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001549 RetAddrFrIdx =
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001550 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1551 // Calculate the new stack slot for the return address.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001552 int SlotSize = is64Bit ? 8 : 4;
1553 int NewReturnAddrFI =
1554 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001555 NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1556 Chain = SDOperand(RetAddrFrIdx.Val, 1);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001557 }
1558
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001559 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1560 SmallVector<SDOperand, 8> MemOpChains;
1561 SmallVector<SDOperand, 8> MemOpChains2;
1562 SDOperand FramePtr, StackPtr;
1563 SDOperand PtrOff;
1564 SDOperand FIN;
1565 int FI = 0;
1566
1567 // Walk the register/memloc assignments, inserting copies/loads. Lower
1568 // arguments first to the stack slot where they would normally - in case of a
1569 // normal function call - be.
1570 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1571 CCValAssign &VA = ArgLocs[i];
1572 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1573
1574 // Promote the value if needed.
1575 switch (VA.getLocInfo()) {
1576 default: assert(0 && "Unknown loc info!");
1577 case CCValAssign::Full: break;
1578 case CCValAssign::SExt:
1579 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1580 break;
1581 case CCValAssign::ZExt:
1582 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1583 break;
1584 case CCValAssign::AExt:
1585 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1586 break;
1587 }
1588
1589 if (VA.isRegLoc()) {
1590 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1591 } else {
1592 assert(VA.isMemLoc());
1593 if (StackPtr.Val == 0)
1594 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1595
1596 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1597 Arg));
1598 }
1599 }
1600
1601 if (!MemOpChains.empty())
1602 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1603 &MemOpChains[0], MemOpChains.size());
1604
1605 // Build a sequence of copy-to-reg nodes chained together with token chain
1606 // and flag operands which copy the outgoing args into registers.
1607 SDOperand InFlag;
1608 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1609 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1610 InFlag);
1611 InFlag = Chain.getValue(1);
1612 }
1613 InFlag = SDOperand();
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001614
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001615 // Copy from stack slots to stack slot of a tail called function. This needs
1616 // to be done because if we would lower the arguments directly to their real
1617 // stack slot we might end up overwriting each other.
1618 // TODO: To make this more efficient (sometimes saving a store/load) we could
1619 // analyse the arguments and emit this store/load/store sequence only for
1620 // arguments which would be overwritten otherwise.
1621 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1622 CCValAssign &VA = ArgLocs[i];
1623 if (!VA.isRegLoc()) {
1624 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1625 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1626
1627 // Get source stack slot.
1628 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1629 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1630 // Create frame index.
1631 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1632 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1633 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1634 FIN = DAG.getFrameIndex(FI, MVT::i32);
1635 if (Flags & ISD::ParamFlags::ByVal) {
1636 // Copy relative to framepointer.
1637 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1638 ISD::ParamFlags::ByValAlignOffs);
1639
1640 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1641 ISD::ParamFlags::ByValSizeOffs;
1642
1643 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1644 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
Arnold Schwaighofer97794942007-11-10 10:48:01 +00001645 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i1);
1646
1647 MemOpChains2.push_back(DAG.getMemcpy(Chain, FIN, PtrOff, SizeNode,
1648 AlignNode,AlwaysInline));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001649 } else {
1650 SDOperand LoadedArg = DAG.getLoad(VA.getValVT(), Chain, PtrOff, NULL,0);
1651 // Store relative to framepointer.
1652 MemOpChains2.push_back(DAG.getStore(Chain, LoadedArg, FIN, NULL, 0));
1653 }
1654 }
1655 }
1656
1657 if (!MemOpChains2.empty())
1658 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1659 &MemOpChains2[0], MemOpChains.size());
1660
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001661 // Store the return address to the appropriate stack slot.
1662 if (FPDiff)
1663 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1664
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001665 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1666 // GOT pointer.
1667 // Does not work with tail call since ebx is not restored correctly by
1668 // tailcaller. TODO: at least for x86 - verify for x86-64
1669
1670 // If the callee is a GlobalAddress node (quite common, every direct call is)
1671 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1672 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1673 // We should use extra load for direct calls to dllimported functions in
1674 // non-JIT mode.
1675 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1676 getTargetMachine(), true))
1677 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1678 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1679 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1680 else {
1681 assert(Callee.getOpcode() == ISD::LOAD &&
1682 "Function destination must be loaded into virtual register");
1683 unsigned Opc = is64Bit ? X86::R9 : X86::ECX;
1684
1685 Chain = DAG.getCopyToReg(Chain,
1686 DAG.getRegister(Opc, getPointerTy()) ,
1687 Callee,InFlag);
1688 Callee = DAG.getRegister(Opc, getPointerTy());
1689 // Add register as live out.
1690 DAG.getMachineFunction().addLiveOut(Opc);
1691 }
1692
1693 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1694 SmallVector<SDOperand, 8> Ops;
1695
1696 Ops.push_back(Chain);
1697 Ops.push_back(DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1698 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1699 if (InFlag.Val)
1700 Ops.push_back(InFlag);
1701 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1702 InFlag = Chain.getValue(1);
1703
1704 // Returns a chain & a flag for retval copy to use.
1705 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1706 Ops.clear();
1707 Ops.push_back(Chain);
1708 Ops.push_back(Callee);
1709 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1710 // Add argument registers to the end of the list so that they are known live
1711 // into the call.
1712 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1713 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1714 RegsToPass[i].second.getValueType()));
1715 if (InFlag.Val)
1716 Ops.push_back(InFlag);
1717 assert(InFlag.Val &&
1718 "Flag must be set. Depend on flag being set in LowerRET");
1719 Chain = DAG.getNode(X86ISD::TAILCALL,
1720 Op.Val->getVTList(), &Ops[0], Ops.size());
1721
1722 return SDOperand(Chain.Val, Op.ResNo);
1723}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001724
1725//===----------------------------------------------------------------------===//
1726// X86-64 C Calling Convention implementation
1727//===----------------------------------------------------------------------===//
1728
1729SDOperand
1730X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1731 MachineFunction &MF = DAG.getMachineFunction();
1732 MachineFrameInfo *MFI = MF.getFrameInfo();
1733 SDOperand Root = Op.getOperand(0);
1734 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001735 unsigned CC= MF.getFunction()->getCallingConv();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001736
1737 static const unsigned GPR64ArgRegs[] = {
1738 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1739 };
1740 static const unsigned XMMArgRegs[] = {
1741 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1742 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1743 };
1744
1745
1746 // Assign locations to all of the incoming arguments.
1747 SmallVector<CCValAssign, 16> ArgLocs;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001748 CCState CCInfo(CC, isVarArg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001749 getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001750 if (CC == CallingConv::Fast && PerformTailCallOpt)
1751 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_TailCall);
1752 else
1753 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001754
1755 SmallVector<SDOperand, 8> ArgValues;
1756 unsigned LastVal = ~0U;
1757 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1758 CCValAssign &VA = ArgLocs[i];
1759 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1760 // places.
1761 assert(VA.getValNo() != LastVal &&
1762 "Don't support value assigned to multiple locs yet");
1763 LastVal = VA.getValNo();
1764
1765 if (VA.isRegLoc()) {
1766 MVT::ValueType RegVT = VA.getLocVT();
1767 TargetRegisterClass *RC;
1768 if (RegVT == MVT::i32)
1769 RC = X86::GR32RegisterClass;
1770 else if (RegVT == MVT::i64)
1771 RC = X86::GR64RegisterClass;
1772 else if (RegVT == MVT::f32)
1773 RC = X86::FR32RegisterClass;
1774 else if (RegVT == MVT::f64)
1775 RC = X86::FR64RegisterClass;
1776 else {
1777 assert(MVT::isVector(RegVT));
1778 if (MVT::getSizeInBits(RegVT) == 64) {
1779 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1780 RegVT = MVT::i64;
1781 } else
1782 RC = X86::VR128RegisterClass;
1783 }
1784
1785 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1786 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1787
1788 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1789 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1790 // right size.
1791 if (VA.getLocInfo() == CCValAssign::SExt)
1792 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1793 DAG.getValueType(VA.getValVT()));
1794 else if (VA.getLocInfo() == CCValAssign::ZExt)
1795 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1796 DAG.getValueType(VA.getValVT()));
1797
1798 if (VA.getLocInfo() != CCValAssign::Full)
1799 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1800
1801 // Handle MMX values passed in GPRs.
1802 if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1803 MVT::getSizeInBits(RegVT) == 64)
1804 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1805
1806 ArgValues.push_back(ArgValue);
1807 } else {
1808 assert(VA.isMemLoc());
Rafael Espindola03cbeb72007-09-14 15:48:13 +00001809 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001810 }
1811 }
1812
1813 unsigned StackSize = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001814 if (CC==CallingConv::Fast)
1815 StackSize =GetAlignedArgumentStackSize(StackSize, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001816
1817 // If the function takes variable number of arguments, make a frame index for
1818 // the start of the first vararg value... for expansion of llvm.va_start.
1819 if (isVarArg) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001820 assert(CC!=CallingConv::Fast
1821 && "Var arg not supported with calling convention fastcc");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001822 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1823 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1824
1825 // For X86-64, if there are vararg parameters that are passed via
1826 // registers, then we must store them to their spots on the stack so they
1827 // may be loaded by deferencing the result of va_next.
1828 VarArgsGPOffset = NumIntRegs * 8;
1829 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1830 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1831 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1832
1833 // Store the integer parameter registers.
1834 SmallVector<SDOperand, 8> MemOps;
1835 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1836 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1837 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1838 for (; NumIntRegs != 6; ++NumIntRegs) {
1839 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1840 X86::GR64RegisterClass);
1841 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1842 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1843 MemOps.push_back(Store);
1844 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1845 DAG.getConstant(8, getPointerTy()));
1846 }
1847
1848 // Now store the XMM (fp + vector) parameter registers.
1849 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1850 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1851 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1852 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1853 X86::VR128RegisterClass);
1854 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1855 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1856 MemOps.push_back(Store);
1857 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1858 DAG.getConstant(16, getPointerTy()));
1859 }
1860 if (!MemOps.empty())
1861 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1862 &MemOps[0], MemOps.size());
1863 }
1864
1865 ArgValues.push_back(Root);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001866 // Tail call convention (fastcc) needs callee pop.
Evan Cheng778fa0f2007-10-14 10:09:39 +00001867 if (CC == CallingConv::Fast && PerformTailCallOpt) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001868 BytesToPopOnReturn = StackSize; // Callee pops everything.
1869 BytesCallerReserves = 0;
1870 } else {
1871 BytesToPopOnReturn = 0; // Callee pops nothing.
1872 BytesCallerReserves = StackSize;
1873 }
Anton Korobeynikove844e472007-08-15 17:12:32 +00001874 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1875 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1876
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001877 // Return the new list of results.
1878 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1879 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1880}
1881
1882SDOperand
1883X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1884 unsigned CC) {
1885 SDOperand Chain = Op.getOperand(0);
1886 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001887 SDOperand Callee = Op.getOperand(4);
1888
1889 // Analyze operands of the call, assigning locations to each operand.
1890 SmallVector<CCValAssign, 16> ArgLocs;
1891 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Evan Cheng778fa0f2007-10-14 10:09:39 +00001892 if (CC==CallingConv::Fast && PerformTailCallOpt)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001893 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1894 else
1895 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001896
1897 // Get a count of how many bytes are to be pushed on the stack.
1898 unsigned NumBytes = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001899 if (CC == CallingConv::Fast)
1900 NumBytes = GetAlignedArgumentStackSize(NumBytes,DAG);
1901
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001902 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1903
1904 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1905 SmallVector<SDOperand, 8> MemOpChains;
1906
1907 SDOperand StackPtr;
1908
1909 // Walk the register/memloc assignments, inserting copies/loads.
1910 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1911 CCValAssign &VA = ArgLocs[i];
1912 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1913
1914 // Promote the value if needed.
1915 switch (VA.getLocInfo()) {
1916 default: assert(0 && "Unknown loc info!");
1917 case CCValAssign::Full: break;
1918 case CCValAssign::SExt:
1919 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1920 break;
1921 case CCValAssign::ZExt:
1922 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1923 break;
1924 case CCValAssign::AExt:
1925 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1926 break;
1927 }
1928
1929 if (VA.isRegLoc()) {
1930 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1931 } else {
1932 assert(VA.isMemLoc());
1933 if (StackPtr.Val == 0)
1934 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindolab8bcfcd2007-08-20 15:18:24 +00001935
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001936 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1937 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001938 }
1939 }
1940
1941 if (!MemOpChains.empty())
1942 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1943 &MemOpChains[0], MemOpChains.size());
1944
1945 // Build a sequence of copy-to-reg nodes chained together with token chain
1946 // and flag operands which copy the outgoing args into registers.
1947 SDOperand InFlag;
1948 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1949 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1950 InFlag);
1951 InFlag = Chain.getValue(1);
1952 }
1953
1954 if (isVarArg) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001955 assert ( CallingConv::Fast != CC &&
1956 "Var args not supported with calling convention fastcc");
1957
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001958 // From AMD64 ABI document:
1959 // For calls that may call functions that use varargs or stdargs
1960 // (prototype-less calls or calls to functions containing ellipsis (...) in
1961 // the declaration) %al is used as hidden argument to specify the number
1962 // of SSE registers used. The contents of %al do not need to match exactly
1963 // the number of registers, but must be an ubound on the number of SSE
1964 // registers used and is in the range 0 - 8 inclusive.
1965
1966 // Count the number of XMM registers allocated.
1967 static const unsigned XMMArgRegs[] = {
1968 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1969 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1970 };
1971 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1972
1973 Chain = DAG.getCopyToReg(Chain, X86::AL,
1974 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1975 InFlag = Chain.getValue(1);
1976 }
1977
1978 // If the callee is a GlobalAddress node (quite common, every direct call is)
1979 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1980 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1981 // We should use extra load for direct calls to dllimported functions in
1982 // non-JIT mode.
1983 if (getTargetMachine().getCodeModel() != CodeModel::Large
1984 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1985 getTargetMachine(), true))
1986 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1987 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1988 if (getTargetMachine().getCodeModel() != CodeModel::Large)
1989 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1990
1991 // Returns a chain & a flag for retval copy to use.
1992 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1993 SmallVector<SDOperand, 8> Ops;
1994 Ops.push_back(Chain);
1995 Ops.push_back(Callee);
1996
1997 // Add argument registers to the end of the list so that they are known live
1998 // into the call.
1999 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2000 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2001 RegsToPass[i].second.getValueType()));
2002
2003 if (InFlag.Val)
2004 Ops.push_back(InFlag);
2005
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002006 Chain = DAG.getNode(X86ISD::CALL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002007 NodeTys, &Ops[0], Ops.size());
2008 InFlag = Chain.getValue(1);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002009 int NumBytesForCalleeToPush = 0;
Evan Cheng778fa0f2007-10-14 10:09:39 +00002010 if (CC==CallingConv::Fast && PerformTailCallOpt) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002011 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002012 } else {
2013 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2014 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002015 // Returns a flag for retval copy to use.
2016 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2017 Ops.clear();
2018 Ops.push_back(Chain);
2019 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002020 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002021 Ops.push_back(InFlag);
2022 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
2023 InFlag = Chain.getValue(1);
2024
2025 // Handle result values, copying them out of physregs into vregs that we
2026 // return.
2027 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
2028}
2029
2030
2031//===----------------------------------------------------------------------===//
2032// Other Lowering Hooks
2033//===----------------------------------------------------------------------===//
2034
2035
2036SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
Anton Korobeynikove844e472007-08-15 17:12:32 +00002037 MachineFunction &MF = DAG.getMachineFunction();
2038 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2039 int ReturnAddrIndex = FuncInfo->getRAIndex();
2040
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002041 if (ReturnAddrIndex == 0) {
2042 // Set up a frame object for the return address.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002043 if (Subtarget->is64Bit())
2044 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
2045 else
2046 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
Anton Korobeynikove844e472007-08-15 17:12:32 +00002047
2048 FuncInfo->setRAIndex(ReturnAddrIndex);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002049 }
2050
2051 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2052}
2053
2054
2055
2056/// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
2057/// specific condition code. It returns a false if it cannot do a direct
2058/// translation. X86CC is the translated CondCode. LHS/RHS are modified as
2059/// needed.
2060static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2061 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
2062 SelectionDAG &DAG) {
2063 X86CC = X86::COND_INVALID;
2064 if (!isFP) {
2065 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2066 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2067 // X > -1 -> X == 0, jump !sign.
2068 RHS = DAG.getConstant(0, RHS.getValueType());
2069 X86CC = X86::COND_NS;
2070 return true;
2071 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2072 // X < 0 -> X == 0, jump on sign.
2073 X86CC = X86::COND_S;
2074 return true;
Dan Gohman37b34262007-09-17 14:49:27 +00002075 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
2076 // X < 1 -> X <= 0
2077 RHS = DAG.getConstant(0, RHS.getValueType());
2078 X86CC = X86::COND_LE;
2079 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002080 }
2081 }
2082
2083 switch (SetCCOpcode) {
2084 default: break;
2085 case ISD::SETEQ: X86CC = X86::COND_E; break;
2086 case ISD::SETGT: X86CC = X86::COND_G; break;
2087 case ISD::SETGE: X86CC = X86::COND_GE; break;
2088 case ISD::SETLT: X86CC = X86::COND_L; break;
2089 case ISD::SETLE: X86CC = X86::COND_LE; break;
2090 case ISD::SETNE: X86CC = X86::COND_NE; break;
2091 case ISD::SETULT: X86CC = X86::COND_B; break;
2092 case ISD::SETUGT: X86CC = X86::COND_A; break;
2093 case ISD::SETULE: X86CC = X86::COND_BE; break;
2094 case ISD::SETUGE: X86CC = X86::COND_AE; break;
2095 }
2096 } else {
2097 // On a floating point condition, the flags are set as follows:
2098 // ZF PF CF op
2099 // 0 | 0 | 0 | X > Y
2100 // 0 | 0 | 1 | X < Y
2101 // 1 | 0 | 0 | X == Y
2102 // 1 | 1 | 1 | unordered
2103 bool Flip = false;
2104 switch (SetCCOpcode) {
2105 default: break;
2106 case ISD::SETUEQ:
2107 case ISD::SETEQ: X86CC = X86::COND_E; break;
2108 case ISD::SETOLT: Flip = true; // Fallthrough
2109 case ISD::SETOGT:
2110 case ISD::SETGT: X86CC = X86::COND_A; break;
2111 case ISD::SETOLE: Flip = true; // Fallthrough
2112 case ISD::SETOGE:
2113 case ISD::SETGE: X86CC = X86::COND_AE; break;
2114 case ISD::SETUGT: Flip = true; // Fallthrough
2115 case ISD::SETULT:
2116 case ISD::SETLT: X86CC = X86::COND_B; break;
2117 case ISD::SETUGE: Flip = true; // Fallthrough
2118 case ISD::SETULE:
2119 case ISD::SETLE: X86CC = X86::COND_BE; break;
2120 case ISD::SETONE:
2121 case ISD::SETNE: X86CC = X86::COND_NE; break;
2122 case ISD::SETUO: X86CC = X86::COND_P; break;
2123 case ISD::SETO: X86CC = X86::COND_NP; break;
2124 }
2125 if (Flip)
2126 std::swap(LHS, RHS);
2127 }
2128
2129 return X86CC != X86::COND_INVALID;
2130}
2131
2132/// hasFPCMov - is there a floating point cmov for the specific X86 condition
2133/// code. Current x86 isa includes the following FP cmov instructions:
2134/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2135static bool hasFPCMov(unsigned X86CC) {
2136 switch (X86CC) {
2137 default:
2138 return false;
2139 case X86::COND_B:
2140 case X86::COND_BE:
2141 case X86::COND_E:
2142 case X86::COND_P:
2143 case X86::COND_A:
2144 case X86::COND_AE:
2145 case X86::COND_NE:
2146 case X86::COND_NP:
2147 return true;
2148 }
2149}
2150
2151/// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2152/// true if Op is undef or if its value falls within the specified range (L, H].
2153static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2154 if (Op.getOpcode() == ISD::UNDEF)
2155 return true;
2156
2157 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2158 return (Val >= Low && Val < Hi);
2159}
2160
2161/// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2162/// true if Op is undef or if its value equal to the specified value.
2163static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2164 if (Op.getOpcode() == ISD::UNDEF)
2165 return true;
2166 return cast<ConstantSDNode>(Op)->getValue() == Val;
2167}
2168
2169/// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2170/// specifies a shuffle of elements that is suitable for input to PSHUFD.
2171bool X86::isPSHUFDMask(SDNode *N) {
2172 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2173
Dan Gohman7dc19012007-08-02 21:17:01 +00002174 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002175 return false;
2176
2177 // Check if the value doesn't reference the second vector.
2178 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2179 SDOperand Arg = N->getOperand(i);
2180 if (Arg.getOpcode() == ISD::UNDEF) continue;
2181 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Dan Gohman7dc19012007-08-02 21:17:01 +00002182 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183 return false;
2184 }
2185
2186 return true;
2187}
2188
2189/// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2190/// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2191bool X86::isPSHUFHWMask(SDNode *N) {
2192 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2193
2194 if (N->getNumOperands() != 8)
2195 return false;
2196
2197 // Lower quadword copied in order.
2198 for (unsigned i = 0; i != 4; ++i) {
2199 SDOperand Arg = N->getOperand(i);
2200 if (Arg.getOpcode() == ISD::UNDEF) continue;
2201 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2202 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2203 return false;
2204 }
2205
2206 // Upper quadword shuffled.
2207 for (unsigned i = 4; i != 8; ++i) {
2208 SDOperand Arg = N->getOperand(i);
2209 if (Arg.getOpcode() == ISD::UNDEF) continue;
2210 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2211 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2212 if (Val < 4 || Val > 7)
2213 return false;
2214 }
2215
2216 return true;
2217}
2218
2219/// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2220/// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2221bool X86::isPSHUFLWMask(SDNode *N) {
2222 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2223
2224 if (N->getNumOperands() != 8)
2225 return false;
2226
2227 // Upper quadword copied in order.
2228 for (unsigned i = 4; i != 8; ++i)
2229 if (!isUndefOrEqual(N->getOperand(i), i))
2230 return false;
2231
2232 // Lower quadword shuffled.
2233 for (unsigned i = 0; i != 4; ++i)
2234 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2235 return false;
2236
2237 return true;
2238}
2239
2240/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2241/// specifies a shuffle of elements that is suitable for input to SHUFP*.
2242static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2243 if (NumElems != 2 && NumElems != 4) return false;
2244
2245 unsigned Half = NumElems / 2;
2246 for (unsigned i = 0; i < Half; ++i)
2247 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2248 return false;
2249 for (unsigned i = Half; i < NumElems; ++i)
2250 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2251 return false;
2252
2253 return true;
2254}
2255
2256bool X86::isSHUFPMask(SDNode *N) {
2257 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2258 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2259}
2260
2261/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2262/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2263/// half elements to come from vector 1 (which would equal the dest.) and
2264/// the upper half to come from vector 2.
2265static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2266 if (NumOps != 2 && NumOps != 4) return false;
2267
2268 unsigned Half = NumOps / 2;
2269 for (unsigned i = 0; i < Half; ++i)
2270 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2271 return false;
2272 for (unsigned i = Half; i < NumOps; ++i)
2273 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2274 return false;
2275 return true;
2276}
2277
2278static bool isCommutedSHUFP(SDNode *N) {
2279 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2280 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2281}
2282
2283/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2284/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2285bool X86::isMOVHLPSMask(SDNode *N) {
2286 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2287
2288 if (N->getNumOperands() != 4)
2289 return false;
2290
2291 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2292 return isUndefOrEqual(N->getOperand(0), 6) &&
2293 isUndefOrEqual(N->getOperand(1), 7) &&
2294 isUndefOrEqual(N->getOperand(2), 2) &&
2295 isUndefOrEqual(N->getOperand(3), 3);
2296}
2297
2298/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2299/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2300/// <2, 3, 2, 3>
2301bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2302 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2303
2304 if (N->getNumOperands() != 4)
2305 return false;
2306
2307 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2308 return isUndefOrEqual(N->getOperand(0), 2) &&
2309 isUndefOrEqual(N->getOperand(1), 3) &&
2310 isUndefOrEqual(N->getOperand(2), 2) &&
2311 isUndefOrEqual(N->getOperand(3), 3);
2312}
2313
2314/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2315/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2316bool X86::isMOVLPMask(SDNode *N) {
2317 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2318
2319 unsigned NumElems = N->getNumOperands();
2320 if (NumElems != 2 && NumElems != 4)
2321 return false;
2322
2323 for (unsigned i = 0; i < NumElems/2; ++i)
2324 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2325 return false;
2326
2327 for (unsigned i = NumElems/2; i < NumElems; ++i)
2328 if (!isUndefOrEqual(N->getOperand(i), i))
2329 return false;
2330
2331 return true;
2332}
2333
2334/// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2335/// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2336/// and MOVLHPS.
2337bool X86::isMOVHPMask(SDNode *N) {
2338 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2339
2340 unsigned NumElems = N->getNumOperands();
2341 if (NumElems != 2 && NumElems != 4)
2342 return false;
2343
2344 for (unsigned i = 0; i < NumElems/2; ++i)
2345 if (!isUndefOrEqual(N->getOperand(i), i))
2346 return false;
2347
2348 for (unsigned i = 0; i < NumElems/2; ++i) {
2349 SDOperand Arg = N->getOperand(i + NumElems/2);
2350 if (!isUndefOrEqual(Arg, i + NumElems))
2351 return false;
2352 }
2353
2354 return true;
2355}
2356
2357/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2358/// specifies a shuffle of elements that is suitable for input to UNPCKL.
2359bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2360 bool V2IsSplat = false) {
2361 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2362 return false;
2363
2364 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2365 SDOperand BitI = Elts[i];
2366 SDOperand BitI1 = Elts[i+1];
2367 if (!isUndefOrEqual(BitI, j))
2368 return false;
2369 if (V2IsSplat) {
2370 if (isUndefOrEqual(BitI1, NumElts))
2371 return false;
2372 } else {
2373 if (!isUndefOrEqual(BitI1, j + NumElts))
2374 return false;
2375 }
2376 }
2377
2378 return true;
2379}
2380
2381bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2382 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2383 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2384}
2385
2386/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2387/// specifies a shuffle of elements that is suitable for input to UNPCKH.
2388bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2389 bool V2IsSplat = false) {
2390 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2391 return false;
2392
2393 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2394 SDOperand BitI = Elts[i];
2395 SDOperand BitI1 = Elts[i+1];
2396 if (!isUndefOrEqual(BitI, j + NumElts/2))
2397 return false;
2398 if (V2IsSplat) {
2399 if (isUndefOrEqual(BitI1, NumElts))
2400 return false;
2401 } else {
2402 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2403 return false;
2404 }
2405 }
2406
2407 return true;
2408}
2409
2410bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2411 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2412 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2413}
2414
2415/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2416/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2417/// <0, 0, 1, 1>
2418bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2419 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2420
2421 unsigned NumElems = N->getNumOperands();
2422 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2423 return false;
2424
2425 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2426 SDOperand BitI = N->getOperand(i);
2427 SDOperand BitI1 = N->getOperand(i+1);
2428
2429 if (!isUndefOrEqual(BitI, j))
2430 return false;
2431 if (!isUndefOrEqual(BitI1, j))
2432 return false;
2433 }
2434
2435 return true;
2436}
2437
2438/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2439/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2440/// <2, 2, 3, 3>
2441bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2442 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2443
2444 unsigned NumElems = N->getNumOperands();
2445 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2446 return false;
2447
2448 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2449 SDOperand BitI = N->getOperand(i);
2450 SDOperand BitI1 = N->getOperand(i + 1);
2451
2452 if (!isUndefOrEqual(BitI, j))
2453 return false;
2454 if (!isUndefOrEqual(BitI1, j))
2455 return false;
2456 }
2457
2458 return true;
2459}
2460
2461/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2462/// specifies a shuffle of elements that is suitable for input to MOVSS,
2463/// MOVSD, and MOVD, i.e. setting the lowest element.
2464static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
Evan Cheng62cdc642007-12-06 22:14:22 +00002465 if (NumElts != 2 && NumElts != 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002466 return false;
2467
2468 if (!isUndefOrEqual(Elts[0], NumElts))
2469 return false;
2470
2471 for (unsigned i = 1; i < NumElts; ++i) {
2472 if (!isUndefOrEqual(Elts[i], i))
2473 return false;
2474 }
2475
2476 return true;
2477}
2478
2479bool X86::isMOVLMask(SDNode *N) {
2480 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2481 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2482}
2483
2484/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2485/// of what x86 movss want. X86 movs requires the lowest element to be lowest
2486/// element of vector 2 and the other elements to come from vector 1 in order.
2487static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2488 bool V2IsSplat = false,
2489 bool V2IsUndef = false) {
2490 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2491 return false;
2492
2493 if (!isUndefOrEqual(Ops[0], 0))
2494 return false;
2495
2496 for (unsigned i = 1; i < NumOps; ++i) {
2497 SDOperand Arg = Ops[i];
2498 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2499 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2500 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2501 return false;
2502 }
2503
2504 return true;
2505}
2506
2507static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2508 bool V2IsUndef = false) {
2509 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2510 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2511 V2IsSplat, V2IsUndef);
2512}
2513
2514/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2515/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2516bool X86::isMOVSHDUPMask(SDNode *N) {
2517 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2518
2519 if (N->getNumOperands() != 4)
2520 return false;
2521
2522 // Expect 1, 1, 3, 3
2523 for (unsigned i = 0; i < 2; ++i) {
2524 SDOperand Arg = N->getOperand(i);
2525 if (Arg.getOpcode() == ISD::UNDEF) continue;
2526 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2527 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2528 if (Val != 1) return false;
2529 }
2530
2531 bool HasHi = false;
2532 for (unsigned i = 2; i < 4; ++i) {
2533 SDOperand Arg = N->getOperand(i);
2534 if (Arg.getOpcode() == ISD::UNDEF) continue;
2535 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2536 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2537 if (Val != 3) return false;
2538 HasHi = true;
2539 }
2540
2541 // Don't use movshdup if it can be done with a shufps.
2542 return HasHi;
2543}
2544
2545/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2546/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2547bool X86::isMOVSLDUPMask(SDNode *N) {
2548 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2549
2550 if (N->getNumOperands() != 4)
2551 return false;
2552
2553 // Expect 0, 0, 2, 2
2554 for (unsigned i = 0; i < 2; ++i) {
2555 SDOperand Arg = N->getOperand(i);
2556 if (Arg.getOpcode() == ISD::UNDEF) continue;
2557 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2558 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2559 if (Val != 0) return false;
2560 }
2561
2562 bool HasHi = false;
2563 for (unsigned i = 2; i < 4; ++i) {
2564 SDOperand Arg = N->getOperand(i);
2565 if (Arg.getOpcode() == ISD::UNDEF) continue;
2566 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2567 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2568 if (Val != 2) return false;
2569 HasHi = true;
2570 }
2571
2572 // Don't use movshdup if it can be done with a shufps.
2573 return HasHi;
2574}
2575
2576/// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2577/// specifies a identity operation on the LHS or RHS.
2578static bool isIdentityMask(SDNode *N, bool RHS = false) {
2579 unsigned NumElems = N->getNumOperands();
2580 for (unsigned i = 0; i < NumElems; ++i)
2581 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2582 return false;
2583 return true;
2584}
2585
2586/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2587/// a splat of a single element.
2588static bool isSplatMask(SDNode *N) {
2589 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2590
2591 // This is a splat operation if each element of the permute is the same, and
2592 // if the value doesn't reference the second vector.
2593 unsigned NumElems = N->getNumOperands();
2594 SDOperand ElementBase;
2595 unsigned i = 0;
2596 for (; i != NumElems; ++i) {
2597 SDOperand Elt = N->getOperand(i);
2598 if (isa<ConstantSDNode>(Elt)) {
2599 ElementBase = Elt;
2600 break;
2601 }
2602 }
2603
2604 if (!ElementBase.Val)
2605 return false;
2606
2607 for (; i != NumElems; ++i) {
2608 SDOperand Arg = N->getOperand(i);
2609 if (Arg.getOpcode() == ISD::UNDEF) continue;
2610 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2611 if (Arg != ElementBase) return false;
2612 }
2613
2614 // Make sure it is a splat of the first vector operand.
2615 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2616}
2617
2618/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2619/// a splat of a single element and it's a 2 or 4 element mask.
2620bool X86::isSplatMask(SDNode *N) {
2621 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2622
2623 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2624 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2625 return false;
2626 return ::isSplatMask(N);
2627}
2628
2629/// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2630/// specifies a splat of zero element.
2631bool X86::isSplatLoMask(SDNode *N) {
2632 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2633
2634 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2635 if (!isUndefOrEqual(N->getOperand(i), 0))
2636 return false;
2637 return true;
2638}
2639
2640/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2641/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2642/// instructions.
2643unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2644 unsigned NumOperands = N->getNumOperands();
2645 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2646 unsigned Mask = 0;
2647 for (unsigned i = 0; i < NumOperands; ++i) {
2648 unsigned Val = 0;
2649 SDOperand Arg = N->getOperand(NumOperands-i-1);
2650 if (Arg.getOpcode() != ISD::UNDEF)
2651 Val = cast<ConstantSDNode>(Arg)->getValue();
2652 if (Val >= NumOperands) Val -= NumOperands;
2653 Mask |= Val;
2654 if (i != NumOperands - 1)
2655 Mask <<= Shift;
2656 }
2657
2658 return Mask;
2659}
2660
2661/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2662/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2663/// instructions.
2664unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2665 unsigned Mask = 0;
2666 // 8 nodes, but we only care about the last 4.
2667 for (unsigned i = 7; i >= 4; --i) {
2668 unsigned Val = 0;
2669 SDOperand Arg = N->getOperand(i);
2670 if (Arg.getOpcode() != ISD::UNDEF)
2671 Val = cast<ConstantSDNode>(Arg)->getValue();
2672 Mask |= (Val - 4);
2673 if (i != 4)
2674 Mask <<= 2;
2675 }
2676
2677 return Mask;
2678}
2679
2680/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2681/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2682/// instructions.
2683unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2684 unsigned Mask = 0;
2685 // 8 nodes, but we only care about the first 4.
2686 for (int i = 3; i >= 0; --i) {
2687 unsigned Val = 0;
2688 SDOperand Arg = N->getOperand(i);
2689 if (Arg.getOpcode() != ISD::UNDEF)
2690 Val = cast<ConstantSDNode>(Arg)->getValue();
2691 Mask |= Val;
2692 if (i != 0)
2693 Mask <<= 2;
2694 }
2695
2696 return Mask;
2697}
2698
2699/// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2700/// specifies a 8 element shuffle that can be broken into a pair of
2701/// PSHUFHW and PSHUFLW.
2702static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2703 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2704
2705 if (N->getNumOperands() != 8)
2706 return false;
2707
2708 // Lower quadword shuffled.
2709 for (unsigned i = 0; i != 4; ++i) {
2710 SDOperand Arg = N->getOperand(i);
2711 if (Arg.getOpcode() == ISD::UNDEF) continue;
2712 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2713 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2714 if (Val > 4)
2715 return false;
2716 }
2717
2718 // Upper quadword shuffled.
2719 for (unsigned i = 4; i != 8; ++i) {
2720 SDOperand Arg = N->getOperand(i);
2721 if (Arg.getOpcode() == ISD::UNDEF) continue;
2722 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2723 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2724 if (Val < 4 || Val > 7)
2725 return false;
2726 }
2727
2728 return true;
2729}
2730
Chris Lattnere6aa3862007-11-25 00:24:49 +00002731/// CommuteVectorShuffle - Swap vector_shuffle operands as well as
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002732/// values in ther permute mask.
2733static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2734 SDOperand &V2, SDOperand &Mask,
2735 SelectionDAG &DAG) {
2736 MVT::ValueType VT = Op.getValueType();
2737 MVT::ValueType MaskVT = Mask.getValueType();
2738 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2739 unsigned NumElems = Mask.getNumOperands();
2740 SmallVector<SDOperand, 8> MaskVec;
2741
2742 for (unsigned i = 0; i != NumElems; ++i) {
2743 SDOperand Arg = Mask.getOperand(i);
2744 if (Arg.getOpcode() == ISD::UNDEF) {
2745 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2746 continue;
2747 }
2748 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2749 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2750 if (Val < NumElems)
2751 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2752 else
2753 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2754 }
2755
2756 std::swap(V1, V2);
Evan Chengfca29242007-12-07 08:07:39 +00002757 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002758 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2759}
2760
Evan Chenga6769df2007-12-07 21:30:01 +00002761/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2762/// the two vector operands have swapped position.
Evan Chengfca29242007-12-07 08:07:39 +00002763static
2764SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2765 MVT::ValueType MaskVT = Mask.getValueType();
2766 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2767 unsigned NumElems = Mask.getNumOperands();
2768 SmallVector<SDOperand, 8> MaskVec;
2769 for (unsigned i = 0; i != NumElems; ++i) {
2770 SDOperand Arg = Mask.getOperand(i);
2771 if (Arg.getOpcode() == ISD::UNDEF) {
2772 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2773 continue;
2774 }
2775 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2776 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2777 if (Val < NumElems)
2778 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2779 else
2780 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2781 }
2782 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2783}
2784
2785
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002786/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2787/// match movhlps. The lower half elements should come from upper half of
2788/// V1 (and in order), and the upper half elements should come from the upper
2789/// half of V2 (and in order).
2790static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2791 unsigned NumElems = Mask->getNumOperands();
2792 if (NumElems != 4)
2793 return false;
2794 for (unsigned i = 0, e = 2; i != e; ++i)
2795 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2796 return false;
2797 for (unsigned i = 2; i != 4; ++i)
2798 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2799 return false;
2800 return true;
2801}
2802
2803/// isScalarLoadToVector - Returns true if the node is a scalar load that
2804/// is promoted to a vector.
2805static inline bool isScalarLoadToVector(SDNode *N) {
2806 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2807 N = N->getOperand(0).Val;
2808 return ISD::isNON_EXTLoad(N);
2809 }
2810 return false;
2811}
2812
2813/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2814/// match movlp{s|d}. The lower half elements should come from lower half of
2815/// V1 (and in order), and the upper half elements should come from the upper
2816/// half of V2 (and in order). And since V1 will become the source of the
2817/// MOVLP, it must be either a vector load or a scalar load to vector.
2818static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2819 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2820 return false;
2821 // Is V2 is a vector load, don't do this transformation. We will try to use
2822 // load folding shufps op.
2823 if (ISD::isNON_EXTLoad(V2))
2824 return false;
2825
2826 unsigned NumElems = Mask->getNumOperands();
2827 if (NumElems != 2 && NumElems != 4)
2828 return false;
2829 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2830 if (!isUndefOrEqual(Mask->getOperand(i), i))
2831 return false;
2832 for (unsigned i = NumElems/2; i != NumElems; ++i)
2833 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2834 return false;
2835 return true;
2836}
2837
2838/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2839/// all the same.
2840static bool isSplatVector(SDNode *N) {
2841 if (N->getOpcode() != ISD::BUILD_VECTOR)
2842 return false;
2843
2844 SDOperand SplatValue = N->getOperand(0);
2845 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2846 if (N->getOperand(i) != SplatValue)
2847 return false;
2848 return true;
2849}
2850
2851/// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2852/// to an undef.
2853static bool isUndefShuffle(SDNode *N) {
2854 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2855 return false;
2856
2857 SDOperand V1 = N->getOperand(0);
2858 SDOperand V2 = N->getOperand(1);
2859 SDOperand Mask = N->getOperand(2);
2860 unsigned NumElems = Mask.getNumOperands();
2861 for (unsigned i = 0; i != NumElems; ++i) {
2862 SDOperand Arg = Mask.getOperand(i);
2863 if (Arg.getOpcode() != ISD::UNDEF) {
2864 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2865 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2866 return false;
2867 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2868 return false;
2869 }
2870 }
2871 return true;
2872}
2873
2874/// isZeroNode - Returns true if Elt is a constant zero or a floating point
2875/// constant +0.0.
2876static inline bool isZeroNode(SDOperand Elt) {
2877 return ((isa<ConstantSDNode>(Elt) &&
2878 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2879 (isa<ConstantFPSDNode>(Elt) &&
Dale Johannesendf8a8312007-08-31 04:03:46 +00002880 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002881}
2882
2883/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2884/// to an zero vector.
2885static bool isZeroShuffle(SDNode *N) {
2886 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2887 return false;
2888
2889 SDOperand V1 = N->getOperand(0);
2890 SDOperand V2 = N->getOperand(1);
2891 SDOperand Mask = N->getOperand(2);
2892 unsigned NumElems = Mask.getNumOperands();
2893 for (unsigned i = 0; i != NumElems; ++i) {
2894 SDOperand Arg = Mask.getOperand(i);
Chris Lattnere6aa3862007-11-25 00:24:49 +00002895 if (Arg.getOpcode() == ISD::UNDEF)
2896 continue;
2897
2898 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2899 if (Idx < NumElems) {
2900 unsigned Opc = V1.Val->getOpcode();
2901 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2902 continue;
2903 if (Opc != ISD::BUILD_VECTOR ||
2904 !isZeroNode(V1.Val->getOperand(Idx)))
2905 return false;
2906 } else if (Idx >= NumElems) {
2907 unsigned Opc = V2.Val->getOpcode();
2908 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2909 continue;
2910 if (Opc != ISD::BUILD_VECTOR ||
2911 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2912 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002913 }
2914 }
2915 return true;
2916}
2917
2918/// getZeroVector - Returns a vector of specified type with all zero elements.
2919///
2920static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2921 assert(MVT::isVector(VT) && "Expected a vector type");
Chris Lattnere6aa3862007-11-25 00:24:49 +00002922
2923 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2924 // type. This ensures they get CSE'd.
2925 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2926 SDOperand Vec;
2927 if (MVT::getSizeInBits(VT) == 64) // MMX
2928 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2929 else // SSE
2930 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2931 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002932}
2933
Chris Lattnere6aa3862007-11-25 00:24:49 +00002934/// getOnesVector - Returns a vector of specified type with all bits set.
2935///
2936static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2937 assert(MVT::isVector(VT) && "Expected a vector type");
2938
2939 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2940 // type. This ensures they get CSE'd.
2941 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2942 SDOperand Vec;
2943 if (MVT::getSizeInBits(VT) == 64) // MMX
2944 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2945 else // SSE
2946 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2947 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2948}
2949
2950
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002951/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2952/// that point to V2 points to its first element.
2953static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2954 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2955
2956 bool Changed = false;
2957 SmallVector<SDOperand, 8> MaskVec;
2958 unsigned NumElems = Mask.getNumOperands();
2959 for (unsigned i = 0; i != NumElems; ++i) {
2960 SDOperand Arg = Mask.getOperand(i);
2961 if (Arg.getOpcode() != ISD::UNDEF) {
2962 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2963 if (Val > NumElems) {
2964 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2965 Changed = true;
2966 }
2967 }
2968 MaskVec.push_back(Arg);
2969 }
2970
2971 if (Changed)
2972 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2973 &MaskVec[0], MaskVec.size());
2974 return Mask;
2975}
2976
2977/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2978/// operation of specified width.
2979static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2980 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2981 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2982
2983 SmallVector<SDOperand, 8> MaskVec;
2984 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2985 for (unsigned i = 1; i != NumElems; ++i)
2986 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2987 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2988}
2989
2990/// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2991/// of specified width.
2992static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2993 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2994 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2995 SmallVector<SDOperand, 8> MaskVec;
2996 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2997 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2998 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2999 }
3000 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3001}
3002
3003/// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3004/// of specified width.
3005static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
3006 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3007 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3008 unsigned Half = NumElems/2;
3009 SmallVector<SDOperand, 8> MaskVec;
3010 for (unsigned i = 0; i != Half; ++i) {
3011 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3012 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3013 }
3014 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3015}
3016
3017/// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
3018///
3019static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
3020 SDOperand V1 = Op.getOperand(0);
3021 SDOperand Mask = Op.getOperand(2);
3022 MVT::ValueType VT = Op.getValueType();
3023 unsigned NumElems = Mask.getNumOperands();
3024 Mask = getUnpacklMask(NumElems, DAG);
3025 while (NumElems != 4) {
3026 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
3027 NumElems >>= 1;
3028 }
3029 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
3030
Chris Lattnere6aa3862007-11-25 00:24:49 +00003031 Mask = getZeroVector(MVT::v4i32, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003032 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
3033 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
3034 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3035}
3036
3037/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
Chris Lattnere6aa3862007-11-25 00:24:49 +00003038/// vector of zero or undef vector. This produces a shuffle where the low
3039/// element of V2 is swizzled into the zero/undef vector, landing at element
3040/// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003041static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
3042 unsigned NumElems, unsigned Idx,
3043 bool isZero, SelectionDAG &DAG) {
3044 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
3045 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3046 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
Chris Lattnere6aa3862007-11-25 00:24:49 +00003047 SmallVector<SDOperand, 16> MaskVec;
3048 for (unsigned i = 0; i != NumElems; ++i)
3049 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3050 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3051 else
3052 MaskVec.push_back(DAG.getConstant(i, EVT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003053 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3054 &MaskVec[0], MaskVec.size());
3055 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3056}
3057
3058/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3059///
3060static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
3061 unsigned NumNonZero, unsigned NumZero,
3062 SelectionDAG &DAG, TargetLowering &TLI) {
3063 if (NumNonZero > 8)
3064 return SDOperand();
3065
3066 SDOperand V(0, 0);
3067 bool First = true;
3068 for (unsigned i = 0; i < 16; ++i) {
3069 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3070 if (ThisIsNonZero && First) {
3071 if (NumZero)
3072 V = getZeroVector(MVT::v8i16, DAG);
3073 else
3074 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3075 First = false;
3076 }
3077
3078 if ((i & 1) != 0) {
3079 SDOperand ThisElt(0, 0), LastElt(0, 0);
3080 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3081 if (LastIsNonZero) {
3082 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3083 }
3084 if (ThisIsNonZero) {
3085 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3086 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3087 ThisElt, DAG.getConstant(8, MVT::i8));
3088 if (LastIsNonZero)
3089 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3090 } else
3091 ThisElt = LastElt;
3092
3093 if (ThisElt.Val)
3094 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3095 DAG.getConstant(i/2, TLI.getPointerTy()));
3096 }
3097 }
3098
3099 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3100}
3101
3102/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3103///
3104static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3105 unsigned NumNonZero, unsigned NumZero,
3106 SelectionDAG &DAG, TargetLowering &TLI) {
3107 if (NumNonZero > 4)
3108 return SDOperand();
3109
3110 SDOperand V(0, 0);
3111 bool First = true;
3112 for (unsigned i = 0; i < 8; ++i) {
3113 bool isNonZero = (NonZeros & (1 << i)) != 0;
3114 if (isNonZero) {
3115 if (First) {
3116 if (NumZero)
3117 V = getZeroVector(MVT::v8i16, DAG);
3118 else
3119 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3120 First = false;
3121 }
3122 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3123 DAG.getConstant(i, TLI.getPointerTy()));
3124 }
3125 }
3126
3127 return V;
3128}
3129
3130SDOperand
3131X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
Chris Lattnere6aa3862007-11-25 00:24:49 +00003132 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3133 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3134 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3135 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3136 // eliminated on x86-32 hosts.
3137 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3138 return Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003139
Chris Lattnere6aa3862007-11-25 00:24:49 +00003140 if (ISD::isBuildVectorAllOnes(Op.Val))
3141 return getOnesVector(Op.getValueType(), DAG);
3142 return getZeroVector(Op.getValueType(), DAG);
3143 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003144
3145 MVT::ValueType VT = Op.getValueType();
3146 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3147 unsigned EVTBits = MVT::getSizeInBits(EVT);
3148
3149 unsigned NumElems = Op.getNumOperands();
3150 unsigned NumZero = 0;
3151 unsigned NumNonZero = 0;
3152 unsigned NonZeros = 0;
Dan Gohman21463242007-07-24 22:55:08 +00003153 unsigned NumNonZeroImms = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003154 std::set<SDOperand> Values;
3155 for (unsigned i = 0; i < NumElems; ++i) {
3156 SDOperand Elt = Op.getOperand(i);
3157 if (Elt.getOpcode() != ISD::UNDEF) {
3158 Values.insert(Elt);
3159 if (isZeroNode(Elt))
3160 NumZero++;
3161 else {
3162 NonZeros |= (1 << i);
3163 NumNonZero++;
Dan Gohman21463242007-07-24 22:55:08 +00003164 if (Elt.getOpcode() == ISD::Constant ||
3165 Elt.getOpcode() == ISD::ConstantFP)
3166 NumNonZeroImms++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003167 }
3168 }
3169 }
3170
3171 if (NumNonZero == 0) {
Chris Lattnere6aa3862007-11-25 00:24:49 +00003172 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3173 return DAG.getNode(ISD::UNDEF, VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003174 }
3175
3176 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3177 if (Values.size() == 1)
3178 return SDOperand();
3179
3180 // Special case for single non-zero element.
3181 if (NumNonZero == 1) {
3182 unsigned Idx = CountTrailingZeros_32(NonZeros);
3183 SDOperand Item = Op.getOperand(Idx);
3184 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3185 if (Idx == 0)
3186 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3187 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
3188 NumZero > 0, DAG);
3189
3190 if (EVTBits == 32) {
3191 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3192 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
3193 DAG);
3194 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3195 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3196 SmallVector<SDOperand, 8> MaskVec;
3197 for (unsigned i = 0; i < NumElems; i++)
3198 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3199 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3200 &MaskVec[0], MaskVec.size());
3201 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3202 DAG.getNode(ISD::UNDEF, VT), Mask);
3203 }
3204 }
3205
Dan Gohman21463242007-07-24 22:55:08 +00003206 // A vector full of immediates; various special cases are already
3207 // handled, so this is best done with a single constant-pool load.
3208 if (NumNonZero == NumNonZeroImms)
3209 return SDOperand();
3210
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003211 // Let legalizer expand 2-wide build_vectors.
3212 if (EVTBits == 64)
3213 return SDOperand();
3214
3215 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3216 if (EVTBits == 8 && NumElems == 16) {
3217 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3218 *this);
3219 if (V.Val) return V;
3220 }
3221
3222 if (EVTBits == 16 && NumElems == 8) {
3223 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3224 *this);
3225 if (V.Val) return V;
3226 }
3227
3228 // If element VT is == 32 bits, turn it into a number of shuffles.
3229 SmallVector<SDOperand, 8> V;
3230 V.resize(NumElems);
3231 if (NumElems == 4 && NumZero > 0) {
3232 for (unsigned i = 0; i < 4; ++i) {
3233 bool isZero = !(NonZeros & (1 << i));
3234 if (isZero)
3235 V[i] = getZeroVector(VT, DAG);
3236 else
3237 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3238 }
3239
3240 for (unsigned i = 0; i < 2; ++i) {
3241 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3242 default: break;
3243 case 0:
3244 V[i] = V[i*2]; // Must be a zero vector.
3245 break;
3246 case 1:
3247 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3248 getMOVLMask(NumElems, DAG));
3249 break;
3250 case 2:
3251 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3252 getMOVLMask(NumElems, DAG));
3253 break;
3254 case 3:
3255 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3256 getUnpacklMask(NumElems, DAG));
3257 break;
3258 }
3259 }
3260
3261 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3262 // clears the upper bits.
3263 // FIXME: we can do the same for v4f32 case when we know both parts of
3264 // the lower half come from scalar_to_vector (loadf32). We should do
3265 // that in post legalizer dag combiner with target specific hooks.
3266 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3267 return V[0];
3268 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3269 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3270 SmallVector<SDOperand, 8> MaskVec;
3271 bool Reverse = (NonZeros & 0x3) == 2;
3272 for (unsigned i = 0; i < 2; ++i)
3273 if (Reverse)
3274 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3275 else
3276 MaskVec.push_back(DAG.getConstant(i, EVT));
3277 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3278 for (unsigned i = 0; i < 2; ++i)
3279 if (Reverse)
3280 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3281 else
3282 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3283 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3284 &MaskVec[0], MaskVec.size());
3285 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3286 }
3287
3288 if (Values.size() > 2) {
3289 // Expand into a number of unpckl*.
3290 // e.g. for v4f32
3291 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3292 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3293 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3294 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3295 for (unsigned i = 0; i < NumElems; ++i)
3296 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3297 NumElems >>= 1;
3298 while (NumElems != 0) {
3299 for (unsigned i = 0; i < NumElems; ++i)
3300 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3301 UnpckMask);
3302 NumElems >>= 1;
3303 }
3304 return V[0];
3305 }
3306
3307 return SDOperand();
3308}
3309
Evan Chengfca29242007-12-07 08:07:39 +00003310static
3311SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3312 SDOperand PermMask, SelectionDAG &DAG,
3313 TargetLowering &TLI) {
3314 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3315 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3316 if (isPSHUFHW_PSHUFLWMask(PermMask.Val)) {
3317 // Handle v8i16 shuffle high / low shuffle node pair.
3318 SmallVector<SDOperand, 8> MaskVec;
3319 for (unsigned i = 0; i != 4; ++i)
3320 MaskVec.push_back(PermMask.getOperand(i));
3321 for (unsigned i = 4; i != 8; ++i)
3322 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3323 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3324 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V2, Mask);
3325 MaskVec.clear();
3326 for (unsigned i = 0; i != 4; ++i)
3327 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3328 for (unsigned i = 4; i != 8; ++i)
3329 MaskVec.push_back(PermMask.getOperand(i));
3330 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3331 return DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V2, Mask);
3332 }
3333
3334 // Lower than into extracts and inserts but try to do as few as possible.
3335 // First, let's find out how many elements are already in the right order.
3336 unsigned V1InOrder = 0;
3337 unsigned V1FromV1 = 0;
3338 unsigned V2InOrder = 0;
3339 unsigned V2FromV2 = 0;
3340 SmallVector<unsigned, 8> V1Elts;
3341 SmallVector<unsigned, 8> V2Elts;
3342 for (unsigned i = 0; i < 8; ++i) {
3343 SDOperand Elt = PermMask.getOperand(i);
3344 if (Elt.getOpcode() == ISD::UNDEF) {
3345 V1Elts.push_back(i);
3346 V2Elts.push_back(i);
3347 ++V1InOrder;
3348 ++V2InOrder;
3349 } else {
3350 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3351 if (EltIdx == i) {
3352 V1Elts.push_back(i);
3353 V2Elts.push_back(i+8);
3354 ++V1InOrder;
3355 } else if (EltIdx == i+8) {
3356 V1Elts.push_back(i+8);
3357 V2Elts.push_back(i);
3358 ++V2InOrder;
3359 } else {
3360 V1Elts.push_back(EltIdx);
3361 V2Elts.push_back(EltIdx);
3362 if (EltIdx < 8)
3363 ++V1FromV1;
3364 else
3365 ++V2FromV2;
3366 }
3367 }
3368 }
3369
3370 if (V2InOrder > V1InOrder) {
3371 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3372 std::swap(V1, V2);
3373 std::swap(V1Elts, V2Elts);
3374 std::swap(V1FromV1, V2FromV2);
3375 }
3376
3377 MVT::ValueType PtrVT = TLI.getPointerTy();
3378 if (V1FromV1) {
3379 // If there are elements that are from V1 but out of place,
3380 // then first sort them in place
3381 SmallVector<SDOperand, 8> MaskVec;
3382 for (unsigned i = 0; i < 8; ++i) {
3383 unsigned EltIdx = V1Elts[i];
3384 if (EltIdx >= 8)
3385 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3386 else
3387 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3388 }
3389 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3390 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3391 }
3392
3393 // Now let's insert elements from the other vector.
3394 for (unsigned i = 0; i < 8; ++i) {
3395 unsigned EltIdx = V1Elts[i];
3396 if (EltIdx < 8)
3397 continue;
3398 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3399 DAG.getConstant(EltIdx - 8, PtrVT));
3400 V1 = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V1, ExtOp,
3401 DAG.getConstant(i, PtrVT));
3402 }
3403 return V1;
3404}
3405
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003406SDOperand
3407X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3408 SDOperand V1 = Op.getOperand(0);
3409 SDOperand V2 = Op.getOperand(1);
3410 SDOperand PermMask = Op.getOperand(2);
3411 MVT::ValueType VT = Op.getValueType();
3412 unsigned NumElems = PermMask.getNumOperands();
3413 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3414 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3415 bool V1IsSplat = false;
3416 bool V2IsSplat = false;
3417
3418 if (isUndefShuffle(Op.Val))
3419 return DAG.getNode(ISD::UNDEF, VT);
3420
3421 if (isZeroShuffle(Op.Val))
3422 return getZeroVector(VT, DAG);
3423
3424 if (isIdentityMask(PermMask.Val))
3425 return V1;
3426 else if (isIdentityMask(PermMask.Val, true))
3427 return V2;
3428
3429 if (isSplatMask(PermMask.Val)) {
3430 if (NumElems <= 4) return Op;
3431 // Promote it to a v4i32 splat.
3432 return PromoteSplat(Op, DAG);
3433 }
3434
3435 if (X86::isMOVLMask(PermMask.Val))
3436 return (V1IsUndef) ? V2 : Op;
3437
3438 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3439 X86::isMOVSLDUPMask(PermMask.Val) ||
3440 X86::isMOVHLPSMask(PermMask.Val) ||
3441 X86::isMOVHPMask(PermMask.Val) ||
3442 X86::isMOVLPMask(PermMask.Val))
3443 return Op;
3444
3445 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3446 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3447 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3448
3449 bool Commuted = false;
Chris Lattnere6aa3862007-11-25 00:24:49 +00003450 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3451 // 1,1,1,1 -> v8i16 though.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003452 V1IsSplat = isSplatVector(V1.Val);
3453 V2IsSplat = isSplatVector(V2.Val);
Chris Lattnere6aa3862007-11-25 00:24:49 +00003454
3455 // Canonicalize the splat or undef, if present, to be on the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3457 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3458 std::swap(V1IsSplat, V2IsSplat);
3459 std::swap(V1IsUndef, V2IsUndef);
3460 Commuted = true;
3461 }
3462
3463 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3464 if (V2IsUndef) return V1;
3465 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3466 if (V2IsSplat) {
3467 // V2 is a splat, so the mask may be malformed. That is, it may point
3468 // to any V2 element. The instruction selectior won't like this. Get
3469 // a corrected mask and commute to form a proper MOVS{S|D}.
3470 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3471 if (NewMask.Val != PermMask.Val)
3472 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3473 }
3474 return Op;
3475 }
3476
3477 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3478 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3479 X86::isUNPCKLMask(PermMask.Val) ||
3480 X86::isUNPCKHMask(PermMask.Val))
3481 return Op;
3482
3483 if (V2IsSplat) {
3484 // Normalize mask so all entries that point to V2 points to its first
3485 // element then try to match unpck{h|l} again. If match, return a
3486 // new vector_shuffle with the corrected mask.
3487 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3488 if (NewMask.Val != PermMask.Val) {
3489 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3490 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3491 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3492 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3493 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3494 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3495 }
3496 }
3497 }
3498
3499 // Normalize the node to match x86 shuffle ops if needed
3500 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3501 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3502
3503 if (Commuted) {
3504 // Commute is back and try unpck* again.
3505 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3506 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3507 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3508 X86::isUNPCKLMask(PermMask.Val) ||
3509 X86::isUNPCKHMask(PermMask.Val))
3510 return Op;
3511 }
3512
3513 // If VT is integer, try PSHUF* first, then SHUFP*.
3514 if (MVT::isInteger(VT)) {
Dan Gohman7dc19012007-08-02 21:17:01 +00003515 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3516 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3517 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3518 X86::isPSHUFDMask(PermMask.Val)) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003519 X86::isPSHUFHWMask(PermMask.Val) ||
3520 X86::isPSHUFLWMask(PermMask.Val)) {
3521 if (V2.getOpcode() != ISD::UNDEF)
3522 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3523 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3524 return Op;
3525 }
3526
3527 if (X86::isSHUFPMask(PermMask.Val) &&
3528 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3529 return Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003530 } else {
3531 // Floating point cases in the other order.
3532 if (X86::isSHUFPMask(PermMask.Val))
3533 return Op;
3534 if (X86::isPSHUFDMask(PermMask.Val) ||
3535 X86::isPSHUFHWMask(PermMask.Val) ||
3536 X86::isPSHUFLWMask(PermMask.Val)) {
3537 if (V2.getOpcode() != ISD::UNDEF)
3538 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3539 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3540 return Op;
3541 }
3542 }
3543
Evan Chengfca29242007-12-07 08:07:39 +00003544 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3545 if (VT == MVT::v8i16)
3546 return LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3547
3548 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3549 // Don't do this for MMX.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003550 MVT::ValueType MaskVT = PermMask.getValueType();
3551 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3552 SmallVector<std::pair<int, int>, 8> Locs;
3553 Locs.reserve(NumElems);
3554 SmallVector<SDOperand, 8> Mask1(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3555 SmallVector<SDOperand, 8> Mask2(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3556 unsigned NumHi = 0;
3557 unsigned NumLo = 0;
3558 // If no more than two elements come from either vector. This can be
3559 // implemented with two shuffles. First shuffle gather the elements.
3560 // The second shuffle, which takes the first shuffle as both of its
3561 // vector operands, put the elements into the right order.
3562 for (unsigned i = 0; i != NumElems; ++i) {
3563 SDOperand Elt = PermMask.getOperand(i);
3564 if (Elt.getOpcode() == ISD::UNDEF) {
3565 Locs[i] = std::make_pair(-1, -1);
3566 } else {
3567 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3568 if (Val < NumElems) {
3569 Locs[i] = std::make_pair(0, NumLo);
3570 Mask1[NumLo] = Elt;
3571 NumLo++;
3572 } else {
3573 Locs[i] = std::make_pair(1, NumHi);
3574 if (2+NumHi < NumElems)
3575 Mask1[2+NumHi] = Elt;
3576 NumHi++;
3577 }
3578 }
3579 }
3580 if (NumLo <= 2 && NumHi <= 2) {
3581 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3582 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3583 &Mask1[0], Mask1.size()));
3584 for (unsigned i = 0; i != NumElems; ++i) {
3585 if (Locs[i].first == -1)
3586 continue;
3587 else {
3588 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3589 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3590 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3591 }
3592 }
3593
3594 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3595 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3596 &Mask2[0], Mask2.size()));
3597 }
3598
3599 // Break it into (shuffle shuffle_hi, shuffle_lo).
3600 Locs.clear();
3601 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3602 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3603 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3604 unsigned MaskIdx = 0;
3605 unsigned LoIdx = 0;
3606 unsigned HiIdx = NumElems/2;
3607 for (unsigned i = 0; i != NumElems; ++i) {
3608 if (i == NumElems/2) {
3609 MaskPtr = &HiMask;
3610 MaskIdx = 1;
3611 LoIdx = 0;
3612 HiIdx = NumElems/2;
3613 }
3614 SDOperand Elt = PermMask.getOperand(i);
3615 if (Elt.getOpcode() == ISD::UNDEF) {
3616 Locs[i] = std::make_pair(-1, -1);
3617 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3618 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3619 (*MaskPtr)[LoIdx] = Elt;
3620 LoIdx++;
3621 } else {
3622 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3623 (*MaskPtr)[HiIdx] = Elt;
3624 HiIdx++;
3625 }
3626 }
3627
3628 SDOperand LoShuffle =
3629 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3630 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3631 &LoMask[0], LoMask.size()));
3632 SDOperand HiShuffle =
3633 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3634 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3635 &HiMask[0], HiMask.size()));
3636 SmallVector<SDOperand, 8> MaskOps;
3637 for (unsigned i = 0; i != NumElems; ++i) {
3638 if (Locs[i].first == -1) {
3639 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3640 } else {
3641 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3642 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3643 }
3644 }
3645 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3646 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3647 &MaskOps[0], MaskOps.size()));
3648 }
3649
3650 return SDOperand();
3651}
3652
3653SDOperand
3654X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3655 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3656 return SDOperand();
3657
3658 MVT::ValueType VT = Op.getValueType();
3659 // TODO: handle v16i8.
3660 if (MVT::getSizeInBits(VT) == 16) {
3661 // Transform it so it match pextrw which produces a 32-bit result.
3662 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3663 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3664 Op.getOperand(0), Op.getOperand(1));
3665 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3666 DAG.getValueType(VT));
3667 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3668 } else if (MVT::getSizeInBits(VT) == 32) {
3669 SDOperand Vec = Op.getOperand(0);
3670 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3671 if (Idx == 0)
3672 return Op;
3673 // SHUFPS the element to the lowest double word, then movss.
3674 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3675 SmallVector<SDOperand, 8> IdxVec;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00003676 IdxVec.
3677 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3678 IdxVec.
3679 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3680 IdxVec.
3681 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3682 IdxVec.
3683 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003684 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3685 &IdxVec[0], IdxVec.size());
3686 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3687 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3688 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3689 DAG.getConstant(0, getPointerTy()));
3690 } else if (MVT::getSizeInBits(VT) == 64) {
3691 SDOperand Vec = Op.getOperand(0);
3692 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3693 if (Idx == 0)
3694 return Op;
3695
3696 // UNPCKHPD the element to the lowest double word, then movsd.
3697 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3698 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3699 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3700 SmallVector<SDOperand, 8> IdxVec;
3701 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00003702 IdxVec.
3703 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003704 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3705 &IdxVec[0], IdxVec.size());
3706 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3707 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3708 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3709 DAG.getConstant(0, getPointerTy()));
3710 }
3711
3712 return SDOperand();
3713}
3714
3715SDOperand
3716X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3717 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3718 // as its second argument.
3719 MVT::ValueType VT = Op.getValueType();
3720 MVT::ValueType BaseVT = MVT::getVectorElementType(VT);
3721 SDOperand N0 = Op.getOperand(0);
3722 SDOperand N1 = Op.getOperand(1);
3723 SDOperand N2 = Op.getOperand(2);
3724 if (MVT::getSizeInBits(BaseVT) == 16) {
3725 if (N1.getValueType() != MVT::i32)
3726 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3727 if (N2.getValueType() != MVT::i32)
3728 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
3729 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3730 } else if (MVT::getSizeInBits(BaseVT) == 32) {
3731 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
3732 if (Idx == 0) {
3733 // Use a movss.
3734 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
3735 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3736 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3737 SmallVector<SDOperand, 8> MaskVec;
3738 MaskVec.push_back(DAG.getConstant(4, BaseVT));
3739 for (unsigned i = 1; i <= 3; ++i)
3740 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3741 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
3742 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3743 &MaskVec[0], MaskVec.size()));
3744 } else {
3745 // Use two pinsrw instructions to insert a 32 bit value.
3746 Idx <<= 1;
3747 if (MVT::isFloatingPoint(N1.getValueType())) {
Evan Cheng1eea6752007-07-31 06:21:44 +00003748 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
3749 N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
3750 N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
3751 DAG.getConstant(0, getPointerTy()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003752 }
3753 N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
3754 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3755 DAG.getConstant(Idx, getPointerTy()));
3756 N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
3757 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3758 DAG.getConstant(Idx+1, getPointerTy()));
3759 return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3760 }
3761 }
3762
3763 return SDOperand();
3764}
3765
3766SDOperand
3767X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3768 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3769 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3770}
3771
3772// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3773// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3774// one of the above mentioned nodes. It has to be wrapped because otherwise
3775// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3776// be used to form addressing mode. These wrapped nodes will be selected
3777// into MOV32ri.
3778SDOperand
3779X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3780 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3781 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3782 getPointerTy(),
3783 CP->getAlignment());
3784 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3785 // With PIC, the address is actually $g + Offset.
3786 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3787 !Subtarget->isPICStyleRIPRel()) {
3788 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3789 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3790 Result);
3791 }
3792
3793 return Result;
3794}
3795
3796SDOperand
3797X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3798 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3799 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3800 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3801 // With PIC, the address is actually $g + Offset.
3802 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3803 !Subtarget->isPICStyleRIPRel()) {
3804 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3805 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3806 Result);
3807 }
3808
3809 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3810 // load the value at address GV, not the value of GV itself. This means that
3811 // the GlobalAddress must be in the base or index register of the address, not
3812 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3813 // The same applies for external symbols during PIC codegen
3814 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3815 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
3816
3817 return Result;
3818}
3819
3820// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3821static SDOperand
3822LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3823 const MVT::ValueType PtrVT) {
3824 SDOperand InFlag;
3825 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3826 DAG.getNode(X86ISD::GlobalBaseReg,
3827 PtrVT), InFlag);
3828 InFlag = Chain.getValue(1);
3829
3830 // emit leal symbol@TLSGD(,%ebx,1), %eax
3831 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3832 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3833 GA->getValueType(0),
3834 GA->getOffset());
3835 SDOperand Ops[] = { Chain, TGA, InFlag };
3836 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3837 InFlag = Result.getValue(2);
3838 Chain = Result.getValue(1);
3839
3840 // call ___tls_get_addr. This function receives its argument in
3841 // the register EAX.
3842 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3843 InFlag = Chain.getValue(1);
3844
3845 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3846 SDOperand Ops1[] = { Chain,
3847 DAG.getTargetExternalSymbol("___tls_get_addr",
3848 PtrVT),
3849 DAG.getRegister(X86::EAX, PtrVT),
3850 DAG.getRegister(X86::EBX, PtrVT),
3851 InFlag };
3852 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3853 InFlag = Chain.getValue(1);
3854
3855 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3856}
3857
3858// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3859// "local exec" model.
3860static SDOperand
3861LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3862 const MVT::ValueType PtrVT) {
3863 // Get the Thread Pointer
3864 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3865 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3866 // exec)
3867 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3868 GA->getValueType(0),
3869 GA->getOffset());
3870 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3871
3872 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3873 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
3874
3875 // The address of the thread local variable is the add of the thread
3876 // pointer with the offset of the variable.
3877 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3878}
3879
3880SDOperand
3881X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3882 // TODO: implement the "local dynamic" model
3883 // TODO: implement the "initial exec"model for pic executables
3884 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3885 "TLS not implemented for non-ELF and 64-bit targets");
3886 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3887 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3888 // otherwise use the "Local Exec"TLS Model
3889 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3890 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3891 else
3892 return LowerToTLSExecModel(GA, DAG, getPointerTy());
3893}
3894
3895SDOperand
3896X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3897 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3898 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3899 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3900 // With PIC, the address is actually $g + Offset.
3901 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3902 !Subtarget->isPICStyleRIPRel()) {
3903 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3904 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3905 Result);
3906 }
3907
3908 return Result;
3909}
3910
3911SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3912 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3913 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3914 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3915 // With PIC, the address is actually $g + Offset.
3916 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3917 !Subtarget->isPICStyleRIPRel()) {
3918 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3919 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3920 Result);
3921 }
3922
3923 return Result;
3924}
3925
Chris Lattner62814a32007-10-17 06:02:13 +00003926/// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
3927/// take a 2 x i32 value to shift plus a shift amount.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003928SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner62814a32007-10-17 06:02:13 +00003929 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
3930 "Not an i64 shift!");
3931 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
3932 SDOperand ShOpLo = Op.getOperand(0);
3933 SDOperand ShOpHi = Op.getOperand(1);
3934 SDOperand ShAmt = Op.getOperand(2);
3935 SDOperand Tmp1 = isSRA ?
3936 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
3937 DAG.getConstant(0, MVT::i32);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003938
Chris Lattner62814a32007-10-17 06:02:13 +00003939 SDOperand Tmp2, Tmp3;
3940 if (Op.getOpcode() == ISD::SHL_PARTS) {
3941 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
3942 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
3943 } else {
3944 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
3945 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
3946 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003947
Chris Lattner62814a32007-10-17 06:02:13 +00003948 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3949 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
3950 DAG.getConstant(32, MVT::i8));
3951 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
3952 AndNode, DAG.getConstant(0, MVT::i8));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003953
Chris Lattner62814a32007-10-17 06:02:13 +00003954 SDOperand Hi, Lo;
3955 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3956 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
3957 SmallVector<SDOperand, 4> Ops;
3958 if (Op.getOpcode() == ISD::SHL_PARTS) {
3959 Ops.push_back(Tmp2);
3960 Ops.push_back(Tmp3);
3961 Ops.push_back(CC);
3962 Ops.push_back(Cond);
3963 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003964
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003965 Ops.clear();
Chris Lattner62814a32007-10-17 06:02:13 +00003966 Ops.push_back(Tmp3);
3967 Ops.push_back(Tmp1);
3968 Ops.push_back(CC);
3969 Ops.push_back(Cond);
3970 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3971 } else {
3972 Ops.push_back(Tmp2);
3973 Ops.push_back(Tmp3);
3974 Ops.push_back(CC);
3975 Ops.push_back(Cond);
3976 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3977
3978 Ops.clear();
3979 Ops.push_back(Tmp3);
3980 Ops.push_back(Tmp1);
3981 Ops.push_back(CC);
3982 Ops.push_back(Cond);
3983 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3984 }
3985
3986 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
3987 Ops.clear();
3988 Ops.push_back(Lo);
3989 Ops.push_back(Hi);
3990 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003991}
3992
3993SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
3994 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
3995 Op.getOperand(0).getValueType() >= MVT::i16 &&
3996 "Unknown SINT_TO_FP to lower!");
3997
3998 SDOperand Result;
3999 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4000 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4001 MachineFunction &MF = DAG.getMachineFunction();
4002 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4003 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4004 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4005 StackSlot, NULL, 0);
4006
Dale Johannesen2fc20782007-09-14 22:26:36 +00004007 // These are really Legal; caller falls through into that case.
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004008 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f32 && X86ScalarSSEf32)
4009 return Result;
4010 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f64 && X86ScalarSSEf64)
Dale Johannesen2fc20782007-09-14 22:26:36 +00004011 return Result;
Dale Johannesen958b08b2007-09-19 23:55:34 +00004012 if (SrcVT==MVT::i64 && Op.getValueType() != MVT::f80 &&
4013 Subtarget->is64Bit())
4014 return Result;
Dale Johannesen2fc20782007-09-14 22:26:36 +00004015
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004016 // Build the FILD
4017 SDVTList Tys;
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004018 bool useSSE = (X86ScalarSSEf32 && Op.getValueType() == MVT::f32) ||
4019 (X86ScalarSSEf64 && Op.getValueType() == MVT::f64);
Dale Johannesen2fc20782007-09-14 22:26:36 +00004020 if (useSSE)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004021 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4022 else
4023 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4024 SmallVector<SDOperand, 8> Ops;
4025 Ops.push_back(Chain);
4026 Ops.push_back(StackSlot);
4027 Ops.push_back(DAG.getValueType(SrcVT));
Dale Johannesen2fc20782007-09-14 22:26:36 +00004028 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004029 Tys, &Ops[0], Ops.size());
4030
Dale Johannesen2fc20782007-09-14 22:26:36 +00004031 if (useSSE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004032 Chain = Result.getValue(1);
4033 SDOperand InFlag = Result.getValue(2);
4034
4035 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4036 // shouldn't be necessary except that RFP cannot be live across
4037 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4038 MachineFunction &MF = DAG.getMachineFunction();
4039 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4040 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4041 Tys = DAG.getVTList(MVT::Other);
4042 SmallVector<SDOperand, 8> Ops;
4043 Ops.push_back(Chain);
4044 Ops.push_back(Result);
4045 Ops.push_back(StackSlot);
4046 Ops.push_back(DAG.getValueType(Op.getValueType()));
4047 Ops.push_back(InFlag);
4048 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4049 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
4050 }
4051
4052 return Result;
4053}
4054
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004055std::pair<SDOperand,SDOperand> X86TargetLowering::
4056FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004057 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4058 "Unknown FP_TO_SINT to lower!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004059
Dale Johannesen2fc20782007-09-14 22:26:36 +00004060 // These are really Legal.
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004061 if (Op.getValueType() == MVT::i32 &&
4062 X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32)
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004063 return std::make_pair(SDOperand(), SDOperand());
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004064 if (Op.getValueType() == MVT::i32 &&
4065 X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004066 return std::make_pair(SDOperand(), SDOperand());
Dale Johannesen958b08b2007-09-19 23:55:34 +00004067 if (Subtarget->is64Bit() &&
4068 Op.getValueType() == MVT::i64 &&
4069 Op.getOperand(0).getValueType() != MVT::f80)
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004070 return std::make_pair(SDOperand(), SDOperand());
Dale Johannesen2fc20782007-09-14 22:26:36 +00004071
Evan Cheng05441e62007-10-15 20:11:21 +00004072 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4073 // stack slot.
4074 MachineFunction &MF = DAG.getMachineFunction();
4075 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4076 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4077 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004078 unsigned Opc;
4079 switch (Op.getValueType()) {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004080 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4081 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4082 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4083 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004084 }
4085
4086 SDOperand Chain = DAG.getEntryNode();
4087 SDOperand Value = Op.getOperand(0);
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004088 if ((X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32) ||
4089 (X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004090 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4091 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
4092 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4093 SDOperand Ops[] = {
4094 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4095 };
4096 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4097 Chain = Value.getValue(1);
4098 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4099 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4100 }
4101
4102 // Build the FP_TO_INT*_IN_MEM
4103 SDOperand Ops[] = { Chain, Value, StackSlot };
4104 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4105
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004106 return std::make_pair(FIST, StackSlot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004107}
4108
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004109SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004110 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4111 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4112 if (FIST.Val == 0) return SDOperand();
4113
4114 // Load the result.
4115 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4116}
4117
4118SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4119 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4120 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4121 if (FIST.Val == 0) return 0;
4122
4123 // Return an i64 load from the stack slot.
4124 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4125
4126 // Use a MERGE_VALUES node to drop the chain result value.
4127 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4128}
4129
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004130SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4131 MVT::ValueType VT = Op.getValueType();
4132 MVT::ValueType EltVT = VT;
4133 if (MVT::isVector(VT))
4134 EltVT = MVT::getVectorElementType(VT);
4135 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4136 std::vector<Constant*> CV;
4137 if (EltVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004138 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004139 CV.push_back(C);
4140 CV.push_back(C);
4141 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004142 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004143 CV.push_back(C);
4144 CV.push_back(C);
4145 CV.push_back(C);
4146 CV.push_back(C);
4147 }
Dan Gohman11821702007-07-27 17:16:43 +00004148 Constant *C = ConstantVector::get(CV);
4149 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4150 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4151 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004152 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4153}
4154
4155SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4156 MVT::ValueType VT = Op.getValueType();
4157 MVT::ValueType EltVT = VT;
Evan Cheng92b8f782007-07-19 23:36:01 +00004158 unsigned EltNum = 1;
4159 if (MVT::isVector(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004160 EltVT = MVT::getVectorElementType(VT);
Evan Cheng92b8f782007-07-19 23:36:01 +00004161 EltNum = MVT::getVectorNumElements(VT);
4162 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004163 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4164 std::vector<Constant*> CV;
4165 if (EltVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004166 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004167 CV.push_back(C);
4168 CV.push_back(C);
4169 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004170 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004171 CV.push_back(C);
4172 CV.push_back(C);
4173 CV.push_back(C);
4174 CV.push_back(C);
4175 }
Dan Gohman11821702007-07-27 17:16:43 +00004176 Constant *C = ConstantVector::get(CV);
4177 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4178 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4179 false, 16);
Evan Cheng92b8f782007-07-19 23:36:01 +00004180 if (MVT::isVector(VT)) {
Evan Cheng92b8f782007-07-19 23:36:01 +00004181 return DAG.getNode(ISD::BIT_CONVERT, VT,
4182 DAG.getNode(ISD::XOR, MVT::v2i64,
4183 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4184 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4185 } else {
Evan Cheng92b8f782007-07-19 23:36:01 +00004186 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4187 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004188}
4189
4190SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4191 SDOperand Op0 = Op.getOperand(0);
4192 SDOperand Op1 = Op.getOperand(1);
4193 MVT::ValueType VT = Op.getValueType();
4194 MVT::ValueType SrcVT = Op1.getValueType();
4195 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4196
4197 // If second operand is smaller, extend it first.
4198 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4199 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4200 SrcVT = VT;
Dale Johannesenb9de9f02007-09-06 18:13:44 +00004201 SrcTy = MVT::getTypeForValueType(SrcVT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004202 }
Dale Johannesenfb0fa912007-10-21 01:07:44 +00004203 // And if it is bigger, shrink it first.
4204 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4205 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1);
4206 SrcVT = VT;
4207 SrcTy = MVT::getTypeForValueType(SrcVT);
4208 }
4209
4210 // At this point the operands and the result should have the same
4211 // type, and that won't be f80 since that is not custom lowered.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004212
4213 // First get the sign bit of second operand.
4214 std::vector<Constant*> CV;
4215 if (SrcVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004216 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4217 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004218 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004219 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4220 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4221 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4222 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004223 }
Dan Gohman11821702007-07-27 17:16:43 +00004224 Constant *C = ConstantVector::get(CV);
4225 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4226 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx, NULL, 0,
4227 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004228 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4229
4230 // Shift sign bit right or left if the two operands have different types.
4231 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4232 // Op0 is MVT::f32, Op1 is MVT::f64.
4233 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4234 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4235 DAG.getConstant(32, MVT::i32));
4236 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4237 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4238 DAG.getConstant(0, getPointerTy()));
4239 }
4240
4241 // Clear first operand sign bit.
4242 CV.clear();
4243 if (VT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004244 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4245 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004246 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004247 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4248 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4249 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4250 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004251 }
Dan Gohman11821702007-07-27 17:16:43 +00004252 C = ConstantVector::get(CV);
4253 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4254 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4255 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004256 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4257
4258 // Or the value with the sign bit.
4259 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4260}
4261
Evan Cheng621216e2007-09-29 00:00:36 +00004262SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
Evan Cheng950aac02007-09-25 01:57:46 +00004263 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
Evan Cheng6afec3d2007-09-26 00:45:55 +00004264 SDOperand Cond;
Evan Cheng950aac02007-09-25 01:57:46 +00004265 SDOperand Op0 = Op.getOperand(0);
4266 SDOperand Op1 = Op.getOperand(1);
4267 SDOperand CC = Op.getOperand(2);
4268 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4269 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4270 unsigned X86CC;
4271
Evan Cheng950aac02007-09-25 01:57:46 +00004272 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
Evan Cheng6afec3d2007-09-26 00:45:55 +00004273 Op0, Op1, DAG)) {
Evan Cheng621216e2007-09-29 00:00:36 +00004274 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4275 return DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004276 DAG.getConstant(X86CC, MVT::i8), Cond);
Evan Cheng6afec3d2007-09-26 00:45:55 +00004277 }
Evan Cheng950aac02007-09-25 01:57:46 +00004278
4279 assert(isFP && "Illegal integer SetCC!");
4280
Evan Cheng621216e2007-09-29 00:00:36 +00004281 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
Evan Cheng950aac02007-09-25 01:57:46 +00004282 switch (SetCCOpcode) {
4283 default: assert(false && "Illegal floating point SetCC!");
4284 case ISD::SETOEQ: { // !PF & ZF
Evan Cheng621216e2007-09-29 00:00:36 +00004285 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004286 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004287 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004288 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4289 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4290 }
4291 case ISD::SETUNE: { // PF | !ZF
Evan Cheng621216e2007-09-29 00:00:36 +00004292 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004293 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004294 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004295 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4296 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4297 }
4298 }
4299}
4300
4301
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004302SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4303 bool addTest = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004304 SDOperand Cond = Op.getOperand(0);
4305 SDOperand CC;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004306
4307 if (Cond.getOpcode() == ISD::SETCC)
Evan Cheng621216e2007-09-29 00:00:36 +00004308 Cond = LowerSETCC(Cond, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004309
Evan Cheng50d37ab2007-10-08 22:16:29 +00004310 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4311 // setting operand in place of the X86ISD::SETCC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004312 if (Cond.getOpcode() == X86ISD::SETCC) {
4313 CC = Cond.getOperand(0);
4314
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004315 SDOperand Cmp = Cond.getOperand(1);
4316 unsigned Opc = Cmp.getOpcode();
Evan Cheng50d37ab2007-10-08 22:16:29 +00004317 MVT::ValueType VT = Op.getValueType();
4318 bool IllegalFPCMov = false;
4319 if (VT == MVT::f32 && !X86ScalarSSEf32)
4320 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4321 else if (VT == MVT::f64 && !X86ScalarSSEf64)
4322 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
Dale Johannesen3b955db2007-10-16 18:09:08 +00004323 else if (VT == MVT::f80)
4324 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
Evan Cheng621216e2007-09-29 00:00:36 +00004325 if ((Opc == X86ISD::CMP ||
4326 Opc == X86ISD::COMI ||
4327 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
Evan Cheng50d37ab2007-10-08 22:16:29 +00004328 Cond = Cmp;
Evan Cheng950aac02007-09-25 01:57:46 +00004329 addTest = false;
4330 }
4331 }
4332
4333 if (addTest) {
4334 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
Evan Cheng50d37ab2007-10-08 22:16:29 +00004335 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
Evan Cheng950aac02007-09-25 01:57:46 +00004336 }
4337
4338 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4339 MVT::Flag);
4340 SmallVector<SDOperand, 4> Ops;
4341 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4342 // condition is true.
4343 Ops.push_back(Op.getOperand(2));
4344 Ops.push_back(Op.getOperand(1));
4345 Ops.push_back(CC);
4346 Ops.push_back(Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004347 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
Evan Cheng950aac02007-09-25 01:57:46 +00004348}
4349
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004350SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4351 bool addTest = true;
4352 SDOperand Chain = Op.getOperand(0);
4353 SDOperand Cond = Op.getOperand(1);
4354 SDOperand Dest = Op.getOperand(2);
4355 SDOperand CC;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004356
4357 if (Cond.getOpcode() == ISD::SETCC)
Evan Cheng621216e2007-09-29 00:00:36 +00004358 Cond = LowerSETCC(Cond, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004359
Evan Cheng50d37ab2007-10-08 22:16:29 +00004360 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4361 // setting operand in place of the X86ISD::SETCC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004362 if (Cond.getOpcode() == X86ISD::SETCC) {
4363 CC = Cond.getOperand(0);
4364
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004365 SDOperand Cmp = Cond.getOperand(1);
4366 unsigned Opc = Cmp.getOpcode();
Evan Cheng621216e2007-09-29 00:00:36 +00004367 if (Opc == X86ISD::CMP ||
4368 Opc == X86ISD::COMI ||
4369 Opc == X86ISD::UCOMI) {
Evan Cheng50d37ab2007-10-08 22:16:29 +00004370 Cond = Cmp;
Evan Cheng950aac02007-09-25 01:57:46 +00004371 addTest = false;
4372 }
4373 }
4374
4375 if (addTest) {
4376 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
Evan Cheng621216e2007-09-29 00:00:36 +00004377 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
Evan Cheng950aac02007-09-25 01:57:46 +00004378 }
Evan Cheng621216e2007-09-29 00:00:36 +00004379 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
Evan Cheng950aac02007-09-25 01:57:46 +00004380 Chain, Op.getOperand(2), CC, Cond);
4381}
4382
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004383SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004384 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4385 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004386
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004387 if (Subtarget->is64Bit())
4388 if(CallingConv==CallingConv::Fast && isTailCall && PerformTailCallOpt)
4389 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4390 else
4391 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004392 else
4393 switch (CallingConv) {
4394 default:
4395 assert(0 && "Unsupported calling convention");
4396 case CallingConv::Fast:
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004397 if (isTailCall && PerformTailCallOpt)
4398 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4399 else
4400 return LowerCCCCallTo(Op,DAG, CallingConv);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004401 case CallingConv::C:
4402 case CallingConv::X86_StdCall:
4403 return LowerCCCCallTo(Op, DAG, CallingConv);
4404 case CallingConv::X86_FastCall:
4405 return LowerFastCCCallTo(Op, DAG, CallingConv);
4406 }
4407}
4408
4409
4410// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4411// Calls to _alloca is needed to probe the stack when allocating more than 4k
4412// bytes in one go. Touching the stack at 4K increments is necessary to ensure
4413// that the guard pages used by the OS virtual memory manager are allocated in
4414// correct sequence.
4415SDOperand
4416X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4417 SelectionDAG &DAG) {
4418 assert(Subtarget->isTargetCygMing() &&
4419 "This should be used only on Cygwin/Mingw targets");
4420
4421 // Get the inputs.
4422 SDOperand Chain = Op.getOperand(0);
4423 SDOperand Size = Op.getOperand(1);
4424 // FIXME: Ensure alignment here
4425
4426 SDOperand Flag;
4427
4428 MVT::ValueType IntPtr = getPointerTy();
4429 MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
4430
4431 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4432 Flag = Chain.getValue(1);
4433
4434 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4435 SDOperand Ops[] = { Chain,
4436 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4437 DAG.getRegister(X86::EAX, IntPtr),
4438 Flag };
4439 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4440 Flag = Chain.getValue(1);
4441
4442 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4443
4444 std::vector<MVT::ValueType> Tys;
4445 Tys.push_back(SPTy);
4446 Tys.push_back(MVT::Other);
4447 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4448 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4449}
4450
4451SDOperand
4452X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
4453 MachineFunction &MF = DAG.getMachineFunction();
4454 const Function* Fn = MF.getFunction();
4455 if (Fn->hasExternalLinkage() &&
4456 Subtarget->isTargetCygMing() &&
4457 Fn->getName() == "main")
4458 MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
4459
4460 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4461 if (Subtarget->is64Bit())
4462 return LowerX86_64CCCArguments(Op, DAG);
4463 else
4464 switch(CC) {
4465 default:
4466 assert(0 && "Unsupported calling convention");
4467 case CallingConv::Fast:
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004468 return LowerCCCArguments(Op,DAG, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004469 // Falls through
4470 case CallingConv::C:
4471 return LowerCCCArguments(Op, DAG);
4472 case CallingConv::X86_StdCall:
4473 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
4474 return LowerCCCArguments(Op, DAG, true);
4475 case CallingConv::X86_FastCall:
4476 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
4477 return LowerFastCCArguments(Op, DAG);
4478 }
4479}
4480
4481SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4482 SDOperand InFlag(0, 0);
4483 SDOperand Chain = Op.getOperand(0);
4484 unsigned Align =
4485 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4486 if (Align == 0) Align = 1;
4487
4488 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
Rafael Espindola5d3e7622007-08-27 10:18:20 +00004489 // If not DWORD aligned or size is more than the threshold, call memset.
Rafael Espindolab2e7a6b2007-08-27 17:48:26 +00004490 // The libc version is likely to be faster for these cases. It can use the
4491 // address value and run time information about the CPU.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004492 if ((Align & 3) != 0 ||
Rafael Espindola7afa9b12007-10-31 11:52:06 +00004493 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004494 MVT::ValueType IntPtr = getPointerTy();
4495 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4496 TargetLowering::ArgListTy Args;
4497 TargetLowering::ArgListEntry Entry;
4498 Entry.Node = Op.getOperand(1);
4499 Entry.Ty = IntPtrTy;
4500 Args.push_back(Entry);
4501 // Extend the unsigned i8 argument to be an int value for the call.
4502 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4503 Entry.Ty = IntPtrTy;
4504 Args.push_back(Entry);
4505 Entry.Node = Op.getOperand(3);
4506 Args.push_back(Entry);
4507 std::pair<SDOperand,SDOperand> CallResult =
4508 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4509 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4510 return CallResult.second;
4511 }
4512
4513 MVT::ValueType AVT;
4514 SDOperand Count;
4515 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4516 unsigned BytesLeft = 0;
4517 bool TwoRepStos = false;
4518 if (ValC) {
4519 unsigned ValReg;
4520 uint64_t Val = ValC->getValue() & 255;
4521
4522 // If the value is a constant, then we can potentially use larger sets.
4523 switch (Align & 3) {
4524 case 2: // WORD aligned
4525 AVT = MVT::i16;
4526 ValReg = X86::AX;
4527 Val = (Val << 8) | Val;
4528 break;
4529 case 0: // DWORD aligned
4530 AVT = MVT::i32;
4531 ValReg = X86::EAX;
4532 Val = (Val << 8) | Val;
4533 Val = (Val << 16) | Val;
4534 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4535 AVT = MVT::i64;
4536 ValReg = X86::RAX;
4537 Val = (Val << 32) | Val;
4538 }
4539 break;
4540 default: // Byte aligned
4541 AVT = MVT::i8;
4542 ValReg = X86::AL;
4543 Count = Op.getOperand(3);
4544 break;
4545 }
4546
4547 if (AVT > MVT::i8) {
4548 if (I) {
4549 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4550 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
4551 BytesLeft = I->getValue() % UBytes;
4552 } else {
4553 assert(AVT >= MVT::i32 &&
4554 "Do not use rep;stos if not at least DWORD aligned");
4555 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4556 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4557 TwoRepStos = true;
4558 }
4559 }
4560
4561 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4562 InFlag);
4563 InFlag = Chain.getValue(1);
4564 } else {
4565 AVT = MVT::i8;
4566 Count = Op.getOperand(3);
4567 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4568 InFlag = Chain.getValue(1);
4569 }
4570
4571 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4572 Count, InFlag);
4573 InFlag = Chain.getValue(1);
4574 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4575 Op.getOperand(1), InFlag);
4576 InFlag = Chain.getValue(1);
4577
4578 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4579 SmallVector<SDOperand, 8> Ops;
4580 Ops.push_back(Chain);
4581 Ops.push_back(DAG.getValueType(AVT));
4582 Ops.push_back(InFlag);
4583 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4584
4585 if (TwoRepStos) {
4586 InFlag = Chain.getValue(1);
4587 Count = Op.getOperand(3);
4588 MVT::ValueType CVT = Count.getValueType();
4589 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4590 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4591 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4592 Left, InFlag);
4593 InFlag = Chain.getValue(1);
4594 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4595 Ops.clear();
4596 Ops.push_back(Chain);
4597 Ops.push_back(DAG.getValueType(MVT::i8));
4598 Ops.push_back(InFlag);
4599 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4600 } else if (BytesLeft) {
4601 // Issue stores for the last 1 - 7 bytes.
4602 SDOperand Value;
4603 unsigned Val = ValC->getValue() & 255;
4604 unsigned Offset = I->getValue() - BytesLeft;
4605 SDOperand DstAddr = Op.getOperand(1);
4606 MVT::ValueType AddrVT = DstAddr.getValueType();
4607 if (BytesLeft >= 4) {
4608 Val = (Val << 8) | Val;
4609 Val = (Val << 16) | Val;
4610 Value = DAG.getConstant(Val, MVT::i32);
4611 Chain = DAG.getStore(Chain, Value,
4612 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4613 DAG.getConstant(Offset, AddrVT)),
4614 NULL, 0);
4615 BytesLeft -= 4;
4616 Offset += 4;
4617 }
4618 if (BytesLeft >= 2) {
4619 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4620 Chain = DAG.getStore(Chain, Value,
4621 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4622 DAG.getConstant(Offset, AddrVT)),
4623 NULL, 0);
4624 BytesLeft -= 2;
4625 Offset += 2;
4626 }
4627 if (BytesLeft == 1) {
4628 Value = DAG.getConstant(Val, MVT::i8);
4629 Chain = DAG.getStore(Chain, Value,
4630 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4631 DAG.getConstant(Offset, AddrVT)),
4632 NULL, 0);
4633 }
4634 }
4635
4636 return Chain;
4637}
4638
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004639SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4640 SDOperand Dest,
4641 SDOperand Source,
4642 unsigned Size,
4643 unsigned Align,
4644 SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004645 MVT::ValueType AVT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004646 unsigned BytesLeft = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004647 switch (Align & 3) {
4648 case 2: // WORD aligned
4649 AVT = MVT::i16;
4650 break;
4651 case 0: // DWORD aligned
4652 AVT = MVT::i32;
4653 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4654 AVT = MVT::i64;
4655 break;
4656 default: // Byte aligned
4657 AVT = MVT::i8;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004658 break;
4659 }
4660
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004661 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4662 SDOperand Count = DAG.getConstant(Size / UBytes, getPointerTy());
4663 BytesLeft = Size % UBytes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004664
4665 SDOperand InFlag(0, 0);
4666 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4667 Count, InFlag);
4668 InFlag = Chain.getValue(1);
4669 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004670 Dest, InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004671 InFlag = Chain.getValue(1);
4672 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004673 Source, InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004674 InFlag = Chain.getValue(1);
4675
4676 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4677 SmallVector<SDOperand, 8> Ops;
4678 Ops.push_back(Chain);
4679 Ops.push_back(DAG.getValueType(AVT));
4680 Ops.push_back(InFlag);
4681 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4682
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004683 if (BytesLeft) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004684 // Issue loads and stores for the last 1 - 7 bytes.
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004685 unsigned Offset = Size - BytesLeft;
4686 SDOperand DstAddr = Dest;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004687 MVT::ValueType DstVT = DstAddr.getValueType();
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004688 SDOperand SrcAddr = Source;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004689 MVT::ValueType SrcVT = SrcAddr.getValueType();
4690 SDOperand Value;
4691 if (BytesLeft >= 4) {
4692 Value = DAG.getLoad(MVT::i32, Chain,
4693 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4694 DAG.getConstant(Offset, SrcVT)),
4695 NULL, 0);
4696 Chain = Value.getValue(1);
4697 Chain = DAG.getStore(Chain, Value,
4698 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4699 DAG.getConstant(Offset, DstVT)),
4700 NULL, 0);
4701 BytesLeft -= 4;
4702 Offset += 4;
4703 }
4704 if (BytesLeft >= 2) {
4705 Value = DAG.getLoad(MVT::i16, Chain,
4706 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4707 DAG.getConstant(Offset, SrcVT)),
4708 NULL, 0);
4709 Chain = Value.getValue(1);
4710 Chain = DAG.getStore(Chain, Value,
4711 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4712 DAG.getConstant(Offset, DstVT)),
4713 NULL, 0);
4714 BytesLeft -= 2;
4715 Offset += 2;
4716 }
4717
4718 if (BytesLeft == 1) {
4719 Value = DAG.getLoad(MVT::i8, Chain,
4720 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4721 DAG.getConstant(Offset, SrcVT)),
4722 NULL, 0);
4723 Chain = Value.getValue(1);
4724 Chain = DAG.getStore(Chain, Value,
4725 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4726 DAG.getConstant(Offset, DstVT)),
4727 NULL, 0);
4728 }
4729 }
4730
4731 return Chain;
4732}
4733
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004734/// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4735SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004736 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004737 SDOperand TheChain = N->getOperand(0);
4738 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004739 if (Subtarget->is64Bit()) {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004740 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4741 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4742 MVT::i64, rax.getValue(2));
4743 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004744 DAG.getConstant(32, MVT::i8));
4745 SDOperand Ops[] = {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004746 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004747 };
4748
4749 Tys = DAG.getVTList(MVT::i64, MVT::Other);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004750 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004751 }
4752
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004753 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4754 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4755 MVT::i32, eax.getValue(2));
4756 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4757 SDOperand Ops[] = { eax, edx };
4758 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4759
4760 // Use a MERGE_VALUES to return the value and chain.
4761 Ops[1] = edx.getValue(1);
4762 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4763 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004764}
4765
4766SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4767 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
4768
4769 if (!Subtarget->is64Bit()) {
4770 // vastart just stores the address of the VarArgsFrameIndex slot into the
4771 // memory location argument.
4772 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4773 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
4774 SV->getOffset());
4775 }
4776
4777 // __va_list_tag:
4778 // gp_offset (0 - 6 * 8)
4779 // fp_offset (48 - 48 + 8 * 16)
4780 // overflow_arg_area (point to parameters coming in memory).
4781 // reg_save_area
4782 SmallVector<SDOperand, 8> MemOps;
4783 SDOperand FIN = Op.getOperand(1);
4784 // Store gp_offset
4785 SDOperand Store = DAG.getStore(Op.getOperand(0),
4786 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4787 FIN, SV->getValue(), SV->getOffset());
4788 MemOps.push_back(Store);
4789
4790 // Store fp_offset
4791 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4792 DAG.getConstant(4, getPointerTy()));
4793 Store = DAG.getStore(Op.getOperand(0),
4794 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4795 FIN, SV->getValue(), SV->getOffset());
4796 MemOps.push_back(Store);
4797
4798 // Store ptr to overflow_arg_area
4799 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4800 DAG.getConstant(4, getPointerTy()));
4801 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4802 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
4803 SV->getOffset());
4804 MemOps.push_back(Store);
4805
4806 // Store ptr to reg_save_area.
4807 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4808 DAG.getConstant(8, getPointerTy()));
4809 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4810 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
4811 SV->getOffset());
4812 MemOps.push_back(Store);
4813 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4814}
4815
4816SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4817 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4818 SDOperand Chain = Op.getOperand(0);
4819 SDOperand DstPtr = Op.getOperand(1);
4820 SDOperand SrcPtr = Op.getOperand(2);
4821 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
4822 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
4823
4824 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
4825 SrcSV->getValue(), SrcSV->getOffset());
4826 Chain = SrcPtr.getValue(1);
4827 for (unsigned i = 0; i < 3; ++i) {
4828 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
4829 SrcSV->getValue(), SrcSV->getOffset());
4830 Chain = Val.getValue(1);
4831 Chain = DAG.getStore(Chain, Val, DstPtr,
4832 DstSV->getValue(), DstSV->getOffset());
4833 if (i == 2)
4834 break;
4835 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
4836 DAG.getConstant(8, getPointerTy()));
4837 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
4838 DAG.getConstant(8, getPointerTy()));
4839 }
4840 return Chain;
4841}
4842
4843SDOperand
4844X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4845 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4846 switch (IntNo) {
4847 default: return SDOperand(); // Don't custom lower most intrinsics.
4848 // Comparison intrinsics.
4849 case Intrinsic::x86_sse_comieq_ss:
4850 case Intrinsic::x86_sse_comilt_ss:
4851 case Intrinsic::x86_sse_comile_ss:
4852 case Intrinsic::x86_sse_comigt_ss:
4853 case Intrinsic::x86_sse_comige_ss:
4854 case Intrinsic::x86_sse_comineq_ss:
4855 case Intrinsic::x86_sse_ucomieq_ss:
4856 case Intrinsic::x86_sse_ucomilt_ss:
4857 case Intrinsic::x86_sse_ucomile_ss:
4858 case Intrinsic::x86_sse_ucomigt_ss:
4859 case Intrinsic::x86_sse_ucomige_ss:
4860 case Intrinsic::x86_sse_ucomineq_ss:
4861 case Intrinsic::x86_sse2_comieq_sd:
4862 case Intrinsic::x86_sse2_comilt_sd:
4863 case Intrinsic::x86_sse2_comile_sd:
4864 case Intrinsic::x86_sse2_comigt_sd:
4865 case Intrinsic::x86_sse2_comige_sd:
4866 case Intrinsic::x86_sse2_comineq_sd:
4867 case Intrinsic::x86_sse2_ucomieq_sd:
4868 case Intrinsic::x86_sse2_ucomilt_sd:
4869 case Intrinsic::x86_sse2_ucomile_sd:
4870 case Intrinsic::x86_sse2_ucomigt_sd:
4871 case Intrinsic::x86_sse2_ucomige_sd:
4872 case Intrinsic::x86_sse2_ucomineq_sd: {
4873 unsigned Opc = 0;
4874 ISD::CondCode CC = ISD::SETCC_INVALID;
4875 switch (IntNo) {
4876 default: break;
4877 case Intrinsic::x86_sse_comieq_ss:
4878 case Intrinsic::x86_sse2_comieq_sd:
4879 Opc = X86ISD::COMI;
4880 CC = ISD::SETEQ;
4881 break;
4882 case Intrinsic::x86_sse_comilt_ss:
4883 case Intrinsic::x86_sse2_comilt_sd:
4884 Opc = X86ISD::COMI;
4885 CC = ISD::SETLT;
4886 break;
4887 case Intrinsic::x86_sse_comile_ss:
4888 case Intrinsic::x86_sse2_comile_sd:
4889 Opc = X86ISD::COMI;
4890 CC = ISD::SETLE;
4891 break;
4892 case Intrinsic::x86_sse_comigt_ss:
4893 case Intrinsic::x86_sse2_comigt_sd:
4894 Opc = X86ISD::COMI;
4895 CC = ISD::SETGT;
4896 break;
4897 case Intrinsic::x86_sse_comige_ss:
4898 case Intrinsic::x86_sse2_comige_sd:
4899 Opc = X86ISD::COMI;
4900 CC = ISD::SETGE;
4901 break;
4902 case Intrinsic::x86_sse_comineq_ss:
4903 case Intrinsic::x86_sse2_comineq_sd:
4904 Opc = X86ISD::COMI;
4905 CC = ISD::SETNE;
4906 break;
4907 case Intrinsic::x86_sse_ucomieq_ss:
4908 case Intrinsic::x86_sse2_ucomieq_sd:
4909 Opc = X86ISD::UCOMI;
4910 CC = ISD::SETEQ;
4911 break;
4912 case Intrinsic::x86_sse_ucomilt_ss:
4913 case Intrinsic::x86_sse2_ucomilt_sd:
4914 Opc = X86ISD::UCOMI;
4915 CC = ISD::SETLT;
4916 break;
4917 case Intrinsic::x86_sse_ucomile_ss:
4918 case Intrinsic::x86_sse2_ucomile_sd:
4919 Opc = X86ISD::UCOMI;
4920 CC = ISD::SETLE;
4921 break;
4922 case Intrinsic::x86_sse_ucomigt_ss:
4923 case Intrinsic::x86_sse2_ucomigt_sd:
4924 Opc = X86ISD::UCOMI;
4925 CC = ISD::SETGT;
4926 break;
4927 case Intrinsic::x86_sse_ucomige_ss:
4928 case Intrinsic::x86_sse2_ucomige_sd:
4929 Opc = X86ISD::UCOMI;
4930 CC = ISD::SETGE;
4931 break;
4932 case Intrinsic::x86_sse_ucomineq_ss:
4933 case Intrinsic::x86_sse2_ucomineq_sd:
4934 Opc = X86ISD::UCOMI;
4935 CC = ISD::SETNE;
4936 break;
4937 }
4938
4939 unsigned X86CC;
4940 SDOperand LHS = Op.getOperand(1);
4941 SDOperand RHS = Op.getOperand(2);
4942 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4943
Evan Cheng621216e2007-09-29 00:00:36 +00004944 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
4945 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
4946 DAG.getConstant(X86CC, MVT::i8), Cond);
4947 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004948 }
4949 }
4950}
4951
4952SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4953 // Depths > 0 not supported yet!
4954 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4955 return SDOperand();
4956
4957 // Just load the return address
4958 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4959 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4960}
4961
4962SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4963 // Depths > 0 not supported yet!
4964 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4965 return SDOperand();
4966
4967 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4968 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
4969 DAG.getConstant(4, getPointerTy()));
4970}
4971
4972SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
4973 SelectionDAG &DAG) {
4974 // Is not yet supported on x86-64
4975 if (Subtarget->is64Bit())
4976 return SDOperand();
4977
4978 return DAG.getConstant(8, getPointerTy());
4979}
4980
4981SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
4982{
4983 assert(!Subtarget->is64Bit() &&
4984 "Lowering of eh_return builtin is not supported yet on x86-64");
4985
4986 MachineFunction &MF = DAG.getMachineFunction();
4987 SDOperand Chain = Op.getOperand(0);
4988 SDOperand Offset = Op.getOperand(1);
4989 SDOperand Handler = Op.getOperand(2);
4990
4991 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
4992 getPointerTy());
4993
4994 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
4995 DAG.getConstant(-4UL, getPointerTy()));
4996 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
4997 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
4998 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
4999 MF.addLiveOut(X86::ECX);
5000
5001 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5002 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5003}
5004
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005005SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5006 SelectionDAG &DAG) {
5007 SDOperand Root = Op.getOperand(0);
5008 SDOperand Trmp = Op.getOperand(1); // trampoline
5009 SDOperand FPtr = Op.getOperand(2); // nested function
5010 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5011
5012 SrcValueSDNode *TrmpSV = cast<SrcValueSDNode>(Op.getOperand(4));
5013
5014 if (Subtarget->is64Bit()) {
5015 return SDOperand(); // not yet supported
5016 } else {
5017 Function *Func = (Function *)
5018 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5019 unsigned CC = Func->getCallingConv();
Duncan Sands466eadd2007-08-29 19:01:20 +00005020 unsigned NestReg;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005021
5022 switch (CC) {
5023 default:
5024 assert(0 && "Unsupported calling convention");
5025 case CallingConv::C:
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005026 case CallingConv::X86_StdCall: {
5027 // Pass 'nest' parameter in ECX.
5028 // Must be kept in sync with X86CallingConv.td
Duncan Sands466eadd2007-08-29 19:01:20 +00005029 NestReg = X86::ECX;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005030
5031 // Check that ECX wasn't needed by an 'inreg' parameter.
5032 const FunctionType *FTy = Func->getFunctionType();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00005033 const ParamAttrsList *Attrs = Func->getParamAttrs();
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005034
5035 if (Attrs && !Func->isVarArg()) {
5036 unsigned InRegCount = 0;
5037 unsigned Idx = 1;
5038
5039 for (FunctionType::param_iterator I = FTy->param_begin(),
5040 E = FTy->param_end(); I != E; ++I, ++Idx)
5041 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5042 // FIXME: should only count parameters that are lowered to integers.
5043 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5044
5045 if (InRegCount > 2) {
5046 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5047 abort();
5048 }
5049 }
5050 break;
5051 }
5052 case CallingConv::X86_FastCall:
5053 // Pass 'nest' parameter in EAX.
5054 // Must be kept in sync with X86CallingConv.td
Duncan Sands466eadd2007-08-29 19:01:20 +00005055 NestReg = X86::EAX;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005056 break;
5057 }
5058
Duncan Sands466eadd2007-08-29 19:01:20 +00005059 const X86InstrInfo *TII =
5060 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5061
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005062 SDOperand OutChains[4];
5063 SDOperand Addr, Disp;
5064
5065 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5066 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5067
Duncan Sands466eadd2007-08-29 19:01:20 +00005068 unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5069 unsigned char N86Reg = ((X86RegisterInfo&)RegInfo).getX86RegNum(NestReg);
5070 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005071 Trmp, TrmpSV->getValue(), TrmpSV->getOffset());
5072
5073 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5074 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpSV->getValue(),
5075 TrmpSV->getOffset() + 1, false, 1);
5076
Duncan Sands466eadd2007-08-29 19:01:20 +00005077 unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005078 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5079 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5080 TrmpSV->getValue() + 5, TrmpSV->getOffset());
5081
5082 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5083 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpSV->getValue(),
5084 TrmpSV->getOffset() + 6, false, 1);
5085
Duncan Sands7407a9f2007-09-11 14:10:23 +00005086 SDOperand Ops[] =
5087 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5088 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005089 }
5090}
5091
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +00005092SDOperand X86TargetLowering::LowerFLT_ROUNDS(SDOperand Op, SelectionDAG &DAG) {
5093 /*
5094 The rounding mode is in bits 11:10 of FPSR, and has the following
5095 settings:
5096 00 Round to nearest
5097 01 Round to -inf
5098 10 Round to +inf
5099 11 Round to 0
5100
5101 FLT_ROUNDS, on the other hand, expects the following:
5102 -1 Undefined
5103 0 Round to 0
5104 1 Round to nearest
5105 2 Round to +inf
5106 3 Round to -inf
5107
5108 To perform the conversion, we do:
5109 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5110 */
5111
5112 MachineFunction &MF = DAG.getMachineFunction();
5113 const TargetMachine &TM = MF.getTarget();
5114 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5115 unsigned StackAlignment = TFI.getStackAlignment();
5116 MVT::ValueType VT = Op.getValueType();
5117
5118 // Save FP Control Word to stack slot
5119 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5120 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5121
5122 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5123 DAG.getEntryNode(), StackSlot);
5124
5125 // Load FP Control Word from stack slot
5126 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5127
5128 // Transform as necessary
5129 SDOperand CWD1 =
5130 DAG.getNode(ISD::SRL, MVT::i16,
5131 DAG.getNode(ISD::AND, MVT::i16,
5132 CWD, DAG.getConstant(0x800, MVT::i16)),
5133 DAG.getConstant(11, MVT::i8));
5134 SDOperand CWD2 =
5135 DAG.getNode(ISD::SRL, MVT::i16,
5136 DAG.getNode(ISD::AND, MVT::i16,
5137 CWD, DAG.getConstant(0x400, MVT::i16)),
5138 DAG.getConstant(9, MVT::i8));
5139
5140 SDOperand RetVal =
5141 DAG.getNode(ISD::AND, MVT::i16,
5142 DAG.getNode(ISD::ADD, MVT::i16,
5143 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5144 DAG.getConstant(1, MVT::i16)),
5145 DAG.getConstant(3, MVT::i16));
5146
5147
5148 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5149 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5150}
5151
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005152/// LowerOperation - Provide custom lowering hooks for some operations.
5153///
5154SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5155 switch (Op.getOpcode()) {
5156 default: assert(0 && "Should not custom lower this!");
5157 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5158 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5159 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5160 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5161 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5162 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5163 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5164 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5165 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5166 case ISD::SHL_PARTS:
5167 case ISD::SRA_PARTS:
5168 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5169 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5170 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5171 case ISD::FABS: return LowerFABS(Op, DAG);
5172 case ISD::FNEG: return LowerFNEG(Op, DAG);
5173 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
Evan Cheng621216e2007-09-29 00:00:36 +00005174 case ISD::SETCC: return LowerSETCC(Op, DAG);
5175 case ISD::SELECT: return LowerSELECT(Op, DAG);
5176 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005177 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5178 case ISD::CALL: return LowerCALL(Op, DAG);
5179 case ISD::RET: return LowerRET(Op, DAG);
5180 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5181 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5182 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005183 case ISD::VASTART: return LowerVASTART(Op, DAG);
5184 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5185 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5186 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5187 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5188 case ISD::FRAME_TO_ARGS_OFFSET:
5189 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5190 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5191 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005192 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +00005193 case ISD::FLT_ROUNDS: return LowerFLT_ROUNDS(Op, DAG);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005194
5195
5196 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5197 case ISD::READCYCLECOUNTER:
5198 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005199 }
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005200}
5201
5202/// ExpandOperation - Provide custom lowering hooks for expanding operations.
5203SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5204 switch (N->getOpcode()) {
5205 default: assert(0 && "Should not custom lower this!");
5206 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5207 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5208 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005209}
5210
5211const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5212 switch (Opcode) {
5213 default: return NULL;
5214 case X86ISD::SHLD: return "X86ISD::SHLD";
5215 case X86ISD::SHRD: return "X86ISD::SHRD";
5216 case X86ISD::FAND: return "X86ISD::FAND";
5217 case X86ISD::FOR: return "X86ISD::FOR";
5218 case X86ISD::FXOR: return "X86ISD::FXOR";
5219 case X86ISD::FSRL: return "X86ISD::FSRL";
5220 case X86ISD::FILD: return "X86ISD::FILD";
5221 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5222 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5223 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5224 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5225 case X86ISD::FLD: return "X86ISD::FLD";
5226 case X86ISD::FST: return "X86ISD::FST";
5227 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5228 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5229 case X86ISD::CALL: return "X86ISD::CALL";
5230 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5231 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5232 case X86ISD::CMP: return "X86ISD::CMP";
5233 case X86ISD::COMI: return "X86ISD::COMI";
5234 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5235 case X86ISD::SETCC: return "X86ISD::SETCC";
5236 case X86ISD::CMOV: return "X86ISD::CMOV";
5237 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5238 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5239 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5240 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005241 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5242 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5243 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5244 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5245 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5246 case X86ISD::FMAX: return "X86ISD::FMAX";
5247 case X86ISD::FMIN: return "X86ISD::FMIN";
5248 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5249 case X86ISD::FRCP: return "X86ISD::FRCP";
5250 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5251 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5252 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00005253 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +00005254 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005255 }
5256}
5257
5258// isLegalAddressingMode - Return true if the addressing mode represented
5259// by AM is legal for this target, for a load/store of the specified type.
5260bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5261 const Type *Ty) const {
5262 // X86 supports extremely general addressing modes.
5263
5264 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5265 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5266 return false;
5267
5268 if (AM.BaseGV) {
Evan Cheng6a1f3f12007-08-01 23:46:47 +00005269 // We can only fold this if we don't need an extra load.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005270 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5271 return false;
Evan Cheng6a1f3f12007-08-01 23:46:47 +00005272
5273 // X86-64 only supports addr of globals in small code model.
5274 if (Subtarget->is64Bit()) {
5275 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5276 return false;
5277 // If lower 4G is not available, then we must use rip-relative addressing.
5278 if (AM.BaseOffs || AM.Scale > 1)
5279 return false;
5280 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005281 }
5282
5283 switch (AM.Scale) {
5284 case 0:
5285 case 1:
5286 case 2:
5287 case 4:
5288 case 8:
5289 // These scales always work.
5290 break;
5291 case 3:
5292 case 5:
5293 case 9:
5294 // These scales are formed with basereg+scalereg. Only accept if there is
5295 // no basereg yet.
5296 if (AM.HasBaseReg)
5297 return false;
5298 break;
5299 default: // Other stuff never works.
5300 return false;
5301 }
5302
5303 return true;
5304}
5305
5306
Evan Cheng27a820a2007-10-26 01:56:11 +00005307bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5308 if (!Ty1->isInteger() || !Ty2->isInteger())
5309 return false;
Evan Cheng7f152602007-10-29 07:57:50 +00005310 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5311 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5312 if (NumBits1 <= NumBits2)
5313 return false;
5314 return Subtarget->is64Bit() || NumBits1 < 64;
Evan Cheng27a820a2007-10-26 01:56:11 +00005315}
5316
Evan Cheng9decb332007-10-29 19:58:20 +00005317bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5318 MVT::ValueType VT2) const {
5319 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5320 return false;
5321 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5322 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5323 if (NumBits1 <= NumBits2)
5324 return false;
5325 return Subtarget->is64Bit() || NumBits1 < 64;
5326}
Evan Cheng27a820a2007-10-26 01:56:11 +00005327
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005328/// isShuffleMaskLegal - Targets can use this to indicate that they only
5329/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5330/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5331/// are assumed to be legal.
5332bool
5333X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5334 // Only do shuffles on 128-bit vector types for now.
5335 if (MVT::getSizeInBits(VT) == 64) return false;
5336 return (Mask.Val->getNumOperands() <= 4 ||
5337 isIdentityMask(Mask.Val) ||
5338 isIdentityMask(Mask.Val, true) ||
5339 isSplatMask(Mask.Val) ||
5340 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5341 X86::isUNPCKLMask(Mask.Val) ||
5342 X86::isUNPCKHMask(Mask.Val) ||
5343 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5344 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5345}
5346
5347bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5348 MVT::ValueType EVT,
5349 SelectionDAG &DAG) const {
5350 unsigned NumElts = BVOps.size();
5351 // Only do shuffles on 128-bit vector types for now.
5352 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5353 if (NumElts == 2) return true;
5354 if (NumElts == 4) {
5355 return (isMOVLMask(&BVOps[0], 4) ||
5356 isCommutedMOVL(&BVOps[0], 4, true) ||
5357 isSHUFPMask(&BVOps[0], 4) ||
5358 isCommutedSHUFP(&BVOps[0], 4));
5359 }
5360 return false;
5361}
5362
5363//===----------------------------------------------------------------------===//
5364// X86 Scheduler Hooks
5365//===----------------------------------------------------------------------===//
5366
5367MachineBasicBlock *
5368X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
5369 MachineBasicBlock *BB) {
5370 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5371 switch (MI->getOpcode()) {
5372 default: assert(false && "Unexpected instr type to insert");
5373 case X86::CMOV_FR32:
5374 case X86::CMOV_FR64:
5375 case X86::CMOV_V4F32:
5376 case X86::CMOV_V2F64:
Evan Cheng621216e2007-09-29 00:00:36 +00005377 case X86::CMOV_V2I64: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005378 // To "insert" a SELECT_CC instruction, we actually have to insert the
5379 // diamond control-flow pattern. The incoming instruction knows the
5380 // destination vreg to set, the condition code register to branch on, the
5381 // true/false values to select between, and a branch opcode to use.
5382 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5383 ilist<MachineBasicBlock>::iterator It = BB;
5384 ++It;
5385
5386 // thisMBB:
5387 // ...
5388 // TrueVal = ...
5389 // cmpTY ccX, r1, r2
5390 // bCC copy1MBB
5391 // fallthrough --> copy0MBB
5392 MachineBasicBlock *thisMBB = BB;
5393 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5394 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5395 unsigned Opc =
5396 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5397 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5398 MachineFunction *F = BB->getParent();
5399 F->getBasicBlockList().insert(It, copy0MBB);
5400 F->getBasicBlockList().insert(It, sinkMBB);
5401 // Update machine-CFG edges by first adding all successors of the current
5402 // block to the new block which will contain the Phi node for the select.
5403 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5404 e = BB->succ_end(); i != e; ++i)
5405 sinkMBB->addSuccessor(*i);
5406 // Next, remove all successors of the current block, and add the true
5407 // and fallthrough blocks as its successors.
5408 while(!BB->succ_empty())
5409 BB->removeSuccessor(BB->succ_begin());
5410 BB->addSuccessor(copy0MBB);
5411 BB->addSuccessor(sinkMBB);
5412
5413 // copy0MBB:
5414 // %FalseValue = ...
5415 // # fallthrough to sinkMBB
5416 BB = copy0MBB;
5417
5418 // Update machine-CFG edges
5419 BB->addSuccessor(sinkMBB);
5420
5421 // sinkMBB:
5422 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5423 // ...
5424 BB = sinkMBB;
5425 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5426 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5427 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5428
5429 delete MI; // The pseudo instruction is gone now.
5430 return BB;
5431 }
5432
5433 case X86::FP32_TO_INT16_IN_MEM:
5434 case X86::FP32_TO_INT32_IN_MEM:
5435 case X86::FP32_TO_INT64_IN_MEM:
5436 case X86::FP64_TO_INT16_IN_MEM:
5437 case X86::FP64_TO_INT32_IN_MEM:
Dale Johannesen6d0e36a2007-08-07 01:17:37 +00005438 case X86::FP64_TO_INT64_IN_MEM:
5439 case X86::FP80_TO_INT16_IN_MEM:
5440 case X86::FP80_TO_INT32_IN_MEM:
5441 case X86::FP80_TO_INT64_IN_MEM: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005442 // Change the floating point control register to use "round towards zero"
5443 // mode when truncating to an integer value.
5444 MachineFunction *F = BB->getParent();
5445 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5446 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5447
5448 // Load the old value of the high byte of the control word...
5449 unsigned OldCW =
5450 F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
5451 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5452
5453 // Set the high part to be round to zero...
5454 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5455 .addImm(0xC7F);
5456
5457 // Reload the modified control word now...
5458 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5459
5460 // Restore the memory image of control word to original value
5461 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5462 .addReg(OldCW);
5463
5464 // Get the X86 opcode to use.
5465 unsigned Opc;
5466 switch (MI->getOpcode()) {
5467 default: assert(0 && "illegal opcode!");
5468 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5469 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5470 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5471 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5472 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5473 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
Dale Johannesen6d0e36a2007-08-07 01:17:37 +00005474 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5475 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5476 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005477 }
5478
5479 X86AddressMode AM;
5480 MachineOperand &Op = MI->getOperand(0);
5481 if (Op.isRegister()) {
5482 AM.BaseType = X86AddressMode::RegBase;
5483 AM.Base.Reg = Op.getReg();
5484 } else {
5485 AM.BaseType = X86AddressMode::FrameIndexBase;
5486 AM.Base.FrameIndex = Op.getFrameIndex();
5487 }
5488 Op = MI->getOperand(1);
5489 if (Op.isImmediate())
5490 AM.Scale = Op.getImm();
5491 Op = MI->getOperand(2);
5492 if (Op.isImmediate())
5493 AM.IndexReg = Op.getImm();
5494 Op = MI->getOperand(3);
5495 if (Op.isGlobalAddress()) {
5496 AM.GV = Op.getGlobal();
5497 } else {
5498 AM.Disp = Op.getImm();
5499 }
5500 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5501 .addReg(MI->getOperand(4).getReg());
5502
5503 // Reload the original control word now.
5504 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5505
5506 delete MI; // The pseudo instruction is gone now.
5507 return BB;
5508 }
5509 }
5510}
5511
5512//===----------------------------------------------------------------------===//
5513// X86 Optimization Hooks
5514//===----------------------------------------------------------------------===//
5515
5516void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5517 uint64_t Mask,
5518 uint64_t &KnownZero,
5519 uint64_t &KnownOne,
5520 const SelectionDAG &DAG,
5521 unsigned Depth) const {
5522 unsigned Opc = Op.getOpcode();
5523 assert((Opc >= ISD::BUILTIN_OP_END ||
5524 Opc == ISD::INTRINSIC_WO_CHAIN ||
5525 Opc == ISD::INTRINSIC_W_CHAIN ||
5526 Opc == ISD::INTRINSIC_VOID) &&
5527 "Should use MaskedValueIsZero if you don't know whether Op"
5528 " is a target node!");
5529
5530 KnownZero = KnownOne = 0; // Don't know anything.
5531 switch (Opc) {
5532 default: break;
5533 case X86ISD::SETCC:
5534 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5535 break;
5536 }
5537}
5538
5539/// getShuffleScalarElt - Returns the scalar element that will make up the ith
5540/// element of the result of the vector shuffle.
5541static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5542 MVT::ValueType VT = N->getValueType(0);
5543 SDOperand PermMask = N->getOperand(2);
5544 unsigned NumElems = PermMask.getNumOperands();
5545 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5546 i %= NumElems;
5547 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5548 return (i == 0)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00005549 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005550 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5551 SDOperand Idx = PermMask.getOperand(i);
5552 if (Idx.getOpcode() == ISD::UNDEF)
5553 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5554 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5555 }
5556 return SDOperand();
5557}
5558
5559/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5560/// node is a GlobalAddress + an offset.
5561static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5562 unsigned Opc = N->getOpcode();
5563 if (Opc == X86ISD::Wrapper) {
5564 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5565 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5566 return true;
5567 }
5568 } else if (Opc == ISD::ADD) {
5569 SDOperand N1 = N->getOperand(0);
5570 SDOperand N2 = N->getOperand(1);
5571 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5572 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5573 if (V) {
5574 Offset += V->getSignExtended();
5575 return true;
5576 }
5577 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5578 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5579 if (V) {
5580 Offset += V->getSignExtended();
5581 return true;
5582 }
5583 }
5584 }
5585 return false;
5586}
5587
5588/// isConsecutiveLoad - Returns true if N is loading from an address of Base
5589/// + Dist * Size.
5590static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5591 MachineFrameInfo *MFI) {
5592 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5593 return false;
5594
5595 SDOperand Loc = N->getOperand(1);
5596 SDOperand BaseLoc = Base->getOperand(1);
5597 if (Loc.getOpcode() == ISD::FrameIndex) {
5598 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5599 return false;
Dan Gohman53491e92007-07-23 20:24:29 +00005600 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5601 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005602 int FS = MFI->getObjectSize(FI);
5603 int BFS = MFI->getObjectSize(BFI);
5604 if (FS != BFS || FS != Size) return false;
5605 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5606 } else {
5607 GlobalValue *GV1 = NULL;
5608 GlobalValue *GV2 = NULL;
5609 int64_t Offset1 = 0;
5610 int64_t Offset2 = 0;
5611 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5612 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5613 if (isGA1 && isGA2 && GV1 == GV2)
5614 return Offset1 == (Offset2 + Dist*Size);
5615 }
5616
5617 return false;
5618}
5619
5620static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5621 const X86Subtarget *Subtarget) {
5622 GlobalValue *GV;
5623 int64_t Offset;
5624 if (isGAPlusOffset(Base, GV, Offset))
5625 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5626 else {
5627 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
Dan Gohman53491e92007-07-23 20:24:29 +00005628 int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005629 if (BFI < 0)
5630 // Fixed objects do not specify alignment, however the offsets are known.
5631 return ((Subtarget->getStackAlignment() % 16) == 0 &&
5632 (MFI->getObjectOffset(BFI) % 16) == 0);
5633 else
5634 return MFI->getObjectAlignment(BFI) >= 16;
5635 }
5636 return false;
5637}
5638
5639
5640/// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5641/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5642/// if the load addresses are consecutive, non-overlapping, and in the right
5643/// order.
5644static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5645 const X86Subtarget *Subtarget) {
5646 MachineFunction &MF = DAG.getMachineFunction();
5647 MachineFrameInfo *MFI = MF.getFrameInfo();
5648 MVT::ValueType VT = N->getValueType(0);
5649 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5650 SDOperand PermMask = N->getOperand(2);
5651 int NumElems = (int)PermMask.getNumOperands();
5652 SDNode *Base = NULL;
5653 for (int i = 0; i < NumElems; ++i) {
5654 SDOperand Idx = PermMask.getOperand(i);
5655 if (Idx.getOpcode() == ISD::UNDEF) {
5656 if (!Base) return SDOperand();
5657 } else {
5658 SDOperand Arg =
5659 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5660 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5661 return SDOperand();
5662 if (!Base)
5663 Base = Arg.Val;
5664 else if (!isConsecutiveLoad(Arg.Val, Base,
5665 i, MVT::getSizeInBits(EVT)/8,MFI))
5666 return SDOperand();
5667 }
5668 }
5669
5670 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
Dan Gohman11821702007-07-27 17:16:43 +00005671 LoadSDNode *LD = cast<LoadSDNode>(Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005672 if (isAlign16) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005673 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
Dan Gohman11821702007-07-27 17:16:43 +00005674 LD->getSrcValueOffset(), LD->isVolatile());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005675 } else {
Dan Gohman11821702007-07-27 17:16:43 +00005676 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5677 LD->getSrcValueOffset(), LD->isVolatile(),
5678 LD->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005679 }
5680}
5681
5682/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5683static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5684 const X86Subtarget *Subtarget) {
5685 SDOperand Cond = N->getOperand(0);
5686
5687 // If we have SSE[12] support, try to form min/max nodes.
5688 if (Subtarget->hasSSE2() &&
5689 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5690 if (Cond.getOpcode() == ISD::SETCC) {
5691 // Get the LHS/RHS of the select.
5692 SDOperand LHS = N->getOperand(1);
5693 SDOperand RHS = N->getOperand(2);
5694 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5695
5696 unsigned Opcode = 0;
5697 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5698 switch (CC) {
5699 default: break;
5700 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5701 case ISD::SETULE:
5702 case ISD::SETLE:
5703 if (!UnsafeFPMath) break;
5704 // FALL THROUGH.
5705 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
5706 case ISD::SETLT:
5707 Opcode = X86ISD::FMIN;
5708 break;
5709
5710 case ISD::SETOGT: // (X > Y) ? X : Y -> max
5711 case ISD::SETUGT:
5712 case ISD::SETGT:
5713 if (!UnsafeFPMath) break;
5714 // FALL THROUGH.
5715 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
5716 case ISD::SETGE:
5717 Opcode = X86ISD::FMAX;
5718 break;
5719 }
5720 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5721 switch (CC) {
5722 default: break;
5723 case ISD::SETOGT: // (X > Y) ? Y : X -> min
5724 case ISD::SETUGT:
5725 case ISD::SETGT:
5726 if (!UnsafeFPMath) break;
5727 // FALL THROUGH.
5728 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
5729 case ISD::SETGE:
5730 Opcode = X86ISD::FMIN;
5731 break;
5732
5733 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
5734 case ISD::SETULE:
5735 case ISD::SETLE:
5736 if (!UnsafeFPMath) break;
5737 // FALL THROUGH.
5738 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
5739 case ISD::SETLT:
5740 Opcode = X86ISD::FMAX;
5741 break;
5742 }
5743 }
5744
5745 if (Opcode)
5746 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5747 }
5748
5749 }
5750
5751 return SDOperand();
5752}
5753
5754
5755SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5756 DAGCombinerInfo &DCI) const {
5757 SelectionDAG &DAG = DCI.DAG;
5758 switch (N->getOpcode()) {
5759 default: break;
5760 case ISD::VECTOR_SHUFFLE:
5761 return PerformShuffleCombine(N, DAG, Subtarget);
5762 case ISD::SELECT:
5763 return PerformSELECTCombine(N, DAG, Subtarget);
5764 }
5765
5766 return SDOperand();
5767}
5768
5769//===----------------------------------------------------------------------===//
5770// X86 Inline Assembly Support
5771//===----------------------------------------------------------------------===//
5772
5773/// getConstraintType - Given a constraint letter, return the type of
5774/// constraint it is for this target.
5775X86TargetLowering::ConstraintType
5776X86TargetLowering::getConstraintType(const std::string &Constraint) const {
5777 if (Constraint.size() == 1) {
5778 switch (Constraint[0]) {
5779 case 'A':
5780 case 'r':
5781 case 'R':
5782 case 'l':
5783 case 'q':
5784 case 'Q':
5785 case 'x':
5786 case 'Y':
5787 return C_RegisterClass;
5788 default:
5789 break;
5790 }
5791 }
5792 return TargetLowering::getConstraintType(Constraint);
5793}
5794
Chris Lattnera531abc2007-08-25 00:47:38 +00005795/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5796/// vector. If it is invalid, don't add anything to Ops.
5797void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
5798 char Constraint,
5799 std::vector<SDOperand>&Ops,
5800 SelectionDAG &DAG) {
5801 SDOperand Result(0, 0);
5802
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005803 switch (Constraint) {
5804 default: break;
5805 case 'I':
5806 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
Chris Lattnera531abc2007-08-25 00:47:38 +00005807 if (C->getValue() <= 31) {
5808 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5809 break;
5810 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005811 }
Chris Lattnera531abc2007-08-25 00:47:38 +00005812 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005813 case 'N':
5814 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
Chris Lattnera531abc2007-08-25 00:47:38 +00005815 if (C->getValue() <= 255) {
5816 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5817 break;
5818 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005819 }
Chris Lattnera531abc2007-08-25 00:47:38 +00005820 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005821 case 'i': {
5822 // Literal immediates are always ok.
Chris Lattnera531abc2007-08-25 00:47:38 +00005823 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
5824 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
5825 break;
5826 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005827
5828 // If we are in non-pic codegen mode, we allow the address of a global (with
5829 // an optional displacement) to be used with 'i'.
5830 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
5831 int64_t Offset = 0;
5832
5833 // Match either (GA) or (GA+C)
5834 if (GA) {
5835 Offset = GA->getOffset();
5836 } else if (Op.getOpcode() == ISD::ADD) {
5837 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5838 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5839 if (C && GA) {
5840 Offset = GA->getOffset()+C->getValue();
5841 } else {
5842 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5843 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5844 if (C && GA)
5845 Offset = GA->getOffset()+C->getValue();
5846 else
5847 C = 0, GA = 0;
5848 }
5849 }
5850
5851 if (GA) {
5852 // If addressing this global requires a load (e.g. in PIC mode), we can't
5853 // match.
5854 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
5855 false))
Chris Lattnera531abc2007-08-25 00:47:38 +00005856 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005857
5858 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5859 Offset);
Chris Lattnera531abc2007-08-25 00:47:38 +00005860 Result = Op;
5861 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005862 }
5863
5864 // Otherwise, not valid for this mode.
Chris Lattnera531abc2007-08-25 00:47:38 +00005865 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005866 }
5867 }
Chris Lattnera531abc2007-08-25 00:47:38 +00005868
5869 if (Result.Val) {
5870 Ops.push_back(Result);
5871 return;
5872 }
5873 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005874}
5875
5876std::vector<unsigned> X86TargetLowering::
5877getRegClassForInlineAsmConstraint(const std::string &Constraint,
5878 MVT::ValueType VT) const {
5879 if (Constraint.size() == 1) {
5880 // FIXME: not handling fp-stack yet!
5881 switch (Constraint[0]) { // GCC X86 Constraint Letters
5882 default: break; // Unknown constraint letter
5883 case 'A': // EAX/EDX
5884 if (VT == MVT::i32 || VT == MVT::i64)
5885 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
5886 break;
5887 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
5888 case 'Q': // Q_REGS
5889 if (VT == MVT::i32)
5890 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
5891 else if (VT == MVT::i16)
5892 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
5893 else if (VT == MVT::i8)
Evan Chengf85c10f2007-08-13 23:27:11 +00005894 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
Chris Lattner35032592007-11-04 06:51:12 +00005895 else if (VT == MVT::i64)
5896 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
5897 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005898 }
5899 }
5900
5901 return std::vector<unsigned>();
5902}
5903
5904std::pair<unsigned, const TargetRegisterClass*>
5905X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
5906 MVT::ValueType VT) const {
5907 // First, see if this is a constraint that directly corresponds to an LLVM
5908 // register class.
5909 if (Constraint.size() == 1) {
5910 // GCC Constraint Letters
5911 switch (Constraint[0]) {
5912 default: break;
5913 case 'r': // GENERAL_REGS
5914 case 'R': // LEGACY_REGS
5915 case 'l': // INDEX_REGS
5916 if (VT == MVT::i64 && Subtarget->is64Bit())
5917 return std::make_pair(0U, X86::GR64RegisterClass);
5918 if (VT == MVT::i32)
5919 return std::make_pair(0U, X86::GR32RegisterClass);
5920 else if (VT == MVT::i16)
5921 return std::make_pair(0U, X86::GR16RegisterClass);
5922 else if (VT == MVT::i8)
5923 return std::make_pair(0U, X86::GR8RegisterClass);
5924 break;
5925 case 'y': // MMX_REGS if MMX allowed.
5926 if (!Subtarget->hasMMX()) break;
5927 return std::make_pair(0U, X86::VR64RegisterClass);
5928 break;
5929 case 'Y': // SSE_REGS if SSE2 allowed
5930 if (!Subtarget->hasSSE2()) break;
5931 // FALL THROUGH.
5932 case 'x': // SSE_REGS if SSE1 allowed
5933 if (!Subtarget->hasSSE1()) break;
5934
5935 switch (VT) {
5936 default: break;
5937 // Scalar SSE types.
5938 case MVT::f32:
5939 case MVT::i32:
5940 return std::make_pair(0U, X86::FR32RegisterClass);
5941 case MVT::f64:
5942 case MVT::i64:
5943 return std::make_pair(0U, X86::FR64RegisterClass);
5944 // Vector types.
5945 case MVT::v16i8:
5946 case MVT::v8i16:
5947 case MVT::v4i32:
5948 case MVT::v2i64:
5949 case MVT::v4f32:
5950 case MVT::v2f64:
5951 return std::make_pair(0U, X86::VR128RegisterClass);
5952 }
5953 break;
5954 }
5955 }
5956
5957 // Use the default implementation in TargetLowering to convert the register
5958 // constraint into a member of a register class.
5959 std::pair<unsigned, const TargetRegisterClass*> Res;
5960 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
5961
5962 // Not found as a standard register?
5963 if (Res.second == 0) {
5964 // GCC calls "st(0)" just plain "st".
5965 if (StringsEqualNoCase("{st}", Constraint)) {
5966 Res.first = X86::ST0;
Chris Lattner3cfe51b2007-09-24 05:27:37 +00005967 Res.second = X86::RFP80RegisterClass;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005968 }
5969
5970 return Res;
5971 }
5972
5973 // Otherwise, check to see if this is a register class of the wrong value
5974 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
5975 // turn into {ax},{dx}.
5976 if (Res.second->hasType(VT))
5977 return Res; // Correct type already, nothing to do.
5978
5979 // All of the single-register GCC register classes map their values onto
5980 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
5981 // really want an 8-bit or 32-bit register, map to the appropriate register
5982 // class and return the appropriate register.
5983 if (Res.second != X86::GR16RegisterClass)
5984 return Res;
5985
5986 if (VT == MVT::i8) {
5987 unsigned DestReg = 0;
5988 switch (Res.first) {
5989 default: break;
5990 case X86::AX: DestReg = X86::AL; break;
5991 case X86::DX: DestReg = X86::DL; break;
5992 case X86::CX: DestReg = X86::CL; break;
5993 case X86::BX: DestReg = X86::BL; break;
5994 }
5995 if (DestReg) {
5996 Res.first = DestReg;
5997 Res.second = Res.second = X86::GR8RegisterClass;
5998 }
5999 } else if (VT == MVT::i32) {
6000 unsigned DestReg = 0;
6001 switch (Res.first) {
6002 default: break;
6003 case X86::AX: DestReg = X86::EAX; break;
6004 case X86::DX: DestReg = X86::EDX; break;
6005 case X86::CX: DestReg = X86::ECX; break;
6006 case X86::BX: DestReg = X86::EBX; break;
6007 case X86::SI: DestReg = X86::ESI; break;
6008 case X86::DI: DestReg = X86::EDI; break;
6009 case X86::BP: DestReg = X86::EBP; break;
6010 case X86::SP: DestReg = X86::ESP; break;
6011 }
6012 if (DestReg) {
6013 Res.first = DestReg;
6014 Res.second = Res.second = X86::GR32RegisterClass;
6015 }
6016 } else if (VT == MVT::i64) {
6017 unsigned DestReg = 0;
6018 switch (Res.first) {
6019 default: break;
6020 case X86::AX: DestReg = X86::RAX; break;
6021 case X86::DX: DestReg = X86::RDX; break;
6022 case X86::CX: DestReg = X86::RCX; break;
6023 case X86::BX: DestReg = X86::RBX; break;
6024 case X86::SI: DestReg = X86::RSI; break;
6025 case X86::DI: DestReg = X86::RDI; break;
6026 case X86::BP: DestReg = X86::RBP; break;
6027 case X86::SP: DestReg = X86::RSP; break;
6028 }
6029 if (DestReg) {
6030 Res.first = DestReg;
6031 Res.second = Res.second = X86::GR64RegisterClass;
6032 }
6033 }
6034
6035 return Res;
6036}