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