blob: 67217fd992499dd8575921135cbc926742e49965 [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"
Evan Cheng75184a92007-12-11 01:46:18 +000026#include "llvm/ADT/BitVector.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/ADT/VectorExtras.h"
28#include "llvm/Analysis/ScalarEvolutionExpressions.h"
29#include "llvm/CodeGen/CallingConvLower.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/CodeGen/SSARegMap.h"
35#include "llvm/Support/MathExtras.h"
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +000036#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038#include "llvm/Target/TargetOptions.h"
Evan Cheng75184a92007-12-11 01:46:18 +000039#include "llvm/ADT/SmallSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/ADT/StringExtras.h"
Duncan Sandsd8455ca2007-07-27 20:02:49 +000041#include "llvm/ParameterAttributes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042using namespace llvm;
43
44X86TargetLowering::X86TargetLowering(TargetMachine &TM)
45 : TargetLowering(TM) {
46 Subtarget = &TM.getSubtarget<X86Subtarget>();
Dale Johannesene0e0fd02007-09-23 14:52:20 +000047 X86ScalarSSEf64 = Subtarget->hasSSE2();
48 X86ScalarSSEf32 = Subtarget->hasSSE1();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +000050
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051
52 RegInfo = TM.getRegisterInfo();
53
54 // Set up the TargetLowering object.
55
56 // X86 is weird, it always uses i8 for shift amounts and setcc results.
57 setShiftAmountType(MVT::i8);
58 setSetCCResultType(MVT::i8);
59 setSetCCResultContents(ZeroOrOneSetCCResult);
60 setSchedulingPreference(SchedulingForRegPressure);
61 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
62 setStackPointerRegisterToSaveRestore(X86StackPtr);
63
64 if (Subtarget->isTargetDarwin()) {
65 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
66 setUseUnderscoreSetJmp(false);
67 setUseUnderscoreLongJmp(false);
68 } else if (Subtarget->isTargetMingw()) {
69 // MS runtime is weird: it exports _setjmp, but longjmp!
70 setUseUnderscoreSetJmp(true);
71 setUseUnderscoreLongJmp(false);
72 } else {
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(true);
75 }
76
77 // Set up the register classes.
78 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
79 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
80 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
81 if (Subtarget->is64Bit())
82 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
83
84 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
85
86 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
87 // operation.
88 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
89 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
90 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
91
92 if (Subtarget->is64Bit()) {
93 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
94 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
95 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +000096 if (X86ScalarSSEf64)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
98 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
99 else
100 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
101 }
102
103 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
104 // this operation.
105 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
106 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
107 // SSE has no i16 to fp conversion, only i32
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000108 if (X86ScalarSSEf32) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000109 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000110 // f32 and f64 cases are Legal, f80 case is not
111 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
112 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
114 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
115 }
116
Dale Johannesen958b08b2007-09-19 23:55:34 +0000117 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
118 // are Legal, f80 is custom lowered.
119 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
120 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000121
122 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
123 // this operation.
124 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
125 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
126
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000127 if (X86ScalarSSEf32) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000129 // f32 and f64 cases are Legal, f80 case is not
130 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131 } else {
132 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
133 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
134 }
135
136 // Handle FP_TO_UINT by promoting the destination to a larger signed
137 // conversion.
138 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
139 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
140 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
141
142 if (Subtarget->is64Bit()) {
143 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
144 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
145 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000146 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147 // Expand FP_TO_UINT into a select.
148 // FIXME: We would like to use a Custom expander here eventually to do
149 // the optimal thing for SSE vs. the default expansion in the legalizer.
150 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
151 else
152 // With SSE3 we can use fisttpll to convert to a signed i64.
153 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
154 }
155
156 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000157 if (!X86ScalarSSEf64) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
159 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
160 }
161
Dan Gohman5a199552007-10-08 18:33:35 +0000162 // Scalar integer multiply, multiply-high, divide, and remainder are
163 // lowered to use operations that produce two results, to match the
164 // available instructions. This exposes the two-result form to trivial
165 // CSE, which is able to combine x/y and x%y into a single instruction,
166 // for example. The single-result multiply instructions are introduced
167 // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
168 // is not needed.
169 setOperationAction(ISD::MUL , MVT::i8 , Expand);
170 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
171 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
172 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
173 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
174 setOperationAction(ISD::SREM , MVT::i8 , Expand);
175 setOperationAction(ISD::UREM , MVT::i8 , Expand);
176 setOperationAction(ISD::MUL , MVT::i16 , Expand);
177 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
178 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
179 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
180 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
181 setOperationAction(ISD::SREM , MVT::i16 , Expand);
182 setOperationAction(ISD::UREM , MVT::i16 , Expand);
183 setOperationAction(ISD::MUL , MVT::i32 , Expand);
184 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
185 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
186 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
187 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
188 setOperationAction(ISD::SREM , MVT::i32 , Expand);
189 setOperationAction(ISD::UREM , MVT::i32 , Expand);
190 setOperationAction(ISD::MUL , MVT::i64 , Expand);
191 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
192 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
193 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
194 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
195 setOperationAction(ISD::SREM , MVT::i64 , Expand);
196 setOperationAction(ISD::UREM , MVT::i64 , Expand);
Dan Gohman242a5ba2007-09-25 18:23:27 +0000197
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
199 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
200 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
201 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
202 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
203 if (Subtarget->is64Bit())
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
206 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
208 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
209 setOperationAction(ISD::FREM , MVT::f64 , Expand);
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +0000210 setOperationAction(ISD::FLT_ROUNDS , MVT::i32 , Custom);
211
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
213 setOperationAction(ISD::CTTZ , MVT::i8 , Expand);
214 setOperationAction(ISD::CTLZ , MVT::i8 , Expand);
215 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
216 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
217 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
218 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
219 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
220 setOperationAction(ISD::CTLZ , MVT::i32 , Expand);
221 if (Subtarget->is64Bit()) {
222 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
223 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
224 setOperationAction(ISD::CTLZ , MVT::i64 , Expand);
225 }
226
227 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
228 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
229
230 // These should be promoted to a larger select which is supported.
231 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
232 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
233 // X86 wants to expand cmov itself.
234 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
235 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
236 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
237 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000238 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
240 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
241 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
242 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
243 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000244 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245 if (Subtarget->is64Bit()) {
246 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
247 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
248 }
249 // X86 ret instruction may pop stack.
250 setOperationAction(ISD::RET , MVT::Other, Custom);
251 if (!Subtarget->is64Bit())
252 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
253
254 // Darwin ABI issue.
255 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
256 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
257 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
258 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
259 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
260 if (Subtarget->is64Bit()) {
261 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
262 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
263 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
264 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
265 }
266 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
267 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
268 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
269 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
270 // X86 wants to expand memset / memcpy itself.
271 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
272 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
273
Dan Gohman21442852007-09-25 15:10:49 +0000274 // Use the default ISD::LOCATION expansion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 // FIXME - use subtarget debug flags
277 if (!Subtarget->isTargetDarwin() &&
278 !Subtarget->isTargetELF() &&
279 !Subtarget->isTargetCygMing())
280 setOperationAction(ISD::LABEL, MVT::Other, Expand);
281
282 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
283 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
284 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
285 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
286 if (Subtarget->is64Bit()) {
287 // FIXME: Verify
288 setExceptionPointerRegister(X86::RAX);
289 setExceptionSelectorRegister(X86::RDX);
290 } else {
291 setExceptionPointerRegister(X86::EAX);
292 setExceptionSelectorRegister(X86::EDX);
293 }
Anton Korobeynikov23ca9c52007-09-03 00:36:06 +0000294 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295
Duncan Sands7407a9f2007-09-11 14:10:23 +0000296 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
Duncan Sandsd8455ca2007-07-27 20:02:49 +0000297
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
299 setOperationAction(ISD::VASTART , MVT::Other, Custom);
300 setOperationAction(ISD::VAARG , MVT::Other, Expand);
301 setOperationAction(ISD::VAEND , MVT::Other, Expand);
302 if (Subtarget->is64Bit())
303 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
304 else
305 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
306
307 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
308 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
309 if (Subtarget->is64Bit())
310 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
311 if (Subtarget->isTargetCygMing())
312 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
313 else
314 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
315
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000316 if (X86ScalarSSEf64) {
317 // f32 and f64 use SSE.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318 // Set up the FP register classes.
319 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
320 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
321
322 // Use ANDPD to simulate FABS.
323 setOperationAction(ISD::FABS , MVT::f64, Custom);
324 setOperationAction(ISD::FABS , MVT::f32, Custom);
325
326 // Use XORP to simulate FNEG.
327 setOperationAction(ISD::FNEG , MVT::f64, Custom);
328 setOperationAction(ISD::FNEG , MVT::f32, Custom);
329
330 // Use ANDPD and ORPD to simulate FCOPYSIGN.
331 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
332 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
333
334 // We don't support sin/cos/fmod
335 setOperationAction(ISD::FSIN , MVT::f64, Expand);
336 setOperationAction(ISD::FCOS , MVT::f64, Expand);
337 setOperationAction(ISD::FREM , MVT::f64, Expand);
338 setOperationAction(ISD::FSIN , MVT::f32, Expand);
339 setOperationAction(ISD::FCOS , MVT::f32, Expand);
340 setOperationAction(ISD::FREM , MVT::f32, Expand);
341
342 // Expand FP immediates into loads from the stack, except for the special
343 // cases we handle.
344 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
345 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000346 addLegalFPImmediate(APFloat(+0.0)); // xorpd
347 addLegalFPImmediate(APFloat(+0.0f)); // xorps
Dale Johannesen8f83a6b2007-08-09 01:04:01 +0000348
349 // Conversions to long double (in X87) go through memory.
350 setConvertAction(MVT::f32, MVT::f80, Expand);
351 setConvertAction(MVT::f64, MVT::f80, Expand);
352
353 // Conversions from long double (in X87) go through memory.
354 setConvertAction(MVT::f80, MVT::f32, Expand);
355 setConvertAction(MVT::f80, MVT::f64, Expand);
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000356 } else if (X86ScalarSSEf32) {
357 // Use SSE for f32, x87 for f64.
358 // Set up the FP register classes.
359 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
360 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
361
362 // Use ANDPS to simulate FABS.
363 setOperationAction(ISD::FABS , MVT::f32, Custom);
364
365 // Use XORP to simulate FNEG.
366 setOperationAction(ISD::FNEG , MVT::f32, Custom);
367
368 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
369
370 // Use ANDPS and ORPS to simulate FCOPYSIGN.
371 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
372 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
373
374 // We don't support sin/cos/fmod
375 setOperationAction(ISD::FSIN , MVT::f32, Expand);
376 setOperationAction(ISD::FCOS , MVT::f32, Expand);
377 setOperationAction(ISD::FREM , MVT::f32, Expand);
378
379 // Expand FP immediates into loads from the stack, except for the special
380 // cases we handle.
381 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
382 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
383 addLegalFPImmediate(APFloat(+0.0f)); // xorps
384 addLegalFPImmediate(APFloat(+0.0)); // FLD0
385 addLegalFPImmediate(APFloat(+1.0)); // FLD1
386 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
387 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
388
389 // SSE->x87 conversions go through memory.
390 setConvertAction(MVT::f32, MVT::f64, Expand);
391 setConvertAction(MVT::f32, MVT::f80, Expand);
392
393 // x87->SSE truncations need to go through memory.
394 setConvertAction(MVT::f80, MVT::f32, Expand);
395 setConvertAction(MVT::f64, MVT::f32, Expand);
396 // And x87->x87 truncations also.
397 setConvertAction(MVT::f80, MVT::f64, Expand);
398
399 if (!UnsafeFPMath) {
400 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
401 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
402 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000404 // f32 and f64 in x87.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405 // Set up the FP register classes.
406 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
407 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
408
409 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
410 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
411 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
412 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
Dale Johannesen8f83a6b2007-08-09 01:04:01 +0000413
414 // Floating truncations need to go through memory.
415 setConvertAction(MVT::f80, MVT::f32, Expand);
416 setConvertAction(MVT::f64, MVT::f32, Expand);
417 setConvertAction(MVT::f80, MVT::f64, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418
419 if (!UnsafeFPMath) {
420 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
421 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
422 }
423
424 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
425 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
Dale Johannesenbbe2b702007-08-30 00:23:21 +0000426 addLegalFPImmediate(APFloat(+0.0)); // FLD0
427 addLegalFPImmediate(APFloat(+1.0)); // FLD1
428 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
429 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000430 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
431 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
432 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
433 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434 }
435
Dale Johannesen4ab00bd2007-08-05 18:49:15 +0000436 // Long double always uses X87.
437 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000438 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
439 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
440 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
Dale Johannesen7f1076b2007-09-26 21:10:55 +0000441 if (!UnsafeFPMath) {
442 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
443 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
444 }
Dale Johannesen4ab00bd2007-08-05 18:49:15 +0000445
Dan Gohman2f7b1982007-10-11 23:21:31 +0000446 // Always use a library call for pow.
447 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
448 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
449 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
450
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000451 // First set operation action for all vector types to expand. Then we
452 // will selectively turn on ones that can be effectively codegen'd.
453 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
454 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
455 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
456 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
457 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
458 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
459 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
460 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
461 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
462 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
463 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
464 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
465 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
466 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
467 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
468 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
469 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
470 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
471 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
472 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
473 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
474 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
475 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
476 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
477 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
Dan Gohman5a199552007-10-08 18:33:35 +0000478 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
479 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
480 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
481 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
Dan Gohman2f7b1982007-10-11 23:21:31 +0000482 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
Dan Gohman1d2dc2c2007-10-12 14:09:42 +0000483 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
484 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
485 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 }
487
488 if (Subtarget->hasMMX()) {
489 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
490 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
491 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
492 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
493
494 // FIXME: add MMX packed arithmetics
495
496 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
497 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
498 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
499 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
500
501 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
502 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
503 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
Dale Johannesen6b65c332007-10-30 01:18:38 +0000504 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000505
506 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
507 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
508
509 setOperationAction(ISD::AND, MVT::v8i8, Promote);
510 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
511 setOperationAction(ISD::AND, MVT::v4i16, Promote);
512 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
513 setOperationAction(ISD::AND, MVT::v2i32, Promote);
514 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
515 setOperationAction(ISD::AND, MVT::v1i64, Legal);
516
517 setOperationAction(ISD::OR, MVT::v8i8, Promote);
518 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
519 setOperationAction(ISD::OR, MVT::v4i16, Promote);
520 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
521 setOperationAction(ISD::OR, MVT::v2i32, Promote);
522 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
523 setOperationAction(ISD::OR, MVT::v1i64, Legal);
524
525 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
526 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
527 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
528 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
529 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
530 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
531 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
532
533 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
534 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
535 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
536 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
537 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
538 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
539 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
540
541 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
542 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
543 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
544 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
545
546 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
547 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
548 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
549 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
550
551 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
552 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
553 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
554 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
555 }
556
557 if (Subtarget->hasSSE1()) {
558 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
559
560 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
561 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
562 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
563 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
564 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
565 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
567 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
568 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
569 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
570 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
571 }
572
573 if (Subtarget->hasSSE2()) {
574 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
575 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
576 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
577 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
578 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
579
580 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
581 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
582 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
583 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
584 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
585 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
586 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
587 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
588 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
589 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
590 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
591 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
592 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
593 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
594 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000595
596 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
597 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
598 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
599 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
600 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
601 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
602
603 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
604 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
Nate Begemanc16406d2007-12-11 01:41:33 +0000605 // Do not attempt to custom lower non-power-of-2 vectors
606 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
607 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000608 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
609 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
610 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
611 }
612 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
613 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
614 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
615 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
616 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
Dale Johannesen2ff963d2007-10-31 00:32:36 +0000617 if (Subtarget->is64Bit())
618 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619
620 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
621 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
622 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
623 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
624 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
625 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
626 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
627 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
628 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
629 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
630 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
631 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
632 }
633
634 // Custom lower v2i64 and v2f64 selects.
635 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
636 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
637 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
638 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
639 }
640
641 // We want to custom lower some of our intrinsics.
642 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
643
644 // We have target-specific dag combine patterns for the following nodes:
645 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
646 setTargetDAGCombine(ISD::SELECT);
647
648 computeRegisterProperties();
649
650 // FIXME: These should be based on subtarget info. Plus, the values should
651 // be smaller when we are in optimizing for size mode.
652 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
653 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
654 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
655 allowUnalignedMemoryAccesses = true; // x86 supports it!
656}
657
658
Evan Cheng6fb06762007-11-09 01:32:10 +0000659/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
660/// jumptable.
661SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
662 SelectionDAG &DAG) const {
663 if (usesGlobalOffsetTable())
664 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
665 if (!Subtarget->isPICStyleRIPRel())
666 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
667 return Table;
668}
669
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670//===----------------------------------------------------------------------===//
671// Return Value Calling Convention Implementation
672//===----------------------------------------------------------------------===//
673
674#include "X86GenCallingConv.inc"
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000675
676/// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
677/// exists skip possible ISD:TokenFactor.
678static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
679 if (Chain.getOpcode()==X86ISD::TAILCALL) {
680 return Chain;
681 } else if (Chain.getOpcode()==ISD::TokenFactor) {
682 if (Chain.getNumOperands() &&
683 Chain.getOperand(0).getOpcode()==X86ISD::TAILCALL)
684 return Chain.getOperand(0);
685 }
686 return Chain;
687}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688
689/// LowerRET - Lower an ISD::RET node.
690SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
691 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
692
693 SmallVector<CCValAssign, 16> RVLocs;
694 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
695 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
696 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
697 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000698
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699 // If this is the first return lowered for this function, add the regs to the
700 // liveout set for the function.
701 if (DAG.getMachineFunction().liveout_empty()) {
702 for (unsigned i = 0; i != RVLocs.size(); ++i)
703 if (RVLocs[i].isRegLoc())
704 DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
705 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 SDOperand Chain = Op.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000708 // Handle tail call return.
709 Chain = GetPossiblePreceedingTailCall(Chain);
710 if (Chain.getOpcode() == X86ISD::TAILCALL) {
711 SDOperand TailCall = Chain;
712 SDOperand TargetAddress = TailCall.getOperand(1);
713 SDOperand StackAdjustment = TailCall.getOperand(2);
714 assert ( ((TargetAddress.getOpcode() == ISD::Register &&
715 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
716 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
717 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
718 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
719 "Expecting an global address, external symbol, or register");
720 assert( StackAdjustment.getOpcode() == ISD::Constant &&
721 "Expecting a const value");
722
723 SmallVector<SDOperand,8> Operands;
724 Operands.push_back(Chain.getOperand(0));
725 Operands.push_back(TargetAddress);
726 Operands.push_back(StackAdjustment);
727 // Copy registers used by the call. Last operand is a flag so it is not
728 // copied.
Arnold Schwaighofer10202b32007-10-16 09:05:00 +0000729 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000730 Operands.push_back(Chain.getOperand(i));
731 }
Arnold Schwaighofer10202b32007-10-16 09:05:00 +0000732 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
733 Operands.size());
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000734 }
735
736 // Regular return.
737 SDOperand Flag;
738
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 // Copy the result values into the output registers.
740 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
741 RVLocs[0].getLocReg() != X86::ST0) {
742 for (unsigned i = 0; i != RVLocs.size(); ++i) {
743 CCValAssign &VA = RVLocs[i];
744 assert(VA.isRegLoc() && "Can only return in registers!");
745 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
746 Flag);
747 Flag = Chain.getValue(1);
748 }
749 } else {
750 // We need to handle a destination of ST0 specially, because it isn't really
751 // a register.
752 SDOperand Value = Op.getOperand(1);
753
754 // If this is an FP return with ScalarSSE, we need to move the value from
755 // an XMM register onto the fp-stack.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000756 if ((X86ScalarSSEf32 && RVLocs[0].getValVT()==MVT::f32) ||
757 (X86ScalarSSEf64 && RVLocs[0].getValVT()==MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 SDOperand MemLoc;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000759
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000760 // If this is a load into a scalarsse value, don't store the loaded value
761 // back to the stack, only to reload it: just replace the scalar-sse load.
762 if (ISD::isNON_EXTLoad(Value.Val) &&
763 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
764 Chain = Value.getOperand(0);
765 MemLoc = Value.getOperand(1);
766 } else {
767 // Spill the value to memory and reload it into top of stack.
768 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
769 MachineFunction &MF = DAG.getMachineFunction();
770 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
771 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
772 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
773 }
774 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
775 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
776 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
777 Chain = Value.getValue(1);
778 }
779
780 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
781 SDOperand Ops[] = { Chain, Value };
782 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
783 Flag = Chain.getValue(1);
784 }
785
786 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
787 if (Flag.Val)
788 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
789 else
790 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
791}
792
793
794/// LowerCallResult - Lower the result values of an ISD::CALL into the
795/// appropriate copies out of appropriate physical registers. This assumes that
796/// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
797/// being lowered. The returns a SDNode with the same number of values as the
798/// ISD::CALL.
799SDNode *X86TargetLowering::
800LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
801 unsigned CallingConv, SelectionDAG &DAG) {
802
803 // Assign locations to each value returned by this call.
804 SmallVector<CCValAssign, 16> RVLocs;
805 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
806 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
807 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
808
809
810 SmallVector<SDOperand, 8> ResultVals;
811
812 // Copy all of the result registers out of their specified physreg.
813 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
814 for (unsigned i = 0; i != RVLocs.size(); ++i) {
815 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
816 RVLocs[i].getValVT(), InFlag).getValue(1);
817 InFlag = Chain.getValue(2);
818 ResultVals.push_back(Chain.getValue(0));
819 }
820 } else {
821 // Copies from the FP stack are special, as ST0 isn't a valid register
822 // before the fp stackifier runs.
823
824 // Copy ST0 into an RFP register with FP_GET_RESULT.
825 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
826 SDOperand GROps[] = { Chain, InFlag };
827 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
828 Chain = RetVal.getValue(1);
829 InFlag = RetVal.getValue(2);
830
831 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
832 // an XMM register.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000833 if ((X86ScalarSSEf32 && RVLocs[0].getValVT() == MVT::f32) ||
834 (X86ScalarSSEf64 && RVLocs[0].getValVT() == MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
836 // shouldn't be necessary except that RFP cannot be live across
837 // multiple blocks. When stackifier is fixed, they can be uncoupled.
838 MachineFunction &MF = DAG.getMachineFunction();
839 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
840 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
841 SDOperand Ops[] = {
842 Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
843 };
844 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
845 RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
846 Chain = RetVal.getValue(1);
847 }
848 ResultVals.push_back(RetVal);
849 }
850
851 // Merge everything together with a MERGE_VALUES node.
852 ResultVals.push_back(Chain);
853 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
854 &ResultVals[0], ResultVals.size()).Val;
855}
856
857
858//===----------------------------------------------------------------------===//
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000859// C & StdCall & Fast Calling Convention implementation
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860//===----------------------------------------------------------------------===//
861// StdCall calling convention seems to be standard for many Windows' API
862// routines and around. It differs from C calling convention just a little:
863// callee should clean up the stack, not caller. Symbols should be also
864// decorated in some fancy way :) It doesn't support any vector arguments.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000865// For info on fast calling convention see Fast Calling Convention (tail call)
866// implementation LowerX86_32FastCCCallTo.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867
868/// AddLiveIn - This helper function adds the specified physical register to the
869/// MachineFunction as a live in value. It also creates a corresponding virtual
870/// register for it.
871static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
872 const TargetRegisterClass *RC) {
873 assert(RC->contains(PReg) && "Not the correct regclass!");
874 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
875 MF.addLiveIn(PReg, VReg);
876 return VReg;
877}
878
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000879// align stack arguments according to platform alignment needed for tail calls
880unsigned GetAlignedArgumentStackSize(unsigned StackSize, SelectionDAG& DAG);
881
Rafael Espindola03cbeb72007-09-14 15:48:13 +0000882SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
883 const CCValAssign &VA,
884 MachineFrameInfo *MFI,
885 SDOperand Root, unsigned i) {
886 // Create the nodes corresponding to a load from this parameter slot.
887 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
888 VA.getLocMemOffset());
889 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
890
891 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
892
893 if (Flags & ISD::ParamFlags::ByVal)
894 return FIN;
895 else
896 return DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0);
897}
898
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
900 bool isStdCall) {
901 unsigned NumArgs = Op.Val->getNumValues() - 1;
902 MachineFunction &MF = DAG.getMachineFunction();
903 MachineFrameInfo *MFI = MF.getFrameInfo();
904 SDOperand Root = Op.getOperand(0);
905 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000906 unsigned CC = MF.getFunction()->getCallingConv();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907 // Assign locations to all of the incoming arguments.
908 SmallVector<CCValAssign, 16> ArgLocs;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000909 CCState CCInfo(CC, isVarArg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000910 getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000911 // Check for possible tail call calling convention.
912 if (CC == CallingConv::Fast && PerformTailCallOpt)
913 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_TailCall);
914 else
915 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
916
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917 SmallVector<SDOperand, 8> ArgValues;
918 unsigned LastVal = ~0U;
919 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
920 CCValAssign &VA = ArgLocs[i];
921 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
922 // places.
923 assert(VA.getValNo() != LastVal &&
924 "Don't support value assigned to multiple locs yet");
925 LastVal = VA.getValNo();
926
927 if (VA.isRegLoc()) {
928 MVT::ValueType RegVT = VA.getLocVT();
929 TargetRegisterClass *RC;
930 if (RegVT == MVT::i32)
931 RC = X86::GR32RegisterClass;
932 else {
933 assert(MVT::isVector(RegVT));
934 RC = X86::VR128RegisterClass;
935 }
936
937 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
938 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
939
940 // If this is an 8 or 16-bit value, it is really passed promoted to 32
941 // bits. Insert an assert[sz]ext to capture this, then truncate to the
942 // right size.
943 if (VA.getLocInfo() == CCValAssign::SExt)
944 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
945 DAG.getValueType(VA.getValVT()));
946 else if (VA.getLocInfo() == CCValAssign::ZExt)
947 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
948 DAG.getValueType(VA.getValVT()));
949
950 if (VA.getLocInfo() != CCValAssign::Full)
951 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
952
953 ArgValues.push_back(ArgValue);
954 } else {
955 assert(VA.isMemLoc());
Rafael Espindola03cbeb72007-09-14 15:48:13 +0000956 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000957 }
958 }
959
960 unsigned StackSize = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000961 // align stack specially for tail calls
962 if (CC==CallingConv::Fast)
963 StackSize = GetAlignedArgumentStackSize(StackSize,DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000964
965 ArgValues.push_back(Root);
966
967 // If the function takes variable number of arguments, make a frame index for
968 // the start of the first vararg value... for expansion of llvm.va_start.
969 if (isVarArg)
970 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
971
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000972 // Tail call calling convention (CallingConv::Fast) does not support varargs.
973 assert( !(isVarArg && CC == CallingConv::Fast) &&
974 "CallingConv::Fast does not support varargs.");
975
976 if (isStdCall && !isVarArg &&
977 (CC==CallingConv::Fast && PerformTailCallOpt || CC!=CallingConv::Fast)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978 BytesToPopOnReturn = StackSize; // Callee pops everything..
979 BytesCallerReserves = 0;
980 } else {
981 BytesToPopOnReturn = 0; // Callee pops nothing.
982
983 // If this is an sret function, the return should pop the hidden pointer.
984 if (NumArgs &&
985 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
986 ISD::ParamFlags::StructReturn))
987 BytesToPopOnReturn = 4;
988
989 BytesCallerReserves = StackSize;
990 }
Anton Korobeynikove844e472007-08-15 17:12:32 +0000991
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993
Anton Korobeynikove844e472007-08-15 17:12:32 +0000994 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
995 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996
997 // Return the new list of results.
998 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
999 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1000}
1001
1002SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
1003 unsigned CC) {
1004 SDOperand Chain = Op.getOperand(0);
1005 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 SDOperand Callee = Op.getOperand(4);
1007 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001008
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 // Analyze operands of the call, assigning locations to each operand.
1010 SmallVector<CCValAssign, 16> ArgLocs;
1011 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001012 if(CC==CallingConv::Fast && PerformTailCallOpt)
1013 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1014 else
1015 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001016
1017 // Get a count of how many bytes are to be pushed on the stack.
1018 unsigned NumBytes = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001019 if (CC==CallingConv::Fast)
1020 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021
1022 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1023
1024 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1025 SmallVector<SDOperand, 8> MemOpChains;
1026
1027 SDOperand StackPtr;
1028
1029 // Walk the register/memloc assignments, inserting copies/loads.
1030 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1031 CCValAssign &VA = ArgLocs[i];
1032 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1033
1034 // Promote the value if needed.
1035 switch (VA.getLocInfo()) {
1036 default: assert(0 && "Unknown loc info!");
1037 case CCValAssign::Full: break;
1038 case CCValAssign::SExt:
1039 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1040 break;
1041 case CCValAssign::ZExt:
1042 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1043 break;
1044 case CCValAssign::AExt:
1045 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1046 break;
1047 }
1048
1049 if (VA.isRegLoc()) {
1050 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1051 } else {
1052 assert(VA.isMemLoc());
1053 if (StackPtr.Val == 0)
1054 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindola007b7142007-09-21 15:50:22 +00001055
1056 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1057 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 }
1059 }
1060
1061 // If the first argument is an sret pointer, remember it.
1062 bool isSRet = NumOps &&
1063 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
1064 ISD::ParamFlags::StructReturn);
1065
1066 if (!MemOpChains.empty())
1067 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1068 &MemOpChains[0], MemOpChains.size());
1069
1070 // Build a sequence of copy-to-reg nodes chained together with token chain
1071 // and flag operands which copy the outgoing args into registers.
1072 SDOperand InFlag;
1073 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1074 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1075 InFlag);
1076 InFlag = Chain.getValue(1);
1077 }
1078
1079 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1080 // GOT pointer.
1081 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1082 Subtarget->isPICStyleGOT()) {
1083 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1084 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1085 InFlag);
1086 InFlag = Chain.getValue(1);
1087 }
1088
1089 // If the callee is a GlobalAddress node (quite common, every direct call is)
1090 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1091 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1092 // We should use extra load for direct calls to dllimported functions in
1093 // non-JIT mode.
1094 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1095 getTargetMachine(), true))
1096 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1097 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1098 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1099
1100 // Returns a chain & a flag for retval copy to use.
1101 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1102 SmallVector<SDOperand, 8> Ops;
1103 Ops.push_back(Chain);
1104 Ops.push_back(Callee);
1105
1106 // Add argument registers to the end of the list so that they are known live
1107 // into the call.
1108 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1109 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1110 RegsToPass[i].second.getValueType()));
1111
1112 // Add an implicit use GOT pointer in EBX.
1113 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1114 Subtarget->isPICStyleGOT())
1115 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1116
1117 if (InFlag.Val)
1118 Ops.push_back(InFlag);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001119
1120 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121 InFlag = Chain.getValue(1);
1122
1123 // Create the CALLSEQ_END node.
1124 unsigned NumBytesForCalleeToPush = 0;
1125
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001126 if (CC == CallingConv::X86_StdCall ||
1127 (CC == CallingConv::Fast && PerformTailCallOpt)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128 if (isVarArg)
1129 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1130 else
1131 NumBytesForCalleeToPush = NumBytes;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001132 assert(!(isVarArg && CC==CallingConv::Fast) &&
1133 "CallingConv::Fast does not support varargs.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134 } else {
1135 // If this is is a call to a struct-return function, the callee
1136 // pops the hidden struct pointer, so we have to push it back.
1137 // This is common for Darwin/X86, Linux & Mingw32 targets.
1138 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1139 }
Bill Wendling22f8deb2007-11-13 00:44:25 +00001140
1141 Chain = DAG.getCALLSEQ_END(Chain,
1142 DAG.getConstant(NumBytes, getPointerTy()),
1143 DAG.getConstant(NumBytesForCalleeToPush,
1144 getPointerTy()),
1145 InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 InFlag = Chain.getValue(1);
1147
1148 // Handle result values, copying them out of physregs into vregs that we
1149 // return.
1150 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1151}
1152
1153
1154//===----------------------------------------------------------------------===//
1155// FastCall Calling Convention implementation
1156//===----------------------------------------------------------------------===//
1157//
1158// The X86 'fastcall' calling convention passes up to two integer arguments in
1159// registers (an appropriate portion of ECX/EDX), passes arguments in C order,
1160// and requires that the callee pop its arguments off the stack (allowing proper
1161// tail calls), and has the same return value conventions as C calling convs.
1162//
1163// This calling convention always arranges for the callee pop value to be 8n+4
1164// bytes, which is needed for tail recursion elimination and stack alignment
1165// reasons.
1166SDOperand
1167X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
1168 MachineFunction &MF = DAG.getMachineFunction();
1169 MachineFrameInfo *MFI = MF.getFrameInfo();
1170 SDOperand Root = Op.getOperand(0);
1171 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1172
1173 // Assign locations to all of the incoming arguments.
1174 SmallVector<CCValAssign, 16> ArgLocs;
1175 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
1176 getTargetMachine(), ArgLocs);
1177 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
1178
1179 SmallVector<SDOperand, 8> ArgValues;
1180 unsigned LastVal = ~0U;
1181 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1182 CCValAssign &VA = ArgLocs[i];
1183 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1184 // places.
1185 assert(VA.getValNo() != LastVal &&
1186 "Don't support value assigned to multiple locs yet");
1187 LastVal = VA.getValNo();
1188
1189 if (VA.isRegLoc()) {
1190 MVT::ValueType RegVT = VA.getLocVT();
1191 TargetRegisterClass *RC;
1192 if (RegVT == MVT::i32)
1193 RC = X86::GR32RegisterClass;
1194 else {
1195 assert(MVT::isVector(RegVT));
1196 RC = X86::VR128RegisterClass;
1197 }
1198
1199 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1200 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1201
1202 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1203 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1204 // right size.
1205 if (VA.getLocInfo() == CCValAssign::SExt)
1206 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1207 DAG.getValueType(VA.getValVT()));
1208 else if (VA.getLocInfo() == CCValAssign::ZExt)
1209 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1210 DAG.getValueType(VA.getValVT()));
1211
1212 if (VA.getLocInfo() != CCValAssign::Full)
1213 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1214
1215 ArgValues.push_back(ArgValue);
1216 } else {
1217 assert(VA.isMemLoc());
Rafael Espindolab53ef122007-09-21 14:55:38 +00001218 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219 }
1220 }
1221
1222 ArgValues.push_back(Root);
1223
1224 unsigned StackSize = CCInfo.getNextStackOffset();
1225
1226 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1227 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001228 // arguments and the arguments after the retaddr has been pushed are
1229 // aligned.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001230 if ((StackSize & 7) == 0)
1231 StackSize += 4;
1232 }
1233
1234 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1235 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001236 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
1237 BytesCallerReserves = 0;
1238
Anton Korobeynikove844e472007-08-15 17:12:32 +00001239 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1240 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001241
1242 // Return the new list of results.
1243 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1244 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1245}
1246
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001247SDOperand
1248X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1249 const SDOperand &StackPtr,
1250 const CCValAssign &VA,
1251 SDOperand Chain,
1252 SDOperand Arg) {
1253 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1254 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1255 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1256 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1257 if (Flags & ISD::ParamFlags::ByVal) {
1258 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1259 ISD::ParamFlags::ByValAlignOffs);
1260
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001261 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1262 ISD::ParamFlags::ByValSizeOffs;
1263
1264 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1265 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00001266 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001267
Rafael Espindola80825902007-10-19 10:41:11 +00001268 return DAG.getMemcpy(Chain, PtrOff, Arg, SizeNode, AlignNode,
1269 AlwaysInline);
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001270 } else {
1271 return DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1272 }
1273}
1274
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1276 unsigned CC) {
1277 SDOperand Chain = Op.getOperand(0);
1278 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1279 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1280 SDOperand Callee = Op.getOperand(4);
1281
1282 // Analyze operands of the call, assigning locations to each operand.
1283 SmallVector<CCValAssign, 16> ArgLocs;
1284 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1285 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1286
1287 // Get a count of how many bytes are to be pushed on the stack.
1288 unsigned NumBytes = CCInfo.getNextStackOffset();
1289
1290 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1291 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001292 // arguments and the arguments after the retaddr has been pushed are
1293 // aligned.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 if ((NumBytes & 7) == 0)
1295 NumBytes += 4;
1296 }
1297
1298 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1299
1300 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1301 SmallVector<SDOperand, 8> MemOpChains;
1302
1303 SDOperand StackPtr;
1304
1305 // Walk the register/memloc assignments, inserting copies/loads.
1306 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1307 CCValAssign &VA = ArgLocs[i];
1308 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1309
1310 // Promote the value if needed.
1311 switch (VA.getLocInfo()) {
1312 default: assert(0 && "Unknown loc info!");
1313 case CCValAssign::Full: break;
1314 case CCValAssign::SExt:
1315 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1316 break;
1317 case CCValAssign::ZExt:
1318 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1319 break;
1320 case CCValAssign::AExt:
1321 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1322 break;
1323 }
1324
1325 if (VA.isRegLoc()) {
1326 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1327 } else {
1328 assert(VA.isMemLoc());
1329 if (StackPtr.Val == 0)
1330 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindola007b7142007-09-21 15:50:22 +00001331
1332 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1333 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 }
1335 }
1336
1337 if (!MemOpChains.empty())
1338 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1339 &MemOpChains[0], MemOpChains.size());
1340
1341 // Build a sequence of copy-to-reg nodes chained together with token chain
1342 // and flag operands which copy the outgoing args into registers.
1343 SDOperand InFlag;
1344 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1345 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1346 InFlag);
1347 InFlag = Chain.getValue(1);
1348 }
1349
1350 // If the callee is a GlobalAddress node (quite common, every direct call is)
1351 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1352 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1353 // We should use extra load for direct calls to dllimported functions in
1354 // non-JIT mode.
1355 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1356 getTargetMachine(), true))
1357 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1358 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1359 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1360
1361 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1362 // GOT pointer.
1363 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1364 Subtarget->isPICStyleGOT()) {
1365 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1366 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1367 InFlag);
1368 InFlag = Chain.getValue(1);
1369 }
1370
1371 // Returns a chain & a flag for retval copy to use.
1372 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1373 SmallVector<SDOperand, 8> Ops;
1374 Ops.push_back(Chain);
1375 Ops.push_back(Callee);
1376
1377 // Add argument registers to the end of the list so that they are known live
1378 // into the call.
1379 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1380 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1381 RegsToPass[i].second.getValueType()));
1382
1383 // Add an implicit use GOT pointer in EBX.
1384 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1385 Subtarget->isPICStyleGOT())
1386 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1387
1388 if (InFlag.Val)
1389 Ops.push_back(InFlag);
1390
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001391 assert(isTailCall==false && "no tail call here");
1392 Chain = DAG.getNode(X86ISD::CALL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393 NodeTys, &Ops[0], Ops.size());
1394 InFlag = Chain.getValue(1);
1395
1396 // Returns a flag for retval copy to use.
1397 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1398 Ops.clear();
1399 Ops.push_back(Chain);
1400 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1401 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1402 Ops.push_back(InFlag);
1403 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1404 InFlag = Chain.getValue(1);
1405
1406 // Handle result values, copying them out of physregs into vregs that we
1407 // return.
1408 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1409}
1410
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001411//===----------------------------------------------------------------------===//
1412// Fast Calling Convention (tail call) implementation
1413//===----------------------------------------------------------------------===//
1414
1415// Like std call, callee cleans arguments, convention except that ECX is
1416// reserved for storing the tail called function address. Only 2 registers are
1417// free for argument passing (inreg). Tail call optimization is performed
1418// provided:
1419// * tailcallopt is enabled
1420// * caller/callee are fastcc
1421// * elf/pic is disabled OR
1422// * elf/pic enabled + callee is in module + callee has
1423// visibility protected or hidden
Arnold Schwaighofer373e8652007-10-12 21:30:57 +00001424// To keep the stack aligned according to platform abi the function
1425// GetAlignedArgumentStackSize ensures that argument delta is always multiples
1426// of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001427// If a tail called function callee has more arguments than the caller the
1428// caller needs to make sure that there is room to move the RETADDR to. This is
Arnold Schwaighofer373e8652007-10-12 21:30:57 +00001429// achieved by reserving an area the size of the argument delta right after the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001430// original REtADDR, but before the saved framepointer or the spilled registers
1431// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1432// stack layout:
1433// arg1
1434// arg2
1435// RETADDR
1436// [ new RETADDR
1437// move area ]
1438// (possible EBP)
1439// ESI
1440// EDI
1441// local1 ..
1442
1443/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1444/// for a 16 byte align requirement.
1445unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1446 SelectionDAG& DAG) {
1447 if (PerformTailCallOpt) {
1448 MachineFunction &MF = DAG.getMachineFunction();
1449 const TargetMachine &TM = MF.getTarget();
1450 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1451 unsigned StackAlignment = TFI.getStackAlignment();
1452 uint64_t AlignMask = StackAlignment - 1;
1453 int64_t Offset = StackSize;
1454 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1455 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1456 // Number smaller than 12 so just add the difference.
1457 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1458 } else {
1459 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1460 Offset = ((~AlignMask) & Offset) + StackAlignment +
1461 (StackAlignment-SlotSize);
1462 }
1463 StackSize = Offset;
1464 }
1465 return StackSize;
1466}
1467
1468/// IsEligibleForTailCallElimination - Check to see whether the next instruction
Evan Chenge7a87392007-11-02 01:26:22 +00001469/// following the call is a return. A function is eligible if caller/callee
1470/// calling conventions match, currently only fastcc supports tail calls, and
1471/// the function CALL is immediatly followed by a RET.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001472bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1473 SDOperand Ret,
1474 SelectionDAG& DAG) const {
Evan Chenge7a87392007-11-02 01:26:22 +00001475 if (!PerformTailCallOpt)
1476 return false;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001477
1478 // Check whether CALL node immediatly preceeds the RET node and whether the
1479 // return uses the result of the node or is a void return.
Evan Chenge7a87392007-11-02 01:26:22 +00001480 unsigned NumOps = Ret.getNumOperands();
1481 if ((NumOps == 1 &&
1482 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1483 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
Evan Cheng26c0e982007-11-02 17:45:40 +00001484 (NumOps > 1 &&
Evan Chenge7a87392007-11-02 01:26:22 +00001485 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1486 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001487 MachineFunction &MF = DAG.getMachineFunction();
1488 unsigned CallerCC = MF.getFunction()->getCallingConv();
1489 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1490 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1491 SDOperand Callee = Call.getOperand(4);
1492 // On elf/pic %ebx needs to be livein.
Evan Chenge7a87392007-11-02 01:26:22 +00001493 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1494 !Subtarget->isPICStyleGOT())
1495 return true;
1496
1497 // Can only do local tail calls with PIC.
1498 GlobalValue * GV = 0;
1499 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1500 if(G != 0 &&
1501 (GV = G->getGlobal()) &&
1502 (GV->hasHiddenVisibility() || GV->hasProtectedVisibility()))
1503 return true;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001504 }
1505 }
Evan Chenge7a87392007-11-02 01:26:22 +00001506
1507 return false;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001508}
1509
1510SDOperand X86TargetLowering::LowerX86_TailCallTo(SDOperand Op,
1511 SelectionDAG &DAG,
1512 unsigned CC) {
1513 SDOperand Chain = Op.getOperand(0);
1514 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1515 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1516 SDOperand Callee = Op.getOperand(4);
1517 bool is64Bit = Subtarget->is64Bit();
1518
1519 assert(isTailCall && PerformTailCallOpt && "Should only emit tail calls.");
1520
1521 // Analyze operands of the call, assigning locations to each operand.
1522 SmallVector<CCValAssign, 16> ArgLocs;
1523 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1524 if (is64Bit)
1525 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1526 else
1527 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1528
1529
1530 // Lower arguments at fp - stackoffset + fpdiff.
1531 MachineFunction &MF = DAG.getMachineFunction();
1532
1533 unsigned NumBytesToBePushed =
1534 GetAlignedArgumentStackSize(CCInfo.getNextStackOffset(), DAG);
1535
1536 unsigned NumBytesCallerPushed =
1537 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1538 int FPDiff = NumBytesCallerPushed - NumBytesToBePushed;
1539
1540 // Set the delta of movement of the returnaddr stackslot.
1541 // But only set if delta is greater than previous delta.
1542 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1543 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1544
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001545 Chain = DAG.
1546 getCALLSEQ_START(Chain, DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1547
1548 // Adjust the Return address stack slot.
1549 SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001550 if (FPDiff) {
1551 MVT::ValueType VT = is64Bit ? MVT::i64 : MVT::i32;
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001552 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1553 // Load the "old" Return address.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001554 RetAddrFrIdx =
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001555 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1556 // Calculate the new stack slot for the return address.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001557 int SlotSize = is64Bit ? 8 : 4;
1558 int NewReturnAddrFI =
1559 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001560 NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1561 Chain = SDOperand(RetAddrFrIdx.Val, 1);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001562 }
1563
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001564 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1565 SmallVector<SDOperand, 8> MemOpChains;
1566 SmallVector<SDOperand, 8> MemOpChains2;
1567 SDOperand FramePtr, StackPtr;
1568 SDOperand PtrOff;
1569 SDOperand FIN;
1570 int FI = 0;
1571
1572 // Walk the register/memloc assignments, inserting copies/loads. Lower
1573 // arguments first to the stack slot where they would normally - in case of a
1574 // normal function call - be.
1575 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1576 CCValAssign &VA = ArgLocs[i];
1577 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1578
1579 // Promote the value if needed.
1580 switch (VA.getLocInfo()) {
1581 default: assert(0 && "Unknown loc info!");
1582 case CCValAssign::Full: break;
1583 case CCValAssign::SExt:
1584 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1585 break;
1586 case CCValAssign::ZExt:
1587 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1588 break;
1589 case CCValAssign::AExt:
1590 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1591 break;
1592 }
1593
1594 if (VA.isRegLoc()) {
1595 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1596 } else {
1597 assert(VA.isMemLoc());
1598 if (StackPtr.Val == 0)
1599 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1600
1601 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1602 Arg));
1603 }
1604 }
1605
1606 if (!MemOpChains.empty())
1607 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1608 &MemOpChains[0], MemOpChains.size());
1609
1610 // Build a sequence of copy-to-reg nodes chained together with token chain
1611 // and flag operands which copy the outgoing args into registers.
1612 SDOperand InFlag;
1613 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1614 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1615 InFlag);
1616 InFlag = Chain.getValue(1);
1617 }
1618 InFlag = SDOperand();
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001619
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001620 // Copy from stack slots to stack slot of a tail called function. This needs
1621 // to be done because if we would lower the arguments directly to their real
1622 // stack slot we might end up overwriting each other.
1623 // TODO: To make this more efficient (sometimes saving a store/load) we could
1624 // analyse the arguments and emit this store/load/store sequence only for
1625 // arguments which would be overwritten otherwise.
1626 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1627 CCValAssign &VA = ArgLocs[i];
1628 if (!VA.isRegLoc()) {
1629 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1630 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1631
1632 // Get source stack slot.
1633 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1634 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1635 // Create frame index.
1636 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1637 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1638 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1639 FIN = DAG.getFrameIndex(FI, MVT::i32);
1640 if (Flags & ISD::ParamFlags::ByVal) {
1641 // Copy relative to framepointer.
1642 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1643 ISD::ParamFlags::ByValAlignOffs);
1644
1645 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1646 ISD::ParamFlags::ByValSizeOffs;
1647
1648 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1649 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
Arnold Schwaighofer97794942007-11-10 10:48:01 +00001650 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i1);
1651
1652 MemOpChains2.push_back(DAG.getMemcpy(Chain, FIN, PtrOff, SizeNode,
1653 AlignNode,AlwaysInline));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001654 } else {
1655 SDOperand LoadedArg = DAG.getLoad(VA.getValVT(), Chain, PtrOff, NULL,0);
1656 // Store relative to framepointer.
1657 MemOpChains2.push_back(DAG.getStore(Chain, LoadedArg, FIN, NULL, 0));
1658 }
1659 }
1660 }
1661
1662 if (!MemOpChains2.empty())
1663 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1664 &MemOpChains2[0], MemOpChains.size());
1665
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001666 // Store the return address to the appropriate stack slot.
1667 if (FPDiff)
1668 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1669
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001670 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1671 // GOT pointer.
1672 // Does not work with tail call since ebx is not restored correctly by
1673 // tailcaller. TODO: at least for x86 - verify for x86-64
1674
1675 // If the callee is a GlobalAddress node (quite common, every direct call is)
1676 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1677 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1678 // We should use extra load for direct calls to dllimported functions in
1679 // non-JIT mode.
1680 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1681 getTargetMachine(), true))
1682 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1683 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1684 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1685 else {
1686 assert(Callee.getOpcode() == ISD::LOAD &&
1687 "Function destination must be loaded into virtual register");
1688 unsigned Opc = is64Bit ? X86::R9 : X86::ECX;
1689
1690 Chain = DAG.getCopyToReg(Chain,
1691 DAG.getRegister(Opc, getPointerTy()) ,
1692 Callee,InFlag);
1693 Callee = DAG.getRegister(Opc, getPointerTy());
1694 // Add register as live out.
1695 DAG.getMachineFunction().addLiveOut(Opc);
1696 }
1697
1698 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1699 SmallVector<SDOperand, 8> Ops;
1700
1701 Ops.push_back(Chain);
1702 Ops.push_back(DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1703 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1704 if (InFlag.Val)
1705 Ops.push_back(InFlag);
1706 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1707 InFlag = Chain.getValue(1);
1708
1709 // Returns a chain & a flag for retval copy to use.
1710 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1711 Ops.clear();
1712 Ops.push_back(Chain);
1713 Ops.push_back(Callee);
1714 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1715 // Add argument registers to the end of the list so that they are known live
1716 // into the call.
1717 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1718 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1719 RegsToPass[i].second.getValueType()));
1720 if (InFlag.Val)
1721 Ops.push_back(InFlag);
1722 assert(InFlag.Val &&
1723 "Flag must be set. Depend on flag being set in LowerRET");
1724 Chain = DAG.getNode(X86ISD::TAILCALL,
1725 Op.Val->getVTList(), &Ops[0], Ops.size());
1726
1727 return SDOperand(Chain.Val, Op.ResNo);
1728}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001729
1730//===----------------------------------------------------------------------===//
1731// X86-64 C Calling Convention implementation
1732//===----------------------------------------------------------------------===//
1733
1734SDOperand
1735X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1736 MachineFunction &MF = DAG.getMachineFunction();
1737 MachineFrameInfo *MFI = MF.getFrameInfo();
1738 SDOperand Root = Op.getOperand(0);
1739 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001740 unsigned CC= MF.getFunction()->getCallingConv();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001741
1742 static const unsigned GPR64ArgRegs[] = {
1743 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1744 };
1745 static const unsigned XMMArgRegs[] = {
1746 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1747 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1748 };
1749
1750
1751 // Assign locations to all of the incoming arguments.
1752 SmallVector<CCValAssign, 16> ArgLocs;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001753 CCState CCInfo(CC, isVarArg,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001754 getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001755 if (CC == CallingConv::Fast && PerformTailCallOpt)
1756 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_TailCall);
1757 else
1758 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001759
1760 SmallVector<SDOperand, 8> ArgValues;
1761 unsigned LastVal = ~0U;
1762 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1763 CCValAssign &VA = ArgLocs[i];
1764 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1765 // places.
1766 assert(VA.getValNo() != LastVal &&
1767 "Don't support value assigned to multiple locs yet");
1768 LastVal = VA.getValNo();
1769
1770 if (VA.isRegLoc()) {
1771 MVT::ValueType RegVT = VA.getLocVT();
1772 TargetRegisterClass *RC;
1773 if (RegVT == MVT::i32)
1774 RC = X86::GR32RegisterClass;
1775 else if (RegVT == MVT::i64)
1776 RC = X86::GR64RegisterClass;
1777 else if (RegVT == MVT::f32)
1778 RC = X86::FR32RegisterClass;
1779 else if (RegVT == MVT::f64)
1780 RC = X86::FR64RegisterClass;
1781 else {
1782 assert(MVT::isVector(RegVT));
1783 if (MVT::getSizeInBits(RegVT) == 64) {
1784 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1785 RegVT = MVT::i64;
1786 } else
1787 RC = X86::VR128RegisterClass;
1788 }
1789
1790 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1791 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1792
1793 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1794 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1795 // right size.
1796 if (VA.getLocInfo() == CCValAssign::SExt)
1797 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1798 DAG.getValueType(VA.getValVT()));
1799 else if (VA.getLocInfo() == CCValAssign::ZExt)
1800 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1801 DAG.getValueType(VA.getValVT()));
1802
1803 if (VA.getLocInfo() != CCValAssign::Full)
1804 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1805
1806 // Handle MMX values passed in GPRs.
1807 if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1808 MVT::getSizeInBits(RegVT) == 64)
1809 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1810
1811 ArgValues.push_back(ArgValue);
1812 } else {
1813 assert(VA.isMemLoc());
Rafael Espindola03cbeb72007-09-14 15:48:13 +00001814 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001815 }
1816 }
1817
1818 unsigned StackSize = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001819 if (CC==CallingConv::Fast)
1820 StackSize =GetAlignedArgumentStackSize(StackSize, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001821
1822 // If the function takes variable number of arguments, make a frame index for
1823 // the start of the first vararg value... for expansion of llvm.va_start.
1824 if (isVarArg) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001825 assert(CC!=CallingConv::Fast
1826 && "Var arg not supported with calling convention fastcc");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001827 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1828 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1829
1830 // For X86-64, if there are vararg parameters that are passed via
1831 // registers, then we must store them to their spots on the stack so they
1832 // may be loaded by deferencing the result of va_next.
1833 VarArgsGPOffset = NumIntRegs * 8;
1834 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1835 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1836 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1837
1838 // Store the integer parameter registers.
1839 SmallVector<SDOperand, 8> MemOps;
1840 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1841 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1842 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1843 for (; NumIntRegs != 6; ++NumIntRegs) {
1844 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1845 X86::GR64RegisterClass);
1846 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1847 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1848 MemOps.push_back(Store);
1849 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1850 DAG.getConstant(8, getPointerTy()));
1851 }
1852
1853 // Now store the XMM (fp + vector) parameter registers.
1854 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1855 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1856 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1857 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1858 X86::VR128RegisterClass);
1859 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1860 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1861 MemOps.push_back(Store);
1862 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1863 DAG.getConstant(16, getPointerTy()));
1864 }
1865 if (!MemOps.empty())
1866 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1867 &MemOps[0], MemOps.size());
1868 }
1869
1870 ArgValues.push_back(Root);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001871 // Tail call convention (fastcc) needs callee pop.
Evan Cheng778fa0f2007-10-14 10:09:39 +00001872 if (CC == CallingConv::Fast && PerformTailCallOpt) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001873 BytesToPopOnReturn = StackSize; // Callee pops everything.
1874 BytesCallerReserves = 0;
1875 } else {
1876 BytesToPopOnReturn = 0; // Callee pops nothing.
1877 BytesCallerReserves = StackSize;
1878 }
Anton Korobeynikove844e472007-08-15 17:12:32 +00001879 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1880 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1881
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001882 // Return the new list of results.
1883 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1884 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1885}
1886
1887SDOperand
1888X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1889 unsigned CC) {
1890 SDOperand Chain = Op.getOperand(0);
1891 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001892 SDOperand Callee = Op.getOperand(4);
1893
1894 // Analyze operands of the call, assigning locations to each operand.
1895 SmallVector<CCValAssign, 16> ArgLocs;
1896 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Evan Cheng778fa0f2007-10-14 10:09:39 +00001897 if (CC==CallingConv::Fast && PerformTailCallOpt)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001898 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1899 else
1900 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001901
1902 // Get a count of how many bytes are to be pushed on the stack.
1903 unsigned NumBytes = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001904 if (CC == CallingConv::Fast)
1905 NumBytes = GetAlignedArgumentStackSize(NumBytes,DAG);
1906
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001907 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1908
1909 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1910 SmallVector<SDOperand, 8> MemOpChains;
1911
1912 SDOperand StackPtr;
1913
1914 // Walk the register/memloc assignments, inserting copies/loads.
1915 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1916 CCValAssign &VA = ArgLocs[i];
1917 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1918
1919 // Promote the value if needed.
1920 switch (VA.getLocInfo()) {
1921 default: assert(0 && "Unknown loc info!");
1922 case CCValAssign::Full: break;
1923 case CCValAssign::SExt:
1924 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1925 break;
1926 case CCValAssign::ZExt:
1927 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1928 break;
1929 case CCValAssign::AExt:
1930 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1931 break;
1932 }
1933
1934 if (VA.isRegLoc()) {
1935 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1936 } else {
1937 assert(VA.isMemLoc());
1938 if (StackPtr.Val == 0)
1939 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindolab8bcfcd2007-08-20 15:18:24 +00001940
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001941 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1942 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001943 }
1944 }
1945
1946 if (!MemOpChains.empty())
1947 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1948 &MemOpChains[0], MemOpChains.size());
1949
1950 // Build a sequence of copy-to-reg nodes chained together with token chain
1951 // and flag operands which copy the outgoing args into registers.
1952 SDOperand InFlag;
1953 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1954 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1955 InFlag);
1956 InFlag = Chain.getValue(1);
1957 }
1958
1959 if (isVarArg) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001960 assert ( CallingConv::Fast != CC &&
1961 "Var args not supported with calling convention fastcc");
1962
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001963 // From AMD64 ABI document:
1964 // For calls that may call functions that use varargs or stdargs
1965 // (prototype-less calls or calls to functions containing ellipsis (...) in
1966 // the declaration) %al is used as hidden argument to specify the number
1967 // of SSE registers used. The contents of %al do not need to match exactly
1968 // the number of registers, but must be an ubound on the number of SSE
1969 // registers used and is in the range 0 - 8 inclusive.
1970
1971 // Count the number of XMM registers allocated.
1972 static const unsigned XMMArgRegs[] = {
1973 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1974 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1975 };
1976 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1977
1978 Chain = DAG.getCopyToReg(Chain, X86::AL,
1979 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1980 InFlag = Chain.getValue(1);
1981 }
1982
1983 // If the callee is a GlobalAddress node (quite common, every direct call is)
1984 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1985 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1986 // We should use extra load for direct calls to dllimported functions in
1987 // non-JIT mode.
1988 if (getTargetMachine().getCodeModel() != CodeModel::Large
1989 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1990 getTargetMachine(), true))
1991 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1992 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1993 if (getTargetMachine().getCodeModel() != CodeModel::Large)
1994 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1995
1996 // Returns a chain & a flag for retval copy to use.
1997 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1998 SmallVector<SDOperand, 8> Ops;
1999 Ops.push_back(Chain);
2000 Ops.push_back(Callee);
2001
2002 // Add argument registers to the end of the list so that they are known live
2003 // into the call.
2004 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2005 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2006 RegsToPass[i].second.getValueType()));
2007
2008 if (InFlag.Val)
2009 Ops.push_back(InFlag);
2010
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002011 Chain = DAG.getNode(X86ISD::CALL,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002012 NodeTys, &Ops[0], Ops.size());
2013 InFlag = Chain.getValue(1);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002014 int NumBytesForCalleeToPush = 0;
Evan Cheng778fa0f2007-10-14 10:09:39 +00002015 if (CC==CallingConv::Fast && PerformTailCallOpt) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002016 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002017 } else {
2018 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2019 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002020 // Returns a flag for retval copy to use.
2021 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2022 Ops.clear();
2023 Ops.push_back(Chain);
2024 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002025 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002026 Ops.push_back(InFlag);
2027 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
2028 InFlag = Chain.getValue(1);
2029
2030 // Handle result values, copying them out of physregs into vregs that we
2031 // return.
2032 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
2033}
2034
2035
2036//===----------------------------------------------------------------------===//
2037// Other Lowering Hooks
2038//===----------------------------------------------------------------------===//
2039
2040
2041SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
Anton Korobeynikove844e472007-08-15 17:12:32 +00002042 MachineFunction &MF = DAG.getMachineFunction();
2043 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2044 int ReturnAddrIndex = FuncInfo->getRAIndex();
2045
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002046 if (ReturnAddrIndex == 0) {
2047 // Set up a frame object for the return address.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002048 if (Subtarget->is64Bit())
2049 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
2050 else
2051 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
Anton Korobeynikove844e472007-08-15 17:12:32 +00002052
2053 FuncInfo->setRAIndex(ReturnAddrIndex);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002054 }
2055
2056 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2057}
2058
2059
2060
2061/// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
2062/// specific condition code. It returns a false if it cannot do a direct
2063/// translation. X86CC is the translated CondCode. LHS/RHS are modified as
2064/// needed.
2065static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2066 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
2067 SelectionDAG &DAG) {
2068 X86CC = X86::COND_INVALID;
2069 if (!isFP) {
2070 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2071 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2072 // X > -1 -> X == 0, jump !sign.
2073 RHS = DAG.getConstant(0, RHS.getValueType());
2074 X86CC = X86::COND_NS;
2075 return true;
2076 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2077 // X < 0 -> X == 0, jump on sign.
2078 X86CC = X86::COND_S;
2079 return true;
Dan Gohman37b34262007-09-17 14:49:27 +00002080 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
2081 // X < 1 -> X <= 0
2082 RHS = DAG.getConstant(0, RHS.getValueType());
2083 X86CC = X86::COND_LE;
2084 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085 }
2086 }
2087
2088 switch (SetCCOpcode) {
2089 default: break;
2090 case ISD::SETEQ: X86CC = X86::COND_E; break;
2091 case ISD::SETGT: X86CC = X86::COND_G; break;
2092 case ISD::SETGE: X86CC = X86::COND_GE; break;
2093 case ISD::SETLT: X86CC = X86::COND_L; break;
2094 case ISD::SETLE: X86CC = X86::COND_LE; break;
2095 case ISD::SETNE: X86CC = X86::COND_NE; break;
2096 case ISD::SETULT: X86CC = X86::COND_B; break;
2097 case ISD::SETUGT: X86CC = X86::COND_A; break;
2098 case ISD::SETULE: X86CC = X86::COND_BE; break;
2099 case ISD::SETUGE: X86CC = X86::COND_AE; break;
2100 }
2101 } else {
2102 // On a floating point condition, the flags are set as follows:
2103 // ZF PF CF op
2104 // 0 | 0 | 0 | X > Y
2105 // 0 | 0 | 1 | X < Y
2106 // 1 | 0 | 0 | X == Y
2107 // 1 | 1 | 1 | unordered
2108 bool Flip = false;
2109 switch (SetCCOpcode) {
2110 default: break;
2111 case ISD::SETUEQ:
2112 case ISD::SETEQ: X86CC = X86::COND_E; break;
2113 case ISD::SETOLT: Flip = true; // Fallthrough
2114 case ISD::SETOGT:
2115 case ISD::SETGT: X86CC = X86::COND_A; break;
2116 case ISD::SETOLE: Flip = true; // Fallthrough
2117 case ISD::SETOGE:
2118 case ISD::SETGE: X86CC = X86::COND_AE; break;
2119 case ISD::SETUGT: Flip = true; // Fallthrough
2120 case ISD::SETULT:
2121 case ISD::SETLT: X86CC = X86::COND_B; break;
2122 case ISD::SETUGE: Flip = true; // Fallthrough
2123 case ISD::SETULE:
2124 case ISD::SETLE: X86CC = X86::COND_BE; break;
2125 case ISD::SETONE:
2126 case ISD::SETNE: X86CC = X86::COND_NE; break;
2127 case ISD::SETUO: X86CC = X86::COND_P; break;
2128 case ISD::SETO: X86CC = X86::COND_NP; break;
2129 }
2130 if (Flip)
2131 std::swap(LHS, RHS);
2132 }
2133
2134 return X86CC != X86::COND_INVALID;
2135}
2136
2137/// hasFPCMov - is there a floating point cmov for the specific X86 condition
2138/// code. Current x86 isa includes the following FP cmov instructions:
2139/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2140static bool hasFPCMov(unsigned X86CC) {
2141 switch (X86CC) {
2142 default:
2143 return false;
2144 case X86::COND_B:
2145 case X86::COND_BE:
2146 case X86::COND_E:
2147 case X86::COND_P:
2148 case X86::COND_A:
2149 case X86::COND_AE:
2150 case X86::COND_NE:
2151 case X86::COND_NP:
2152 return true;
2153 }
2154}
2155
2156/// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2157/// true if Op is undef or if its value falls within the specified range (L, H].
2158static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2159 if (Op.getOpcode() == ISD::UNDEF)
2160 return true;
2161
2162 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2163 return (Val >= Low && Val < Hi);
2164}
2165
2166/// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2167/// true if Op is undef or if its value equal to the specified value.
2168static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2169 if (Op.getOpcode() == ISD::UNDEF)
2170 return true;
2171 return cast<ConstantSDNode>(Op)->getValue() == Val;
2172}
2173
2174/// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2175/// specifies a shuffle of elements that is suitable for input to PSHUFD.
2176bool X86::isPSHUFDMask(SDNode *N) {
2177 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2178
Dan Gohman7dc19012007-08-02 21:17:01 +00002179 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002180 return false;
2181
2182 // Check if the value doesn't reference the second vector.
2183 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2184 SDOperand Arg = N->getOperand(i);
2185 if (Arg.getOpcode() == ISD::UNDEF) continue;
2186 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Dan Gohman7dc19012007-08-02 21:17:01 +00002187 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002188 return false;
2189 }
2190
2191 return true;
2192}
2193
2194/// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2195/// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2196bool X86::isPSHUFHWMask(SDNode *N) {
2197 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2198
2199 if (N->getNumOperands() != 8)
2200 return false;
2201
2202 // Lower quadword copied in order.
2203 for (unsigned i = 0; i != 4; ++i) {
2204 SDOperand Arg = N->getOperand(i);
2205 if (Arg.getOpcode() == ISD::UNDEF) continue;
2206 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2207 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2208 return false;
2209 }
2210
2211 // Upper quadword shuffled.
2212 for (unsigned i = 4; i != 8; ++i) {
2213 SDOperand Arg = N->getOperand(i);
2214 if (Arg.getOpcode() == ISD::UNDEF) continue;
2215 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2216 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2217 if (Val < 4 || Val > 7)
2218 return false;
2219 }
2220
2221 return true;
2222}
2223
2224/// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2225/// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2226bool X86::isPSHUFLWMask(SDNode *N) {
2227 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2228
2229 if (N->getNumOperands() != 8)
2230 return false;
2231
2232 // Upper quadword copied in order.
2233 for (unsigned i = 4; i != 8; ++i)
2234 if (!isUndefOrEqual(N->getOperand(i), i))
2235 return false;
2236
2237 // Lower quadword shuffled.
2238 for (unsigned i = 0; i != 4; ++i)
2239 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2240 return false;
2241
2242 return true;
2243}
2244
2245/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2246/// specifies a shuffle of elements that is suitable for input to SHUFP*.
2247static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2248 if (NumElems != 2 && NumElems != 4) return false;
2249
2250 unsigned Half = NumElems / 2;
2251 for (unsigned i = 0; i < Half; ++i)
2252 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2253 return false;
2254 for (unsigned i = Half; i < NumElems; ++i)
2255 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2256 return false;
2257
2258 return true;
2259}
2260
2261bool X86::isSHUFPMask(SDNode *N) {
2262 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2263 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2264}
2265
2266/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2267/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2268/// half elements to come from vector 1 (which would equal the dest.) and
2269/// the upper half to come from vector 2.
2270static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2271 if (NumOps != 2 && NumOps != 4) return false;
2272
2273 unsigned Half = NumOps / 2;
2274 for (unsigned i = 0; i < Half; ++i)
2275 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2276 return false;
2277 for (unsigned i = Half; i < NumOps; ++i)
2278 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2279 return false;
2280 return true;
2281}
2282
2283static bool isCommutedSHUFP(SDNode *N) {
2284 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2285 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2286}
2287
2288/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2289/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2290bool X86::isMOVHLPSMask(SDNode *N) {
2291 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2292
2293 if (N->getNumOperands() != 4)
2294 return false;
2295
2296 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2297 return isUndefOrEqual(N->getOperand(0), 6) &&
2298 isUndefOrEqual(N->getOperand(1), 7) &&
2299 isUndefOrEqual(N->getOperand(2), 2) &&
2300 isUndefOrEqual(N->getOperand(3), 3);
2301}
2302
2303/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2304/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2305/// <2, 3, 2, 3>
2306bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2307 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2308
2309 if (N->getNumOperands() != 4)
2310 return false;
2311
2312 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2313 return isUndefOrEqual(N->getOperand(0), 2) &&
2314 isUndefOrEqual(N->getOperand(1), 3) &&
2315 isUndefOrEqual(N->getOperand(2), 2) &&
2316 isUndefOrEqual(N->getOperand(3), 3);
2317}
2318
2319/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2320/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2321bool X86::isMOVLPMask(SDNode *N) {
2322 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2323
2324 unsigned NumElems = N->getNumOperands();
2325 if (NumElems != 2 && NumElems != 4)
2326 return false;
2327
2328 for (unsigned i = 0; i < NumElems/2; ++i)
2329 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2330 return false;
2331
2332 for (unsigned i = NumElems/2; i < NumElems; ++i)
2333 if (!isUndefOrEqual(N->getOperand(i), i))
2334 return false;
2335
2336 return true;
2337}
2338
2339/// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2340/// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2341/// and MOVLHPS.
2342bool X86::isMOVHPMask(SDNode *N) {
2343 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2344
2345 unsigned NumElems = N->getNumOperands();
2346 if (NumElems != 2 && NumElems != 4)
2347 return false;
2348
2349 for (unsigned i = 0; i < NumElems/2; ++i)
2350 if (!isUndefOrEqual(N->getOperand(i), i))
2351 return false;
2352
2353 for (unsigned i = 0; i < NumElems/2; ++i) {
2354 SDOperand Arg = N->getOperand(i + NumElems/2);
2355 if (!isUndefOrEqual(Arg, i + NumElems))
2356 return false;
2357 }
2358
2359 return true;
2360}
2361
2362/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2363/// specifies a shuffle of elements that is suitable for input to UNPCKL.
2364bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2365 bool V2IsSplat = false) {
2366 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2367 return false;
2368
2369 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2370 SDOperand BitI = Elts[i];
2371 SDOperand BitI1 = Elts[i+1];
2372 if (!isUndefOrEqual(BitI, j))
2373 return false;
2374 if (V2IsSplat) {
2375 if (isUndefOrEqual(BitI1, NumElts))
2376 return false;
2377 } else {
2378 if (!isUndefOrEqual(BitI1, j + NumElts))
2379 return false;
2380 }
2381 }
2382
2383 return true;
2384}
2385
2386bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2387 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2388 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2389}
2390
2391/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2392/// specifies a shuffle of elements that is suitable for input to UNPCKH.
2393bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2394 bool V2IsSplat = false) {
2395 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2396 return false;
2397
2398 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2399 SDOperand BitI = Elts[i];
2400 SDOperand BitI1 = Elts[i+1];
2401 if (!isUndefOrEqual(BitI, j + NumElts/2))
2402 return false;
2403 if (V2IsSplat) {
2404 if (isUndefOrEqual(BitI1, NumElts))
2405 return false;
2406 } else {
2407 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2408 return false;
2409 }
2410 }
2411
2412 return true;
2413}
2414
2415bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2416 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2417 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2418}
2419
2420/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2421/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2422/// <0, 0, 1, 1>
2423bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2424 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2425
2426 unsigned NumElems = N->getNumOperands();
2427 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2428 return false;
2429
2430 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2431 SDOperand BitI = N->getOperand(i);
2432 SDOperand BitI1 = N->getOperand(i+1);
2433
2434 if (!isUndefOrEqual(BitI, j))
2435 return false;
2436 if (!isUndefOrEqual(BitI1, j))
2437 return false;
2438 }
2439
2440 return true;
2441}
2442
2443/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2444/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2445/// <2, 2, 3, 3>
2446bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2447 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2448
2449 unsigned NumElems = N->getNumOperands();
2450 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2451 return false;
2452
2453 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2454 SDOperand BitI = N->getOperand(i);
2455 SDOperand BitI1 = N->getOperand(i + 1);
2456
2457 if (!isUndefOrEqual(BitI, j))
2458 return false;
2459 if (!isUndefOrEqual(BitI1, j))
2460 return false;
2461 }
2462
2463 return true;
2464}
2465
2466/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2467/// specifies a shuffle of elements that is suitable for input to MOVSS,
2468/// MOVSD, and MOVD, i.e. setting the lowest element.
2469static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
Evan Cheng62cdc642007-12-06 22:14:22 +00002470 if (NumElts != 2 && NumElts != 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002471 return false;
2472
2473 if (!isUndefOrEqual(Elts[0], NumElts))
2474 return false;
2475
2476 for (unsigned i = 1; i < NumElts; ++i) {
2477 if (!isUndefOrEqual(Elts[i], i))
2478 return false;
2479 }
2480
2481 return true;
2482}
2483
2484bool X86::isMOVLMask(SDNode *N) {
2485 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2486 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2487}
2488
2489/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2490/// of what x86 movss want. X86 movs requires the lowest element to be lowest
2491/// element of vector 2 and the other elements to come from vector 1 in order.
2492static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2493 bool V2IsSplat = false,
2494 bool V2IsUndef = false) {
2495 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2496 return false;
2497
2498 if (!isUndefOrEqual(Ops[0], 0))
2499 return false;
2500
2501 for (unsigned i = 1; i < NumOps; ++i) {
2502 SDOperand Arg = Ops[i];
2503 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2504 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2505 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2506 return false;
2507 }
2508
2509 return true;
2510}
2511
2512static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2513 bool V2IsUndef = false) {
2514 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2515 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2516 V2IsSplat, V2IsUndef);
2517}
2518
2519/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2520/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2521bool X86::isMOVSHDUPMask(SDNode *N) {
2522 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2523
2524 if (N->getNumOperands() != 4)
2525 return false;
2526
2527 // Expect 1, 1, 3, 3
2528 for (unsigned i = 0; i < 2; ++i) {
2529 SDOperand Arg = N->getOperand(i);
2530 if (Arg.getOpcode() == ISD::UNDEF) continue;
2531 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2532 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2533 if (Val != 1) return false;
2534 }
2535
2536 bool HasHi = false;
2537 for (unsigned i = 2; i < 4; ++i) {
2538 SDOperand Arg = N->getOperand(i);
2539 if (Arg.getOpcode() == ISD::UNDEF) continue;
2540 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2541 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2542 if (Val != 3) return false;
2543 HasHi = true;
2544 }
2545
2546 // Don't use movshdup if it can be done with a shufps.
2547 return HasHi;
2548}
2549
2550/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2551/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2552bool X86::isMOVSLDUPMask(SDNode *N) {
2553 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2554
2555 if (N->getNumOperands() != 4)
2556 return false;
2557
2558 // Expect 0, 0, 2, 2
2559 for (unsigned i = 0; i < 2; ++i) {
2560 SDOperand Arg = N->getOperand(i);
2561 if (Arg.getOpcode() == ISD::UNDEF) continue;
2562 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2563 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2564 if (Val != 0) return false;
2565 }
2566
2567 bool HasHi = false;
2568 for (unsigned i = 2; i < 4; ++i) {
2569 SDOperand Arg = N->getOperand(i);
2570 if (Arg.getOpcode() == ISD::UNDEF) continue;
2571 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2572 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2573 if (Val != 2) return false;
2574 HasHi = true;
2575 }
2576
2577 // Don't use movshdup if it can be done with a shufps.
2578 return HasHi;
2579}
2580
2581/// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2582/// specifies a identity operation on the LHS or RHS.
2583static bool isIdentityMask(SDNode *N, bool RHS = false) {
2584 unsigned NumElems = N->getNumOperands();
2585 for (unsigned i = 0; i < NumElems; ++i)
2586 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2587 return false;
2588 return true;
2589}
2590
2591/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2592/// a splat of a single element.
2593static bool isSplatMask(SDNode *N) {
2594 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2595
2596 // This is a splat operation if each element of the permute is the same, and
2597 // if the value doesn't reference the second vector.
2598 unsigned NumElems = N->getNumOperands();
2599 SDOperand ElementBase;
2600 unsigned i = 0;
2601 for (; i != NumElems; ++i) {
2602 SDOperand Elt = N->getOperand(i);
2603 if (isa<ConstantSDNode>(Elt)) {
2604 ElementBase = Elt;
2605 break;
2606 }
2607 }
2608
2609 if (!ElementBase.Val)
2610 return false;
2611
2612 for (; i != NumElems; ++i) {
2613 SDOperand Arg = N->getOperand(i);
2614 if (Arg.getOpcode() == ISD::UNDEF) continue;
2615 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2616 if (Arg != ElementBase) return false;
2617 }
2618
2619 // Make sure it is a splat of the first vector operand.
2620 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2621}
2622
2623/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2624/// a splat of a single element and it's a 2 or 4 element mask.
2625bool X86::isSplatMask(SDNode *N) {
2626 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2627
2628 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2629 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2630 return false;
2631 return ::isSplatMask(N);
2632}
2633
2634/// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2635/// specifies a splat of zero element.
2636bool X86::isSplatLoMask(SDNode *N) {
2637 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2638
2639 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2640 if (!isUndefOrEqual(N->getOperand(i), 0))
2641 return false;
2642 return true;
2643}
2644
2645/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2646/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2647/// instructions.
2648unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2649 unsigned NumOperands = N->getNumOperands();
2650 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2651 unsigned Mask = 0;
2652 for (unsigned i = 0; i < NumOperands; ++i) {
2653 unsigned Val = 0;
2654 SDOperand Arg = N->getOperand(NumOperands-i-1);
2655 if (Arg.getOpcode() != ISD::UNDEF)
2656 Val = cast<ConstantSDNode>(Arg)->getValue();
2657 if (Val >= NumOperands) Val -= NumOperands;
2658 Mask |= Val;
2659 if (i != NumOperands - 1)
2660 Mask <<= Shift;
2661 }
2662
2663 return Mask;
2664}
2665
2666/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2667/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2668/// instructions.
2669unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2670 unsigned Mask = 0;
2671 // 8 nodes, but we only care about the last 4.
2672 for (unsigned i = 7; i >= 4; --i) {
2673 unsigned Val = 0;
2674 SDOperand Arg = N->getOperand(i);
2675 if (Arg.getOpcode() != ISD::UNDEF)
2676 Val = cast<ConstantSDNode>(Arg)->getValue();
2677 Mask |= (Val - 4);
2678 if (i != 4)
2679 Mask <<= 2;
2680 }
2681
2682 return Mask;
2683}
2684
2685/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2686/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2687/// instructions.
2688unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2689 unsigned Mask = 0;
2690 // 8 nodes, but we only care about the first 4.
2691 for (int i = 3; i >= 0; --i) {
2692 unsigned Val = 0;
2693 SDOperand Arg = N->getOperand(i);
2694 if (Arg.getOpcode() != ISD::UNDEF)
2695 Val = cast<ConstantSDNode>(Arg)->getValue();
2696 Mask |= Val;
2697 if (i != 0)
2698 Mask <<= 2;
2699 }
2700
2701 return Mask;
2702}
2703
2704/// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2705/// specifies a 8 element shuffle that can be broken into a pair of
2706/// PSHUFHW and PSHUFLW.
2707static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2708 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2709
2710 if (N->getNumOperands() != 8)
2711 return false;
2712
2713 // Lower quadword shuffled.
2714 for (unsigned i = 0; i != 4; ++i) {
2715 SDOperand Arg = N->getOperand(i);
2716 if (Arg.getOpcode() == ISD::UNDEF) continue;
2717 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2718 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
Evan Cheng75184a92007-12-11 01:46:18 +00002719 if (Val >= 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002720 return false;
2721 }
2722
2723 // Upper quadword shuffled.
2724 for (unsigned i = 4; i != 8; ++i) {
2725 SDOperand Arg = N->getOperand(i);
2726 if (Arg.getOpcode() == ISD::UNDEF) continue;
2727 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2728 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2729 if (Val < 4 || Val > 7)
2730 return false;
2731 }
2732
2733 return true;
2734}
2735
Chris Lattnere6aa3862007-11-25 00:24:49 +00002736/// CommuteVectorShuffle - Swap vector_shuffle operands as well as
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002737/// values in ther permute mask.
2738static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2739 SDOperand &V2, SDOperand &Mask,
2740 SelectionDAG &DAG) {
2741 MVT::ValueType VT = Op.getValueType();
2742 MVT::ValueType MaskVT = Mask.getValueType();
2743 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2744 unsigned NumElems = Mask.getNumOperands();
2745 SmallVector<SDOperand, 8> MaskVec;
2746
2747 for (unsigned i = 0; i != NumElems; ++i) {
2748 SDOperand Arg = Mask.getOperand(i);
2749 if (Arg.getOpcode() == ISD::UNDEF) {
2750 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2751 continue;
2752 }
2753 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2754 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2755 if (Val < NumElems)
2756 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2757 else
2758 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2759 }
2760
2761 std::swap(V1, V2);
Evan Chengfca29242007-12-07 08:07:39 +00002762 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002763 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2764}
2765
Evan Chenga6769df2007-12-07 21:30:01 +00002766/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2767/// the two vector operands have swapped position.
Evan Chengfca29242007-12-07 08:07:39 +00002768static
2769SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2770 MVT::ValueType MaskVT = Mask.getValueType();
2771 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2772 unsigned NumElems = Mask.getNumOperands();
2773 SmallVector<SDOperand, 8> MaskVec;
2774 for (unsigned i = 0; i != NumElems; ++i) {
2775 SDOperand Arg = Mask.getOperand(i);
2776 if (Arg.getOpcode() == ISD::UNDEF) {
2777 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2778 continue;
2779 }
2780 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2781 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2782 if (Val < NumElems)
2783 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2784 else
2785 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2786 }
2787 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2788}
2789
2790
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002791/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2792/// match movhlps. The lower half elements should come from upper half of
2793/// V1 (and in order), and the upper half elements should come from the upper
2794/// half of V2 (and in order).
2795static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2796 unsigned NumElems = Mask->getNumOperands();
2797 if (NumElems != 4)
2798 return false;
2799 for (unsigned i = 0, e = 2; i != e; ++i)
2800 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2801 return false;
2802 for (unsigned i = 2; i != 4; ++i)
2803 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2804 return false;
2805 return true;
2806}
2807
2808/// isScalarLoadToVector - Returns true if the node is a scalar load that
2809/// is promoted to a vector.
2810static inline bool isScalarLoadToVector(SDNode *N) {
2811 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2812 N = N->getOperand(0).Val;
2813 return ISD::isNON_EXTLoad(N);
2814 }
2815 return false;
2816}
2817
2818/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2819/// match movlp{s|d}. The lower half elements should come from lower half of
2820/// V1 (and in order), and the upper half elements should come from the upper
2821/// half of V2 (and in order). And since V1 will become the source of the
2822/// MOVLP, it must be either a vector load or a scalar load to vector.
2823static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2824 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2825 return false;
2826 // Is V2 is a vector load, don't do this transformation. We will try to use
2827 // load folding shufps op.
2828 if (ISD::isNON_EXTLoad(V2))
2829 return false;
2830
2831 unsigned NumElems = Mask->getNumOperands();
2832 if (NumElems != 2 && NumElems != 4)
2833 return false;
2834 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2835 if (!isUndefOrEqual(Mask->getOperand(i), i))
2836 return false;
2837 for (unsigned i = NumElems/2; i != NumElems; ++i)
2838 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2839 return false;
2840 return true;
2841}
2842
2843/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2844/// all the same.
2845static bool isSplatVector(SDNode *N) {
2846 if (N->getOpcode() != ISD::BUILD_VECTOR)
2847 return false;
2848
2849 SDOperand SplatValue = N->getOperand(0);
2850 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2851 if (N->getOperand(i) != SplatValue)
2852 return false;
2853 return true;
2854}
2855
2856/// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2857/// to an undef.
2858static bool isUndefShuffle(SDNode *N) {
2859 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2860 return false;
2861
2862 SDOperand V1 = N->getOperand(0);
2863 SDOperand V2 = N->getOperand(1);
2864 SDOperand Mask = N->getOperand(2);
2865 unsigned NumElems = Mask.getNumOperands();
2866 for (unsigned i = 0; i != NumElems; ++i) {
2867 SDOperand Arg = Mask.getOperand(i);
2868 if (Arg.getOpcode() != ISD::UNDEF) {
2869 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2870 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2871 return false;
2872 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2873 return false;
2874 }
2875 }
2876 return true;
2877}
2878
2879/// isZeroNode - Returns true if Elt is a constant zero or a floating point
2880/// constant +0.0.
2881static inline bool isZeroNode(SDOperand Elt) {
2882 return ((isa<ConstantSDNode>(Elt) &&
2883 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2884 (isa<ConstantFPSDNode>(Elt) &&
Dale Johannesendf8a8312007-08-31 04:03:46 +00002885 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886}
2887
2888/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2889/// to an zero vector.
2890static bool isZeroShuffle(SDNode *N) {
2891 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2892 return false;
2893
2894 SDOperand V1 = N->getOperand(0);
2895 SDOperand V2 = N->getOperand(1);
2896 SDOperand Mask = N->getOperand(2);
2897 unsigned NumElems = Mask.getNumOperands();
2898 for (unsigned i = 0; i != NumElems; ++i) {
2899 SDOperand Arg = Mask.getOperand(i);
Chris Lattnere6aa3862007-11-25 00:24:49 +00002900 if (Arg.getOpcode() == ISD::UNDEF)
2901 continue;
2902
2903 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2904 if (Idx < NumElems) {
2905 unsigned Opc = V1.Val->getOpcode();
2906 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2907 continue;
2908 if (Opc != ISD::BUILD_VECTOR ||
2909 !isZeroNode(V1.Val->getOperand(Idx)))
2910 return false;
2911 } else if (Idx >= NumElems) {
2912 unsigned Opc = V2.Val->getOpcode();
2913 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2914 continue;
2915 if (Opc != ISD::BUILD_VECTOR ||
2916 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2917 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002918 }
2919 }
2920 return true;
2921}
2922
2923/// getZeroVector - Returns a vector of specified type with all zero elements.
2924///
2925static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2926 assert(MVT::isVector(VT) && "Expected a vector type");
Chris Lattnere6aa3862007-11-25 00:24:49 +00002927
2928 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2929 // type. This ensures they get CSE'd.
2930 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2931 SDOperand Vec;
2932 if (MVT::getSizeInBits(VT) == 64) // MMX
2933 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2934 else // SSE
2935 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2936 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002937}
2938
Chris Lattnere6aa3862007-11-25 00:24:49 +00002939/// getOnesVector - Returns a vector of specified type with all bits set.
2940///
2941static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2942 assert(MVT::isVector(VT) && "Expected a vector type");
2943
2944 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2945 // type. This ensures they get CSE'd.
2946 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2947 SDOperand Vec;
2948 if (MVT::getSizeInBits(VT) == 64) // MMX
2949 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2950 else // SSE
2951 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2952 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2953}
2954
2955
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002956/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2957/// that point to V2 points to its first element.
2958static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2959 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2960
2961 bool Changed = false;
2962 SmallVector<SDOperand, 8> MaskVec;
2963 unsigned NumElems = Mask.getNumOperands();
2964 for (unsigned i = 0; i != NumElems; ++i) {
2965 SDOperand Arg = Mask.getOperand(i);
2966 if (Arg.getOpcode() != ISD::UNDEF) {
2967 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2968 if (Val > NumElems) {
2969 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2970 Changed = true;
2971 }
2972 }
2973 MaskVec.push_back(Arg);
2974 }
2975
2976 if (Changed)
2977 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2978 &MaskVec[0], MaskVec.size());
2979 return Mask;
2980}
2981
2982/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2983/// operation of specified width.
2984static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2985 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2986 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2987
2988 SmallVector<SDOperand, 8> MaskVec;
2989 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2990 for (unsigned i = 1; i != NumElems; ++i)
2991 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2992 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2993}
2994
2995/// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2996/// of specified width.
2997static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2998 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2999 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3000 SmallVector<SDOperand, 8> MaskVec;
3001 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3002 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3003 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
3004 }
3005 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3006}
3007
3008/// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3009/// of specified width.
3010static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
3011 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3012 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3013 unsigned Half = NumElems/2;
3014 SmallVector<SDOperand, 8> MaskVec;
3015 for (unsigned i = 0; i != Half; ++i) {
3016 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3017 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3018 }
3019 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3020}
3021
3022/// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
3023///
3024static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
3025 SDOperand V1 = Op.getOperand(0);
3026 SDOperand Mask = Op.getOperand(2);
3027 MVT::ValueType VT = Op.getValueType();
3028 unsigned NumElems = Mask.getNumOperands();
3029 Mask = getUnpacklMask(NumElems, DAG);
3030 while (NumElems != 4) {
3031 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
3032 NumElems >>= 1;
3033 }
3034 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
3035
Chris Lattnere6aa3862007-11-25 00:24:49 +00003036 Mask = getZeroVector(MVT::v4i32, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003037 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
3038 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
3039 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3040}
3041
3042/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
Chris Lattnere6aa3862007-11-25 00:24:49 +00003043/// vector of zero or undef vector. This produces a shuffle where the low
3044/// element of V2 is swizzled into the zero/undef vector, landing at element
3045/// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003046static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
3047 unsigned NumElems, unsigned Idx,
3048 bool isZero, SelectionDAG &DAG) {
3049 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
3050 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3051 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
Chris Lattnere6aa3862007-11-25 00:24:49 +00003052 SmallVector<SDOperand, 16> MaskVec;
3053 for (unsigned i = 0; i != NumElems; ++i)
3054 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3055 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3056 else
3057 MaskVec.push_back(DAG.getConstant(i, EVT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003058 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3059 &MaskVec[0], MaskVec.size());
3060 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3061}
3062
3063/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3064///
3065static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
3066 unsigned NumNonZero, unsigned NumZero,
3067 SelectionDAG &DAG, TargetLowering &TLI) {
3068 if (NumNonZero > 8)
3069 return SDOperand();
3070
3071 SDOperand V(0, 0);
3072 bool First = true;
3073 for (unsigned i = 0; i < 16; ++i) {
3074 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3075 if (ThisIsNonZero && First) {
3076 if (NumZero)
3077 V = getZeroVector(MVT::v8i16, DAG);
3078 else
3079 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3080 First = false;
3081 }
3082
3083 if ((i & 1) != 0) {
3084 SDOperand ThisElt(0, 0), LastElt(0, 0);
3085 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3086 if (LastIsNonZero) {
3087 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3088 }
3089 if (ThisIsNonZero) {
3090 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3091 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3092 ThisElt, DAG.getConstant(8, MVT::i8));
3093 if (LastIsNonZero)
3094 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3095 } else
3096 ThisElt = LastElt;
3097
3098 if (ThisElt.Val)
3099 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3100 DAG.getConstant(i/2, TLI.getPointerTy()));
3101 }
3102 }
3103
3104 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3105}
3106
3107/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3108///
3109static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3110 unsigned NumNonZero, unsigned NumZero,
3111 SelectionDAG &DAG, TargetLowering &TLI) {
3112 if (NumNonZero > 4)
3113 return SDOperand();
3114
3115 SDOperand V(0, 0);
3116 bool First = true;
3117 for (unsigned i = 0; i < 8; ++i) {
3118 bool isNonZero = (NonZeros & (1 << i)) != 0;
3119 if (isNonZero) {
3120 if (First) {
3121 if (NumZero)
3122 V = getZeroVector(MVT::v8i16, DAG);
3123 else
3124 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3125 First = false;
3126 }
3127 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3128 DAG.getConstant(i, TLI.getPointerTy()));
3129 }
3130 }
3131
3132 return V;
3133}
3134
Evan Cheng75184a92007-12-11 01:46:18 +00003135/// is4WideVector - Returns true if the specific v8i16 or v16i8 vector is
3136/// actually just a 4 wide vector. e.g. <a, a, y, y, d, d, x, x>
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003137SDOperand
3138X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
Chris Lattnere6aa3862007-11-25 00:24:49 +00003139 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3140 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3141 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3142 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3143 // eliminated on x86-32 hosts.
3144 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3145 return Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003146
Chris Lattnere6aa3862007-11-25 00:24:49 +00003147 if (ISD::isBuildVectorAllOnes(Op.Val))
3148 return getOnesVector(Op.getValueType(), DAG);
3149 return getZeroVector(Op.getValueType(), DAG);
3150 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003151
3152 MVT::ValueType VT = Op.getValueType();
3153 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3154 unsigned EVTBits = MVT::getSizeInBits(EVT);
3155
3156 unsigned NumElems = Op.getNumOperands();
3157 unsigned NumZero = 0;
3158 unsigned NumNonZero = 0;
3159 unsigned NonZeros = 0;
Evan Chengc1073492007-12-12 06:45:40 +00003160 bool HasNonImms = false;
Evan Cheng75184a92007-12-11 01:46:18 +00003161 SmallSet<SDOperand, 8> Values;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003162 for (unsigned i = 0; i < NumElems; ++i) {
3163 SDOperand Elt = Op.getOperand(i);
Evan Chengc1073492007-12-12 06:45:40 +00003164 if (Elt.getOpcode() == ISD::UNDEF)
3165 continue;
3166 Values.insert(Elt);
3167 if (Elt.getOpcode() != ISD::Constant &&
3168 Elt.getOpcode() != ISD::ConstantFP)
3169 HasNonImms = true;
3170 if (isZeroNode(Elt))
3171 NumZero++;
3172 else {
3173 NonZeros |= (1 << i);
3174 NumNonZero++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003175 }
3176 }
3177
3178 if (NumNonZero == 0) {
Chris Lattnere6aa3862007-11-25 00:24:49 +00003179 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3180 return DAG.getNode(ISD::UNDEF, VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003181 }
3182
3183 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3184 if (Values.size() == 1)
3185 return SDOperand();
3186
3187 // Special case for single non-zero element.
Evan Chengc1073492007-12-12 06:45:40 +00003188 if (NumNonZero == 1 && NumElems <= 4) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003189 unsigned Idx = CountTrailingZeros_32(NonZeros);
3190 SDOperand Item = Op.getOperand(Idx);
3191 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3192 if (Idx == 0)
3193 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3194 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
3195 NumZero > 0, DAG);
Evan Chengc1073492007-12-12 06:45:40 +00003196 else if (!HasNonImms) // Otherwise, it's better to do a constpool load.
3197 return SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003198
3199 if (EVTBits == 32) {
3200 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3201 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
3202 DAG);
3203 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3204 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3205 SmallVector<SDOperand, 8> MaskVec;
3206 for (unsigned i = 0; i < NumElems; i++)
3207 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3208 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3209 &MaskVec[0], MaskVec.size());
3210 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3211 DAG.getNode(ISD::UNDEF, VT), Mask);
3212 }
3213 }
3214
Dan Gohman21463242007-07-24 22:55:08 +00003215 // A vector full of immediates; various special cases are already
3216 // handled, so this is best done with a single constant-pool load.
Evan Chengc1073492007-12-12 06:45:40 +00003217 if (!HasNonImms)
Dan Gohman21463242007-07-24 22:55:08 +00003218 return SDOperand();
3219
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003220 // Let legalizer expand 2-wide build_vectors.
3221 if (EVTBits == 64)
3222 return SDOperand();
3223
3224 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3225 if (EVTBits == 8 && NumElems == 16) {
3226 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3227 *this);
3228 if (V.Val) return V;
3229 }
3230
3231 if (EVTBits == 16 && NumElems == 8) {
3232 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3233 *this);
3234 if (V.Val) return V;
3235 }
3236
3237 // If element VT is == 32 bits, turn it into a number of shuffles.
3238 SmallVector<SDOperand, 8> V;
3239 V.resize(NumElems);
3240 if (NumElems == 4 && NumZero > 0) {
3241 for (unsigned i = 0; i < 4; ++i) {
3242 bool isZero = !(NonZeros & (1 << i));
3243 if (isZero)
3244 V[i] = getZeroVector(VT, DAG);
3245 else
3246 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3247 }
3248
3249 for (unsigned i = 0; i < 2; ++i) {
3250 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3251 default: break;
3252 case 0:
3253 V[i] = V[i*2]; // Must be a zero vector.
3254 break;
3255 case 1:
3256 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3257 getMOVLMask(NumElems, DAG));
3258 break;
3259 case 2:
3260 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3261 getMOVLMask(NumElems, DAG));
3262 break;
3263 case 3:
3264 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3265 getUnpacklMask(NumElems, DAG));
3266 break;
3267 }
3268 }
3269
3270 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3271 // clears the upper bits.
3272 // FIXME: we can do the same for v4f32 case when we know both parts of
3273 // the lower half come from scalar_to_vector (loadf32). We should do
3274 // that in post legalizer dag combiner with target specific hooks.
3275 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3276 return V[0];
3277 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3278 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3279 SmallVector<SDOperand, 8> MaskVec;
3280 bool Reverse = (NonZeros & 0x3) == 2;
3281 for (unsigned i = 0; i < 2; ++i)
3282 if (Reverse)
3283 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3284 else
3285 MaskVec.push_back(DAG.getConstant(i, EVT));
3286 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3287 for (unsigned i = 0; i < 2; ++i)
3288 if (Reverse)
3289 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3290 else
3291 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3292 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3293 &MaskVec[0], MaskVec.size());
3294 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3295 }
3296
3297 if (Values.size() > 2) {
3298 // Expand into a number of unpckl*.
3299 // e.g. for v4f32
3300 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3301 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3302 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3303 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3304 for (unsigned i = 0; i < NumElems; ++i)
3305 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3306 NumElems >>= 1;
3307 while (NumElems != 0) {
3308 for (unsigned i = 0; i < NumElems; ++i)
3309 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3310 UnpckMask);
3311 NumElems >>= 1;
3312 }
3313 return V[0];
3314 }
3315
3316 return SDOperand();
3317}
3318
Evan Chengfca29242007-12-07 08:07:39 +00003319static
3320SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3321 SDOperand PermMask, SelectionDAG &DAG,
3322 TargetLowering &TLI) {
Evan Cheng75184a92007-12-11 01:46:18 +00003323 SDOperand NewV;
Evan Chengfca29242007-12-07 08:07:39 +00003324 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3325 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
Evan Cheng75184a92007-12-11 01:46:18 +00003326 MVT::ValueType PtrVT = TLI.getPointerTy();
3327 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3328 PermMask.Val->op_end());
3329
3330 // First record which half of which vector the low elements come from.
3331 SmallVector<unsigned, 4> LowQuad(4);
3332 for (unsigned i = 0; i < 4; ++i) {
3333 SDOperand Elt = MaskElts[i];
3334 if (Elt.getOpcode() == ISD::UNDEF)
3335 continue;
3336 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3337 int QuadIdx = EltIdx / 4;
3338 ++LowQuad[QuadIdx];
3339 }
3340 int BestLowQuad = -1;
3341 unsigned MaxQuad = 1;
3342 for (unsigned i = 0; i < 4; ++i) {
3343 if (LowQuad[i] > MaxQuad) {
3344 BestLowQuad = i;
3345 MaxQuad = LowQuad[i];
3346 }
Evan Chengfca29242007-12-07 08:07:39 +00003347 }
3348
Evan Cheng75184a92007-12-11 01:46:18 +00003349 // Record which half of which vector the high elements come from.
3350 SmallVector<unsigned, 4> HighQuad(4);
3351 for (unsigned i = 4; i < 8; ++i) {
3352 SDOperand Elt = MaskElts[i];
3353 if (Elt.getOpcode() == ISD::UNDEF)
3354 continue;
3355 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3356 int QuadIdx = EltIdx / 4;
3357 ++HighQuad[QuadIdx];
3358 }
3359 int BestHighQuad = -1;
3360 MaxQuad = 1;
3361 for (unsigned i = 0; i < 4; ++i) {
3362 if (HighQuad[i] > MaxQuad) {
3363 BestHighQuad = i;
3364 MaxQuad = HighQuad[i];
3365 }
3366 }
3367
3368 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3369 if (BestLowQuad != -1 || BestHighQuad != -1) {
3370 // First sort the 4 chunks in order using shufpd.
3371 SmallVector<SDOperand, 8> MaskVec;
3372 if (BestLowQuad != -1)
3373 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3374 else
3375 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3376 if (BestHighQuad != -1)
3377 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3378 else
3379 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3380 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3381 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3382 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3383 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3384 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3385
3386 // Now sort high and low parts separately.
3387 BitVector InOrder(8);
3388 if (BestLowQuad != -1) {
3389 // Sort lower half in order using PSHUFLW.
3390 MaskVec.clear();
3391 bool AnyOutOrder = false;
3392 for (unsigned i = 0; i != 4; ++i) {
3393 SDOperand Elt = MaskElts[i];
3394 if (Elt.getOpcode() == ISD::UNDEF) {
3395 MaskVec.push_back(Elt);
3396 InOrder.set(i);
3397 } else {
3398 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3399 if (EltIdx != i)
3400 AnyOutOrder = true;
3401 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3402 // If this element is in the right place after this shuffle, then
3403 // remember it.
3404 if ((int)(EltIdx / 4) == BestLowQuad)
3405 InOrder.set(i);
3406 }
3407 }
3408 if (AnyOutOrder) {
3409 for (unsigned i = 4; i != 8; ++i)
3410 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3411 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3412 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3413 }
3414 }
3415
3416 if (BestHighQuad != -1) {
3417 // Sort high half in order using PSHUFHW if possible.
3418 MaskVec.clear();
3419 for (unsigned i = 0; i != 4; ++i)
3420 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3421 bool AnyOutOrder = false;
3422 for (unsigned i = 4; i != 8; ++i) {
3423 SDOperand Elt = MaskElts[i];
3424 if (Elt.getOpcode() == ISD::UNDEF) {
3425 MaskVec.push_back(Elt);
3426 InOrder.set(i);
3427 } else {
3428 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3429 if (EltIdx != i)
3430 AnyOutOrder = true;
3431 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3432 // If this element is in the right place after this shuffle, then
3433 // remember it.
3434 if ((int)(EltIdx / 4) == BestHighQuad)
3435 InOrder.set(i);
3436 }
3437 }
3438 if (AnyOutOrder) {
3439 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3440 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3441 }
3442 }
3443
3444 // The other elements are put in the right place using pextrw and pinsrw.
3445 for (unsigned i = 0; i != 8; ++i) {
3446 if (InOrder[i])
3447 continue;
3448 SDOperand Elt = MaskElts[i];
3449 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3450 if (EltIdx == i)
3451 continue;
3452 SDOperand ExtOp = (EltIdx < 8)
3453 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3454 DAG.getConstant(EltIdx, PtrVT))
3455 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3456 DAG.getConstant(EltIdx - 8, PtrVT));
3457 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3458 DAG.getConstant(i, PtrVT));
3459 }
3460 return NewV;
3461 }
3462
3463 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3464 ///as few as possible.
Evan Chengfca29242007-12-07 08:07:39 +00003465 // First, let's find out how many elements are already in the right order.
3466 unsigned V1InOrder = 0;
3467 unsigned V1FromV1 = 0;
3468 unsigned V2InOrder = 0;
3469 unsigned V2FromV2 = 0;
Evan Cheng75184a92007-12-11 01:46:18 +00003470 SmallVector<SDOperand, 8> V1Elts;
3471 SmallVector<SDOperand, 8> V2Elts;
Evan Chengfca29242007-12-07 08:07:39 +00003472 for (unsigned i = 0; i < 8; ++i) {
Evan Cheng75184a92007-12-11 01:46:18 +00003473 SDOperand Elt = MaskElts[i];
Evan Chengfca29242007-12-07 08:07:39 +00003474 if (Elt.getOpcode() == ISD::UNDEF) {
Evan Cheng75184a92007-12-11 01:46:18 +00003475 V1Elts.push_back(Elt);
3476 V2Elts.push_back(Elt);
Evan Chengfca29242007-12-07 08:07:39 +00003477 ++V1InOrder;
3478 ++V2InOrder;
Evan Cheng75184a92007-12-11 01:46:18 +00003479 continue;
3480 }
3481 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3482 if (EltIdx == i) {
3483 V1Elts.push_back(Elt);
3484 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3485 ++V1InOrder;
3486 } else if (EltIdx == i+8) {
3487 V1Elts.push_back(Elt);
3488 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3489 ++V2InOrder;
3490 } else if (EltIdx < 8) {
3491 V1Elts.push_back(Elt);
3492 ++V1FromV1;
Evan Chengfca29242007-12-07 08:07:39 +00003493 } else {
Evan Cheng75184a92007-12-11 01:46:18 +00003494 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3495 ++V2FromV2;
Evan Chengfca29242007-12-07 08:07:39 +00003496 }
3497 }
3498
3499 if (V2InOrder > V1InOrder) {
3500 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3501 std::swap(V1, V2);
3502 std::swap(V1Elts, V2Elts);
3503 std::swap(V1FromV1, V2FromV2);
3504 }
3505
Evan Cheng75184a92007-12-11 01:46:18 +00003506 if ((V1FromV1 + V1InOrder) != 8) {
3507 // Some elements are from V2.
3508 if (V1FromV1) {
3509 // If there are elements that are from V1 but out of place,
3510 // then first sort them in place
3511 SmallVector<SDOperand, 8> MaskVec;
3512 for (unsigned i = 0; i < 8; ++i) {
3513 SDOperand Elt = V1Elts[i];
3514 if (Elt.getOpcode() == ISD::UNDEF) {
3515 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3516 continue;
3517 }
3518 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3519 if (EltIdx >= 8)
3520 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3521 else
3522 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3523 }
3524 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3525 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
Evan Chengfca29242007-12-07 08:07:39 +00003526 }
Evan Cheng75184a92007-12-11 01:46:18 +00003527
3528 NewV = V1;
3529 for (unsigned i = 0; i < 8; ++i) {
3530 SDOperand Elt = V1Elts[i];
3531 if (Elt.getOpcode() == ISD::UNDEF)
3532 continue;
3533 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3534 if (EltIdx < 8)
3535 continue;
3536 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3537 DAG.getConstant(EltIdx - 8, PtrVT));
3538 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3539 DAG.getConstant(i, PtrVT));
3540 }
3541 return NewV;
3542 } else {
3543 // All elements are from V1.
3544 NewV = V1;
3545 for (unsigned i = 0; i < 8; ++i) {
3546 SDOperand Elt = V1Elts[i];
3547 if (Elt.getOpcode() == ISD::UNDEF)
3548 continue;
3549 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3550 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3551 DAG.getConstant(EltIdx, PtrVT));
3552 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3553 DAG.getConstant(i, PtrVT));
3554 }
3555 return NewV;
3556 }
3557}
3558
3559/// RewriteAs4WideShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3560/// ones if possible. This can be done when every pair / quad of shuffle mask
3561/// elements point to elements in the right sequence. e.g.
3562/// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3563static
3564SDOperand RewriteAs4WideShuffle(SDOperand V1, SDOperand V2,
3565 SDOperand PermMask, SelectionDAG &DAG,
3566 TargetLowering &TLI) {
3567 unsigned NumElems = PermMask.getNumOperands();
3568 unsigned Scale = NumElems / 4;
3569 SmallVector<SDOperand, 4> MaskVec;
3570 for (unsigned i = 0; i < NumElems; i += Scale) {
3571 unsigned StartIdx = ~0U;
3572 for (unsigned j = 0; j < Scale; ++j) {
3573 SDOperand Elt = PermMask.getOperand(i+j);
3574 if (Elt.getOpcode() == ISD::UNDEF)
3575 continue;
3576 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3577 if (StartIdx == ~0U)
3578 StartIdx = EltIdx - (EltIdx % Scale);
3579 if (EltIdx != StartIdx + j)
3580 return SDOperand();
3581 }
3582 if (StartIdx == ~0U)
3583 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3584 else
3585 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
Evan Chengfca29242007-12-07 08:07:39 +00003586 }
3587
Evan Cheng75184a92007-12-11 01:46:18 +00003588 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
3589 V2 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V2);
3590 return DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1, V2,
3591 DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, &MaskVec[0],4));
Evan Chengfca29242007-12-07 08:07:39 +00003592}
3593
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003594SDOperand
3595X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3596 SDOperand V1 = Op.getOperand(0);
3597 SDOperand V2 = Op.getOperand(1);
3598 SDOperand PermMask = Op.getOperand(2);
3599 MVT::ValueType VT = Op.getValueType();
3600 unsigned NumElems = PermMask.getNumOperands();
3601 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3602 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3603 bool V1IsSplat = false;
3604 bool V2IsSplat = false;
3605
3606 if (isUndefShuffle(Op.Val))
3607 return DAG.getNode(ISD::UNDEF, VT);
3608
3609 if (isZeroShuffle(Op.Val))
3610 return getZeroVector(VT, DAG);
3611
3612 if (isIdentityMask(PermMask.Val))
3613 return V1;
3614 else if (isIdentityMask(PermMask.Val, true))
3615 return V2;
3616
3617 if (isSplatMask(PermMask.Val)) {
3618 if (NumElems <= 4) return Op;
3619 // Promote it to a v4i32 splat.
3620 return PromoteSplat(Op, DAG);
3621 }
3622
3623 if (X86::isMOVLMask(PermMask.Val))
3624 return (V1IsUndef) ? V2 : Op;
3625
3626 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3627 X86::isMOVSLDUPMask(PermMask.Val) ||
3628 X86::isMOVHLPSMask(PermMask.Val) ||
3629 X86::isMOVHPMask(PermMask.Val) ||
3630 X86::isMOVLPMask(PermMask.Val))
3631 return Op;
3632
3633 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3634 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3635 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3636
3637 bool Commuted = false;
Chris Lattnere6aa3862007-11-25 00:24:49 +00003638 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3639 // 1,1,1,1 -> v8i16 though.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003640 V1IsSplat = isSplatVector(V1.Val);
3641 V2IsSplat = isSplatVector(V2.Val);
Chris Lattnere6aa3862007-11-25 00:24:49 +00003642
3643 // Canonicalize the splat or undef, if present, to be on the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003644 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3645 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3646 std::swap(V1IsSplat, V2IsSplat);
3647 std::swap(V1IsUndef, V2IsUndef);
3648 Commuted = true;
3649 }
3650
3651 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3652 if (V2IsUndef) return V1;
3653 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3654 if (V2IsSplat) {
3655 // V2 is a splat, so the mask may be malformed. That is, it may point
3656 // to any V2 element. The instruction selectior won't like this. Get
3657 // a corrected mask and commute to form a proper MOVS{S|D}.
3658 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3659 if (NewMask.Val != PermMask.Val)
3660 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3661 }
3662 return Op;
3663 }
3664
3665 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3666 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3667 X86::isUNPCKLMask(PermMask.Val) ||
3668 X86::isUNPCKHMask(PermMask.Val))
3669 return Op;
3670
3671 if (V2IsSplat) {
3672 // Normalize mask so all entries that point to V2 points to its first
3673 // element then try to match unpck{h|l} again. If match, return a
3674 // new vector_shuffle with the corrected mask.
3675 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3676 if (NewMask.Val != PermMask.Val) {
3677 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3678 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3679 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3680 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3681 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3682 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3683 }
3684 }
3685 }
3686
3687 // Normalize the node to match x86 shuffle ops if needed
3688 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3689 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3690
3691 if (Commuted) {
3692 // Commute is back and try unpck* again.
3693 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3694 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3695 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3696 X86::isUNPCKLMask(PermMask.Val) ||
3697 X86::isUNPCKHMask(PermMask.Val))
3698 return Op;
3699 }
3700
3701 // If VT is integer, try PSHUF* first, then SHUFP*.
3702 if (MVT::isInteger(VT)) {
Dan Gohman7dc19012007-08-02 21:17:01 +00003703 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3704 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3705 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3706 X86::isPSHUFDMask(PermMask.Val)) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003707 X86::isPSHUFHWMask(PermMask.Val) ||
3708 X86::isPSHUFLWMask(PermMask.Val)) {
3709 if (V2.getOpcode() != ISD::UNDEF)
3710 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3711 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3712 return Op;
3713 }
3714
3715 if (X86::isSHUFPMask(PermMask.Val) &&
3716 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3717 return Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003718 } else {
3719 // Floating point cases in the other order.
3720 if (X86::isSHUFPMask(PermMask.Val))
3721 return Op;
3722 if (X86::isPSHUFDMask(PermMask.Val) ||
3723 X86::isPSHUFHWMask(PermMask.Val) ||
3724 X86::isPSHUFLWMask(PermMask.Val)) {
3725 if (V2.getOpcode() != ISD::UNDEF)
3726 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3727 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3728 return Op;
3729 }
3730 }
3731
Evan Cheng75184a92007-12-11 01:46:18 +00003732 // If the shuffle can be rewritten as a 4 wide shuffle, then do it!
3733 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3734 SDOperand NewOp = RewriteAs4WideShuffle(V1, V2, PermMask, DAG, *this);
3735 if (NewOp.Val)
3736 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3737 }
Evan Chengfca29242007-12-07 08:07:39 +00003738
Evan Cheng75184a92007-12-11 01:46:18 +00003739 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3740 if (VT == MVT::v8i16) {
3741 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3742 if (NewOp.Val)
3743 return NewOp;
3744 }
3745
3746 // Handle all 4 wide cases with a number of shuffles.
3747 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
Evan Chengfca29242007-12-07 08:07:39 +00003748 // Don't do this for MMX.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003749 MVT::ValueType MaskVT = PermMask.getValueType();
3750 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3751 SmallVector<std::pair<int, int>, 8> Locs;
3752 Locs.reserve(NumElems);
Evan Cheng75184a92007-12-11 01:46:18 +00003753 SmallVector<SDOperand, 8> Mask1(NumElems,
3754 DAG.getNode(ISD::UNDEF, MaskEVT));
3755 SmallVector<SDOperand, 8> Mask2(NumElems,
3756 DAG.getNode(ISD::UNDEF, MaskEVT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003757 unsigned NumHi = 0;
3758 unsigned NumLo = 0;
3759 // If no more than two elements come from either vector. This can be
3760 // implemented with two shuffles. First shuffle gather the elements.
3761 // The second shuffle, which takes the first shuffle as both of its
3762 // vector operands, put the elements into the right order.
3763 for (unsigned i = 0; i != NumElems; ++i) {
3764 SDOperand Elt = PermMask.getOperand(i);
3765 if (Elt.getOpcode() == ISD::UNDEF) {
3766 Locs[i] = std::make_pair(-1, -1);
3767 } else {
3768 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3769 if (Val < NumElems) {
3770 Locs[i] = std::make_pair(0, NumLo);
3771 Mask1[NumLo] = Elt;
3772 NumLo++;
3773 } else {
3774 Locs[i] = std::make_pair(1, NumHi);
3775 if (2+NumHi < NumElems)
3776 Mask1[2+NumHi] = Elt;
3777 NumHi++;
3778 }
3779 }
3780 }
3781 if (NumLo <= 2 && NumHi <= 2) {
3782 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3783 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3784 &Mask1[0], Mask1.size()));
3785 for (unsigned i = 0; i != NumElems; ++i) {
3786 if (Locs[i].first == -1)
3787 continue;
3788 else {
3789 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3790 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3791 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3792 }
3793 }
3794
3795 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3796 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3797 &Mask2[0], Mask2.size()));
3798 }
3799
3800 // Break it into (shuffle shuffle_hi, shuffle_lo).
3801 Locs.clear();
3802 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3803 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3804 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3805 unsigned MaskIdx = 0;
3806 unsigned LoIdx = 0;
3807 unsigned HiIdx = NumElems/2;
3808 for (unsigned i = 0; i != NumElems; ++i) {
3809 if (i == NumElems/2) {
3810 MaskPtr = &HiMask;
3811 MaskIdx = 1;
3812 LoIdx = 0;
3813 HiIdx = NumElems/2;
3814 }
3815 SDOperand Elt = PermMask.getOperand(i);
3816 if (Elt.getOpcode() == ISD::UNDEF) {
3817 Locs[i] = std::make_pair(-1, -1);
3818 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3819 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3820 (*MaskPtr)[LoIdx] = Elt;
3821 LoIdx++;
3822 } else {
3823 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3824 (*MaskPtr)[HiIdx] = Elt;
3825 HiIdx++;
3826 }
3827 }
3828
3829 SDOperand LoShuffle =
3830 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3831 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3832 &LoMask[0], LoMask.size()));
3833 SDOperand HiShuffle =
3834 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3835 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3836 &HiMask[0], HiMask.size()));
3837 SmallVector<SDOperand, 8> MaskOps;
3838 for (unsigned i = 0; i != NumElems; ++i) {
3839 if (Locs[i].first == -1) {
3840 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3841 } else {
3842 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3843 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3844 }
3845 }
3846 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3847 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3848 &MaskOps[0], MaskOps.size()));
3849 }
3850
3851 return SDOperand();
3852}
3853
3854SDOperand
3855X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3856 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3857 return SDOperand();
3858
3859 MVT::ValueType VT = Op.getValueType();
3860 // TODO: handle v16i8.
3861 if (MVT::getSizeInBits(VT) == 16) {
Evan Cheng75184a92007-12-11 01:46:18 +00003862 SDOperand Vec = Op.getOperand(0);
3863 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3864 if (Idx == 0)
3865 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3866 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3867 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3868 Op.getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003869 // Transform it so it match pextrw which produces a 32-bit result.
3870 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3871 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3872 Op.getOperand(0), Op.getOperand(1));
3873 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3874 DAG.getValueType(VT));
3875 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3876 } else if (MVT::getSizeInBits(VT) == 32) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003877 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3878 if (Idx == 0)
3879 return Op;
3880 // SHUFPS the element to the lowest double word, then movss.
3881 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3882 SmallVector<SDOperand, 8> IdxVec;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00003883 IdxVec.
3884 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3885 IdxVec.
3886 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3887 IdxVec.
3888 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3889 IdxVec.
3890 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003891 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3892 &IdxVec[0], IdxVec.size());
Evan Cheng75184a92007-12-11 01:46:18 +00003893 SDOperand Vec = Op.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003894 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3895 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3896 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3897 DAG.getConstant(0, getPointerTy()));
3898 } else if (MVT::getSizeInBits(VT) == 64) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003899 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3900 if (Idx == 0)
3901 return Op;
3902
3903 // UNPCKHPD the element to the lowest double word, then movsd.
3904 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3905 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3906 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3907 SmallVector<SDOperand, 8> IdxVec;
3908 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00003909 IdxVec.
3910 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003911 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3912 &IdxVec[0], IdxVec.size());
Evan Cheng75184a92007-12-11 01:46:18 +00003913 SDOperand Vec = Op.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003914 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3915 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3916 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3917 DAG.getConstant(0, getPointerTy()));
3918 }
3919
3920 return SDOperand();
3921}
3922
3923SDOperand
3924X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003925 MVT::ValueType VT = Op.getValueType();
Evan Chenge12a7eb2007-12-12 07:55:34 +00003926 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3927 if (EVT == MVT::i8)
3928 return SDOperand();
3929
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003930 SDOperand N0 = Op.getOperand(0);
3931 SDOperand N1 = Op.getOperand(1);
3932 SDOperand N2 = Op.getOperand(2);
Evan Chenge12a7eb2007-12-12 07:55:34 +00003933
3934 if (MVT::getSizeInBits(EVT) == 16) {
3935 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3936 // as its second argument.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003937 if (N1.getValueType() != MVT::i32)
3938 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3939 if (N2.getValueType() != MVT::i32)
3940 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
3941 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003942 }
3943
Evan Chenge12a7eb2007-12-12 07:55:34 +00003944 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
3945 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
3946 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3947 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3948 SmallVector<SDOperand, 4> MaskVec;
3949 for (unsigned i = 0; i < 4; ++i)
3950 MaskVec.push_back(DAG.getConstant((i == Idx) ? i+4 : i, MaskEVT));
3951 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
3952 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3953 &MaskVec[0], MaskVec.size()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003954}
3955
3956SDOperand
3957X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3958 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3959 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3960}
3961
3962// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3963// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3964// one of the above mentioned nodes. It has to be wrapped because otherwise
3965// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3966// be used to form addressing mode. These wrapped nodes will be selected
3967// into MOV32ri.
3968SDOperand
3969X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3970 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3971 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3972 getPointerTy(),
3973 CP->getAlignment());
3974 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3975 // With PIC, the address is actually $g + Offset.
3976 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3977 !Subtarget->isPICStyleRIPRel()) {
3978 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3979 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3980 Result);
3981 }
3982
3983 return Result;
3984}
3985
3986SDOperand
3987X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3988 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3989 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3990 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3991 // With PIC, the address is actually $g + Offset.
3992 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3993 !Subtarget->isPICStyleRIPRel()) {
3994 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3995 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3996 Result);
3997 }
3998
3999 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4000 // load the value at address GV, not the value of GV itself. This means that
4001 // the GlobalAddress must be in the base or index register of the address, not
4002 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4003 // The same applies for external symbols during PIC codegen
4004 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4005 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
4006
4007 return Result;
4008}
4009
4010// Lower ISD::GlobalTLSAddress using the "general dynamic" model
4011static SDOperand
4012LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4013 const MVT::ValueType PtrVT) {
4014 SDOperand InFlag;
4015 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4016 DAG.getNode(X86ISD::GlobalBaseReg,
4017 PtrVT), InFlag);
4018 InFlag = Chain.getValue(1);
4019
4020 // emit leal symbol@TLSGD(,%ebx,1), %eax
4021 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4022 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4023 GA->getValueType(0),
4024 GA->getOffset());
4025 SDOperand Ops[] = { Chain, TGA, InFlag };
4026 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4027 InFlag = Result.getValue(2);
4028 Chain = Result.getValue(1);
4029
4030 // call ___tls_get_addr. This function receives its argument in
4031 // the register EAX.
4032 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4033 InFlag = Chain.getValue(1);
4034
4035 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4036 SDOperand Ops1[] = { Chain,
4037 DAG.getTargetExternalSymbol("___tls_get_addr",
4038 PtrVT),
4039 DAG.getRegister(X86::EAX, PtrVT),
4040 DAG.getRegister(X86::EBX, PtrVT),
4041 InFlag };
4042 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4043 InFlag = Chain.getValue(1);
4044
4045 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4046}
4047
4048// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4049// "local exec" model.
4050static SDOperand
4051LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4052 const MVT::ValueType PtrVT) {
4053 // Get the Thread Pointer
4054 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4055 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4056 // exec)
4057 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4058 GA->getValueType(0),
4059 GA->getOffset());
4060 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4061
4062 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4063 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
4064
4065 // The address of the thread local variable is the add of the thread
4066 // pointer with the offset of the variable.
4067 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4068}
4069
4070SDOperand
4071X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4072 // TODO: implement the "local dynamic" model
4073 // TODO: implement the "initial exec"model for pic executables
4074 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4075 "TLS not implemented for non-ELF and 64-bit targets");
4076 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4077 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4078 // otherwise use the "Local Exec"TLS Model
4079 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4080 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4081 else
4082 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4083}
4084
4085SDOperand
4086X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4087 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4088 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4089 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4090 // With PIC, the address is actually $g + Offset.
4091 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4092 !Subtarget->isPICStyleRIPRel()) {
4093 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4094 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4095 Result);
4096 }
4097
4098 return Result;
4099}
4100
4101SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4102 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4103 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4104 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4105 // With PIC, the address is actually $g + Offset.
4106 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4107 !Subtarget->isPICStyleRIPRel()) {
4108 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4109 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4110 Result);
4111 }
4112
4113 return Result;
4114}
4115
Chris Lattner62814a32007-10-17 06:02:13 +00004116/// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4117/// take a 2 x i32 value to shift plus a shift amount.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004118SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner62814a32007-10-17 06:02:13 +00004119 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
4120 "Not an i64 shift!");
4121 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4122 SDOperand ShOpLo = Op.getOperand(0);
4123 SDOperand ShOpHi = Op.getOperand(1);
4124 SDOperand ShAmt = Op.getOperand(2);
4125 SDOperand Tmp1 = isSRA ?
4126 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
4127 DAG.getConstant(0, MVT::i32);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004128
Chris Lattner62814a32007-10-17 06:02:13 +00004129 SDOperand Tmp2, Tmp3;
4130 if (Op.getOpcode() == ISD::SHL_PARTS) {
4131 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
4132 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
4133 } else {
4134 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
4135 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
4136 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004137
Chris Lattner62814a32007-10-17 06:02:13 +00004138 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4139 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4140 DAG.getConstant(32, MVT::i8));
4141 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
4142 AndNode, DAG.getConstant(0, MVT::i8));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004143
Chris Lattner62814a32007-10-17 06:02:13 +00004144 SDOperand Hi, Lo;
4145 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4146 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
4147 SmallVector<SDOperand, 4> Ops;
4148 if (Op.getOpcode() == ISD::SHL_PARTS) {
4149 Ops.push_back(Tmp2);
4150 Ops.push_back(Tmp3);
4151 Ops.push_back(CC);
4152 Ops.push_back(Cond);
4153 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004154
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004155 Ops.clear();
Chris Lattner62814a32007-10-17 06:02:13 +00004156 Ops.push_back(Tmp3);
4157 Ops.push_back(Tmp1);
4158 Ops.push_back(CC);
4159 Ops.push_back(Cond);
4160 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4161 } else {
4162 Ops.push_back(Tmp2);
4163 Ops.push_back(Tmp3);
4164 Ops.push_back(CC);
4165 Ops.push_back(Cond);
4166 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4167
4168 Ops.clear();
4169 Ops.push_back(Tmp3);
4170 Ops.push_back(Tmp1);
4171 Ops.push_back(CC);
4172 Ops.push_back(Cond);
4173 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4174 }
4175
4176 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
4177 Ops.clear();
4178 Ops.push_back(Lo);
4179 Ops.push_back(Hi);
4180 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004181}
4182
4183SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4184 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
4185 Op.getOperand(0).getValueType() >= MVT::i16 &&
4186 "Unknown SINT_TO_FP to lower!");
4187
4188 SDOperand Result;
4189 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4190 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4191 MachineFunction &MF = DAG.getMachineFunction();
4192 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4193 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4194 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4195 StackSlot, NULL, 0);
4196
Dale Johannesen2fc20782007-09-14 22:26:36 +00004197 // These are really Legal; caller falls through into that case.
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004198 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f32 && X86ScalarSSEf32)
4199 return Result;
4200 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f64 && X86ScalarSSEf64)
Dale Johannesen2fc20782007-09-14 22:26:36 +00004201 return Result;
Dale Johannesen958b08b2007-09-19 23:55:34 +00004202 if (SrcVT==MVT::i64 && Op.getValueType() != MVT::f80 &&
4203 Subtarget->is64Bit())
4204 return Result;
Dale Johannesen2fc20782007-09-14 22:26:36 +00004205
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004206 // Build the FILD
4207 SDVTList Tys;
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004208 bool useSSE = (X86ScalarSSEf32 && Op.getValueType() == MVT::f32) ||
4209 (X86ScalarSSEf64 && Op.getValueType() == MVT::f64);
Dale Johannesen2fc20782007-09-14 22:26:36 +00004210 if (useSSE)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004211 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4212 else
4213 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4214 SmallVector<SDOperand, 8> Ops;
4215 Ops.push_back(Chain);
4216 Ops.push_back(StackSlot);
4217 Ops.push_back(DAG.getValueType(SrcVT));
Dale Johannesen2fc20782007-09-14 22:26:36 +00004218 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004219 Tys, &Ops[0], Ops.size());
4220
Dale Johannesen2fc20782007-09-14 22:26:36 +00004221 if (useSSE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004222 Chain = Result.getValue(1);
4223 SDOperand InFlag = Result.getValue(2);
4224
4225 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4226 // shouldn't be necessary except that RFP cannot be live across
4227 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4228 MachineFunction &MF = DAG.getMachineFunction();
4229 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4230 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4231 Tys = DAG.getVTList(MVT::Other);
4232 SmallVector<SDOperand, 8> Ops;
4233 Ops.push_back(Chain);
4234 Ops.push_back(Result);
4235 Ops.push_back(StackSlot);
4236 Ops.push_back(DAG.getValueType(Op.getValueType()));
4237 Ops.push_back(InFlag);
4238 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4239 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
4240 }
4241
4242 return Result;
4243}
4244
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004245std::pair<SDOperand,SDOperand> X86TargetLowering::
4246FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004247 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4248 "Unknown FP_TO_SINT to lower!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004249
Dale Johannesen2fc20782007-09-14 22:26:36 +00004250 // These are really Legal.
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004251 if (Op.getValueType() == MVT::i32 &&
4252 X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32)
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004253 return std::make_pair(SDOperand(), SDOperand());
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004254 if (Op.getValueType() == MVT::i32 &&
4255 X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004256 return std::make_pair(SDOperand(), SDOperand());
Dale Johannesen958b08b2007-09-19 23:55:34 +00004257 if (Subtarget->is64Bit() &&
4258 Op.getValueType() == MVT::i64 &&
4259 Op.getOperand(0).getValueType() != MVT::f80)
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004260 return std::make_pair(SDOperand(), SDOperand());
Dale Johannesen2fc20782007-09-14 22:26:36 +00004261
Evan Cheng05441e62007-10-15 20:11:21 +00004262 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4263 // stack slot.
4264 MachineFunction &MF = DAG.getMachineFunction();
4265 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4266 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4267 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004268 unsigned Opc;
4269 switch (Op.getValueType()) {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004270 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4271 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4272 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4273 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004274 }
4275
4276 SDOperand Chain = DAG.getEntryNode();
4277 SDOperand Value = Op.getOperand(0);
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004278 if ((X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32) ||
4279 (X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004280 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4281 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
4282 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4283 SDOperand Ops[] = {
4284 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4285 };
4286 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4287 Chain = Value.getValue(1);
4288 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4289 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4290 }
4291
4292 // Build the FP_TO_INT*_IN_MEM
4293 SDOperand Ops[] = { Chain, Value, StackSlot };
4294 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4295
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004296 return std::make_pair(FIST, StackSlot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004297}
4298
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004299SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004300 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4301 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4302 if (FIST.Val == 0) return SDOperand();
4303
4304 // Load the result.
4305 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4306}
4307
4308SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4309 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4310 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4311 if (FIST.Val == 0) return 0;
4312
4313 // Return an i64 load from the stack slot.
4314 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4315
4316 // Use a MERGE_VALUES node to drop the chain result value.
4317 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4318}
4319
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004320SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4321 MVT::ValueType VT = Op.getValueType();
4322 MVT::ValueType EltVT = VT;
4323 if (MVT::isVector(VT))
4324 EltVT = MVT::getVectorElementType(VT);
4325 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4326 std::vector<Constant*> CV;
4327 if (EltVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004328 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004329 CV.push_back(C);
4330 CV.push_back(C);
4331 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004332 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004333 CV.push_back(C);
4334 CV.push_back(C);
4335 CV.push_back(C);
4336 CV.push_back(C);
4337 }
Dan Gohman11821702007-07-27 17:16:43 +00004338 Constant *C = ConstantVector::get(CV);
4339 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4340 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4341 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004342 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4343}
4344
4345SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4346 MVT::ValueType VT = Op.getValueType();
4347 MVT::ValueType EltVT = VT;
Evan Cheng92b8f782007-07-19 23:36:01 +00004348 unsigned EltNum = 1;
4349 if (MVT::isVector(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004350 EltVT = MVT::getVectorElementType(VT);
Evan Cheng92b8f782007-07-19 23:36:01 +00004351 EltNum = MVT::getVectorNumElements(VT);
4352 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004353 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4354 std::vector<Constant*> CV;
4355 if (EltVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004356 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004357 CV.push_back(C);
4358 CV.push_back(C);
4359 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004360 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004361 CV.push_back(C);
4362 CV.push_back(C);
4363 CV.push_back(C);
4364 CV.push_back(C);
4365 }
Dan Gohman11821702007-07-27 17:16:43 +00004366 Constant *C = ConstantVector::get(CV);
4367 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4368 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4369 false, 16);
Evan Cheng92b8f782007-07-19 23:36:01 +00004370 if (MVT::isVector(VT)) {
Evan Cheng92b8f782007-07-19 23:36:01 +00004371 return DAG.getNode(ISD::BIT_CONVERT, VT,
4372 DAG.getNode(ISD::XOR, MVT::v2i64,
4373 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4374 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4375 } else {
Evan Cheng92b8f782007-07-19 23:36:01 +00004376 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4377 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004378}
4379
4380SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4381 SDOperand Op0 = Op.getOperand(0);
4382 SDOperand Op1 = Op.getOperand(1);
4383 MVT::ValueType VT = Op.getValueType();
4384 MVT::ValueType SrcVT = Op1.getValueType();
4385 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4386
4387 // If second operand is smaller, extend it first.
4388 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4389 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4390 SrcVT = VT;
Dale Johannesenb9de9f02007-09-06 18:13:44 +00004391 SrcTy = MVT::getTypeForValueType(SrcVT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004392 }
Dale Johannesenfb0fa912007-10-21 01:07:44 +00004393 // And if it is bigger, shrink it first.
4394 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4395 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1);
4396 SrcVT = VT;
4397 SrcTy = MVT::getTypeForValueType(SrcVT);
4398 }
4399
4400 // At this point the operands and the result should have the same
4401 // type, and that won't be f80 since that is not custom lowered.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004402
4403 // First get the sign bit of second operand.
4404 std::vector<Constant*> CV;
4405 if (SrcVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004406 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4407 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004408 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004409 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4410 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4411 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4412 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004413 }
Dan Gohman11821702007-07-27 17:16:43 +00004414 Constant *C = ConstantVector::get(CV);
4415 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4416 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx, NULL, 0,
4417 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004418 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4419
4420 // Shift sign bit right or left if the two operands have different types.
4421 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4422 // Op0 is MVT::f32, Op1 is MVT::f64.
4423 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4424 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4425 DAG.getConstant(32, MVT::i32));
4426 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4427 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4428 DAG.getConstant(0, getPointerTy()));
4429 }
4430
4431 // Clear first operand sign bit.
4432 CV.clear();
4433 if (VT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004434 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4435 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004436 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004437 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4438 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4439 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4440 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004441 }
Dan Gohman11821702007-07-27 17:16:43 +00004442 C = ConstantVector::get(CV);
4443 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4444 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4445 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004446 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4447
4448 // Or the value with the sign bit.
4449 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4450}
4451
Evan Cheng621216e2007-09-29 00:00:36 +00004452SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
Evan Cheng950aac02007-09-25 01:57:46 +00004453 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
Evan Cheng6afec3d2007-09-26 00:45:55 +00004454 SDOperand Cond;
Evan Cheng950aac02007-09-25 01:57:46 +00004455 SDOperand Op0 = Op.getOperand(0);
4456 SDOperand Op1 = Op.getOperand(1);
4457 SDOperand CC = Op.getOperand(2);
4458 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4459 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4460 unsigned X86CC;
4461
Evan Cheng950aac02007-09-25 01:57:46 +00004462 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
Evan Cheng6afec3d2007-09-26 00:45:55 +00004463 Op0, Op1, DAG)) {
Evan Cheng621216e2007-09-29 00:00:36 +00004464 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4465 return DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004466 DAG.getConstant(X86CC, MVT::i8), Cond);
Evan Cheng6afec3d2007-09-26 00:45:55 +00004467 }
Evan Cheng950aac02007-09-25 01:57:46 +00004468
4469 assert(isFP && "Illegal integer SetCC!");
4470
Evan Cheng621216e2007-09-29 00:00:36 +00004471 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
Evan Cheng950aac02007-09-25 01:57:46 +00004472 switch (SetCCOpcode) {
4473 default: assert(false && "Illegal floating point SetCC!");
4474 case ISD::SETOEQ: { // !PF & ZF
Evan Cheng621216e2007-09-29 00:00:36 +00004475 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004476 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004477 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004478 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4479 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4480 }
4481 case ISD::SETUNE: { // PF | !ZF
Evan Cheng621216e2007-09-29 00:00:36 +00004482 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004483 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004484 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004485 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4486 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4487 }
4488 }
4489}
4490
4491
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004492SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4493 bool addTest = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004494 SDOperand Cond = Op.getOperand(0);
4495 SDOperand CC;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004496
4497 if (Cond.getOpcode() == ISD::SETCC)
Evan Cheng621216e2007-09-29 00:00:36 +00004498 Cond = LowerSETCC(Cond, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004499
Evan Cheng50d37ab2007-10-08 22:16:29 +00004500 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4501 // setting operand in place of the X86ISD::SETCC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004502 if (Cond.getOpcode() == X86ISD::SETCC) {
4503 CC = Cond.getOperand(0);
4504
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004505 SDOperand Cmp = Cond.getOperand(1);
4506 unsigned Opc = Cmp.getOpcode();
Evan Cheng50d37ab2007-10-08 22:16:29 +00004507 MVT::ValueType VT = Op.getValueType();
4508 bool IllegalFPCMov = false;
4509 if (VT == MVT::f32 && !X86ScalarSSEf32)
4510 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4511 else if (VT == MVT::f64 && !X86ScalarSSEf64)
4512 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
Dale Johannesen3b955db2007-10-16 18:09:08 +00004513 else if (VT == MVT::f80)
4514 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
Evan Cheng621216e2007-09-29 00:00:36 +00004515 if ((Opc == X86ISD::CMP ||
4516 Opc == X86ISD::COMI ||
4517 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
Evan Cheng50d37ab2007-10-08 22:16:29 +00004518 Cond = Cmp;
Evan Cheng950aac02007-09-25 01:57:46 +00004519 addTest = false;
4520 }
4521 }
4522
4523 if (addTest) {
4524 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
Evan Cheng50d37ab2007-10-08 22:16:29 +00004525 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
Evan Cheng950aac02007-09-25 01:57:46 +00004526 }
4527
4528 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4529 MVT::Flag);
4530 SmallVector<SDOperand, 4> Ops;
4531 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4532 // condition is true.
4533 Ops.push_back(Op.getOperand(2));
4534 Ops.push_back(Op.getOperand(1));
4535 Ops.push_back(CC);
4536 Ops.push_back(Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004537 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
Evan Cheng950aac02007-09-25 01:57:46 +00004538}
4539
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004540SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4541 bool addTest = true;
4542 SDOperand Chain = Op.getOperand(0);
4543 SDOperand Cond = Op.getOperand(1);
4544 SDOperand Dest = Op.getOperand(2);
4545 SDOperand CC;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004546
4547 if (Cond.getOpcode() == ISD::SETCC)
Evan Cheng621216e2007-09-29 00:00:36 +00004548 Cond = LowerSETCC(Cond, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004549
Evan Cheng50d37ab2007-10-08 22:16:29 +00004550 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4551 // setting operand in place of the X86ISD::SETCC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004552 if (Cond.getOpcode() == X86ISD::SETCC) {
4553 CC = Cond.getOperand(0);
4554
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004555 SDOperand Cmp = Cond.getOperand(1);
4556 unsigned Opc = Cmp.getOpcode();
Evan Cheng621216e2007-09-29 00:00:36 +00004557 if (Opc == X86ISD::CMP ||
4558 Opc == X86ISD::COMI ||
4559 Opc == X86ISD::UCOMI) {
Evan Cheng50d37ab2007-10-08 22:16:29 +00004560 Cond = Cmp;
Evan Cheng950aac02007-09-25 01:57:46 +00004561 addTest = false;
4562 }
4563 }
4564
4565 if (addTest) {
4566 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
Evan Cheng621216e2007-09-29 00:00:36 +00004567 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
Evan Cheng950aac02007-09-25 01:57:46 +00004568 }
Evan Cheng621216e2007-09-29 00:00:36 +00004569 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
Evan Cheng950aac02007-09-25 01:57:46 +00004570 Chain, Op.getOperand(2), CC, Cond);
4571}
4572
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004573SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004574 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4575 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004576
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004577 if (Subtarget->is64Bit())
4578 if(CallingConv==CallingConv::Fast && isTailCall && PerformTailCallOpt)
4579 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4580 else
4581 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004582 else
4583 switch (CallingConv) {
4584 default:
4585 assert(0 && "Unsupported calling convention");
4586 case CallingConv::Fast:
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004587 if (isTailCall && PerformTailCallOpt)
4588 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4589 else
4590 return LowerCCCCallTo(Op,DAG, CallingConv);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004591 case CallingConv::C:
4592 case CallingConv::X86_StdCall:
4593 return LowerCCCCallTo(Op, DAG, CallingConv);
4594 case CallingConv::X86_FastCall:
4595 return LowerFastCCCallTo(Op, DAG, CallingConv);
4596 }
4597}
4598
4599
4600// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4601// Calls to _alloca is needed to probe the stack when allocating more than 4k
4602// bytes in one go. Touching the stack at 4K increments is necessary to ensure
4603// that the guard pages used by the OS virtual memory manager are allocated in
4604// correct sequence.
4605SDOperand
4606X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4607 SelectionDAG &DAG) {
4608 assert(Subtarget->isTargetCygMing() &&
4609 "This should be used only on Cygwin/Mingw targets");
4610
4611 // Get the inputs.
4612 SDOperand Chain = Op.getOperand(0);
4613 SDOperand Size = Op.getOperand(1);
4614 // FIXME: Ensure alignment here
4615
4616 SDOperand Flag;
4617
4618 MVT::ValueType IntPtr = getPointerTy();
4619 MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
4620
4621 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4622 Flag = Chain.getValue(1);
4623
4624 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4625 SDOperand Ops[] = { Chain,
4626 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4627 DAG.getRegister(X86::EAX, IntPtr),
4628 Flag };
4629 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4630 Flag = Chain.getValue(1);
4631
4632 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4633
4634 std::vector<MVT::ValueType> Tys;
4635 Tys.push_back(SPTy);
4636 Tys.push_back(MVT::Other);
4637 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4638 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4639}
4640
4641SDOperand
4642X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
4643 MachineFunction &MF = DAG.getMachineFunction();
4644 const Function* Fn = MF.getFunction();
4645 if (Fn->hasExternalLinkage() &&
4646 Subtarget->isTargetCygMing() &&
4647 Fn->getName() == "main")
4648 MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
4649
4650 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4651 if (Subtarget->is64Bit())
4652 return LowerX86_64CCCArguments(Op, DAG);
4653 else
4654 switch(CC) {
4655 default:
4656 assert(0 && "Unsupported calling convention");
4657 case CallingConv::Fast:
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004658 return LowerCCCArguments(Op,DAG, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004659 // Falls through
4660 case CallingConv::C:
4661 return LowerCCCArguments(Op, DAG);
4662 case CallingConv::X86_StdCall:
4663 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
4664 return LowerCCCArguments(Op, DAG, true);
4665 case CallingConv::X86_FastCall:
4666 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
4667 return LowerFastCCArguments(Op, DAG);
4668 }
4669}
4670
4671SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4672 SDOperand InFlag(0, 0);
4673 SDOperand Chain = Op.getOperand(0);
4674 unsigned Align =
4675 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4676 if (Align == 0) Align = 1;
4677
4678 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
Rafael Espindola5d3e7622007-08-27 10:18:20 +00004679 // If not DWORD aligned or size is more than the threshold, call memset.
Rafael Espindolab2e7a6b2007-08-27 17:48:26 +00004680 // The libc version is likely to be faster for these cases. It can use the
4681 // address value and run time information about the CPU.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004682 if ((Align & 3) != 0 ||
Rafael Espindola7afa9b12007-10-31 11:52:06 +00004683 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004684 MVT::ValueType IntPtr = getPointerTy();
4685 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4686 TargetLowering::ArgListTy Args;
4687 TargetLowering::ArgListEntry Entry;
4688 Entry.Node = Op.getOperand(1);
4689 Entry.Ty = IntPtrTy;
4690 Args.push_back(Entry);
4691 // Extend the unsigned i8 argument to be an int value for the call.
4692 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4693 Entry.Ty = IntPtrTy;
4694 Args.push_back(Entry);
4695 Entry.Node = Op.getOperand(3);
4696 Args.push_back(Entry);
4697 std::pair<SDOperand,SDOperand> CallResult =
4698 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4699 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4700 return CallResult.second;
4701 }
4702
4703 MVT::ValueType AVT;
4704 SDOperand Count;
4705 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4706 unsigned BytesLeft = 0;
4707 bool TwoRepStos = false;
4708 if (ValC) {
4709 unsigned ValReg;
4710 uint64_t Val = ValC->getValue() & 255;
4711
4712 // If the value is a constant, then we can potentially use larger sets.
4713 switch (Align & 3) {
4714 case 2: // WORD aligned
4715 AVT = MVT::i16;
4716 ValReg = X86::AX;
4717 Val = (Val << 8) | Val;
4718 break;
4719 case 0: // DWORD aligned
4720 AVT = MVT::i32;
4721 ValReg = X86::EAX;
4722 Val = (Val << 8) | Val;
4723 Val = (Val << 16) | Val;
4724 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4725 AVT = MVT::i64;
4726 ValReg = X86::RAX;
4727 Val = (Val << 32) | Val;
4728 }
4729 break;
4730 default: // Byte aligned
4731 AVT = MVT::i8;
4732 ValReg = X86::AL;
4733 Count = Op.getOperand(3);
4734 break;
4735 }
4736
4737 if (AVT > MVT::i8) {
4738 if (I) {
4739 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4740 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
4741 BytesLeft = I->getValue() % UBytes;
4742 } else {
4743 assert(AVT >= MVT::i32 &&
4744 "Do not use rep;stos if not at least DWORD aligned");
4745 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4746 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4747 TwoRepStos = true;
4748 }
4749 }
4750
4751 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4752 InFlag);
4753 InFlag = Chain.getValue(1);
4754 } else {
4755 AVT = MVT::i8;
4756 Count = Op.getOperand(3);
4757 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4758 InFlag = Chain.getValue(1);
4759 }
4760
4761 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4762 Count, InFlag);
4763 InFlag = Chain.getValue(1);
4764 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4765 Op.getOperand(1), InFlag);
4766 InFlag = Chain.getValue(1);
4767
4768 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4769 SmallVector<SDOperand, 8> Ops;
4770 Ops.push_back(Chain);
4771 Ops.push_back(DAG.getValueType(AVT));
4772 Ops.push_back(InFlag);
4773 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4774
4775 if (TwoRepStos) {
4776 InFlag = Chain.getValue(1);
4777 Count = Op.getOperand(3);
4778 MVT::ValueType CVT = Count.getValueType();
4779 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4780 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4781 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4782 Left, InFlag);
4783 InFlag = Chain.getValue(1);
4784 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4785 Ops.clear();
4786 Ops.push_back(Chain);
4787 Ops.push_back(DAG.getValueType(MVT::i8));
4788 Ops.push_back(InFlag);
4789 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4790 } else if (BytesLeft) {
4791 // Issue stores for the last 1 - 7 bytes.
4792 SDOperand Value;
4793 unsigned Val = ValC->getValue() & 255;
4794 unsigned Offset = I->getValue() - BytesLeft;
4795 SDOperand DstAddr = Op.getOperand(1);
4796 MVT::ValueType AddrVT = DstAddr.getValueType();
4797 if (BytesLeft >= 4) {
4798 Val = (Val << 8) | Val;
4799 Val = (Val << 16) | Val;
4800 Value = DAG.getConstant(Val, MVT::i32);
4801 Chain = DAG.getStore(Chain, Value,
4802 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4803 DAG.getConstant(Offset, AddrVT)),
4804 NULL, 0);
4805 BytesLeft -= 4;
4806 Offset += 4;
4807 }
4808 if (BytesLeft >= 2) {
4809 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4810 Chain = DAG.getStore(Chain, Value,
4811 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4812 DAG.getConstant(Offset, AddrVT)),
4813 NULL, 0);
4814 BytesLeft -= 2;
4815 Offset += 2;
4816 }
4817 if (BytesLeft == 1) {
4818 Value = DAG.getConstant(Val, MVT::i8);
4819 Chain = DAG.getStore(Chain, Value,
4820 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4821 DAG.getConstant(Offset, AddrVT)),
4822 NULL, 0);
4823 }
4824 }
4825
4826 return Chain;
4827}
4828
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004829SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4830 SDOperand Dest,
4831 SDOperand Source,
4832 unsigned Size,
4833 unsigned Align,
4834 SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004835 MVT::ValueType AVT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004836 unsigned BytesLeft = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004837 switch (Align & 3) {
4838 case 2: // WORD aligned
4839 AVT = MVT::i16;
4840 break;
4841 case 0: // DWORD aligned
4842 AVT = MVT::i32;
4843 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4844 AVT = MVT::i64;
4845 break;
4846 default: // Byte aligned
4847 AVT = MVT::i8;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004848 break;
4849 }
4850
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004851 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4852 SDOperand Count = DAG.getConstant(Size / UBytes, getPointerTy());
4853 BytesLeft = Size % UBytes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004854
4855 SDOperand InFlag(0, 0);
4856 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4857 Count, InFlag);
4858 InFlag = Chain.getValue(1);
4859 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004860 Dest, InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004861 InFlag = Chain.getValue(1);
4862 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004863 Source, InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004864 InFlag = Chain.getValue(1);
4865
4866 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4867 SmallVector<SDOperand, 8> Ops;
4868 Ops.push_back(Chain);
4869 Ops.push_back(DAG.getValueType(AVT));
4870 Ops.push_back(InFlag);
4871 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4872
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004873 if (BytesLeft) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004874 // Issue loads and stores for the last 1 - 7 bytes.
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004875 unsigned Offset = Size - BytesLeft;
4876 SDOperand DstAddr = Dest;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004877 MVT::ValueType DstVT = DstAddr.getValueType();
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004878 SDOperand SrcAddr = Source;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004879 MVT::ValueType SrcVT = SrcAddr.getValueType();
4880 SDOperand Value;
4881 if (BytesLeft >= 4) {
4882 Value = DAG.getLoad(MVT::i32, Chain,
4883 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4884 DAG.getConstant(Offset, SrcVT)),
4885 NULL, 0);
4886 Chain = Value.getValue(1);
4887 Chain = DAG.getStore(Chain, Value,
4888 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4889 DAG.getConstant(Offset, DstVT)),
4890 NULL, 0);
4891 BytesLeft -= 4;
4892 Offset += 4;
4893 }
4894 if (BytesLeft >= 2) {
4895 Value = DAG.getLoad(MVT::i16, Chain,
4896 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4897 DAG.getConstant(Offset, SrcVT)),
4898 NULL, 0);
4899 Chain = Value.getValue(1);
4900 Chain = DAG.getStore(Chain, Value,
4901 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4902 DAG.getConstant(Offset, DstVT)),
4903 NULL, 0);
4904 BytesLeft -= 2;
4905 Offset += 2;
4906 }
4907
4908 if (BytesLeft == 1) {
4909 Value = DAG.getLoad(MVT::i8, Chain,
4910 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4911 DAG.getConstant(Offset, SrcVT)),
4912 NULL, 0);
4913 Chain = Value.getValue(1);
4914 Chain = DAG.getStore(Chain, Value,
4915 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4916 DAG.getConstant(Offset, DstVT)),
4917 NULL, 0);
4918 }
4919 }
4920
4921 return Chain;
4922}
4923
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004924/// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4925SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004926 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004927 SDOperand TheChain = N->getOperand(0);
4928 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004929 if (Subtarget->is64Bit()) {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004930 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4931 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4932 MVT::i64, rax.getValue(2));
4933 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004934 DAG.getConstant(32, MVT::i8));
4935 SDOperand Ops[] = {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004936 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004937 };
4938
4939 Tys = DAG.getVTList(MVT::i64, MVT::Other);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004940 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004941 }
4942
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004943 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4944 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4945 MVT::i32, eax.getValue(2));
4946 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4947 SDOperand Ops[] = { eax, edx };
4948 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4949
4950 // Use a MERGE_VALUES to return the value and chain.
4951 Ops[1] = edx.getValue(1);
4952 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4953 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004954}
4955
4956SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4957 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
4958
4959 if (!Subtarget->is64Bit()) {
4960 // vastart just stores the address of the VarArgsFrameIndex slot into the
4961 // memory location argument.
4962 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4963 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
4964 SV->getOffset());
4965 }
4966
4967 // __va_list_tag:
4968 // gp_offset (0 - 6 * 8)
4969 // fp_offset (48 - 48 + 8 * 16)
4970 // overflow_arg_area (point to parameters coming in memory).
4971 // reg_save_area
4972 SmallVector<SDOperand, 8> MemOps;
4973 SDOperand FIN = Op.getOperand(1);
4974 // Store gp_offset
4975 SDOperand Store = DAG.getStore(Op.getOperand(0),
4976 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4977 FIN, SV->getValue(), SV->getOffset());
4978 MemOps.push_back(Store);
4979
4980 // Store fp_offset
4981 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4982 DAG.getConstant(4, getPointerTy()));
4983 Store = DAG.getStore(Op.getOperand(0),
4984 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4985 FIN, SV->getValue(), SV->getOffset());
4986 MemOps.push_back(Store);
4987
4988 // Store ptr to overflow_arg_area
4989 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4990 DAG.getConstant(4, getPointerTy()));
4991 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4992 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
4993 SV->getOffset());
4994 MemOps.push_back(Store);
4995
4996 // Store ptr to reg_save_area.
4997 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4998 DAG.getConstant(8, getPointerTy()));
4999 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5000 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
5001 SV->getOffset());
5002 MemOps.push_back(Store);
5003 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5004}
5005
5006SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
5007 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5008 SDOperand Chain = Op.getOperand(0);
5009 SDOperand DstPtr = Op.getOperand(1);
5010 SDOperand SrcPtr = Op.getOperand(2);
5011 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
5012 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
5013
5014 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
5015 SrcSV->getValue(), SrcSV->getOffset());
5016 Chain = SrcPtr.getValue(1);
5017 for (unsigned i = 0; i < 3; ++i) {
5018 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
5019 SrcSV->getValue(), SrcSV->getOffset());
5020 Chain = Val.getValue(1);
5021 Chain = DAG.getStore(Chain, Val, DstPtr,
5022 DstSV->getValue(), DstSV->getOffset());
5023 if (i == 2)
5024 break;
5025 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
5026 DAG.getConstant(8, getPointerTy()));
5027 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
5028 DAG.getConstant(8, getPointerTy()));
5029 }
5030 return Chain;
5031}
5032
5033SDOperand
5034X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5035 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5036 switch (IntNo) {
5037 default: return SDOperand(); // Don't custom lower most intrinsics.
5038 // Comparison intrinsics.
5039 case Intrinsic::x86_sse_comieq_ss:
5040 case Intrinsic::x86_sse_comilt_ss:
5041 case Intrinsic::x86_sse_comile_ss:
5042 case Intrinsic::x86_sse_comigt_ss:
5043 case Intrinsic::x86_sse_comige_ss:
5044 case Intrinsic::x86_sse_comineq_ss:
5045 case Intrinsic::x86_sse_ucomieq_ss:
5046 case Intrinsic::x86_sse_ucomilt_ss:
5047 case Intrinsic::x86_sse_ucomile_ss:
5048 case Intrinsic::x86_sse_ucomigt_ss:
5049 case Intrinsic::x86_sse_ucomige_ss:
5050 case Intrinsic::x86_sse_ucomineq_ss:
5051 case Intrinsic::x86_sse2_comieq_sd:
5052 case Intrinsic::x86_sse2_comilt_sd:
5053 case Intrinsic::x86_sse2_comile_sd:
5054 case Intrinsic::x86_sse2_comigt_sd:
5055 case Intrinsic::x86_sse2_comige_sd:
5056 case Intrinsic::x86_sse2_comineq_sd:
5057 case Intrinsic::x86_sse2_ucomieq_sd:
5058 case Intrinsic::x86_sse2_ucomilt_sd:
5059 case Intrinsic::x86_sse2_ucomile_sd:
5060 case Intrinsic::x86_sse2_ucomigt_sd:
5061 case Intrinsic::x86_sse2_ucomige_sd:
5062 case Intrinsic::x86_sse2_ucomineq_sd: {
5063 unsigned Opc = 0;
5064 ISD::CondCode CC = ISD::SETCC_INVALID;
5065 switch (IntNo) {
5066 default: break;
5067 case Intrinsic::x86_sse_comieq_ss:
5068 case Intrinsic::x86_sse2_comieq_sd:
5069 Opc = X86ISD::COMI;
5070 CC = ISD::SETEQ;
5071 break;
5072 case Intrinsic::x86_sse_comilt_ss:
5073 case Intrinsic::x86_sse2_comilt_sd:
5074 Opc = X86ISD::COMI;
5075 CC = ISD::SETLT;
5076 break;
5077 case Intrinsic::x86_sse_comile_ss:
5078 case Intrinsic::x86_sse2_comile_sd:
5079 Opc = X86ISD::COMI;
5080 CC = ISD::SETLE;
5081 break;
5082 case Intrinsic::x86_sse_comigt_ss:
5083 case Intrinsic::x86_sse2_comigt_sd:
5084 Opc = X86ISD::COMI;
5085 CC = ISD::SETGT;
5086 break;
5087 case Intrinsic::x86_sse_comige_ss:
5088 case Intrinsic::x86_sse2_comige_sd:
5089 Opc = X86ISD::COMI;
5090 CC = ISD::SETGE;
5091 break;
5092 case Intrinsic::x86_sse_comineq_ss:
5093 case Intrinsic::x86_sse2_comineq_sd:
5094 Opc = X86ISD::COMI;
5095 CC = ISD::SETNE;
5096 break;
5097 case Intrinsic::x86_sse_ucomieq_ss:
5098 case Intrinsic::x86_sse2_ucomieq_sd:
5099 Opc = X86ISD::UCOMI;
5100 CC = ISD::SETEQ;
5101 break;
5102 case Intrinsic::x86_sse_ucomilt_ss:
5103 case Intrinsic::x86_sse2_ucomilt_sd:
5104 Opc = X86ISD::UCOMI;
5105 CC = ISD::SETLT;
5106 break;
5107 case Intrinsic::x86_sse_ucomile_ss:
5108 case Intrinsic::x86_sse2_ucomile_sd:
5109 Opc = X86ISD::UCOMI;
5110 CC = ISD::SETLE;
5111 break;
5112 case Intrinsic::x86_sse_ucomigt_ss:
5113 case Intrinsic::x86_sse2_ucomigt_sd:
5114 Opc = X86ISD::UCOMI;
5115 CC = ISD::SETGT;
5116 break;
5117 case Intrinsic::x86_sse_ucomige_ss:
5118 case Intrinsic::x86_sse2_ucomige_sd:
5119 Opc = X86ISD::UCOMI;
5120 CC = ISD::SETGE;
5121 break;
5122 case Intrinsic::x86_sse_ucomineq_ss:
5123 case Intrinsic::x86_sse2_ucomineq_sd:
5124 Opc = X86ISD::UCOMI;
5125 CC = ISD::SETNE;
5126 break;
5127 }
5128
5129 unsigned X86CC;
5130 SDOperand LHS = Op.getOperand(1);
5131 SDOperand RHS = Op.getOperand(2);
5132 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5133
Evan Cheng621216e2007-09-29 00:00:36 +00005134 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5135 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5136 DAG.getConstant(X86CC, MVT::i8), Cond);
5137 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005138 }
5139 }
5140}
5141
5142SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5143 // Depths > 0 not supported yet!
5144 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5145 return SDOperand();
5146
5147 // Just load the return address
5148 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5149 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5150}
5151
5152SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5153 // Depths > 0 not supported yet!
5154 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5155 return SDOperand();
5156
5157 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5158 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5159 DAG.getConstant(4, getPointerTy()));
5160}
5161
5162SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5163 SelectionDAG &DAG) {
5164 // Is not yet supported on x86-64
5165 if (Subtarget->is64Bit())
5166 return SDOperand();
5167
5168 return DAG.getConstant(8, getPointerTy());
5169}
5170
5171SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5172{
5173 assert(!Subtarget->is64Bit() &&
5174 "Lowering of eh_return builtin is not supported yet on x86-64");
5175
5176 MachineFunction &MF = DAG.getMachineFunction();
5177 SDOperand Chain = Op.getOperand(0);
5178 SDOperand Offset = Op.getOperand(1);
5179 SDOperand Handler = Op.getOperand(2);
5180
5181 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5182 getPointerTy());
5183
5184 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5185 DAG.getConstant(-4UL, getPointerTy()));
5186 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5187 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5188 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5189 MF.addLiveOut(X86::ECX);
5190
5191 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5192 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5193}
5194
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005195SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5196 SelectionDAG &DAG) {
5197 SDOperand Root = Op.getOperand(0);
5198 SDOperand Trmp = Op.getOperand(1); // trampoline
5199 SDOperand FPtr = Op.getOperand(2); // nested function
5200 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5201
5202 SrcValueSDNode *TrmpSV = cast<SrcValueSDNode>(Op.getOperand(4));
5203
5204 if (Subtarget->is64Bit()) {
5205 return SDOperand(); // not yet supported
5206 } else {
5207 Function *Func = (Function *)
5208 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5209 unsigned CC = Func->getCallingConv();
Duncan Sands466eadd2007-08-29 19:01:20 +00005210 unsigned NestReg;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005211
5212 switch (CC) {
5213 default:
5214 assert(0 && "Unsupported calling convention");
5215 case CallingConv::C:
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005216 case CallingConv::X86_StdCall: {
5217 // Pass 'nest' parameter in ECX.
5218 // Must be kept in sync with X86CallingConv.td
Duncan Sands466eadd2007-08-29 19:01:20 +00005219 NestReg = X86::ECX;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005220
5221 // Check that ECX wasn't needed by an 'inreg' parameter.
5222 const FunctionType *FTy = Func->getFunctionType();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00005223 const ParamAttrsList *Attrs = Func->getParamAttrs();
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005224
5225 if (Attrs && !Func->isVarArg()) {
5226 unsigned InRegCount = 0;
5227 unsigned Idx = 1;
5228
5229 for (FunctionType::param_iterator I = FTy->param_begin(),
5230 E = FTy->param_end(); I != E; ++I, ++Idx)
5231 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5232 // FIXME: should only count parameters that are lowered to integers.
5233 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5234
5235 if (InRegCount > 2) {
5236 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5237 abort();
5238 }
5239 }
5240 break;
5241 }
5242 case CallingConv::X86_FastCall:
5243 // Pass 'nest' parameter in EAX.
5244 // Must be kept in sync with X86CallingConv.td
Duncan Sands466eadd2007-08-29 19:01:20 +00005245 NestReg = X86::EAX;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005246 break;
5247 }
5248
Duncan Sands466eadd2007-08-29 19:01:20 +00005249 const X86InstrInfo *TII =
5250 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5251
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005252 SDOperand OutChains[4];
5253 SDOperand Addr, Disp;
5254
5255 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5256 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5257
Duncan Sands466eadd2007-08-29 19:01:20 +00005258 unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5259 unsigned char N86Reg = ((X86RegisterInfo&)RegInfo).getX86RegNum(NestReg);
5260 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005261 Trmp, TrmpSV->getValue(), TrmpSV->getOffset());
5262
5263 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5264 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpSV->getValue(),
5265 TrmpSV->getOffset() + 1, false, 1);
5266
Duncan Sands466eadd2007-08-29 19:01:20 +00005267 unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005268 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5269 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5270 TrmpSV->getValue() + 5, TrmpSV->getOffset());
5271
5272 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5273 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpSV->getValue(),
5274 TrmpSV->getOffset() + 6, false, 1);
5275
Duncan Sands7407a9f2007-09-11 14:10:23 +00005276 SDOperand Ops[] =
5277 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5278 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005279 }
5280}
5281
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +00005282SDOperand X86TargetLowering::LowerFLT_ROUNDS(SDOperand Op, SelectionDAG &DAG) {
5283 /*
5284 The rounding mode is in bits 11:10 of FPSR, and has the following
5285 settings:
5286 00 Round to nearest
5287 01 Round to -inf
5288 10 Round to +inf
5289 11 Round to 0
5290
5291 FLT_ROUNDS, on the other hand, expects the following:
5292 -1 Undefined
5293 0 Round to 0
5294 1 Round to nearest
5295 2 Round to +inf
5296 3 Round to -inf
5297
5298 To perform the conversion, we do:
5299 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5300 */
5301
5302 MachineFunction &MF = DAG.getMachineFunction();
5303 const TargetMachine &TM = MF.getTarget();
5304 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5305 unsigned StackAlignment = TFI.getStackAlignment();
5306 MVT::ValueType VT = Op.getValueType();
5307
5308 // Save FP Control Word to stack slot
5309 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5310 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5311
5312 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5313 DAG.getEntryNode(), StackSlot);
5314
5315 // Load FP Control Word from stack slot
5316 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5317
5318 // Transform as necessary
5319 SDOperand CWD1 =
5320 DAG.getNode(ISD::SRL, MVT::i16,
5321 DAG.getNode(ISD::AND, MVT::i16,
5322 CWD, DAG.getConstant(0x800, MVT::i16)),
5323 DAG.getConstant(11, MVT::i8));
5324 SDOperand CWD2 =
5325 DAG.getNode(ISD::SRL, MVT::i16,
5326 DAG.getNode(ISD::AND, MVT::i16,
5327 CWD, DAG.getConstant(0x400, MVT::i16)),
5328 DAG.getConstant(9, MVT::i8));
5329
5330 SDOperand RetVal =
5331 DAG.getNode(ISD::AND, MVT::i16,
5332 DAG.getNode(ISD::ADD, MVT::i16,
5333 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5334 DAG.getConstant(1, MVT::i16)),
5335 DAG.getConstant(3, MVT::i16));
5336
5337
5338 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5339 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5340}
5341
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005342/// LowerOperation - Provide custom lowering hooks for some operations.
5343///
5344SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5345 switch (Op.getOpcode()) {
5346 default: assert(0 && "Should not custom lower this!");
5347 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5348 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5349 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5350 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5351 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5352 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5353 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5354 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5355 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5356 case ISD::SHL_PARTS:
5357 case ISD::SRA_PARTS:
5358 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5359 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5360 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5361 case ISD::FABS: return LowerFABS(Op, DAG);
5362 case ISD::FNEG: return LowerFNEG(Op, DAG);
5363 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
Evan Cheng621216e2007-09-29 00:00:36 +00005364 case ISD::SETCC: return LowerSETCC(Op, DAG);
5365 case ISD::SELECT: return LowerSELECT(Op, DAG);
5366 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005367 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5368 case ISD::CALL: return LowerCALL(Op, DAG);
5369 case ISD::RET: return LowerRET(Op, DAG);
5370 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5371 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5372 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005373 case ISD::VASTART: return LowerVASTART(Op, DAG);
5374 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5375 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5376 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5377 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5378 case ISD::FRAME_TO_ARGS_OFFSET:
5379 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5380 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5381 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005382 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +00005383 case ISD::FLT_ROUNDS: return LowerFLT_ROUNDS(Op, DAG);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005384
5385
5386 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5387 case ISD::READCYCLECOUNTER:
5388 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005389 }
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005390}
5391
5392/// ExpandOperation - Provide custom lowering hooks for expanding operations.
5393SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5394 switch (N->getOpcode()) {
5395 default: assert(0 && "Should not custom lower this!");
5396 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5397 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5398 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005399}
5400
5401const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5402 switch (Opcode) {
5403 default: return NULL;
5404 case X86ISD::SHLD: return "X86ISD::SHLD";
5405 case X86ISD::SHRD: return "X86ISD::SHRD";
5406 case X86ISD::FAND: return "X86ISD::FAND";
5407 case X86ISD::FOR: return "X86ISD::FOR";
5408 case X86ISD::FXOR: return "X86ISD::FXOR";
5409 case X86ISD::FSRL: return "X86ISD::FSRL";
5410 case X86ISD::FILD: return "X86ISD::FILD";
5411 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5412 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5413 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5414 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5415 case X86ISD::FLD: return "X86ISD::FLD";
5416 case X86ISD::FST: return "X86ISD::FST";
5417 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5418 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5419 case X86ISD::CALL: return "X86ISD::CALL";
5420 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5421 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5422 case X86ISD::CMP: return "X86ISD::CMP";
5423 case X86ISD::COMI: return "X86ISD::COMI";
5424 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5425 case X86ISD::SETCC: return "X86ISD::SETCC";
5426 case X86ISD::CMOV: return "X86ISD::CMOV";
5427 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5428 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5429 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5430 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005431 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5432 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5433 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5434 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5435 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5436 case X86ISD::FMAX: return "X86ISD::FMAX";
5437 case X86ISD::FMIN: return "X86ISD::FMIN";
5438 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5439 case X86ISD::FRCP: return "X86ISD::FRCP";
5440 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5441 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5442 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00005443 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +00005444 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005445 }
5446}
5447
5448// isLegalAddressingMode - Return true if the addressing mode represented
5449// by AM is legal for this target, for a load/store of the specified type.
5450bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5451 const Type *Ty) const {
5452 // X86 supports extremely general addressing modes.
5453
5454 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5455 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5456 return false;
5457
5458 if (AM.BaseGV) {
Evan Cheng6a1f3f12007-08-01 23:46:47 +00005459 // We can only fold this if we don't need an extra load.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005460 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5461 return false;
Evan Cheng6a1f3f12007-08-01 23:46:47 +00005462
5463 // X86-64 only supports addr of globals in small code model.
5464 if (Subtarget->is64Bit()) {
5465 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5466 return false;
5467 // If lower 4G is not available, then we must use rip-relative addressing.
5468 if (AM.BaseOffs || AM.Scale > 1)
5469 return false;
5470 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005471 }
5472
5473 switch (AM.Scale) {
5474 case 0:
5475 case 1:
5476 case 2:
5477 case 4:
5478 case 8:
5479 // These scales always work.
5480 break;
5481 case 3:
5482 case 5:
5483 case 9:
5484 // These scales are formed with basereg+scalereg. Only accept if there is
5485 // no basereg yet.
5486 if (AM.HasBaseReg)
5487 return false;
5488 break;
5489 default: // Other stuff never works.
5490 return false;
5491 }
5492
5493 return true;
5494}
5495
5496
Evan Cheng27a820a2007-10-26 01:56:11 +00005497bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5498 if (!Ty1->isInteger() || !Ty2->isInteger())
5499 return false;
Evan Cheng7f152602007-10-29 07:57:50 +00005500 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5501 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5502 if (NumBits1 <= NumBits2)
5503 return false;
5504 return Subtarget->is64Bit() || NumBits1 < 64;
Evan Cheng27a820a2007-10-26 01:56:11 +00005505}
5506
Evan Cheng9decb332007-10-29 19:58:20 +00005507bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5508 MVT::ValueType VT2) const {
5509 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5510 return false;
5511 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5512 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5513 if (NumBits1 <= NumBits2)
5514 return false;
5515 return Subtarget->is64Bit() || NumBits1 < 64;
5516}
Evan Cheng27a820a2007-10-26 01:56:11 +00005517
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005518/// isShuffleMaskLegal - Targets can use this to indicate that they only
5519/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5520/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5521/// are assumed to be legal.
5522bool
5523X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5524 // Only do shuffles on 128-bit vector types for now.
5525 if (MVT::getSizeInBits(VT) == 64) return false;
5526 return (Mask.Val->getNumOperands() <= 4 ||
5527 isIdentityMask(Mask.Val) ||
5528 isIdentityMask(Mask.Val, true) ||
5529 isSplatMask(Mask.Val) ||
5530 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5531 X86::isUNPCKLMask(Mask.Val) ||
5532 X86::isUNPCKHMask(Mask.Val) ||
5533 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5534 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5535}
5536
5537bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5538 MVT::ValueType EVT,
5539 SelectionDAG &DAG) const {
5540 unsigned NumElts = BVOps.size();
5541 // Only do shuffles on 128-bit vector types for now.
5542 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5543 if (NumElts == 2) return true;
5544 if (NumElts == 4) {
5545 return (isMOVLMask(&BVOps[0], 4) ||
5546 isCommutedMOVL(&BVOps[0], 4, true) ||
5547 isSHUFPMask(&BVOps[0], 4) ||
5548 isCommutedSHUFP(&BVOps[0], 4));
5549 }
5550 return false;
5551}
5552
5553//===----------------------------------------------------------------------===//
5554// X86 Scheduler Hooks
5555//===----------------------------------------------------------------------===//
5556
5557MachineBasicBlock *
5558X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
5559 MachineBasicBlock *BB) {
5560 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5561 switch (MI->getOpcode()) {
5562 default: assert(false && "Unexpected instr type to insert");
5563 case X86::CMOV_FR32:
5564 case X86::CMOV_FR64:
5565 case X86::CMOV_V4F32:
5566 case X86::CMOV_V2F64:
Evan Cheng621216e2007-09-29 00:00:36 +00005567 case X86::CMOV_V2I64: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005568 // To "insert" a SELECT_CC instruction, we actually have to insert the
5569 // diamond control-flow pattern. The incoming instruction knows the
5570 // destination vreg to set, the condition code register to branch on, the
5571 // true/false values to select between, and a branch opcode to use.
5572 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5573 ilist<MachineBasicBlock>::iterator It = BB;
5574 ++It;
5575
5576 // thisMBB:
5577 // ...
5578 // TrueVal = ...
5579 // cmpTY ccX, r1, r2
5580 // bCC copy1MBB
5581 // fallthrough --> copy0MBB
5582 MachineBasicBlock *thisMBB = BB;
5583 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5584 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5585 unsigned Opc =
5586 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5587 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5588 MachineFunction *F = BB->getParent();
5589 F->getBasicBlockList().insert(It, copy0MBB);
5590 F->getBasicBlockList().insert(It, sinkMBB);
5591 // Update machine-CFG edges by first adding all successors of the current
5592 // block to the new block which will contain the Phi node for the select.
5593 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5594 e = BB->succ_end(); i != e; ++i)
5595 sinkMBB->addSuccessor(*i);
5596 // Next, remove all successors of the current block, and add the true
5597 // and fallthrough blocks as its successors.
5598 while(!BB->succ_empty())
5599 BB->removeSuccessor(BB->succ_begin());
5600 BB->addSuccessor(copy0MBB);
5601 BB->addSuccessor(sinkMBB);
5602
5603 // copy0MBB:
5604 // %FalseValue = ...
5605 // # fallthrough to sinkMBB
5606 BB = copy0MBB;
5607
5608 // Update machine-CFG edges
5609 BB->addSuccessor(sinkMBB);
5610
5611 // sinkMBB:
5612 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5613 // ...
5614 BB = sinkMBB;
5615 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5616 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5617 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5618
5619 delete MI; // The pseudo instruction is gone now.
5620 return BB;
5621 }
5622
5623 case X86::FP32_TO_INT16_IN_MEM:
5624 case X86::FP32_TO_INT32_IN_MEM:
5625 case X86::FP32_TO_INT64_IN_MEM:
5626 case X86::FP64_TO_INT16_IN_MEM:
5627 case X86::FP64_TO_INT32_IN_MEM:
Dale Johannesen6d0e36a2007-08-07 01:17:37 +00005628 case X86::FP64_TO_INT64_IN_MEM:
5629 case X86::FP80_TO_INT16_IN_MEM:
5630 case X86::FP80_TO_INT32_IN_MEM:
5631 case X86::FP80_TO_INT64_IN_MEM: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005632 // Change the floating point control register to use "round towards zero"
5633 // mode when truncating to an integer value.
5634 MachineFunction *F = BB->getParent();
5635 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5636 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5637
5638 // Load the old value of the high byte of the control word...
5639 unsigned OldCW =
5640 F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
5641 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5642
5643 // Set the high part to be round to zero...
5644 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5645 .addImm(0xC7F);
5646
5647 // Reload the modified control word now...
5648 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5649
5650 // Restore the memory image of control word to original value
5651 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5652 .addReg(OldCW);
5653
5654 // Get the X86 opcode to use.
5655 unsigned Opc;
5656 switch (MI->getOpcode()) {
5657 default: assert(0 && "illegal opcode!");
5658 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5659 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5660 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5661 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5662 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5663 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
Dale Johannesen6d0e36a2007-08-07 01:17:37 +00005664 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5665 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5666 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005667 }
5668
5669 X86AddressMode AM;
5670 MachineOperand &Op = MI->getOperand(0);
5671 if (Op.isRegister()) {
5672 AM.BaseType = X86AddressMode::RegBase;
5673 AM.Base.Reg = Op.getReg();
5674 } else {
5675 AM.BaseType = X86AddressMode::FrameIndexBase;
5676 AM.Base.FrameIndex = Op.getFrameIndex();
5677 }
5678 Op = MI->getOperand(1);
5679 if (Op.isImmediate())
5680 AM.Scale = Op.getImm();
5681 Op = MI->getOperand(2);
5682 if (Op.isImmediate())
5683 AM.IndexReg = Op.getImm();
5684 Op = MI->getOperand(3);
5685 if (Op.isGlobalAddress()) {
5686 AM.GV = Op.getGlobal();
5687 } else {
5688 AM.Disp = Op.getImm();
5689 }
5690 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5691 .addReg(MI->getOperand(4).getReg());
5692
5693 // Reload the original control word now.
5694 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5695
5696 delete MI; // The pseudo instruction is gone now.
5697 return BB;
5698 }
5699 }
5700}
5701
5702//===----------------------------------------------------------------------===//
5703// X86 Optimization Hooks
5704//===----------------------------------------------------------------------===//
5705
5706void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5707 uint64_t Mask,
5708 uint64_t &KnownZero,
5709 uint64_t &KnownOne,
5710 const SelectionDAG &DAG,
5711 unsigned Depth) const {
5712 unsigned Opc = Op.getOpcode();
5713 assert((Opc >= ISD::BUILTIN_OP_END ||
5714 Opc == ISD::INTRINSIC_WO_CHAIN ||
5715 Opc == ISD::INTRINSIC_W_CHAIN ||
5716 Opc == ISD::INTRINSIC_VOID) &&
5717 "Should use MaskedValueIsZero if you don't know whether Op"
5718 " is a target node!");
5719
5720 KnownZero = KnownOne = 0; // Don't know anything.
5721 switch (Opc) {
5722 default: break;
5723 case X86ISD::SETCC:
5724 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5725 break;
5726 }
5727}
5728
5729/// getShuffleScalarElt - Returns the scalar element that will make up the ith
5730/// element of the result of the vector shuffle.
5731static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5732 MVT::ValueType VT = N->getValueType(0);
5733 SDOperand PermMask = N->getOperand(2);
5734 unsigned NumElems = PermMask.getNumOperands();
5735 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5736 i %= NumElems;
5737 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5738 return (i == 0)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00005739 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005740 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5741 SDOperand Idx = PermMask.getOperand(i);
5742 if (Idx.getOpcode() == ISD::UNDEF)
5743 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5744 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5745 }
5746 return SDOperand();
5747}
5748
5749/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5750/// node is a GlobalAddress + an offset.
5751static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5752 unsigned Opc = N->getOpcode();
5753 if (Opc == X86ISD::Wrapper) {
5754 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5755 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5756 return true;
5757 }
5758 } else if (Opc == ISD::ADD) {
5759 SDOperand N1 = N->getOperand(0);
5760 SDOperand N2 = N->getOperand(1);
5761 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5762 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5763 if (V) {
5764 Offset += V->getSignExtended();
5765 return true;
5766 }
5767 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5768 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5769 if (V) {
5770 Offset += V->getSignExtended();
5771 return true;
5772 }
5773 }
5774 }
5775 return false;
5776}
5777
5778/// isConsecutiveLoad - Returns true if N is loading from an address of Base
5779/// + Dist * Size.
5780static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5781 MachineFrameInfo *MFI) {
5782 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5783 return false;
5784
5785 SDOperand Loc = N->getOperand(1);
5786 SDOperand BaseLoc = Base->getOperand(1);
5787 if (Loc.getOpcode() == ISD::FrameIndex) {
5788 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5789 return false;
Dan Gohman53491e92007-07-23 20:24:29 +00005790 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5791 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005792 int FS = MFI->getObjectSize(FI);
5793 int BFS = MFI->getObjectSize(BFI);
5794 if (FS != BFS || FS != Size) return false;
5795 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5796 } else {
5797 GlobalValue *GV1 = NULL;
5798 GlobalValue *GV2 = NULL;
5799 int64_t Offset1 = 0;
5800 int64_t Offset2 = 0;
5801 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5802 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5803 if (isGA1 && isGA2 && GV1 == GV2)
5804 return Offset1 == (Offset2 + Dist*Size);
5805 }
5806
5807 return false;
5808}
5809
5810static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5811 const X86Subtarget *Subtarget) {
5812 GlobalValue *GV;
5813 int64_t Offset;
5814 if (isGAPlusOffset(Base, GV, Offset))
5815 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5816 else {
5817 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
Dan Gohman53491e92007-07-23 20:24:29 +00005818 int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005819 if (BFI < 0)
5820 // Fixed objects do not specify alignment, however the offsets are known.
5821 return ((Subtarget->getStackAlignment() % 16) == 0 &&
5822 (MFI->getObjectOffset(BFI) % 16) == 0);
5823 else
5824 return MFI->getObjectAlignment(BFI) >= 16;
5825 }
5826 return false;
5827}
5828
5829
5830/// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5831/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5832/// if the load addresses are consecutive, non-overlapping, and in the right
5833/// order.
5834static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5835 const X86Subtarget *Subtarget) {
5836 MachineFunction &MF = DAG.getMachineFunction();
5837 MachineFrameInfo *MFI = MF.getFrameInfo();
5838 MVT::ValueType VT = N->getValueType(0);
5839 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5840 SDOperand PermMask = N->getOperand(2);
5841 int NumElems = (int)PermMask.getNumOperands();
5842 SDNode *Base = NULL;
5843 for (int i = 0; i < NumElems; ++i) {
5844 SDOperand Idx = PermMask.getOperand(i);
5845 if (Idx.getOpcode() == ISD::UNDEF) {
5846 if (!Base) return SDOperand();
5847 } else {
5848 SDOperand Arg =
5849 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5850 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5851 return SDOperand();
5852 if (!Base)
5853 Base = Arg.Val;
5854 else if (!isConsecutiveLoad(Arg.Val, Base,
5855 i, MVT::getSizeInBits(EVT)/8,MFI))
5856 return SDOperand();
5857 }
5858 }
5859
5860 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
Dan Gohman11821702007-07-27 17:16:43 +00005861 LoadSDNode *LD = cast<LoadSDNode>(Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005862 if (isAlign16) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005863 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
Dan Gohman11821702007-07-27 17:16:43 +00005864 LD->getSrcValueOffset(), LD->isVolatile());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005865 } else {
Dan Gohman11821702007-07-27 17:16:43 +00005866 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5867 LD->getSrcValueOffset(), LD->isVolatile(),
5868 LD->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005869 }
5870}
5871
5872/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5873static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5874 const X86Subtarget *Subtarget) {
5875 SDOperand Cond = N->getOperand(0);
5876
5877 // If we have SSE[12] support, try to form min/max nodes.
5878 if (Subtarget->hasSSE2() &&
5879 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5880 if (Cond.getOpcode() == ISD::SETCC) {
5881 // Get the LHS/RHS of the select.
5882 SDOperand LHS = N->getOperand(1);
5883 SDOperand RHS = N->getOperand(2);
5884 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5885
5886 unsigned Opcode = 0;
5887 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5888 switch (CC) {
5889 default: break;
5890 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5891 case ISD::SETULE:
5892 case ISD::SETLE:
5893 if (!UnsafeFPMath) break;
5894 // FALL THROUGH.
5895 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
5896 case ISD::SETLT:
5897 Opcode = X86ISD::FMIN;
5898 break;
5899
5900 case ISD::SETOGT: // (X > Y) ? X : Y -> max
5901 case ISD::SETUGT:
5902 case ISD::SETGT:
5903 if (!UnsafeFPMath) break;
5904 // FALL THROUGH.
5905 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
5906 case ISD::SETGE:
5907 Opcode = X86ISD::FMAX;
5908 break;
5909 }
5910 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5911 switch (CC) {
5912 default: break;
5913 case ISD::SETOGT: // (X > Y) ? Y : X -> min
5914 case ISD::SETUGT:
5915 case ISD::SETGT:
5916 if (!UnsafeFPMath) break;
5917 // FALL THROUGH.
5918 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
5919 case ISD::SETGE:
5920 Opcode = X86ISD::FMIN;
5921 break;
5922
5923 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
5924 case ISD::SETULE:
5925 case ISD::SETLE:
5926 if (!UnsafeFPMath) break;
5927 // FALL THROUGH.
5928 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
5929 case ISD::SETLT:
5930 Opcode = X86ISD::FMAX;
5931 break;
5932 }
5933 }
5934
5935 if (Opcode)
5936 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5937 }
5938
5939 }
5940
5941 return SDOperand();
5942}
5943
5944
5945SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5946 DAGCombinerInfo &DCI) const {
5947 SelectionDAG &DAG = DCI.DAG;
5948 switch (N->getOpcode()) {
5949 default: break;
5950 case ISD::VECTOR_SHUFFLE:
5951 return PerformShuffleCombine(N, DAG, Subtarget);
5952 case ISD::SELECT:
5953 return PerformSELECTCombine(N, DAG, Subtarget);
5954 }
5955
5956 return SDOperand();
5957}
5958
5959//===----------------------------------------------------------------------===//
5960// X86 Inline Assembly Support
5961//===----------------------------------------------------------------------===//
5962
5963/// getConstraintType - Given a constraint letter, return the type of
5964/// constraint it is for this target.
5965X86TargetLowering::ConstraintType
5966X86TargetLowering::getConstraintType(const std::string &Constraint) const {
5967 if (Constraint.size() == 1) {
5968 switch (Constraint[0]) {
5969 case 'A':
5970 case 'r':
5971 case 'R':
5972 case 'l':
5973 case 'q':
5974 case 'Q':
5975 case 'x':
5976 case 'Y':
5977 return C_RegisterClass;
5978 default:
5979 break;
5980 }
5981 }
5982 return TargetLowering::getConstraintType(Constraint);
5983}
5984
Chris Lattnera531abc2007-08-25 00:47:38 +00005985/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5986/// vector. If it is invalid, don't add anything to Ops.
5987void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
5988 char Constraint,
5989 std::vector<SDOperand>&Ops,
5990 SelectionDAG &DAG) {
5991 SDOperand Result(0, 0);
5992
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005993 switch (Constraint) {
5994 default: break;
5995 case 'I':
5996 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
Chris Lattnera531abc2007-08-25 00:47:38 +00005997 if (C->getValue() <= 31) {
5998 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5999 break;
6000 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006001 }
Chris Lattnera531abc2007-08-25 00:47:38 +00006002 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006003 case 'N':
6004 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
Chris Lattnera531abc2007-08-25 00:47:38 +00006005 if (C->getValue() <= 255) {
6006 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6007 break;
6008 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006009 }
Chris Lattnera531abc2007-08-25 00:47:38 +00006010 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006011 case 'i': {
6012 // Literal immediates are always ok.
Chris Lattnera531abc2007-08-25 00:47:38 +00006013 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6014 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6015 break;
6016 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006017
6018 // If we are in non-pic codegen mode, we allow the address of a global (with
6019 // an optional displacement) to be used with 'i'.
6020 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6021 int64_t Offset = 0;
6022
6023 // Match either (GA) or (GA+C)
6024 if (GA) {
6025 Offset = GA->getOffset();
6026 } else if (Op.getOpcode() == ISD::ADD) {
6027 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6028 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6029 if (C && GA) {
6030 Offset = GA->getOffset()+C->getValue();
6031 } else {
6032 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6033 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6034 if (C && GA)
6035 Offset = GA->getOffset()+C->getValue();
6036 else
6037 C = 0, GA = 0;
6038 }
6039 }
6040
6041 if (GA) {
6042 // If addressing this global requires a load (e.g. in PIC mode), we can't
6043 // match.
6044 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6045 false))
Chris Lattnera531abc2007-08-25 00:47:38 +00006046 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006047
6048 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6049 Offset);
Chris Lattnera531abc2007-08-25 00:47:38 +00006050 Result = Op;
6051 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006052 }
6053
6054 // Otherwise, not valid for this mode.
Chris Lattnera531abc2007-08-25 00:47:38 +00006055 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006056 }
6057 }
Chris Lattnera531abc2007-08-25 00:47:38 +00006058
6059 if (Result.Val) {
6060 Ops.push_back(Result);
6061 return;
6062 }
6063 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006064}
6065
6066std::vector<unsigned> X86TargetLowering::
6067getRegClassForInlineAsmConstraint(const std::string &Constraint,
6068 MVT::ValueType VT) const {
6069 if (Constraint.size() == 1) {
6070 // FIXME: not handling fp-stack yet!
6071 switch (Constraint[0]) { // GCC X86 Constraint Letters
6072 default: break; // Unknown constraint letter
6073 case 'A': // EAX/EDX
6074 if (VT == MVT::i32 || VT == MVT::i64)
6075 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6076 break;
6077 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6078 case 'Q': // Q_REGS
6079 if (VT == MVT::i32)
6080 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6081 else if (VT == MVT::i16)
6082 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6083 else if (VT == MVT::i8)
Evan Chengf85c10f2007-08-13 23:27:11 +00006084 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
Chris Lattner35032592007-11-04 06:51:12 +00006085 else if (VT == MVT::i64)
6086 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6087 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006088 }
6089 }
6090
6091 return std::vector<unsigned>();
6092}
6093
6094std::pair<unsigned, const TargetRegisterClass*>
6095X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6096 MVT::ValueType VT) const {
6097 // First, see if this is a constraint that directly corresponds to an LLVM
6098 // register class.
6099 if (Constraint.size() == 1) {
6100 // GCC Constraint Letters
6101 switch (Constraint[0]) {
6102 default: break;
6103 case 'r': // GENERAL_REGS
6104 case 'R': // LEGACY_REGS
6105 case 'l': // INDEX_REGS
6106 if (VT == MVT::i64 && Subtarget->is64Bit())
6107 return std::make_pair(0U, X86::GR64RegisterClass);
6108 if (VT == MVT::i32)
6109 return std::make_pair(0U, X86::GR32RegisterClass);
6110 else if (VT == MVT::i16)
6111 return std::make_pair(0U, X86::GR16RegisterClass);
6112 else if (VT == MVT::i8)
6113 return std::make_pair(0U, X86::GR8RegisterClass);
6114 break;
6115 case 'y': // MMX_REGS if MMX allowed.
6116 if (!Subtarget->hasMMX()) break;
6117 return std::make_pair(0U, X86::VR64RegisterClass);
6118 break;
6119 case 'Y': // SSE_REGS if SSE2 allowed
6120 if (!Subtarget->hasSSE2()) break;
6121 // FALL THROUGH.
6122 case 'x': // SSE_REGS if SSE1 allowed
6123 if (!Subtarget->hasSSE1()) break;
6124
6125 switch (VT) {
6126 default: break;
6127 // Scalar SSE types.
6128 case MVT::f32:
6129 case MVT::i32:
6130 return std::make_pair(0U, X86::FR32RegisterClass);
6131 case MVT::f64:
6132 case MVT::i64:
6133 return std::make_pair(0U, X86::FR64RegisterClass);
6134 // Vector types.
6135 case MVT::v16i8:
6136 case MVT::v8i16:
6137 case MVT::v4i32:
6138 case MVT::v2i64:
6139 case MVT::v4f32:
6140 case MVT::v2f64:
6141 return std::make_pair(0U, X86::VR128RegisterClass);
6142 }
6143 break;
6144 }
6145 }
6146
6147 // Use the default implementation in TargetLowering to convert the register
6148 // constraint into a member of a register class.
6149 std::pair<unsigned, const TargetRegisterClass*> Res;
6150 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6151
6152 // Not found as a standard register?
6153 if (Res.second == 0) {
6154 // GCC calls "st(0)" just plain "st".
6155 if (StringsEqualNoCase("{st}", Constraint)) {
6156 Res.first = X86::ST0;
Chris Lattner3cfe51b2007-09-24 05:27:37 +00006157 Res.second = X86::RFP80RegisterClass;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006158 }
6159
6160 return Res;
6161 }
6162
6163 // Otherwise, check to see if this is a register class of the wrong value
6164 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6165 // turn into {ax},{dx}.
6166 if (Res.second->hasType(VT))
6167 return Res; // Correct type already, nothing to do.
6168
6169 // All of the single-register GCC register classes map their values onto
6170 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6171 // really want an 8-bit or 32-bit register, map to the appropriate register
6172 // class and return the appropriate register.
6173 if (Res.second != X86::GR16RegisterClass)
6174 return Res;
6175
6176 if (VT == MVT::i8) {
6177 unsigned DestReg = 0;
6178 switch (Res.first) {
6179 default: break;
6180 case X86::AX: DestReg = X86::AL; break;
6181 case X86::DX: DestReg = X86::DL; break;
6182 case X86::CX: DestReg = X86::CL; break;
6183 case X86::BX: DestReg = X86::BL; break;
6184 }
6185 if (DestReg) {
6186 Res.first = DestReg;
6187 Res.second = Res.second = X86::GR8RegisterClass;
6188 }
6189 } else if (VT == MVT::i32) {
6190 unsigned DestReg = 0;
6191 switch (Res.first) {
6192 default: break;
6193 case X86::AX: DestReg = X86::EAX; break;
6194 case X86::DX: DestReg = X86::EDX; break;
6195 case X86::CX: DestReg = X86::ECX; break;
6196 case X86::BX: DestReg = X86::EBX; break;
6197 case X86::SI: DestReg = X86::ESI; break;
6198 case X86::DI: DestReg = X86::EDI; break;
6199 case X86::BP: DestReg = X86::EBP; break;
6200 case X86::SP: DestReg = X86::ESP; break;
6201 }
6202 if (DestReg) {
6203 Res.first = DestReg;
6204 Res.second = Res.second = X86::GR32RegisterClass;
6205 }
6206 } else if (VT == MVT::i64) {
6207 unsigned DestReg = 0;
6208 switch (Res.first) {
6209 default: break;
6210 case X86::AX: DestReg = X86::RAX; break;
6211 case X86::DX: DestReg = X86::RDX; break;
6212 case X86::CX: DestReg = X86::RCX; break;
6213 case X86::BX: DestReg = X86::RBX; break;
6214 case X86::SI: DestReg = X86::RSI; break;
6215 case X86::DI: DestReg = X86::RDI; break;
6216 case X86::BP: DestReg = X86::RBP; break;
6217 case X86::SP: DestReg = X86::RSP; break;
6218 }
6219 if (DestReg) {
6220 Res.first = DestReg;
6221 Res.second = Res.second = X86::GR64RegisterClass;
6222 }
6223 }
6224
6225 return Res;
6226}