blob: 939ddf819a6dc654ede039224907a5206950fc2b [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2//
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"
Duncan Sandsd8455ca2007-07-27 20:02:49 +000016#include "X86CodeEmitter.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000017#include "X86InstrBuilder.h"
18#include "X86ISelLowering.h"
19#include "X86MachineFunctionInfo.h"
20#include "X86TargetMachine.h"
21#include "llvm/CallingConv.h"
22#include "llvm/Constants.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/GlobalVariable.h"
25#include "llvm/Function.h"
26#include "llvm/Intrinsics.h"
27#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"
36#include "llvm/Target/TargetOptions.h"
37#include "llvm/ADT/StringExtras.h"
Duncan Sandsd8455ca2007-07-27 20:02:49 +000038#include "llvm/ParameterAttributes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039using namespace llvm;
40
41X86TargetLowering::X86TargetLowering(TargetMachine &TM)
42 : TargetLowering(TM) {
43 Subtarget = &TM.getSubtarget<X86Subtarget>();
44 X86ScalarSSE = Subtarget->hasSSE2();
45 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
46
47 RegInfo = TM.getRegisterInfo();
48
49 // Set up the TargetLowering object.
50
51 // X86 is weird, it always uses i8 for shift amounts and setcc results.
52 setShiftAmountType(MVT::i8);
53 setSetCCResultType(MVT::i8);
54 setSetCCResultContents(ZeroOrOneSetCCResult);
55 setSchedulingPreference(SchedulingForRegPressure);
56 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
57 setStackPointerRegisterToSaveRestore(X86StackPtr);
58
59 if (Subtarget->isTargetDarwin()) {
60 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
61 setUseUnderscoreSetJmp(false);
62 setUseUnderscoreLongJmp(false);
63 } else if (Subtarget->isTargetMingw()) {
64 // MS runtime is weird: it exports _setjmp, but longjmp!
65 setUseUnderscoreSetJmp(true);
66 setUseUnderscoreLongJmp(false);
67 } else {
68 setUseUnderscoreSetJmp(true);
69 setUseUnderscoreLongJmp(true);
70 }
71
72 // Set up the register classes.
73 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
74 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
75 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
76 if (Subtarget->is64Bit())
77 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
78
79 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
80
81 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
82 // operation.
83 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
84 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
85 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
86
87 if (Subtarget->is64Bit()) {
88 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
89 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
90 } else {
91 if (X86ScalarSSE)
92 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
93 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
94 else
95 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
96 }
97
98 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
99 // this operation.
100 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
101 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
102 // SSE has no i16 to fp conversion, only i32
103 if (X86ScalarSSE)
104 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
105 else {
106 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
107 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
108 }
109
110 if (!Subtarget->is64Bit()) {
111 // Custom lower SINT_TO_FP and FP_TO_SINT from/to i64 in 32-bit mode.
112 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
113 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
114 }
115
116 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
117 // this operation.
118 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
119 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
120
121 if (X86ScalarSSE) {
122 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
123 } else {
124 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
125 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
126 }
127
128 // Handle FP_TO_UINT by promoting the destination to a larger signed
129 // conversion.
130 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
131 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
132 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
133
134 if (Subtarget->is64Bit()) {
135 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
136 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
137 } else {
138 if (X86ScalarSSE && !Subtarget->hasSSE3())
139 // Expand FP_TO_UINT into a select.
140 // FIXME: We would like to use a Custom expander here eventually to do
141 // the optimal thing for SSE vs. the default expansion in the legalizer.
142 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
143 else
144 // With SSE3 we can use fisttpll to convert to a signed i64.
145 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
146 }
147
148 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
149 if (!X86ScalarSSE) {
150 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
151 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
152 }
153
154 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
155 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
156 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
157 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
158 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
159 if (Subtarget->is64Bit())
160 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Expand);
161 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Expand);
162 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
163 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
164 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
165 setOperationAction(ISD::FREM , MVT::f64 , Expand);
166
167 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
168 setOperationAction(ISD::CTTZ , MVT::i8 , Expand);
169 setOperationAction(ISD::CTLZ , MVT::i8 , Expand);
170 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
171 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
172 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
173 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
174 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
175 setOperationAction(ISD::CTLZ , MVT::i32 , Expand);
176 if (Subtarget->is64Bit()) {
177 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
178 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
179 setOperationAction(ISD::CTLZ , MVT::i64 , Expand);
180 }
181
182 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
183 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
184
185 // These should be promoted to a larger select which is supported.
186 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
187 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
188 // X86 wants to expand cmov itself.
189 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
190 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
191 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
192 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
193 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
194 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
195 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
196 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
197 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
198 if (Subtarget->is64Bit()) {
199 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
200 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
201 }
202 // X86 ret instruction may pop stack.
203 setOperationAction(ISD::RET , MVT::Other, Custom);
204 if (!Subtarget->is64Bit())
205 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
206
207 // Darwin ABI issue.
208 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
209 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
210 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
211 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
212 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
213 if (Subtarget->is64Bit()) {
214 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
215 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
216 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
217 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
218 }
219 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
220 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
221 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
222 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
223 // X86 wants to expand memset / memcpy itself.
224 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
225 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
226
227 // We don't have line number support yet.
228 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
229 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
230 // FIXME - use subtarget debug flags
231 if (!Subtarget->isTargetDarwin() &&
232 !Subtarget->isTargetELF() &&
233 !Subtarget->isTargetCygMing())
234 setOperationAction(ISD::LABEL, MVT::Other, Expand);
235
236 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
237 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
238 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
239 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
240 if (Subtarget->is64Bit()) {
241 // FIXME: Verify
242 setExceptionPointerRegister(X86::RAX);
243 setExceptionSelectorRegister(X86::RDX);
244 } else {
245 setExceptionPointerRegister(X86::EAX);
246 setExceptionSelectorRegister(X86::EDX);
247 }
248
Duncan Sandsd8455ca2007-07-27 20:02:49 +0000249 setOperationAction(ISD::ADJUST_TRAMP, MVT::i32, Expand);
250 setOperationAction(ISD::ADJUST_TRAMP, MVT::i64, Expand);
251 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
252
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
254 setOperationAction(ISD::VASTART , MVT::Other, Custom);
255 setOperationAction(ISD::VAARG , MVT::Other, Expand);
256 setOperationAction(ISD::VAEND , MVT::Other, Expand);
257 if (Subtarget->is64Bit())
258 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
259 else
260 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
261
262 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
263 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
264 if (Subtarget->is64Bit())
265 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
266 if (Subtarget->isTargetCygMing())
267 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
268 else
269 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
270
271 if (X86ScalarSSE) {
272 // Set up the FP register classes.
273 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
274 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
275
276 // Use ANDPD to simulate FABS.
277 setOperationAction(ISD::FABS , MVT::f64, Custom);
278 setOperationAction(ISD::FABS , MVT::f32, Custom);
279
280 // Use XORP to simulate FNEG.
281 setOperationAction(ISD::FNEG , MVT::f64, Custom);
282 setOperationAction(ISD::FNEG , MVT::f32, Custom);
283
284 // Use ANDPD and ORPD to simulate FCOPYSIGN.
285 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
286 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
287
288 // We don't support sin/cos/fmod
289 setOperationAction(ISD::FSIN , MVT::f64, Expand);
290 setOperationAction(ISD::FCOS , MVT::f64, Expand);
291 setOperationAction(ISD::FREM , MVT::f64, Expand);
292 setOperationAction(ISD::FSIN , MVT::f32, Expand);
293 setOperationAction(ISD::FCOS , MVT::f32, Expand);
294 setOperationAction(ISD::FREM , MVT::f32, Expand);
295
296 // Expand FP immediates into loads from the stack, except for the special
297 // cases we handle.
298 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
299 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
300 addLegalFPImmediate(+0.0); // xorps / xorpd
301 } else {
302 // Set up the FP register classes.
303 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
304 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
305
306 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
307 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
308 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
309 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
310 setOperationAction(ISD::FP_ROUND, MVT::f32, Expand);
311
312 if (!UnsafeFPMath) {
313 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
314 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
315 }
316
317 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
318 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
319 addLegalFPImmediate(+0.0); // FLD0
320 addLegalFPImmediate(+1.0); // FLD1
321 addLegalFPImmediate(-0.0); // FLD0/FCHS
322 addLegalFPImmediate(-1.0); // FLD1/FCHS
323 }
324
325 // First set operation action for all vector types to expand. Then we
326 // will selectively turn on ones that can be effectively codegen'd.
327 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
328 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
329 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
330 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
331 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
332 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
333 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
334 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
335 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
336 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
337 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
338 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
339 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
340 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
341 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
342 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
343 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
344 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
345 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
346 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
347 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
348 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
349 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
350 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
351 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
352 }
353
354 if (Subtarget->hasMMX()) {
355 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
356 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
357 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
358 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
359
360 // FIXME: add MMX packed arithmetics
361
362 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
363 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
364 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
365 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
366
367 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
368 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
369 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
370
371 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
372 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
373
374 setOperationAction(ISD::AND, MVT::v8i8, Promote);
375 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
376 setOperationAction(ISD::AND, MVT::v4i16, Promote);
377 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
378 setOperationAction(ISD::AND, MVT::v2i32, Promote);
379 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
380 setOperationAction(ISD::AND, MVT::v1i64, Legal);
381
382 setOperationAction(ISD::OR, MVT::v8i8, Promote);
383 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
384 setOperationAction(ISD::OR, MVT::v4i16, Promote);
385 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
386 setOperationAction(ISD::OR, MVT::v2i32, Promote);
387 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
388 setOperationAction(ISD::OR, MVT::v1i64, Legal);
389
390 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
391 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
392 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
393 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
394 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
395 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
396 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
397
398 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
399 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
400 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
401 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
402 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
403 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
404 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
405
406 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
407 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
408 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
409 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
410
411 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
412 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
413 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
414 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
415
416 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
417 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
418 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
419 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
420 }
421
422 if (Subtarget->hasSSE1()) {
423 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
424
425 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
426 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
427 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
428 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
429 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
430 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
432 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
433 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
434 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
435 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
436 }
437
438 if (Subtarget->hasSSE2()) {
439 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
440 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
441 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
442 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
443 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
444
445 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
446 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
447 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
448 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
449 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
450 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
451 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
452 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
453 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
454 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
455 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
456 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
457 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
458 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
459 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460
461 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
462 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
463 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
464 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
465 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
466 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
467
468 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
469 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
470 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
471 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
472 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
473 }
474 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
475 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
476 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
477 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
478 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
479 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
480
481 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
482 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
483 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
484 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
485 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
486 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
487 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
488 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
489 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
490 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
491 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
492 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
493 }
494
495 // Custom lower v2i64 and v2f64 selects.
496 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
497 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
498 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
499 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
500 }
501
502 // We want to custom lower some of our intrinsics.
503 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
504
505 // We have target-specific dag combine patterns for the following nodes:
506 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
507 setTargetDAGCombine(ISD::SELECT);
508
509 computeRegisterProperties();
510
511 // FIXME: These should be based on subtarget info. Plus, the values should
512 // be smaller when we are in optimizing for size mode.
513 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
514 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
515 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
516 allowUnalignedMemoryAccesses = true; // x86 supports it!
517}
518
519
520//===----------------------------------------------------------------------===//
521// Return Value Calling Convention Implementation
522//===----------------------------------------------------------------------===//
523
524#include "X86GenCallingConv.inc"
525
526/// LowerRET - Lower an ISD::RET node.
527SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
528 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
529
530 SmallVector<CCValAssign, 16> RVLocs;
531 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
532 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
533 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
534 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
535
536
537 // If this is the first return lowered for this function, add the regs to the
538 // liveout set for the function.
539 if (DAG.getMachineFunction().liveout_empty()) {
540 for (unsigned i = 0; i != RVLocs.size(); ++i)
541 if (RVLocs[i].isRegLoc())
542 DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
543 }
544
545 SDOperand Chain = Op.getOperand(0);
546 SDOperand Flag;
547
548 // Copy the result values into the output registers.
549 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
550 RVLocs[0].getLocReg() != X86::ST0) {
551 for (unsigned i = 0; i != RVLocs.size(); ++i) {
552 CCValAssign &VA = RVLocs[i];
553 assert(VA.isRegLoc() && "Can only return in registers!");
554 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
555 Flag);
556 Flag = Chain.getValue(1);
557 }
558 } else {
559 // We need to handle a destination of ST0 specially, because it isn't really
560 // a register.
561 SDOperand Value = Op.getOperand(1);
562
563 // If this is an FP return with ScalarSSE, we need to move the value from
564 // an XMM register onto the fp-stack.
565 if (X86ScalarSSE) {
566 SDOperand MemLoc;
567
568 // If this is a load into a scalarsse value, don't store the loaded value
569 // back to the stack, only to reload it: just replace the scalar-sse load.
570 if (ISD::isNON_EXTLoad(Value.Val) &&
571 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
572 Chain = Value.getOperand(0);
573 MemLoc = Value.getOperand(1);
574 } else {
575 // Spill the value to memory and reload it into top of stack.
576 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
577 MachineFunction &MF = DAG.getMachineFunction();
578 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
579 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
580 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
581 }
582 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
583 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
584 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
585 Chain = Value.getValue(1);
586 }
587
588 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
589 SDOperand Ops[] = { Chain, Value };
590 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
591 Flag = Chain.getValue(1);
592 }
593
594 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
595 if (Flag.Val)
596 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
597 else
598 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
599}
600
601
602/// LowerCallResult - Lower the result values of an ISD::CALL into the
603/// appropriate copies out of appropriate physical registers. This assumes that
604/// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
605/// being lowered. The returns a SDNode with the same number of values as the
606/// ISD::CALL.
607SDNode *X86TargetLowering::
608LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
609 unsigned CallingConv, SelectionDAG &DAG) {
610
611 // Assign locations to each value returned by this call.
612 SmallVector<CCValAssign, 16> RVLocs;
613 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
614 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
615 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
616
617
618 SmallVector<SDOperand, 8> ResultVals;
619
620 // Copy all of the result registers out of their specified physreg.
621 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
622 for (unsigned i = 0; i != RVLocs.size(); ++i) {
623 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
624 RVLocs[i].getValVT(), InFlag).getValue(1);
625 InFlag = Chain.getValue(2);
626 ResultVals.push_back(Chain.getValue(0));
627 }
628 } else {
629 // Copies from the FP stack are special, as ST0 isn't a valid register
630 // before the fp stackifier runs.
631
632 // Copy ST0 into an RFP register with FP_GET_RESULT.
633 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
634 SDOperand GROps[] = { Chain, InFlag };
635 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
636 Chain = RetVal.getValue(1);
637 InFlag = RetVal.getValue(2);
638
639 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
640 // an XMM register.
641 if (X86ScalarSSE) {
642 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
643 // shouldn't be necessary except that RFP cannot be live across
644 // multiple blocks. When stackifier is fixed, they can be uncoupled.
645 MachineFunction &MF = DAG.getMachineFunction();
646 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
647 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
648 SDOperand Ops[] = {
649 Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
650 };
651 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
652 RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
653 Chain = RetVal.getValue(1);
654 }
655 ResultVals.push_back(RetVal);
656 }
657
658 // Merge everything together with a MERGE_VALUES node.
659 ResultVals.push_back(Chain);
660 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
661 &ResultVals[0], ResultVals.size()).Val;
662}
663
664
665//===----------------------------------------------------------------------===//
666// C & StdCall Calling Convention implementation
667//===----------------------------------------------------------------------===//
668// StdCall calling convention seems to be standard for many Windows' API
669// routines and around. It differs from C calling convention just a little:
670// callee should clean up the stack, not caller. Symbols should be also
671// decorated in some fancy way :) It doesn't support any vector arguments.
672
673/// AddLiveIn - This helper function adds the specified physical register to the
674/// MachineFunction as a live in value. It also creates a corresponding virtual
675/// register for it.
676static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
677 const TargetRegisterClass *RC) {
678 assert(RC->contains(PReg) && "Not the correct regclass!");
679 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
680 MF.addLiveIn(PReg, VReg);
681 return VReg;
682}
683
684SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
685 bool isStdCall) {
686 unsigned NumArgs = Op.Val->getNumValues() - 1;
687 MachineFunction &MF = DAG.getMachineFunction();
688 MachineFrameInfo *MFI = MF.getFrameInfo();
689 SDOperand Root = Op.getOperand(0);
690 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
691
692 // Assign locations to all of the incoming arguments.
693 SmallVector<CCValAssign, 16> ArgLocs;
694 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
695 getTargetMachine(), ArgLocs);
696 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
697
698 SmallVector<SDOperand, 8> ArgValues;
699 unsigned LastVal = ~0U;
700 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
701 CCValAssign &VA = ArgLocs[i];
702 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
703 // places.
704 assert(VA.getValNo() != LastVal &&
705 "Don't support value assigned to multiple locs yet");
706 LastVal = VA.getValNo();
707
708 if (VA.isRegLoc()) {
709 MVT::ValueType RegVT = VA.getLocVT();
710 TargetRegisterClass *RC;
711 if (RegVT == MVT::i32)
712 RC = X86::GR32RegisterClass;
713 else {
714 assert(MVT::isVector(RegVT));
715 RC = X86::VR128RegisterClass;
716 }
717
718 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
719 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
720
721 // If this is an 8 or 16-bit value, it is really passed promoted to 32
722 // bits. Insert an assert[sz]ext to capture this, then truncate to the
723 // right size.
724 if (VA.getLocInfo() == CCValAssign::SExt)
725 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
726 DAG.getValueType(VA.getValVT()));
727 else if (VA.getLocInfo() == CCValAssign::ZExt)
728 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
729 DAG.getValueType(VA.getValVT()));
730
731 if (VA.getLocInfo() != CCValAssign::Full)
732 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
733
734 ArgValues.push_back(ArgValue);
735 } else {
736 assert(VA.isMemLoc());
737
738 // Create the nodes corresponding to a load from this parameter slot.
739 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
740 VA.getLocMemOffset());
741 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
742 ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
743 }
744 }
745
746 unsigned StackSize = CCInfo.getNextStackOffset();
747
748 ArgValues.push_back(Root);
749
750 // If the function takes variable number of arguments, make a frame index for
751 // the start of the first vararg value... for expansion of llvm.va_start.
752 if (isVarArg)
753 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
754
755 if (isStdCall && !isVarArg) {
756 BytesToPopOnReturn = StackSize; // Callee pops everything..
757 BytesCallerReserves = 0;
758 } else {
759 BytesToPopOnReturn = 0; // Callee pops nothing.
760
761 // If this is an sret function, the return should pop the hidden pointer.
762 if (NumArgs &&
763 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
764 ISD::ParamFlags::StructReturn))
765 BytesToPopOnReturn = 4;
766
767 BytesCallerReserves = StackSize;
768 }
769
770 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
771 ReturnAddrIndex = 0; // No return address slot generated yet.
772
773 MF.getInfo<X86MachineFunctionInfo>()
774 ->setBytesToPopOnReturn(BytesToPopOnReturn);
775
776 // Return the new list of results.
777 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
778 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
779}
780
781SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
782 unsigned CC) {
783 SDOperand Chain = Op.getOperand(0);
784 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
785 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
786 SDOperand Callee = Op.getOperand(4);
787 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
788
789 // Analyze operands of the call, assigning locations to each operand.
790 SmallVector<CCValAssign, 16> ArgLocs;
791 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
792 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
793
794 // Get a count of how many bytes are to be pushed on the stack.
795 unsigned NumBytes = CCInfo.getNextStackOffset();
796
797 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
798
799 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
800 SmallVector<SDOperand, 8> MemOpChains;
801
802 SDOperand StackPtr;
803
804 // Walk the register/memloc assignments, inserting copies/loads.
805 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
806 CCValAssign &VA = ArgLocs[i];
807 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
808
809 // Promote the value if needed.
810 switch (VA.getLocInfo()) {
811 default: assert(0 && "Unknown loc info!");
812 case CCValAssign::Full: break;
813 case CCValAssign::SExt:
814 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
815 break;
816 case CCValAssign::ZExt:
817 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
818 break;
819 case CCValAssign::AExt:
820 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
821 break;
822 }
823
824 if (VA.isRegLoc()) {
825 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
826 } else {
827 assert(VA.isMemLoc());
828 if (StackPtr.Val == 0)
829 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
830 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
831 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
832 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
833 }
834 }
835
836 // If the first argument is an sret pointer, remember it.
837 bool isSRet = NumOps &&
838 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
839 ISD::ParamFlags::StructReturn);
840
841 if (!MemOpChains.empty())
842 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
843 &MemOpChains[0], MemOpChains.size());
844
845 // Build a sequence of copy-to-reg nodes chained together with token chain
846 // and flag operands which copy the outgoing args into registers.
847 SDOperand InFlag;
848 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
849 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
850 InFlag);
851 InFlag = Chain.getValue(1);
852 }
853
854 // ELF / PIC requires GOT in the EBX register before function calls via PLT
855 // GOT pointer.
856 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
857 Subtarget->isPICStyleGOT()) {
858 Chain = DAG.getCopyToReg(Chain, X86::EBX,
859 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
860 InFlag);
861 InFlag = Chain.getValue(1);
862 }
863
864 // If the callee is a GlobalAddress node (quite common, every direct call is)
865 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
866 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
867 // We should use extra load for direct calls to dllimported functions in
868 // non-JIT mode.
869 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
870 getTargetMachine(), true))
871 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
872 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
873 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
874
875 // Returns a chain & a flag for retval copy to use.
876 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
877 SmallVector<SDOperand, 8> Ops;
878 Ops.push_back(Chain);
879 Ops.push_back(Callee);
880
881 // Add argument registers to the end of the list so that they are known live
882 // into the call.
883 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
884 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
885 RegsToPass[i].second.getValueType()));
886
887 // Add an implicit use GOT pointer in EBX.
888 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
889 Subtarget->isPICStyleGOT())
890 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
891
892 if (InFlag.Val)
893 Ops.push_back(InFlag);
894
895 Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
896 NodeTys, &Ops[0], Ops.size());
897 InFlag = Chain.getValue(1);
898
899 // Create the CALLSEQ_END node.
900 unsigned NumBytesForCalleeToPush = 0;
901
902 if (CC == CallingConv::X86_StdCall) {
903 if (isVarArg)
904 NumBytesForCalleeToPush = isSRet ? 4 : 0;
905 else
906 NumBytesForCalleeToPush = NumBytes;
907 } else {
908 // If this is is a call to a struct-return function, the callee
909 // pops the hidden struct pointer, so we have to push it back.
910 // This is common for Darwin/X86, Linux & Mingw32 targets.
911 NumBytesForCalleeToPush = isSRet ? 4 : 0;
912 }
913
914 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
915 Ops.clear();
916 Ops.push_back(Chain);
917 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
918 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
919 Ops.push_back(InFlag);
920 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
921 InFlag = Chain.getValue(1);
922
923 // Handle result values, copying them out of physregs into vregs that we
924 // return.
925 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
926}
927
928
929//===----------------------------------------------------------------------===//
930// FastCall Calling Convention implementation
931//===----------------------------------------------------------------------===//
932//
933// The X86 'fastcall' calling convention passes up to two integer arguments in
934// registers (an appropriate portion of ECX/EDX), passes arguments in C order,
935// and requires that the callee pop its arguments off the stack (allowing proper
936// tail calls), and has the same return value conventions as C calling convs.
937//
938// This calling convention always arranges for the callee pop value to be 8n+4
939// bytes, which is needed for tail recursion elimination and stack alignment
940// reasons.
941SDOperand
942X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
943 MachineFunction &MF = DAG.getMachineFunction();
944 MachineFrameInfo *MFI = MF.getFrameInfo();
945 SDOperand Root = Op.getOperand(0);
946 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
947
948 // Assign locations to all of the incoming arguments.
949 SmallVector<CCValAssign, 16> ArgLocs;
950 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
951 getTargetMachine(), ArgLocs);
952 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
953
954 SmallVector<SDOperand, 8> ArgValues;
955 unsigned LastVal = ~0U;
956 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
957 CCValAssign &VA = ArgLocs[i];
958 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
959 // places.
960 assert(VA.getValNo() != LastVal &&
961 "Don't support value assigned to multiple locs yet");
962 LastVal = VA.getValNo();
963
964 if (VA.isRegLoc()) {
965 MVT::ValueType RegVT = VA.getLocVT();
966 TargetRegisterClass *RC;
967 if (RegVT == MVT::i32)
968 RC = X86::GR32RegisterClass;
969 else {
970 assert(MVT::isVector(RegVT));
971 RC = X86::VR128RegisterClass;
972 }
973
974 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
975 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
976
977 // If this is an 8 or 16-bit value, it is really passed promoted to 32
978 // bits. Insert an assert[sz]ext to capture this, then truncate to the
979 // right size.
980 if (VA.getLocInfo() == CCValAssign::SExt)
981 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
982 DAG.getValueType(VA.getValVT()));
983 else if (VA.getLocInfo() == CCValAssign::ZExt)
984 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
985 DAG.getValueType(VA.getValVT()));
986
987 if (VA.getLocInfo() != CCValAssign::Full)
988 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
989
990 ArgValues.push_back(ArgValue);
991 } else {
992 assert(VA.isMemLoc());
993
994 // Create the nodes corresponding to a load from this parameter slot.
995 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
996 VA.getLocMemOffset());
997 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
998 ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
999 }
1000 }
1001
1002 ArgValues.push_back(Root);
1003
1004 unsigned StackSize = CCInfo.getNextStackOffset();
1005
1006 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1007 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1008 // arguments and the arguments after the retaddr has been pushed are aligned.
1009 if ((StackSize & 7) == 0)
1010 StackSize += 4;
1011 }
1012
1013 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1014 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
1015 ReturnAddrIndex = 0; // No return address slot generated yet.
1016 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
1017 BytesCallerReserves = 0;
1018
1019 MF.getInfo<X86MachineFunctionInfo>()
1020 ->setBytesToPopOnReturn(BytesToPopOnReturn);
1021
1022 // Return the new list of results.
1023 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1024 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1025}
1026
1027SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1028 unsigned CC) {
1029 SDOperand Chain = Op.getOperand(0);
1030 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1031 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1032 SDOperand Callee = Op.getOperand(4);
1033
1034 // Analyze operands of the call, assigning locations to each operand.
1035 SmallVector<CCValAssign, 16> ArgLocs;
1036 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1037 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1038
1039 // Get a count of how many bytes are to be pushed on the stack.
1040 unsigned NumBytes = CCInfo.getNextStackOffset();
1041
1042 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1043 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1044 // arguments and the arguments after the retaddr has been pushed are aligned.
1045 if ((NumBytes & 7) == 0)
1046 NumBytes += 4;
1047 }
1048
1049 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1050
1051 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1052 SmallVector<SDOperand, 8> MemOpChains;
1053
1054 SDOperand StackPtr;
1055
1056 // Walk the register/memloc assignments, inserting copies/loads.
1057 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1058 CCValAssign &VA = ArgLocs[i];
1059 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1060
1061 // Promote the value if needed.
1062 switch (VA.getLocInfo()) {
1063 default: assert(0 && "Unknown loc info!");
1064 case CCValAssign::Full: break;
1065 case CCValAssign::SExt:
1066 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1067 break;
1068 case CCValAssign::ZExt:
1069 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1070 break;
1071 case CCValAssign::AExt:
1072 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1073 break;
1074 }
1075
1076 if (VA.isRegLoc()) {
1077 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1078 } else {
1079 assert(VA.isMemLoc());
1080 if (StackPtr.Val == 0)
1081 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1082 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1083 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1084 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
1085 }
1086 }
1087
1088 if (!MemOpChains.empty())
1089 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1090 &MemOpChains[0], MemOpChains.size());
1091
1092 // Build a sequence of copy-to-reg nodes chained together with token chain
1093 // and flag operands which copy the outgoing args into registers.
1094 SDOperand InFlag;
1095 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1096 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1097 InFlag);
1098 InFlag = Chain.getValue(1);
1099 }
1100
1101 // If the callee is a GlobalAddress node (quite common, every direct call is)
1102 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1103 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1104 // We should use extra load for direct calls to dllimported functions in
1105 // non-JIT mode.
1106 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1107 getTargetMachine(), true))
1108 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1109 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1110 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1111
1112 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1113 // GOT pointer.
1114 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1115 Subtarget->isPICStyleGOT()) {
1116 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1117 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1118 InFlag);
1119 InFlag = Chain.getValue(1);
1120 }
1121
1122 // Returns a chain & a flag for retval copy to use.
1123 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1124 SmallVector<SDOperand, 8> Ops;
1125 Ops.push_back(Chain);
1126 Ops.push_back(Callee);
1127
1128 // Add argument registers to the end of the list so that they are known live
1129 // into the call.
1130 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1131 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1132 RegsToPass[i].second.getValueType()));
1133
1134 // Add an implicit use GOT pointer in EBX.
1135 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1136 Subtarget->isPICStyleGOT())
1137 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1138
1139 if (InFlag.Val)
1140 Ops.push_back(InFlag);
1141
1142 // FIXME: Do not generate X86ISD::TAILCALL for now.
1143 Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1144 NodeTys, &Ops[0], Ops.size());
1145 InFlag = Chain.getValue(1);
1146
1147 // Returns a flag for retval copy to use.
1148 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1149 Ops.clear();
1150 Ops.push_back(Chain);
1151 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1152 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1153 Ops.push_back(InFlag);
1154 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1155 InFlag = Chain.getValue(1);
1156
1157 // Handle result values, copying them out of physregs into vregs that we
1158 // return.
1159 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1160}
1161
1162
1163//===----------------------------------------------------------------------===//
1164// X86-64 C Calling Convention implementation
1165//===----------------------------------------------------------------------===//
1166
1167SDOperand
1168X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1169 MachineFunction &MF = DAG.getMachineFunction();
1170 MachineFrameInfo *MFI = MF.getFrameInfo();
1171 SDOperand Root = Op.getOperand(0);
1172 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1173
1174 static const unsigned GPR64ArgRegs[] = {
1175 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1176 };
1177 static const unsigned XMMArgRegs[] = {
1178 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1179 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1180 };
1181
1182
1183 // Assign locations to all of the incoming arguments.
1184 SmallVector<CCValAssign, 16> ArgLocs;
1185 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
1186 getTargetMachine(), ArgLocs);
1187 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
1188
1189 SmallVector<SDOperand, 8> ArgValues;
1190 unsigned LastVal = ~0U;
1191 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1192 CCValAssign &VA = ArgLocs[i];
1193 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1194 // places.
1195 assert(VA.getValNo() != LastVal &&
1196 "Don't support value assigned to multiple locs yet");
1197 LastVal = VA.getValNo();
1198
1199 if (VA.isRegLoc()) {
1200 MVT::ValueType RegVT = VA.getLocVT();
1201 TargetRegisterClass *RC;
1202 if (RegVT == MVT::i32)
1203 RC = X86::GR32RegisterClass;
1204 else if (RegVT == MVT::i64)
1205 RC = X86::GR64RegisterClass;
1206 else if (RegVT == MVT::f32)
1207 RC = X86::FR32RegisterClass;
1208 else if (RegVT == MVT::f64)
1209 RC = X86::FR64RegisterClass;
1210 else {
1211 assert(MVT::isVector(RegVT));
1212 if (MVT::getSizeInBits(RegVT) == 64) {
1213 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1214 RegVT = MVT::i64;
1215 } else
1216 RC = X86::VR128RegisterClass;
1217 }
1218
1219 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1220 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1221
1222 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1223 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1224 // right size.
1225 if (VA.getLocInfo() == CCValAssign::SExt)
1226 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1227 DAG.getValueType(VA.getValVT()));
1228 else if (VA.getLocInfo() == CCValAssign::ZExt)
1229 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1230 DAG.getValueType(VA.getValVT()));
1231
1232 if (VA.getLocInfo() != CCValAssign::Full)
1233 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1234
1235 // Handle MMX values passed in GPRs.
1236 if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1237 MVT::getSizeInBits(RegVT) == 64)
1238 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1239
1240 ArgValues.push_back(ArgValue);
1241 } else {
1242 assert(VA.isMemLoc());
1243
1244 // Create the nodes corresponding to a load from this parameter slot.
1245 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1246 VA.getLocMemOffset());
1247 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1248 ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
1249 }
1250 }
1251
1252 unsigned StackSize = CCInfo.getNextStackOffset();
1253
1254 // If the function takes variable number of arguments, make a frame index for
1255 // the start of the first vararg value... for expansion of llvm.va_start.
1256 if (isVarArg) {
1257 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1258 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1259
1260 // For X86-64, if there are vararg parameters that are passed via
1261 // registers, then we must store them to their spots on the stack so they
1262 // may be loaded by deferencing the result of va_next.
1263 VarArgsGPOffset = NumIntRegs * 8;
1264 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1265 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1266 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1267
1268 // Store the integer parameter registers.
1269 SmallVector<SDOperand, 8> MemOps;
1270 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1271 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1272 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1273 for (; NumIntRegs != 6; ++NumIntRegs) {
1274 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1275 X86::GR64RegisterClass);
1276 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1277 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1278 MemOps.push_back(Store);
1279 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1280 DAG.getConstant(8, getPointerTy()));
1281 }
1282
1283 // Now store the XMM (fp + vector) parameter registers.
1284 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1285 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1286 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1287 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1288 X86::VR128RegisterClass);
1289 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1290 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1291 MemOps.push_back(Store);
1292 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1293 DAG.getConstant(16, getPointerTy()));
1294 }
1295 if (!MemOps.empty())
1296 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1297 &MemOps[0], MemOps.size());
1298 }
1299
1300 ArgValues.push_back(Root);
1301
1302 ReturnAddrIndex = 0; // No return address slot generated yet.
1303 BytesToPopOnReturn = 0; // Callee pops nothing.
1304 BytesCallerReserves = StackSize;
1305
1306 // Return the new list of results.
1307 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1308 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1309}
1310
1311SDOperand
1312X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1313 unsigned CC) {
1314 SDOperand Chain = Op.getOperand(0);
1315 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1316 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1317 SDOperand Callee = Op.getOperand(4);
1318
1319 // Analyze operands of the call, assigning locations to each operand.
1320 SmallVector<CCValAssign, 16> ArgLocs;
1321 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1322 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
1323
1324 // Get a count of how many bytes are to be pushed on the stack.
1325 unsigned NumBytes = CCInfo.getNextStackOffset();
1326 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1327
1328 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1329 SmallVector<SDOperand, 8> MemOpChains;
1330
1331 SDOperand StackPtr;
1332
1333 // Walk the register/memloc assignments, inserting copies/loads.
1334 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1335 CCValAssign &VA = ArgLocs[i];
1336 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1337
1338 // Promote the value if needed.
1339 switch (VA.getLocInfo()) {
1340 default: assert(0 && "Unknown loc info!");
1341 case CCValAssign::Full: break;
1342 case CCValAssign::SExt:
1343 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1344 break;
1345 case CCValAssign::ZExt:
1346 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1347 break;
1348 case CCValAssign::AExt:
1349 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1350 break;
1351 }
1352
1353 if (VA.isRegLoc()) {
1354 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1355 } else {
1356 assert(VA.isMemLoc());
1357 if (StackPtr.Val == 0)
1358 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1359 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1360 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1361 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
1362 }
1363 }
1364
1365 if (!MemOpChains.empty())
1366 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1367 &MemOpChains[0], MemOpChains.size());
1368
1369 // Build a sequence of copy-to-reg nodes chained together with token chain
1370 // and flag operands which copy the outgoing args into registers.
1371 SDOperand InFlag;
1372 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1373 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1374 InFlag);
1375 InFlag = Chain.getValue(1);
1376 }
1377
1378 if (isVarArg) {
1379 // From AMD64 ABI document:
1380 // For calls that may call functions that use varargs or stdargs
1381 // (prototype-less calls or calls to functions containing ellipsis (...) in
1382 // the declaration) %al is used as hidden argument to specify the number
1383 // of SSE registers used. The contents of %al do not need to match exactly
1384 // the number of registers, but must be an ubound on the number of SSE
1385 // registers used and is in the range 0 - 8 inclusive.
1386
1387 // Count the number of XMM registers allocated.
1388 static const unsigned XMMArgRegs[] = {
1389 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1390 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1391 };
1392 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1393
1394 Chain = DAG.getCopyToReg(Chain, X86::AL,
1395 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1396 InFlag = Chain.getValue(1);
1397 }
1398
1399 // If the callee is a GlobalAddress node (quite common, every direct call is)
1400 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1401 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1402 // We should use extra load for direct calls to dllimported functions in
1403 // non-JIT mode.
1404 if (getTargetMachine().getCodeModel() != CodeModel::Large
1405 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1406 getTargetMachine(), true))
1407 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1408 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1409 if (getTargetMachine().getCodeModel() != CodeModel::Large)
1410 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1411
1412 // Returns a chain & a flag for retval copy to use.
1413 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1414 SmallVector<SDOperand, 8> Ops;
1415 Ops.push_back(Chain);
1416 Ops.push_back(Callee);
1417
1418 // Add argument registers to the end of the list so that they are known live
1419 // into the call.
1420 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1421 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1422 RegsToPass[i].second.getValueType()));
1423
1424 if (InFlag.Val)
1425 Ops.push_back(InFlag);
1426
1427 // FIXME: Do not generate X86ISD::TAILCALL for now.
1428 Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1429 NodeTys, &Ops[0], Ops.size());
1430 InFlag = Chain.getValue(1);
1431
1432 // Returns a flag for retval copy to use.
1433 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1434 Ops.clear();
1435 Ops.push_back(Chain);
1436 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1437 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1438 Ops.push_back(InFlag);
1439 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1440 InFlag = Chain.getValue(1);
1441
1442 // Handle result values, copying them out of physregs into vregs that we
1443 // return.
1444 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1445}
1446
1447
1448//===----------------------------------------------------------------------===//
1449// Other Lowering Hooks
1450//===----------------------------------------------------------------------===//
1451
1452
1453SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1454 if (ReturnAddrIndex == 0) {
1455 // Set up a frame object for the return address.
1456 MachineFunction &MF = DAG.getMachineFunction();
1457 if (Subtarget->is64Bit())
1458 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1459 else
1460 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1461 }
1462
1463 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1464}
1465
1466
1467
1468/// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1469/// specific condition code. It returns a false if it cannot do a direct
1470/// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1471/// needed.
1472static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1473 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1474 SelectionDAG &DAG) {
1475 X86CC = X86::COND_INVALID;
1476 if (!isFP) {
1477 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1478 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1479 // X > -1 -> X == 0, jump !sign.
1480 RHS = DAG.getConstant(0, RHS.getValueType());
1481 X86CC = X86::COND_NS;
1482 return true;
1483 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1484 // X < 0 -> X == 0, jump on sign.
1485 X86CC = X86::COND_S;
1486 return true;
1487 }
1488 }
1489
1490 switch (SetCCOpcode) {
1491 default: break;
1492 case ISD::SETEQ: X86CC = X86::COND_E; break;
1493 case ISD::SETGT: X86CC = X86::COND_G; break;
1494 case ISD::SETGE: X86CC = X86::COND_GE; break;
1495 case ISD::SETLT: X86CC = X86::COND_L; break;
1496 case ISD::SETLE: X86CC = X86::COND_LE; break;
1497 case ISD::SETNE: X86CC = X86::COND_NE; break;
1498 case ISD::SETULT: X86CC = X86::COND_B; break;
1499 case ISD::SETUGT: X86CC = X86::COND_A; break;
1500 case ISD::SETULE: X86CC = X86::COND_BE; break;
1501 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1502 }
1503 } else {
1504 // On a floating point condition, the flags are set as follows:
1505 // ZF PF CF op
1506 // 0 | 0 | 0 | X > Y
1507 // 0 | 0 | 1 | X < Y
1508 // 1 | 0 | 0 | X == Y
1509 // 1 | 1 | 1 | unordered
1510 bool Flip = false;
1511 switch (SetCCOpcode) {
1512 default: break;
1513 case ISD::SETUEQ:
1514 case ISD::SETEQ: X86CC = X86::COND_E; break;
1515 case ISD::SETOLT: Flip = true; // Fallthrough
1516 case ISD::SETOGT:
1517 case ISD::SETGT: X86CC = X86::COND_A; break;
1518 case ISD::SETOLE: Flip = true; // Fallthrough
1519 case ISD::SETOGE:
1520 case ISD::SETGE: X86CC = X86::COND_AE; break;
1521 case ISD::SETUGT: Flip = true; // Fallthrough
1522 case ISD::SETULT:
1523 case ISD::SETLT: X86CC = X86::COND_B; break;
1524 case ISD::SETUGE: Flip = true; // Fallthrough
1525 case ISD::SETULE:
1526 case ISD::SETLE: X86CC = X86::COND_BE; break;
1527 case ISD::SETONE:
1528 case ISD::SETNE: X86CC = X86::COND_NE; break;
1529 case ISD::SETUO: X86CC = X86::COND_P; break;
1530 case ISD::SETO: X86CC = X86::COND_NP; break;
1531 }
1532 if (Flip)
1533 std::swap(LHS, RHS);
1534 }
1535
1536 return X86CC != X86::COND_INVALID;
1537}
1538
1539/// hasFPCMov - is there a floating point cmov for the specific X86 condition
1540/// code. Current x86 isa includes the following FP cmov instructions:
1541/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1542static bool hasFPCMov(unsigned X86CC) {
1543 switch (X86CC) {
1544 default:
1545 return false;
1546 case X86::COND_B:
1547 case X86::COND_BE:
1548 case X86::COND_E:
1549 case X86::COND_P:
1550 case X86::COND_A:
1551 case X86::COND_AE:
1552 case X86::COND_NE:
1553 case X86::COND_NP:
1554 return true;
1555 }
1556}
1557
1558/// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1559/// true if Op is undef or if its value falls within the specified range (L, H].
1560static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1561 if (Op.getOpcode() == ISD::UNDEF)
1562 return true;
1563
1564 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1565 return (Val >= Low && Val < Hi);
1566}
1567
1568/// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
1569/// true if Op is undef or if its value equal to the specified value.
1570static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1571 if (Op.getOpcode() == ISD::UNDEF)
1572 return true;
1573 return cast<ConstantSDNode>(Op)->getValue() == Val;
1574}
1575
1576/// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1577/// specifies a shuffle of elements that is suitable for input to PSHUFD.
1578bool X86::isPSHUFDMask(SDNode *N) {
1579 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1580
1581 if (N->getNumOperands() != 4)
1582 return false;
1583
1584 // Check if the value doesn't reference the second vector.
1585 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1586 SDOperand Arg = N->getOperand(i);
1587 if (Arg.getOpcode() == ISD::UNDEF) continue;
1588 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1589 if (cast<ConstantSDNode>(Arg)->getValue() >= 4)
1590 return false;
1591 }
1592
1593 return true;
1594}
1595
1596/// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1597/// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1598bool X86::isPSHUFHWMask(SDNode *N) {
1599 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1600
1601 if (N->getNumOperands() != 8)
1602 return false;
1603
1604 // Lower quadword copied in order.
1605 for (unsigned i = 0; i != 4; ++i) {
1606 SDOperand Arg = N->getOperand(i);
1607 if (Arg.getOpcode() == ISD::UNDEF) continue;
1608 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1609 if (cast<ConstantSDNode>(Arg)->getValue() != i)
1610 return false;
1611 }
1612
1613 // Upper quadword shuffled.
1614 for (unsigned i = 4; i != 8; ++i) {
1615 SDOperand Arg = N->getOperand(i);
1616 if (Arg.getOpcode() == ISD::UNDEF) continue;
1617 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1618 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1619 if (Val < 4 || Val > 7)
1620 return false;
1621 }
1622
1623 return true;
1624}
1625
1626/// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
1627/// specifies a shuffle of elements that is suitable for input to PSHUFLW.
1628bool X86::isPSHUFLWMask(SDNode *N) {
1629 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1630
1631 if (N->getNumOperands() != 8)
1632 return false;
1633
1634 // Upper quadword copied in order.
1635 for (unsigned i = 4; i != 8; ++i)
1636 if (!isUndefOrEqual(N->getOperand(i), i))
1637 return false;
1638
1639 // Lower quadword shuffled.
1640 for (unsigned i = 0; i != 4; ++i)
1641 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
1642 return false;
1643
1644 return true;
1645}
1646
1647/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
1648/// specifies a shuffle of elements that is suitable for input to SHUFP*.
1649static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
1650 if (NumElems != 2 && NumElems != 4) return false;
1651
1652 unsigned Half = NumElems / 2;
1653 for (unsigned i = 0; i < Half; ++i)
1654 if (!isUndefOrInRange(Elems[i], 0, NumElems))
1655 return false;
1656 for (unsigned i = Half; i < NumElems; ++i)
1657 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
1658 return false;
1659
1660 return true;
1661}
1662
1663bool X86::isSHUFPMask(SDNode *N) {
1664 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1665 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
1666}
1667
1668/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
1669/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
1670/// half elements to come from vector 1 (which would equal the dest.) and
1671/// the upper half to come from vector 2.
1672static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
1673 if (NumOps != 2 && NumOps != 4) return false;
1674
1675 unsigned Half = NumOps / 2;
1676 for (unsigned i = 0; i < Half; ++i)
1677 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
1678 return false;
1679 for (unsigned i = Half; i < NumOps; ++i)
1680 if (!isUndefOrInRange(Ops[i], 0, NumOps))
1681 return false;
1682 return true;
1683}
1684
1685static bool isCommutedSHUFP(SDNode *N) {
1686 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1687 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
1688}
1689
1690/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
1691/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
1692bool X86::isMOVHLPSMask(SDNode *N) {
1693 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1694
1695 if (N->getNumOperands() != 4)
1696 return false;
1697
1698 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
1699 return isUndefOrEqual(N->getOperand(0), 6) &&
1700 isUndefOrEqual(N->getOperand(1), 7) &&
1701 isUndefOrEqual(N->getOperand(2), 2) &&
1702 isUndefOrEqual(N->getOperand(3), 3);
1703}
1704
1705/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
1706/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
1707/// <2, 3, 2, 3>
1708bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
1709 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1710
1711 if (N->getNumOperands() != 4)
1712 return false;
1713
1714 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
1715 return isUndefOrEqual(N->getOperand(0), 2) &&
1716 isUndefOrEqual(N->getOperand(1), 3) &&
1717 isUndefOrEqual(N->getOperand(2), 2) &&
1718 isUndefOrEqual(N->getOperand(3), 3);
1719}
1720
1721/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
1722/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
1723bool X86::isMOVLPMask(SDNode *N) {
1724 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1725
1726 unsigned NumElems = N->getNumOperands();
1727 if (NumElems != 2 && NumElems != 4)
1728 return false;
1729
1730 for (unsigned i = 0; i < NumElems/2; ++i)
1731 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
1732 return false;
1733
1734 for (unsigned i = NumElems/2; i < NumElems; ++i)
1735 if (!isUndefOrEqual(N->getOperand(i), i))
1736 return false;
1737
1738 return true;
1739}
1740
1741/// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
1742/// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
1743/// and MOVLHPS.
1744bool X86::isMOVHPMask(SDNode *N) {
1745 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1746
1747 unsigned NumElems = N->getNumOperands();
1748 if (NumElems != 2 && NumElems != 4)
1749 return false;
1750
1751 for (unsigned i = 0; i < NumElems/2; ++i)
1752 if (!isUndefOrEqual(N->getOperand(i), i))
1753 return false;
1754
1755 for (unsigned i = 0; i < NumElems/2; ++i) {
1756 SDOperand Arg = N->getOperand(i + NumElems/2);
1757 if (!isUndefOrEqual(Arg, i + NumElems))
1758 return false;
1759 }
1760
1761 return true;
1762}
1763
1764/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
1765/// specifies a shuffle of elements that is suitable for input to UNPCKL.
1766bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
1767 bool V2IsSplat = false) {
1768 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1769 return false;
1770
1771 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
1772 SDOperand BitI = Elts[i];
1773 SDOperand BitI1 = Elts[i+1];
1774 if (!isUndefOrEqual(BitI, j))
1775 return false;
1776 if (V2IsSplat) {
1777 if (isUndefOrEqual(BitI1, NumElts))
1778 return false;
1779 } else {
1780 if (!isUndefOrEqual(BitI1, j + NumElts))
1781 return false;
1782 }
1783 }
1784
1785 return true;
1786}
1787
1788bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
1789 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1790 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
1791}
1792
1793/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
1794/// specifies a shuffle of elements that is suitable for input to UNPCKH.
1795bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
1796 bool V2IsSplat = false) {
1797 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1798 return false;
1799
1800 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
1801 SDOperand BitI = Elts[i];
1802 SDOperand BitI1 = Elts[i+1];
1803 if (!isUndefOrEqual(BitI, j + NumElts/2))
1804 return false;
1805 if (V2IsSplat) {
1806 if (isUndefOrEqual(BitI1, NumElts))
1807 return false;
1808 } else {
1809 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
1810 return false;
1811 }
1812 }
1813
1814 return true;
1815}
1816
1817bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
1818 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1819 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
1820}
1821
1822/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
1823/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
1824/// <0, 0, 1, 1>
1825bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
1826 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1827
1828 unsigned NumElems = N->getNumOperands();
1829 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1830 return false;
1831
1832 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
1833 SDOperand BitI = N->getOperand(i);
1834 SDOperand BitI1 = N->getOperand(i+1);
1835
1836 if (!isUndefOrEqual(BitI, j))
1837 return false;
1838 if (!isUndefOrEqual(BitI1, j))
1839 return false;
1840 }
1841
1842 return true;
1843}
1844
1845/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
1846/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
1847/// <2, 2, 3, 3>
1848bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
1849 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1850
1851 unsigned NumElems = N->getNumOperands();
1852 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1853 return false;
1854
1855 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
1856 SDOperand BitI = N->getOperand(i);
1857 SDOperand BitI1 = N->getOperand(i + 1);
1858
1859 if (!isUndefOrEqual(BitI, j))
1860 return false;
1861 if (!isUndefOrEqual(BitI1, j))
1862 return false;
1863 }
1864
1865 return true;
1866}
1867
1868/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
1869/// specifies a shuffle of elements that is suitable for input to MOVSS,
1870/// MOVSD, and MOVD, i.e. setting the lowest element.
1871static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
1872 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1873 return false;
1874
1875 if (!isUndefOrEqual(Elts[0], NumElts))
1876 return false;
1877
1878 for (unsigned i = 1; i < NumElts; ++i) {
1879 if (!isUndefOrEqual(Elts[i], i))
1880 return false;
1881 }
1882
1883 return true;
1884}
1885
1886bool X86::isMOVLMask(SDNode *N) {
1887 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1888 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
1889}
1890
1891/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
1892/// of what x86 movss want. X86 movs requires the lowest element to be lowest
1893/// element of vector 2 and the other elements to come from vector 1 in order.
1894static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
1895 bool V2IsSplat = false,
1896 bool V2IsUndef = false) {
1897 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
1898 return false;
1899
1900 if (!isUndefOrEqual(Ops[0], 0))
1901 return false;
1902
1903 for (unsigned i = 1; i < NumOps; ++i) {
1904 SDOperand Arg = Ops[i];
1905 if (!(isUndefOrEqual(Arg, i+NumOps) ||
1906 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
1907 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
1908 return false;
1909 }
1910
1911 return true;
1912}
1913
1914static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
1915 bool V2IsUndef = false) {
1916 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1917 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
1918 V2IsSplat, V2IsUndef);
1919}
1920
1921/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1922/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
1923bool X86::isMOVSHDUPMask(SDNode *N) {
1924 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1925
1926 if (N->getNumOperands() != 4)
1927 return false;
1928
1929 // Expect 1, 1, 3, 3
1930 for (unsigned i = 0; i < 2; ++i) {
1931 SDOperand Arg = N->getOperand(i);
1932 if (Arg.getOpcode() == ISD::UNDEF) continue;
1933 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1934 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1935 if (Val != 1) return false;
1936 }
1937
1938 bool HasHi = false;
1939 for (unsigned i = 2; i < 4; ++i) {
1940 SDOperand Arg = N->getOperand(i);
1941 if (Arg.getOpcode() == ISD::UNDEF) continue;
1942 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1943 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1944 if (Val != 3) return false;
1945 HasHi = true;
1946 }
1947
1948 // Don't use movshdup if it can be done with a shufps.
1949 return HasHi;
1950}
1951
1952/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1953/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
1954bool X86::isMOVSLDUPMask(SDNode *N) {
1955 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1956
1957 if (N->getNumOperands() != 4)
1958 return false;
1959
1960 // Expect 0, 0, 2, 2
1961 for (unsigned i = 0; i < 2; ++i) {
1962 SDOperand Arg = N->getOperand(i);
1963 if (Arg.getOpcode() == ISD::UNDEF) continue;
1964 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1965 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1966 if (Val != 0) return false;
1967 }
1968
1969 bool HasHi = false;
1970 for (unsigned i = 2; i < 4; ++i) {
1971 SDOperand Arg = N->getOperand(i);
1972 if (Arg.getOpcode() == ISD::UNDEF) continue;
1973 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1974 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1975 if (Val != 2) return false;
1976 HasHi = true;
1977 }
1978
1979 // Don't use movshdup if it can be done with a shufps.
1980 return HasHi;
1981}
1982
1983/// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
1984/// specifies a identity operation on the LHS or RHS.
1985static bool isIdentityMask(SDNode *N, bool RHS = false) {
1986 unsigned NumElems = N->getNumOperands();
1987 for (unsigned i = 0; i < NumElems; ++i)
1988 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
1989 return false;
1990 return true;
1991}
1992
1993/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
1994/// a splat of a single element.
1995static bool isSplatMask(SDNode *N) {
1996 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1997
1998 // This is a splat operation if each element of the permute is the same, and
1999 // if the value doesn't reference the second vector.
2000 unsigned NumElems = N->getNumOperands();
2001 SDOperand ElementBase;
2002 unsigned i = 0;
2003 for (; i != NumElems; ++i) {
2004 SDOperand Elt = N->getOperand(i);
2005 if (isa<ConstantSDNode>(Elt)) {
2006 ElementBase = Elt;
2007 break;
2008 }
2009 }
2010
2011 if (!ElementBase.Val)
2012 return false;
2013
2014 for (; i != NumElems; ++i) {
2015 SDOperand Arg = N->getOperand(i);
2016 if (Arg.getOpcode() == ISD::UNDEF) continue;
2017 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2018 if (Arg != ElementBase) return false;
2019 }
2020
2021 // Make sure it is a splat of the first vector operand.
2022 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2023}
2024
2025/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2026/// a splat of a single element and it's a 2 or 4 element mask.
2027bool X86::isSplatMask(SDNode *N) {
2028 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2029
2030 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2031 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2032 return false;
2033 return ::isSplatMask(N);
2034}
2035
2036/// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2037/// specifies a splat of zero element.
2038bool X86::isSplatLoMask(SDNode *N) {
2039 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2040
2041 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2042 if (!isUndefOrEqual(N->getOperand(i), 0))
2043 return false;
2044 return true;
2045}
2046
2047/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2048/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2049/// instructions.
2050unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2051 unsigned NumOperands = N->getNumOperands();
2052 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2053 unsigned Mask = 0;
2054 for (unsigned i = 0; i < NumOperands; ++i) {
2055 unsigned Val = 0;
2056 SDOperand Arg = N->getOperand(NumOperands-i-1);
2057 if (Arg.getOpcode() != ISD::UNDEF)
2058 Val = cast<ConstantSDNode>(Arg)->getValue();
2059 if (Val >= NumOperands) Val -= NumOperands;
2060 Mask |= Val;
2061 if (i != NumOperands - 1)
2062 Mask <<= Shift;
2063 }
2064
2065 return Mask;
2066}
2067
2068/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2069/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2070/// instructions.
2071unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2072 unsigned Mask = 0;
2073 // 8 nodes, but we only care about the last 4.
2074 for (unsigned i = 7; i >= 4; --i) {
2075 unsigned Val = 0;
2076 SDOperand Arg = N->getOperand(i);
2077 if (Arg.getOpcode() != ISD::UNDEF)
2078 Val = cast<ConstantSDNode>(Arg)->getValue();
2079 Mask |= (Val - 4);
2080 if (i != 4)
2081 Mask <<= 2;
2082 }
2083
2084 return Mask;
2085}
2086
2087/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2088/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2089/// instructions.
2090unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2091 unsigned Mask = 0;
2092 // 8 nodes, but we only care about the first 4.
2093 for (int i = 3; i >= 0; --i) {
2094 unsigned Val = 0;
2095 SDOperand Arg = N->getOperand(i);
2096 if (Arg.getOpcode() != ISD::UNDEF)
2097 Val = cast<ConstantSDNode>(Arg)->getValue();
2098 Mask |= Val;
2099 if (i != 0)
2100 Mask <<= 2;
2101 }
2102
2103 return Mask;
2104}
2105
2106/// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2107/// specifies a 8 element shuffle that can be broken into a pair of
2108/// PSHUFHW and PSHUFLW.
2109static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2110 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2111
2112 if (N->getNumOperands() != 8)
2113 return false;
2114
2115 // Lower quadword shuffled.
2116 for (unsigned i = 0; i != 4; ++i) {
2117 SDOperand Arg = N->getOperand(i);
2118 if (Arg.getOpcode() == ISD::UNDEF) continue;
2119 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2120 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2121 if (Val > 4)
2122 return false;
2123 }
2124
2125 // Upper quadword shuffled.
2126 for (unsigned i = 4; i != 8; ++i) {
2127 SDOperand Arg = N->getOperand(i);
2128 if (Arg.getOpcode() == ISD::UNDEF) continue;
2129 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2130 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2131 if (Val < 4 || Val > 7)
2132 return false;
2133 }
2134
2135 return true;
2136}
2137
2138/// CommuteVectorShuffle - Swap vector_shuffle operandsas well as
2139/// values in ther permute mask.
2140static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2141 SDOperand &V2, SDOperand &Mask,
2142 SelectionDAG &DAG) {
2143 MVT::ValueType VT = Op.getValueType();
2144 MVT::ValueType MaskVT = Mask.getValueType();
2145 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2146 unsigned NumElems = Mask.getNumOperands();
2147 SmallVector<SDOperand, 8> MaskVec;
2148
2149 for (unsigned i = 0; i != NumElems; ++i) {
2150 SDOperand Arg = Mask.getOperand(i);
2151 if (Arg.getOpcode() == ISD::UNDEF) {
2152 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2153 continue;
2154 }
2155 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2156 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2157 if (Val < NumElems)
2158 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2159 else
2160 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2161 }
2162
2163 std::swap(V1, V2);
2164 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2165 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2166}
2167
2168/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2169/// match movhlps. The lower half elements should come from upper half of
2170/// V1 (and in order), and the upper half elements should come from the upper
2171/// half of V2 (and in order).
2172static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2173 unsigned NumElems = Mask->getNumOperands();
2174 if (NumElems != 4)
2175 return false;
2176 for (unsigned i = 0, e = 2; i != e; ++i)
2177 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2178 return false;
2179 for (unsigned i = 2; i != 4; ++i)
2180 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2181 return false;
2182 return true;
2183}
2184
2185/// isScalarLoadToVector - Returns true if the node is a scalar load that
2186/// is promoted to a vector.
2187static inline bool isScalarLoadToVector(SDNode *N) {
2188 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2189 N = N->getOperand(0).Val;
2190 return ISD::isNON_EXTLoad(N);
2191 }
2192 return false;
2193}
2194
2195/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2196/// match movlp{s|d}. The lower half elements should come from lower half of
2197/// V1 (and in order), and the upper half elements should come from the upper
2198/// half of V2 (and in order). And since V1 will become the source of the
2199/// MOVLP, it must be either a vector load or a scalar load to vector.
2200static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2201 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2202 return false;
2203 // Is V2 is a vector load, don't do this transformation. We will try to use
2204 // load folding shufps op.
2205 if (ISD::isNON_EXTLoad(V2))
2206 return false;
2207
2208 unsigned NumElems = Mask->getNumOperands();
2209 if (NumElems != 2 && NumElems != 4)
2210 return false;
2211 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2212 if (!isUndefOrEqual(Mask->getOperand(i), i))
2213 return false;
2214 for (unsigned i = NumElems/2; i != NumElems; ++i)
2215 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2216 return false;
2217 return true;
2218}
2219
2220/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2221/// all the same.
2222static bool isSplatVector(SDNode *N) {
2223 if (N->getOpcode() != ISD::BUILD_VECTOR)
2224 return false;
2225
2226 SDOperand SplatValue = N->getOperand(0);
2227 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2228 if (N->getOperand(i) != SplatValue)
2229 return false;
2230 return true;
2231}
2232
2233/// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2234/// to an undef.
2235static bool isUndefShuffle(SDNode *N) {
2236 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2237 return false;
2238
2239 SDOperand V1 = N->getOperand(0);
2240 SDOperand V2 = N->getOperand(1);
2241 SDOperand Mask = N->getOperand(2);
2242 unsigned NumElems = Mask.getNumOperands();
2243 for (unsigned i = 0; i != NumElems; ++i) {
2244 SDOperand Arg = Mask.getOperand(i);
2245 if (Arg.getOpcode() != ISD::UNDEF) {
2246 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2247 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2248 return false;
2249 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2250 return false;
2251 }
2252 }
2253 return true;
2254}
2255
2256/// isZeroNode - Returns true if Elt is a constant zero or a floating point
2257/// constant +0.0.
2258static inline bool isZeroNode(SDOperand Elt) {
2259 return ((isa<ConstantSDNode>(Elt) &&
2260 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2261 (isa<ConstantFPSDNode>(Elt) &&
2262 cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
2263}
2264
2265/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2266/// to an zero vector.
2267static bool isZeroShuffle(SDNode *N) {
2268 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2269 return false;
2270
2271 SDOperand V1 = N->getOperand(0);
2272 SDOperand V2 = N->getOperand(1);
2273 SDOperand Mask = N->getOperand(2);
2274 unsigned NumElems = Mask.getNumOperands();
2275 for (unsigned i = 0; i != NumElems; ++i) {
2276 SDOperand Arg = Mask.getOperand(i);
2277 if (Arg.getOpcode() != ISD::UNDEF) {
2278 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2279 if (Idx < NumElems) {
2280 unsigned Opc = V1.Val->getOpcode();
2281 if (Opc == ISD::UNDEF)
2282 continue;
2283 if (Opc != ISD::BUILD_VECTOR ||
2284 !isZeroNode(V1.Val->getOperand(Idx)))
2285 return false;
2286 } else if (Idx >= NumElems) {
2287 unsigned Opc = V2.Val->getOpcode();
2288 if (Opc == ISD::UNDEF)
2289 continue;
2290 if (Opc != ISD::BUILD_VECTOR ||
2291 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2292 return false;
2293 }
2294 }
2295 }
2296 return true;
2297}
2298
2299/// getZeroVector - Returns a vector of specified type with all zero elements.
2300///
2301static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2302 assert(MVT::isVector(VT) && "Expected a vector type");
2303 unsigned NumElems = MVT::getVectorNumElements(VT);
2304 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2305 bool isFP = MVT::isFloatingPoint(EVT);
2306 SDOperand Zero = isFP ? DAG.getConstantFP(0.0, EVT) : DAG.getConstant(0, EVT);
2307 SmallVector<SDOperand, 8> ZeroVec(NumElems, Zero);
2308 return DAG.getNode(ISD::BUILD_VECTOR, VT, &ZeroVec[0], ZeroVec.size());
2309}
2310
2311/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2312/// that point to V2 points to its first element.
2313static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2314 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2315
2316 bool Changed = false;
2317 SmallVector<SDOperand, 8> MaskVec;
2318 unsigned NumElems = Mask.getNumOperands();
2319 for (unsigned i = 0; i != NumElems; ++i) {
2320 SDOperand Arg = Mask.getOperand(i);
2321 if (Arg.getOpcode() != ISD::UNDEF) {
2322 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2323 if (Val > NumElems) {
2324 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2325 Changed = true;
2326 }
2327 }
2328 MaskVec.push_back(Arg);
2329 }
2330
2331 if (Changed)
2332 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2333 &MaskVec[0], MaskVec.size());
2334 return Mask;
2335}
2336
2337/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2338/// operation of specified width.
2339static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2340 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2341 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2342
2343 SmallVector<SDOperand, 8> MaskVec;
2344 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2345 for (unsigned i = 1; i != NumElems; ++i)
2346 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2347 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2348}
2349
2350/// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2351/// of specified width.
2352static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2353 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2354 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2355 SmallVector<SDOperand, 8> MaskVec;
2356 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2357 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2358 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2359 }
2360 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2361}
2362
2363/// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2364/// of specified width.
2365static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2366 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2367 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2368 unsigned Half = NumElems/2;
2369 SmallVector<SDOperand, 8> MaskVec;
2370 for (unsigned i = 0; i != Half; ++i) {
2371 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2372 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2373 }
2374 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2375}
2376
2377/// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2378///
2379static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2380 SDOperand V1 = Op.getOperand(0);
2381 SDOperand Mask = Op.getOperand(2);
2382 MVT::ValueType VT = Op.getValueType();
2383 unsigned NumElems = Mask.getNumOperands();
2384 Mask = getUnpacklMask(NumElems, DAG);
2385 while (NumElems != 4) {
2386 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2387 NumElems >>= 1;
2388 }
2389 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2390
2391 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2392 Mask = getZeroVector(MaskVT, DAG);
2393 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2394 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2395 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2396}
2397
2398/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2399/// vector of zero or undef vector.
2400static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2401 unsigned NumElems, unsigned Idx,
2402 bool isZero, SelectionDAG &DAG) {
2403 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2404 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2405 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2406 SDOperand Zero = DAG.getConstant(0, EVT);
2407 SmallVector<SDOperand, 8> MaskVec(NumElems, Zero);
2408 MaskVec[Idx] = DAG.getConstant(NumElems, EVT);
2409 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2410 &MaskVec[0], MaskVec.size());
2411 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2412}
2413
2414/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2415///
2416static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2417 unsigned NumNonZero, unsigned NumZero,
2418 SelectionDAG &DAG, TargetLowering &TLI) {
2419 if (NumNonZero > 8)
2420 return SDOperand();
2421
2422 SDOperand V(0, 0);
2423 bool First = true;
2424 for (unsigned i = 0; i < 16; ++i) {
2425 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2426 if (ThisIsNonZero && First) {
2427 if (NumZero)
2428 V = getZeroVector(MVT::v8i16, DAG);
2429 else
2430 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2431 First = false;
2432 }
2433
2434 if ((i & 1) != 0) {
2435 SDOperand ThisElt(0, 0), LastElt(0, 0);
2436 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2437 if (LastIsNonZero) {
2438 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2439 }
2440 if (ThisIsNonZero) {
2441 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2442 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2443 ThisElt, DAG.getConstant(8, MVT::i8));
2444 if (LastIsNonZero)
2445 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2446 } else
2447 ThisElt = LastElt;
2448
2449 if (ThisElt.Val)
2450 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2451 DAG.getConstant(i/2, TLI.getPointerTy()));
2452 }
2453 }
2454
2455 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2456}
2457
2458/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2459///
2460static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2461 unsigned NumNonZero, unsigned NumZero,
2462 SelectionDAG &DAG, TargetLowering &TLI) {
2463 if (NumNonZero > 4)
2464 return SDOperand();
2465
2466 SDOperand V(0, 0);
2467 bool First = true;
2468 for (unsigned i = 0; i < 8; ++i) {
2469 bool isNonZero = (NonZeros & (1 << i)) != 0;
2470 if (isNonZero) {
2471 if (First) {
2472 if (NumZero)
2473 V = getZeroVector(MVT::v8i16, DAG);
2474 else
2475 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2476 First = false;
2477 }
2478 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2479 DAG.getConstant(i, TLI.getPointerTy()));
2480 }
2481 }
2482
2483 return V;
2484}
2485
2486SDOperand
2487X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2488 // All zero's are handled with pxor.
2489 if (ISD::isBuildVectorAllZeros(Op.Val))
2490 return Op;
2491
2492 // All one's are handled with pcmpeqd.
2493 if (ISD::isBuildVectorAllOnes(Op.Val))
2494 return Op;
2495
2496 MVT::ValueType VT = Op.getValueType();
2497 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2498 unsigned EVTBits = MVT::getSizeInBits(EVT);
2499
2500 unsigned NumElems = Op.getNumOperands();
2501 unsigned NumZero = 0;
2502 unsigned NumNonZero = 0;
2503 unsigned NonZeros = 0;
Dan Gohman21463242007-07-24 22:55:08 +00002504 unsigned NumNonZeroImms = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002505 std::set<SDOperand> Values;
2506 for (unsigned i = 0; i < NumElems; ++i) {
2507 SDOperand Elt = Op.getOperand(i);
2508 if (Elt.getOpcode() != ISD::UNDEF) {
2509 Values.insert(Elt);
2510 if (isZeroNode(Elt))
2511 NumZero++;
2512 else {
2513 NonZeros |= (1 << i);
2514 NumNonZero++;
Dan Gohman21463242007-07-24 22:55:08 +00002515 if (Elt.getOpcode() == ISD::Constant ||
2516 Elt.getOpcode() == ISD::ConstantFP)
2517 NumNonZeroImms++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002518 }
2519 }
2520 }
2521
2522 if (NumNonZero == 0) {
2523 if (NumZero == 0)
2524 // All undef vector. Return an UNDEF.
2525 return DAG.getNode(ISD::UNDEF, VT);
2526 else
2527 // A mix of zero and undef. Return a zero vector.
2528 return getZeroVector(VT, DAG);
2529 }
2530
2531 // Splat is obviously ok. Let legalizer expand it to a shuffle.
2532 if (Values.size() == 1)
2533 return SDOperand();
2534
2535 // Special case for single non-zero element.
2536 if (NumNonZero == 1) {
2537 unsigned Idx = CountTrailingZeros_32(NonZeros);
2538 SDOperand Item = Op.getOperand(Idx);
2539 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
2540 if (Idx == 0)
2541 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
2542 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
2543 NumZero > 0, DAG);
2544
2545 if (EVTBits == 32) {
2546 // Turn it into a shuffle of zero and zero-extended scalar to vector.
2547 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
2548 DAG);
2549 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2550 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
2551 SmallVector<SDOperand, 8> MaskVec;
2552 for (unsigned i = 0; i < NumElems; i++)
2553 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
2554 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2555 &MaskVec[0], MaskVec.size());
2556 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
2557 DAG.getNode(ISD::UNDEF, VT), Mask);
2558 }
2559 }
2560
Dan Gohman21463242007-07-24 22:55:08 +00002561 // A vector full of immediates; various special cases are already
2562 // handled, so this is best done with a single constant-pool load.
2563 if (NumNonZero == NumNonZeroImms)
2564 return SDOperand();
2565
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002566 // Let legalizer expand 2-wide build_vectors.
2567 if (EVTBits == 64)
2568 return SDOperand();
2569
2570 // If element VT is < 32 bits, convert it to inserts into a zero vector.
2571 if (EVTBits == 8 && NumElems == 16) {
2572 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
2573 *this);
2574 if (V.Val) return V;
2575 }
2576
2577 if (EVTBits == 16 && NumElems == 8) {
2578 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
2579 *this);
2580 if (V.Val) return V;
2581 }
2582
2583 // If element VT is == 32 bits, turn it into a number of shuffles.
2584 SmallVector<SDOperand, 8> V;
2585 V.resize(NumElems);
2586 if (NumElems == 4 && NumZero > 0) {
2587 for (unsigned i = 0; i < 4; ++i) {
2588 bool isZero = !(NonZeros & (1 << i));
2589 if (isZero)
2590 V[i] = getZeroVector(VT, DAG);
2591 else
2592 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2593 }
2594
2595 for (unsigned i = 0; i < 2; ++i) {
2596 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
2597 default: break;
2598 case 0:
2599 V[i] = V[i*2]; // Must be a zero vector.
2600 break;
2601 case 1:
2602 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
2603 getMOVLMask(NumElems, DAG));
2604 break;
2605 case 2:
2606 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2607 getMOVLMask(NumElems, DAG));
2608 break;
2609 case 3:
2610 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2611 getUnpacklMask(NumElems, DAG));
2612 break;
2613 }
2614 }
2615
2616 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
2617 // clears the upper bits.
2618 // FIXME: we can do the same for v4f32 case when we know both parts of
2619 // the lower half come from scalar_to_vector (loadf32). We should do
2620 // that in post legalizer dag combiner with target specific hooks.
2621 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
2622 return V[0];
2623 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2624 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2625 SmallVector<SDOperand, 8> MaskVec;
2626 bool Reverse = (NonZeros & 0x3) == 2;
2627 for (unsigned i = 0; i < 2; ++i)
2628 if (Reverse)
2629 MaskVec.push_back(DAG.getConstant(1-i, EVT));
2630 else
2631 MaskVec.push_back(DAG.getConstant(i, EVT));
2632 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
2633 for (unsigned i = 0; i < 2; ++i)
2634 if (Reverse)
2635 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
2636 else
2637 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
2638 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2639 &MaskVec[0], MaskVec.size());
2640 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
2641 }
2642
2643 if (Values.size() > 2) {
2644 // Expand into a number of unpckl*.
2645 // e.g. for v4f32
2646 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
2647 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
2648 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
2649 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
2650 for (unsigned i = 0; i < NumElems; ++i)
2651 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2652 NumElems >>= 1;
2653 while (NumElems != 0) {
2654 for (unsigned i = 0; i < NumElems; ++i)
2655 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
2656 UnpckMask);
2657 NumElems >>= 1;
2658 }
2659 return V[0];
2660 }
2661
2662 return SDOperand();
2663}
2664
2665SDOperand
2666X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
2667 SDOperand V1 = Op.getOperand(0);
2668 SDOperand V2 = Op.getOperand(1);
2669 SDOperand PermMask = Op.getOperand(2);
2670 MVT::ValueType VT = Op.getValueType();
2671 unsigned NumElems = PermMask.getNumOperands();
2672 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
2673 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
2674 bool V1IsSplat = false;
2675 bool V2IsSplat = false;
2676
2677 if (isUndefShuffle(Op.Val))
2678 return DAG.getNode(ISD::UNDEF, VT);
2679
2680 if (isZeroShuffle(Op.Val))
2681 return getZeroVector(VT, DAG);
2682
2683 if (isIdentityMask(PermMask.Val))
2684 return V1;
2685 else if (isIdentityMask(PermMask.Val, true))
2686 return V2;
2687
2688 if (isSplatMask(PermMask.Val)) {
2689 if (NumElems <= 4) return Op;
2690 // Promote it to a v4i32 splat.
2691 return PromoteSplat(Op, DAG);
2692 }
2693
2694 if (X86::isMOVLMask(PermMask.Val))
2695 return (V1IsUndef) ? V2 : Op;
2696
2697 if (X86::isMOVSHDUPMask(PermMask.Val) ||
2698 X86::isMOVSLDUPMask(PermMask.Val) ||
2699 X86::isMOVHLPSMask(PermMask.Val) ||
2700 X86::isMOVHPMask(PermMask.Val) ||
2701 X86::isMOVLPMask(PermMask.Val))
2702 return Op;
2703
2704 if (ShouldXformToMOVHLPS(PermMask.Val) ||
2705 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
2706 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2707
2708 bool Commuted = false;
2709 V1IsSplat = isSplatVector(V1.Val);
2710 V2IsSplat = isSplatVector(V2.Val);
2711 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
2712 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2713 std::swap(V1IsSplat, V2IsSplat);
2714 std::swap(V1IsUndef, V2IsUndef);
2715 Commuted = true;
2716 }
2717
2718 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
2719 if (V2IsUndef) return V1;
2720 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2721 if (V2IsSplat) {
2722 // V2 is a splat, so the mask may be malformed. That is, it may point
2723 // to any V2 element. The instruction selectior won't like this. Get
2724 // a corrected mask and commute to form a proper MOVS{S|D}.
2725 SDOperand NewMask = getMOVLMask(NumElems, DAG);
2726 if (NewMask.Val != PermMask.Val)
2727 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2728 }
2729 return Op;
2730 }
2731
2732 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
2733 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
2734 X86::isUNPCKLMask(PermMask.Val) ||
2735 X86::isUNPCKHMask(PermMask.Val))
2736 return Op;
2737
2738 if (V2IsSplat) {
2739 // Normalize mask so all entries that point to V2 points to its first
2740 // element then try to match unpck{h|l} again. If match, return a
2741 // new vector_shuffle with the corrected mask.
2742 SDOperand NewMask = NormalizeMask(PermMask, DAG);
2743 if (NewMask.Val != PermMask.Val) {
2744 if (X86::isUNPCKLMask(PermMask.Val, true)) {
2745 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
2746 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2747 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
2748 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
2749 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2750 }
2751 }
2752 }
2753
2754 // Normalize the node to match x86 shuffle ops if needed
2755 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
2756 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2757
2758 if (Commuted) {
2759 // Commute is back and try unpck* again.
2760 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2761 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
2762 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
2763 X86::isUNPCKLMask(PermMask.Val) ||
2764 X86::isUNPCKHMask(PermMask.Val))
2765 return Op;
2766 }
2767
2768 // If VT is integer, try PSHUF* first, then SHUFP*.
2769 if (MVT::isInteger(VT)) {
2770 if (X86::isPSHUFDMask(PermMask.Val) ||
2771 X86::isPSHUFHWMask(PermMask.Val) ||
2772 X86::isPSHUFLWMask(PermMask.Val)) {
2773 if (V2.getOpcode() != ISD::UNDEF)
2774 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2775 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2776 return Op;
2777 }
2778
2779 if (X86::isSHUFPMask(PermMask.Val) &&
2780 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
2781 return Op;
2782
2783 // Handle v8i16 shuffle high / low shuffle node pair.
2784 if (VT == MVT::v8i16 && isPSHUFHW_PSHUFLWMask(PermMask.Val)) {
2785 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2786 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2787 SmallVector<SDOperand, 8> MaskVec;
2788 for (unsigned i = 0; i != 4; ++i)
2789 MaskVec.push_back(PermMask.getOperand(i));
2790 for (unsigned i = 4; i != 8; ++i)
2791 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2792 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2793 &MaskVec[0], MaskVec.size());
2794 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2795 MaskVec.clear();
2796 for (unsigned i = 0; i != 4; ++i)
2797 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2798 for (unsigned i = 4; i != 8; ++i)
2799 MaskVec.push_back(PermMask.getOperand(i));
2800 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0],MaskVec.size());
2801 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2802 }
2803 } else {
2804 // Floating point cases in the other order.
2805 if (X86::isSHUFPMask(PermMask.Val))
2806 return Op;
2807 if (X86::isPSHUFDMask(PermMask.Val) ||
2808 X86::isPSHUFHWMask(PermMask.Val) ||
2809 X86::isPSHUFLWMask(PermMask.Val)) {
2810 if (V2.getOpcode() != ISD::UNDEF)
2811 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2812 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2813 return Op;
2814 }
2815 }
2816
2817 if (NumElems == 4 &&
2818 // Don't do this for MMX.
2819 MVT::getSizeInBits(VT) != 64) {
2820 MVT::ValueType MaskVT = PermMask.getValueType();
2821 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
2822 SmallVector<std::pair<int, int>, 8> Locs;
2823 Locs.reserve(NumElems);
2824 SmallVector<SDOperand, 8> Mask1(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2825 SmallVector<SDOperand, 8> Mask2(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2826 unsigned NumHi = 0;
2827 unsigned NumLo = 0;
2828 // If no more than two elements come from either vector. This can be
2829 // implemented with two shuffles. First shuffle gather the elements.
2830 // The second shuffle, which takes the first shuffle as both of its
2831 // vector operands, put the elements into the right order.
2832 for (unsigned i = 0; i != NumElems; ++i) {
2833 SDOperand Elt = PermMask.getOperand(i);
2834 if (Elt.getOpcode() == ISD::UNDEF) {
2835 Locs[i] = std::make_pair(-1, -1);
2836 } else {
2837 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
2838 if (Val < NumElems) {
2839 Locs[i] = std::make_pair(0, NumLo);
2840 Mask1[NumLo] = Elt;
2841 NumLo++;
2842 } else {
2843 Locs[i] = std::make_pair(1, NumHi);
2844 if (2+NumHi < NumElems)
2845 Mask1[2+NumHi] = Elt;
2846 NumHi++;
2847 }
2848 }
2849 }
2850 if (NumLo <= 2 && NumHi <= 2) {
2851 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2852 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2853 &Mask1[0], Mask1.size()));
2854 for (unsigned i = 0; i != NumElems; ++i) {
2855 if (Locs[i].first == -1)
2856 continue;
2857 else {
2858 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
2859 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
2860 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
2861 }
2862 }
2863
2864 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
2865 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2866 &Mask2[0], Mask2.size()));
2867 }
2868
2869 // Break it into (shuffle shuffle_hi, shuffle_lo).
2870 Locs.clear();
2871 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2872 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2873 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
2874 unsigned MaskIdx = 0;
2875 unsigned LoIdx = 0;
2876 unsigned HiIdx = NumElems/2;
2877 for (unsigned i = 0; i != NumElems; ++i) {
2878 if (i == NumElems/2) {
2879 MaskPtr = &HiMask;
2880 MaskIdx = 1;
2881 LoIdx = 0;
2882 HiIdx = NumElems/2;
2883 }
2884 SDOperand Elt = PermMask.getOperand(i);
2885 if (Elt.getOpcode() == ISD::UNDEF) {
2886 Locs[i] = std::make_pair(-1, -1);
2887 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
2888 Locs[i] = std::make_pair(MaskIdx, LoIdx);
2889 (*MaskPtr)[LoIdx] = Elt;
2890 LoIdx++;
2891 } else {
2892 Locs[i] = std::make_pair(MaskIdx, HiIdx);
2893 (*MaskPtr)[HiIdx] = Elt;
2894 HiIdx++;
2895 }
2896 }
2897
2898 SDOperand LoShuffle =
2899 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2900 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2901 &LoMask[0], LoMask.size()));
2902 SDOperand HiShuffle =
2903 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2904 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2905 &HiMask[0], HiMask.size()));
2906 SmallVector<SDOperand, 8> MaskOps;
2907 for (unsigned i = 0; i != NumElems; ++i) {
2908 if (Locs[i].first == -1) {
2909 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
2910 } else {
2911 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
2912 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
2913 }
2914 }
2915 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
2916 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2917 &MaskOps[0], MaskOps.size()));
2918 }
2919
2920 return SDOperand();
2921}
2922
2923SDOperand
2924X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2925 if (!isa<ConstantSDNode>(Op.getOperand(1)))
2926 return SDOperand();
2927
2928 MVT::ValueType VT = Op.getValueType();
2929 // TODO: handle v16i8.
2930 if (MVT::getSizeInBits(VT) == 16) {
2931 // Transform it so it match pextrw which produces a 32-bit result.
2932 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
2933 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
2934 Op.getOperand(0), Op.getOperand(1));
2935 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
2936 DAG.getValueType(VT));
2937 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
2938 } else if (MVT::getSizeInBits(VT) == 32) {
2939 SDOperand Vec = Op.getOperand(0);
2940 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2941 if (Idx == 0)
2942 return Op;
2943 // SHUFPS the element to the lowest double word, then movss.
2944 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2945 SmallVector<SDOperand, 8> IdxVec;
2946 IdxVec.push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
2947 IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
2948 IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
2949 IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
2950 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2951 &IdxVec[0], IdxVec.size());
2952 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2953 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
2954 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2955 DAG.getConstant(0, getPointerTy()));
2956 } else if (MVT::getSizeInBits(VT) == 64) {
2957 SDOperand Vec = Op.getOperand(0);
2958 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2959 if (Idx == 0)
2960 return Op;
2961
2962 // UNPCKHPD the element to the lowest double word, then movsd.
2963 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
2964 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
2965 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2966 SmallVector<SDOperand, 8> IdxVec;
2967 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
2968 IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
2969 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2970 &IdxVec[0], IdxVec.size());
2971 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2972 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
2973 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2974 DAG.getConstant(0, getPointerTy()));
2975 }
2976
2977 return SDOperand();
2978}
2979
2980SDOperand
2981X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2982 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
2983 // as its second argument.
2984 MVT::ValueType VT = Op.getValueType();
2985 MVT::ValueType BaseVT = MVT::getVectorElementType(VT);
2986 SDOperand N0 = Op.getOperand(0);
2987 SDOperand N1 = Op.getOperand(1);
2988 SDOperand N2 = Op.getOperand(2);
2989 if (MVT::getSizeInBits(BaseVT) == 16) {
2990 if (N1.getValueType() != MVT::i32)
2991 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
2992 if (N2.getValueType() != MVT::i32)
2993 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
2994 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
2995 } else if (MVT::getSizeInBits(BaseVT) == 32) {
2996 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
2997 if (Idx == 0) {
2998 // Use a movss.
2999 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
3000 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3001 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3002 SmallVector<SDOperand, 8> MaskVec;
3003 MaskVec.push_back(DAG.getConstant(4, BaseVT));
3004 for (unsigned i = 1; i <= 3; ++i)
3005 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3006 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
3007 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3008 &MaskVec[0], MaskVec.size()));
3009 } else {
3010 // Use two pinsrw instructions to insert a 32 bit value.
3011 Idx <<= 1;
3012 if (MVT::isFloatingPoint(N1.getValueType())) {
Evan Cheng1eea6752007-07-31 06:21:44 +00003013 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
3014 N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
3015 N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
3016 DAG.getConstant(0, getPointerTy()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017 }
3018 N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
3019 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3020 DAG.getConstant(Idx, getPointerTy()));
3021 N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
3022 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3023 DAG.getConstant(Idx+1, getPointerTy()));
3024 return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3025 }
3026 }
3027
3028 return SDOperand();
3029}
3030
3031SDOperand
3032X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3033 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3034 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3035}
3036
3037// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3038// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3039// one of the above mentioned nodes. It has to be wrapped because otherwise
3040// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3041// be used to form addressing mode. These wrapped nodes will be selected
3042// into MOV32ri.
3043SDOperand
3044X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3045 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3046 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3047 getPointerTy(),
3048 CP->getAlignment());
3049 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3050 // With PIC, the address is actually $g + Offset.
3051 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3052 !Subtarget->isPICStyleRIPRel()) {
3053 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3054 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3055 Result);
3056 }
3057
3058 return Result;
3059}
3060
3061SDOperand
3062X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3063 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3064 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3065 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3066 // With PIC, the address is actually $g + Offset.
3067 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3068 !Subtarget->isPICStyleRIPRel()) {
3069 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3070 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3071 Result);
3072 }
3073
3074 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3075 // load the value at address GV, not the value of GV itself. This means that
3076 // the GlobalAddress must be in the base or index register of the address, not
3077 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3078 // The same applies for external symbols during PIC codegen
3079 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3080 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
3081
3082 return Result;
3083}
3084
3085// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3086static SDOperand
3087LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3088 const MVT::ValueType PtrVT) {
3089 SDOperand InFlag;
3090 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3091 DAG.getNode(X86ISD::GlobalBaseReg,
3092 PtrVT), InFlag);
3093 InFlag = Chain.getValue(1);
3094
3095 // emit leal symbol@TLSGD(,%ebx,1), %eax
3096 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3097 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3098 GA->getValueType(0),
3099 GA->getOffset());
3100 SDOperand Ops[] = { Chain, TGA, InFlag };
3101 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3102 InFlag = Result.getValue(2);
3103 Chain = Result.getValue(1);
3104
3105 // call ___tls_get_addr. This function receives its argument in
3106 // the register EAX.
3107 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3108 InFlag = Chain.getValue(1);
3109
3110 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3111 SDOperand Ops1[] = { Chain,
3112 DAG.getTargetExternalSymbol("___tls_get_addr",
3113 PtrVT),
3114 DAG.getRegister(X86::EAX, PtrVT),
3115 DAG.getRegister(X86::EBX, PtrVT),
3116 InFlag };
3117 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3118 InFlag = Chain.getValue(1);
3119
3120 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3121}
3122
3123// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3124// "local exec" model.
3125static SDOperand
3126LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3127 const MVT::ValueType PtrVT) {
3128 // Get the Thread Pointer
3129 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3130 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3131 // exec)
3132 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3133 GA->getValueType(0),
3134 GA->getOffset());
3135 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3136
3137 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3138 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
3139
3140 // The address of the thread local variable is the add of the thread
3141 // pointer with the offset of the variable.
3142 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3143}
3144
3145SDOperand
3146X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3147 // TODO: implement the "local dynamic" model
3148 // TODO: implement the "initial exec"model for pic executables
3149 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3150 "TLS not implemented for non-ELF and 64-bit targets");
3151 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3152 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3153 // otherwise use the "Local Exec"TLS Model
3154 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3155 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3156 else
3157 return LowerToTLSExecModel(GA, DAG, getPointerTy());
3158}
3159
3160SDOperand
3161X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3162 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3163 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3164 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3165 // With PIC, the address is actually $g + Offset.
3166 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3167 !Subtarget->isPICStyleRIPRel()) {
3168 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3169 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3170 Result);
3171 }
3172
3173 return Result;
3174}
3175
3176SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3177 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3178 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3179 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3180 // With PIC, the address is actually $g + Offset.
3181 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3182 !Subtarget->isPICStyleRIPRel()) {
3183 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3184 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3185 Result);
3186 }
3187
3188 return Result;
3189}
3190
3191SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
3192 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
3193 "Not an i64 shift!");
3194 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
3195 SDOperand ShOpLo = Op.getOperand(0);
3196 SDOperand ShOpHi = Op.getOperand(1);
3197 SDOperand ShAmt = Op.getOperand(2);
3198 SDOperand Tmp1 = isSRA ?
3199 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
3200 DAG.getConstant(0, MVT::i32);
3201
3202 SDOperand Tmp2, Tmp3;
3203 if (Op.getOpcode() == ISD::SHL_PARTS) {
3204 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
3205 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
3206 } else {
3207 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
3208 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
3209 }
3210
3211 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3212 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
3213 DAG.getConstant(32, MVT::i8));
3214 SDOperand COps[]={DAG.getEntryNode(), AndNode, DAG.getConstant(0, MVT::i8)};
3215 SDOperand InFlag = DAG.getNode(X86ISD::CMP, VTs, 2, COps, 3).getValue(1);
3216
3217 SDOperand Hi, Lo;
3218 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3219
3220 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
3221 SmallVector<SDOperand, 4> Ops;
3222 if (Op.getOpcode() == ISD::SHL_PARTS) {
3223 Ops.push_back(Tmp2);
3224 Ops.push_back(Tmp3);
3225 Ops.push_back(CC);
3226 Ops.push_back(InFlag);
3227 Hi = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3228 InFlag = Hi.getValue(1);
3229
3230 Ops.clear();
3231 Ops.push_back(Tmp3);
3232 Ops.push_back(Tmp1);
3233 Ops.push_back(CC);
3234 Ops.push_back(InFlag);
3235 Lo = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3236 } else {
3237 Ops.push_back(Tmp2);
3238 Ops.push_back(Tmp3);
3239 Ops.push_back(CC);
3240 Ops.push_back(InFlag);
3241 Lo = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3242 InFlag = Lo.getValue(1);
3243
3244 Ops.clear();
3245 Ops.push_back(Tmp3);
3246 Ops.push_back(Tmp1);
3247 Ops.push_back(CC);
3248 Ops.push_back(InFlag);
3249 Hi = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3250 }
3251
3252 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
3253 Ops.clear();
3254 Ops.push_back(Lo);
3255 Ops.push_back(Hi);
3256 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
3257}
3258
3259SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
3260 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
3261 Op.getOperand(0).getValueType() >= MVT::i16 &&
3262 "Unknown SINT_TO_FP to lower!");
3263
3264 SDOperand Result;
3265 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
3266 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
3267 MachineFunction &MF = DAG.getMachineFunction();
3268 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
3269 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3270 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
3271 StackSlot, NULL, 0);
3272
3273 // Build the FILD
3274 SDVTList Tys;
3275 if (X86ScalarSSE)
3276 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
3277 else
3278 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
3279 SmallVector<SDOperand, 8> Ops;
3280 Ops.push_back(Chain);
3281 Ops.push_back(StackSlot);
3282 Ops.push_back(DAG.getValueType(SrcVT));
3283 Result = DAG.getNode(X86ScalarSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
3284 Tys, &Ops[0], Ops.size());
3285
3286 if (X86ScalarSSE) {
3287 Chain = Result.getValue(1);
3288 SDOperand InFlag = Result.getValue(2);
3289
3290 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
3291 // shouldn't be necessary except that RFP cannot be live across
3292 // multiple blocks. When stackifier is fixed, they can be uncoupled.
3293 MachineFunction &MF = DAG.getMachineFunction();
3294 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3295 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3296 Tys = DAG.getVTList(MVT::Other);
3297 SmallVector<SDOperand, 8> Ops;
3298 Ops.push_back(Chain);
3299 Ops.push_back(Result);
3300 Ops.push_back(StackSlot);
3301 Ops.push_back(DAG.getValueType(Op.getValueType()));
3302 Ops.push_back(InFlag);
3303 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
3304 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
3305 }
3306
3307 return Result;
3308}
3309
3310SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
3311 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
3312 "Unknown FP_TO_SINT to lower!");
3313 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
3314 // stack slot.
3315 MachineFunction &MF = DAG.getMachineFunction();
3316 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
3317 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3318 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3319
3320 unsigned Opc;
3321 switch (Op.getValueType()) {
3322 default: assert(0 && "Invalid FP_TO_SINT to lower!");
3323 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
3324 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
3325 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
3326 }
3327
3328 SDOperand Chain = DAG.getEntryNode();
3329 SDOperand Value = Op.getOperand(0);
3330 if (X86ScalarSSE) {
3331 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
3332 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
3333 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
3334 SDOperand Ops[] = {
3335 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
3336 };
3337 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
3338 Chain = Value.getValue(1);
3339 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3340 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3341 }
3342
3343 // Build the FP_TO_INT*_IN_MEM
3344 SDOperand Ops[] = { Chain, Value, StackSlot };
3345 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
3346
3347 // Load the result.
3348 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
3349}
3350
3351SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
3352 MVT::ValueType VT = Op.getValueType();
3353 MVT::ValueType EltVT = VT;
3354 if (MVT::isVector(VT))
3355 EltVT = MVT::getVectorElementType(VT);
3356 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
3357 std::vector<Constant*> CV;
3358 if (EltVT == MVT::f64) {
3359 Constant *C = ConstantFP::get(OpNTy, BitsToDouble(~(1ULL << 63)));
3360 CV.push_back(C);
3361 CV.push_back(C);
3362 } else {
3363 Constant *C = ConstantFP::get(OpNTy, BitsToFloat(~(1U << 31)));
3364 CV.push_back(C);
3365 CV.push_back(C);
3366 CV.push_back(C);
3367 CV.push_back(C);
3368 }
Dan Gohman11821702007-07-27 17:16:43 +00003369 Constant *C = ConstantVector::get(CV);
3370 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
3371 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
3372 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003373 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
3374}
3375
3376SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
3377 MVT::ValueType VT = Op.getValueType();
3378 MVT::ValueType EltVT = VT;
Evan Cheng92b8f782007-07-19 23:36:01 +00003379 unsigned EltNum = 1;
3380 if (MVT::isVector(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003381 EltVT = MVT::getVectorElementType(VT);
Evan Cheng92b8f782007-07-19 23:36:01 +00003382 EltNum = MVT::getVectorNumElements(VT);
3383 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003384 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
3385 std::vector<Constant*> CV;
3386 if (EltVT == MVT::f64) {
3387 Constant *C = ConstantFP::get(OpNTy, BitsToDouble(1ULL << 63));
3388 CV.push_back(C);
3389 CV.push_back(C);
3390 } else {
3391 Constant *C = ConstantFP::get(OpNTy, BitsToFloat(1U << 31));
3392 CV.push_back(C);
3393 CV.push_back(C);
3394 CV.push_back(C);
3395 CV.push_back(C);
3396 }
Dan Gohman11821702007-07-27 17:16:43 +00003397 Constant *C = ConstantVector::get(CV);
3398 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
3399 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
3400 false, 16);
Evan Cheng92b8f782007-07-19 23:36:01 +00003401 if (MVT::isVector(VT)) {
Evan Cheng92b8f782007-07-19 23:36:01 +00003402 return DAG.getNode(ISD::BIT_CONVERT, VT,
3403 DAG.getNode(ISD::XOR, MVT::v2i64,
3404 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
3405 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
3406 } else {
Evan Cheng92b8f782007-07-19 23:36:01 +00003407 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
3408 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003409}
3410
3411SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
3412 SDOperand Op0 = Op.getOperand(0);
3413 SDOperand Op1 = Op.getOperand(1);
3414 MVT::ValueType VT = Op.getValueType();
3415 MVT::ValueType SrcVT = Op1.getValueType();
3416 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
3417
3418 // If second operand is smaller, extend it first.
3419 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
3420 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
3421 SrcVT = VT;
3422 }
3423
3424 // First get the sign bit of second operand.
3425 std::vector<Constant*> CV;
3426 if (SrcVT == MVT::f64) {
3427 CV.push_back(ConstantFP::get(SrcTy, BitsToDouble(1ULL << 63)));
3428 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3429 } else {
3430 CV.push_back(ConstantFP::get(SrcTy, BitsToFloat(1U << 31)));
3431 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3432 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3433 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3434 }
Dan Gohman11821702007-07-27 17:16:43 +00003435 Constant *C = ConstantVector::get(CV);
3436 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
3437 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx, NULL, 0,
3438 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003439 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
3440
3441 // Shift sign bit right or left if the two operands have different types.
3442 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
3443 // Op0 is MVT::f32, Op1 is MVT::f64.
3444 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
3445 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
3446 DAG.getConstant(32, MVT::i32));
3447 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
3448 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
3449 DAG.getConstant(0, getPointerTy()));
3450 }
3451
3452 // Clear first operand sign bit.
3453 CV.clear();
3454 if (VT == MVT::f64) {
3455 CV.push_back(ConstantFP::get(SrcTy, BitsToDouble(~(1ULL << 63))));
3456 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3457 } else {
3458 CV.push_back(ConstantFP::get(SrcTy, BitsToFloat(~(1U << 31))));
3459 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3460 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3461 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3462 }
Dan Gohman11821702007-07-27 17:16:43 +00003463 C = ConstantVector::get(CV);
3464 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
3465 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
3466 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003467 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
3468
3469 // Or the value with the sign bit.
3470 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
3471}
3472
3473SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG,
3474 SDOperand Chain) {
3475 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
3476 SDOperand Cond;
3477 SDOperand Op0 = Op.getOperand(0);
3478 SDOperand Op1 = Op.getOperand(1);
3479 SDOperand CC = Op.getOperand(2);
3480 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3481 const MVT::ValueType *VTs1 = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3482 const MVT::ValueType *VTs2 = DAG.getNodeValueTypes(MVT::i8, MVT::Flag);
3483 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
3484 unsigned X86CC;
3485
3486 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
3487 Op0, Op1, DAG)) {
3488 SDOperand Ops1[] = { Chain, Op0, Op1 };
3489 Cond = DAG.getNode(X86ISD::CMP, VTs1, 2, Ops1, 3).getValue(1);
3490 SDOperand Ops2[] = { DAG.getConstant(X86CC, MVT::i8), Cond };
3491 return DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3492 }
3493
3494 assert(isFP && "Illegal integer SetCC!");
3495
3496 SDOperand COps[] = { Chain, Op0, Op1 };
3497 Cond = DAG.getNode(X86ISD::CMP, VTs1, 2, COps, 3).getValue(1);
3498
3499 switch (SetCCOpcode) {
3500 default: assert(false && "Illegal floating point SetCC!");
3501 case ISD::SETOEQ: { // !PF & ZF
3502 SDOperand Ops1[] = { DAG.getConstant(X86::COND_NP, MVT::i8), Cond };
3503 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops1, 2);
3504 SDOperand Ops2[] = { DAG.getConstant(X86::COND_E, MVT::i8),
3505 Tmp1.getValue(1) };
3506 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3507 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
3508 }
3509 case ISD::SETUNE: { // PF | !ZF
3510 SDOperand Ops1[] = { DAG.getConstant(X86::COND_P, MVT::i8), Cond };
3511 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops1, 2);
3512 SDOperand Ops2[] = { DAG.getConstant(X86::COND_NE, MVT::i8),
3513 Tmp1.getValue(1) };
3514 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3515 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
3516 }
3517 }
3518}
3519
3520SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
3521 bool addTest = true;
3522 SDOperand Chain = DAG.getEntryNode();
3523 SDOperand Cond = Op.getOperand(0);
3524 SDOperand CC;
3525 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3526
3527 if (Cond.getOpcode() == ISD::SETCC)
3528 Cond = LowerSETCC(Cond, DAG, Chain);
3529
3530 if (Cond.getOpcode() == X86ISD::SETCC) {
3531 CC = Cond.getOperand(0);
3532
3533 // If condition flag is set by a X86ISD::CMP, then make a copy of it
3534 // (since flag operand cannot be shared). Use it as the condition setting
3535 // operand in place of the X86ISD::SETCC.
3536 // If the X86ISD::SETCC has more than one use, then perhaps it's better
3537 // to use a test instead of duplicating the X86ISD::CMP (for register
3538 // pressure reason)?
3539 SDOperand Cmp = Cond.getOperand(1);
3540 unsigned Opc = Cmp.getOpcode();
3541 bool IllegalFPCMov = !X86ScalarSSE &&
3542 MVT::isFloatingPoint(Op.getValueType()) &&
3543 !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
3544 if ((Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) &&
3545 !IllegalFPCMov) {
3546 SDOperand Ops[] = { Chain, Cmp.getOperand(1), Cmp.getOperand(2) };
3547 Cond = DAG.getNode(Opc, VTs, 2, Ops, 3);
3548 addTest = false;
3549 }
3550 }
3551
3552 if (addTest) {
3553 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3554 SDOperand Ops[] = { Chain, Cond, DAG.getConstant(0, MVT::i8) };
3555 Cond = DAG.getNode(X86ISD::CMP, VTs, 2, Ops, 3);
3556 }
3557
3558 VTs = DAG.getNodeValueTypes(Op.getValueType(), MVT::Flag);
3559 SmallVector<SDOperand, 4> Ops;
3560 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
3561 // condition is true.
3562 Ops.push_back(Op.getOperand(2));
3563 Ops.push_back(Op.getOperand(1));
3564 Ops.push_back(CC);
3565 Ops.push_back(Cond.getValue(1));
3566 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3567}
3568
3569SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
3570 bool addTest = true;
3571 SDOperand Chain = Op.getOperand(0);
3572 SDOperand Cond = Op.getOperand(1);
3573 SDOperand Dest = Op.getOperand(2);
3574 SDOperand CC;
3575 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3576
3577 if (Cond.getOpcode() == ISD::SETCC)
3578 Cond = LowerSETCC(Cond, DAG, Chain);
3579
3580 if (Cond.getOpcode() == X86ISD::SETCC) {
3581 CC = Cond.getOperand(0);
3582
3583 // If condition flag is set by a X86ISD::CMP, then make a copy of it
3584 // (since flag operand cannot be shared). Use it as the condition setting
3585 // operand in place of the X86ISD::SETCC.
3586 // If the X86ISD::SETCC has more than one use, then perhaps it's better
3587 // to use a test instead of duplicating the X86ISD::CMP (for register
3588 // pressure reason)?
3589 SDOperand Cmp = Cond.getOperand(1);
3590 unsigned Opc = Cmp.getOpcode();
3591 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) {
3592 SDOperand Ops[] = { Chain, Cmp.getOperand(1), Cmp.getOperand(2) };
3593 Cond = DAG.getNode(Opc, VTs, 2, Ops, 3);
3594 addTest = false;
3595 }
3596 }
3597
3598 if (addTest) {
3599 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3600 SDOperand Ops[] = { Chain, Cond, DAG.getConstant(0, MVT::i8) };
3601 Cond = DAG.getNode(X86ISD::CMP, VTs, 2, Ops, 3);
3602 }
3603 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
3604 Cond, Op.getOperand(2), CC, Cond.getValue(1));
3605}
3606
3607SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
3608 unsigned CallingConv= cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3609
3610 if (Subtarget->is64Bit())
3611 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
3612 else
3613 switch (CallingConv) {
3614 default:
3615 assert(0 && "Unsupported calling convention");
3616 case CallingConv::Fast:
3617 // TODO: Implement fastcc
3618 // Falls through
3619 case CallingConv::C:
3620 case CallingConv::X86_StdCall:
3621 return LowerCCCCallTo(Op, DAG, CallingConv);
3622 case CallingConv::X86_FastCall:
3623 return LowerFastCCCallTo(Op, DAG, CallingConv);
3624 }
3625}
3626
3627
3628// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
3629// Calls to _alloca is needed to probe the stack when allocating more than 4k
3630// bytes in one go. Touching the stack at 4K increments is necessary to ensure
3631// that the guard pages used by the OS virtual memory manager are allocated in
3632// correct sequence.
3633SDOperand
3634X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
3635 SelectionDAG &DAG) {
3636 assert(Subtarget->isTargetCygMing() &&
3637 "This should be used only on Cygwin/Mingw targets");
3638
3639 // Get the inputs.
3640 SDOperand Chain = Op.getOperand(0);
3641 SDOperand Size = Op.getOperand(1);
3642 // FIXME: Ensure alignment here
3643
3644 SDOperand Flag;
3645
3646 MVT::ValueType IntPtr = getPointerTy();
3647 MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
3648
3649 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
3650 Flag = Chain.getValue(1);
3651
3652 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3653 SDOperand Ops[] = { Chain,
3654 DAG.getTargetExternalSymbol("_alloca", IntPtr),
3655 DAG.getRegister(X86::EAX, IntPtr),
3656 Flag };
3657 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
3658 Flag = Chain.getValue(1);
3659
3660 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
3661
3662 std::vector<MVT::ValueType> Tys;
3663 Tys.push_back(SPTy);
3664 Tys.push_back(MVT::Other);
3665 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
3666 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
3667}
3668
3669SDOperand
3670X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
3671 MachineFunction &MF = DAG.getMachineFunction();
3672 const Function* Fn = MF.getFunction();
3673 if (Fn->hasExternalLinkage() &&
3674 Subtarget->isTargetCygMing() &&
3675 Fn->getName() == "main")
3676 MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
3677
3678 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3679 if (Subtarget->is64Bit())
3680 return LowerX86_64CCCArguments(Op, DAG);
3681 else
3682 switch(CC) {
3683 default:
3684 assert(0 && "Unsupported calling convention");
3685 case CallingConv::Fast:
3686 // TODO: implement fastcc.
3687
3688 // Falls through
3689 case CallingConv::C:
3690 return LowerCCCArguments(Op, DAG);
3691 case CallingConv::X86_StdCall:
3692 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
3693 return LowerCCCArguments(Op, DAG, true);
3694 case CallingConv::X86_FastCall:
3695 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
3696 return LowerFastCCArguments(Op, DAG);
3697 }
3698}
3699
3700SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
3701 SDOperand InFlag(0, 0);
3702 SDOperand Chain = Op.getOperand(0);
3703 unsigned Align =
3704 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3705 if (Align == 0) Align = 1;
3706
3707 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3708 // If not DWORD aligned, call memset if size is less than the threshold.
3709 // It knows how to align to the right boundary first.
3710 if ((Align & 3) != 0 ||
3711 (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3712 MVT::ValueType IntPtr = getPointerTy();
3713 const Type *IntPtrTy = getTargetData()->getIntPtrType();
3714 TargetLowering::ArgListTy Args;
3715 TargetLowering::ArgListEntry Entry;
3716 Entry.Node = Op.getOperand(1);
3717 Entry.Ty = IntPtrTy;
3718 Args.push_back(Entry);
3719 // Extend the unsigned i8 argument to be an int value for the call.
3720 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
3721 Entry.Ty = IntPtrTy;
3722 Args.push_back(Entry);
3723 Entry.Node = Op.getOperand(3);
3724 Args.push_back(Entry);
3725 std::pair<SDOperand,SDOperand> CallResult =
3726 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
3727 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
3728 return CallResult.second;
3729 }
3730
3731 MVT::ValueType AVT;
3732 SDOperand Count;
3733 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3734 unsigned BytesLeft = 0;
3735 bool TwoRepStos = false;
3736 if (ValC) {
3737 unsigned ValReg;
3738 uint64_t Val = ValC->getValue() & 255;
3739
3740 // If the value is a constant, then we can potentially use larger sets.
3741 switch (Align & 3) {
3742 case 2: // WORD aligned
3743 AVT = MVT::i16;
3744 ValReg = X86::AX;
3745 Val = (Val << 8) | Val;
3746 break;
3747 case 0: // DWORD aligned
3748 AVT = MVT::i32;
3749 ValReg = X86::EAX;
3750 Val = (Val << 8) | Val;
3751 Val = (Val << 16) | Val;
3752 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
3753 AVT = MVT::i64;
3754 ValReg = X86::RAX;
3755 Val = (Val << 32) | Val;
3756 }
3757 break;
3758 default: // Byte aligned
3759 AVT = MVT::i8;
3760 ValReg = X86::AL;
3761 Count = Op.getOperand(3);
3762 break;
3763 }
3764
3765 if (AVT > MVT::i8) {
3766 if (I) {
3767 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
3768 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
3769 BytesLeft = I->getValue() % UBytes;
3770 } else {
3771 assert(AVT >= MVT::i32 &&
3772 "Do not use rep;stos if not at least DWORD aligned");
3773 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
3774 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
3775 TwoRepStos = true;
3776 }
3777 }
3778
3779 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
3780 InFlag);
3781 InFlag = Chain.getValue(1);
3782 } else {
3783 AVT = MVT::i8;
3784 Count = Op.getOperand(3);
3785 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
3786 InFlag = Chain.getValue(1);
3787 }
3788
3789 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
3790 Count, InFlag);
3791 InFlag = Chain.getValue(1);
3792 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
3793 Op.getOperand(1), InFlag);
3794 InFlag = Chain.getValue(1);
3795
3796 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3797 SmallVector<SDOperand, 8> Ops;
3798 Ops.push_back(Chain);
3799 Ops.push_back(DAG.getValueType(AVT));
3800 Ops.push_back(InFlag);
3801 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
3802
3803 if (TwoRepStos) {
3804 InFlag = Chain.getValue(1);
3805 Count = Op.getOperand(3);
3806 MVT::ValueType CVT = Count.getValueType();
3807 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3808 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
3809 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
3810 Left, InFlag);
3811 InFlag = Chain.getValue(1);
3812 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3813 Ops.clear();
3814 Ops.push_back(Chain);
3815 Ops.push_back(DAG.getValueType(MVT::i8));
3816 Ops.push_back(InFlag);
3817 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
3818 } else if (BytesLeft) {
3819 // Issue stores for the last 1 - 7 bytes.
3820 SDOperand Value;
3821 unsigned Val = ValC->getValue() & 255;
3822 unsigned Offset = I->getValue() - BytesLeft;
3823 SDOperand DstAddr = Op.getOperand(1);
3824 MVT::ValueType AddrVT = DstAddr.getValueType();
3825 if (BytesLeft >= 4) {
3826 Val = (Val << 8) | Val;
3827 Val = (Val << 16) | Val;
3828 Value = DAG.getConstant(Val, MVT::i32);
3829 Chain = DAG.getStore(Chain, Value,
3830 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3831 DAG.getConstant(Offset, AddrVT)),
3832 NULL, 0);
3833 BytesLeft -= 4;
3834 Offset += 4;
3835 }
3836 if (BytesLeft >= 2) {
3837 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
3838 Chain = DAG.getStore(Chain, Value,
3839 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3840 DAG.getConstant(Offset, AddrVT)),
3841 NULL, 0);
3842 BytesLeft -= 2;
3843 Offset += 2;
3844 }
3845 if (BytesLeft == 1) {
3846 Value = DAG.getConstant(Val, MVT::i8);
3847 Chain = DAG.getStore(Chain, Value,
3848 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3849 DAG.getConstant(Offset, AddrVT)),
3850 NULL, 0);
3851 }
3852 }
3853
3854 return Chain;
3855}
3856
3857SDOperand X86TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
3858 SDOperand Chain = Op.getOperand(0);
3859 unsigned Align =
3860 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3861 if (Align == 0) Align = 1;
3862
3863 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3864 // If not DWORD aligned, call memcpy if size is less than the threshold.
3865 // It knows how to align to the right boundary first.
3866 if ((Align & 3) != 0 ||
3867 (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3868 MVT::ValueType IntPtr = getPointerTy();
3869 TargetLowering::ArgListTy Args;
3870 TargetLowering::ArgListEntry Entry;
3871 Entry.Ty = getTargetData()->getIntPtrType();
3872 Entry.Node = Op.getOperand(1); Args.push_back(Entry);
3873 Entry.Node = Op.getOperand(2); Args.push_back(Entry);
3874 Entry.Node = Op.getOperand(3); Args.push_back(Entry);
3875 std::pair<SDOperand,SDOperand> CallResult =
3876 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
3877 DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
3878 return CallResult.second;
3879 }
3880
3881 MVT::ValueType AVT;
3882 SDOperand Count;
3883 unsigned BytesLeft = 0;
3884 bool TwoRepMovs = false;
3885 switch (Align & 3) {
3886 case 2: // WORD aligned
3887 AVT = MVT::i16;
3888 break;
3889 case 0: // DWORD aligned
3890 AVT = MVT::i32;
3891 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
3892 AVT = MVT::i64;
3893 break;
3894 default: // Byte aligned
3895 AVT = MVT::i8;
3896 Count = Op.getOperand(3);
3897 break;
3898 }
3899
3900 if (AVT > MVT::i8) {
3901 if (I) {
3902 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
3903 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
3904 BytesLeft = I->getValue() % UBytes;
3905 } else {
3906 assert(AVT >= MVT::i32 &&
3907 "Do not use rep;movs if not at least DWORD aligned");
3908 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
3909 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
3910 TwoRepMovs = true;
3911 }
3912 }
3913
3914 SDOperand InFlag(0, 0);
3915 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
3916 Count, InFlag);
3917 InFlag = Chain.getValue(1);
3918 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
3919 Op.getOperand(1), InFlag);
3920 InFlag = Chain.getValue(1);
3921 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
3922 Op.getOperand(2), InFlag);
3923 InFlag = Chain.getValue(1);
3924
3925 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3926 SmallVector<SDOperand, 8> Ops;
3927 Ops.push_back(Chain);
3928 Ops.push_back(DAG.getValueType(AVT));
3929 Ops.push_back(InFlag);
3930 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
3931
3932 if (TwoRepMovs) {
3933 InFlag = Chain.getValue(1);
3934 Count = Op.getOperand(3);
3935 MVT::ValueType CVT = Count.getValueType();
3936 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3937 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
3938 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
3939 Left, InFlag);
3940 InFlag = Chain.getValue(1);
3941 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3942 Ops.clear();
3943 Ops.push_back(Chain);
3944 Ops.push_back(DAG.getValueType(MVT::i8));
3945 Ops.push_back(InFlag);
3946 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
3947 } else if (BytesLeft) {
3948 // Issue loads and stores for the last 1 - 7 bytes.
3949 unsigned Offset = I->getValue() - BytesLeft;
3950 SDOperand DstAddr = Op.getOperand(1);
3951 MVT::ValueType DstVT = DstAddr.getValueType();
3952 SDOperand SrcAddr = Op.getOperand(2);
3953 MVT::ValueType SrcVT = SrcAddr.getValueType();
3954 SDOperand Value;
3955 if (BytesLeft >= 4) {
3956 Value = DAG.getLoad(MVT::i32, Chain,
3957 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3958 DAG.getConstant(Offset, SrcVT)),
3959 NULL, 0);
3960 Chain = Value.getValue(1);
3961 Chain = DAG.getStore(Chain, Value,
3962 DAG.getNode(ISD::ADD, DstVT, DstAddr,
3963 DAG.getConstant(Offset, DstVT)),
3964 NULL, 0);
3965 BytesLeft -= 4;
3966 Offset += 4;
3967 }
3968 if (BytesLeft >= 2) {
3969 Value = DAG.getLoad(MVT::i16, Chain,
3970 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3971 DAG.getConstant(Offset, SrcVT)),
3972 NULL, 0);
3973 Chain = Value.getValue(1);
3974 Chain = DAG.getStore(Chain, Value,
3975 DAG.getNode(ISD::ADD, DstVT, DstAddr,
3976 DAG.getConstant(Offset, DstVT)),
3977 NULL, 0);
3978 BytesLeft -= 2;
3979 Offset += 2;
3980 }
3981
3982 if (BytesLeft == 1) {
3983 Value = DAG.getLoad(MVT::i8, Chain,
3984 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3985 DAG.getConstant(Offset, SrcVT)),
3986 NULL, 0);
3987 Chain = Value.getValue(1);
3988 Chain = DAG.getStore(Chain, Value,
3989 DAG.getNode(ISD::ADD, DstVT, DstAddr,
3990 DAG.getConstant(Offset, DstVT)),
3991 NULL, 0);
3992 }
3993 }
3994
3995 return Chain;
3996}
3997
3998SDOperand
3999X86TargetLowering::LowerREADCYCLCECOUNTER(SDOperand Op, SelectionDAG &DAG) {
4000 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4001 SDOperand TheOp = Op.getOperand(0);
4002 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheOp, 1);
4003 if (Subtarget->is64Bit()) {
4004 SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4005 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::RDX,
4006 MVT::i64, Copy1.getValue(2));
4007 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, Copy2,
4008 DAG.getConstant(32, MVT::i8));
4009 SDOperand Ops[] = {
4010 DAG.getNode(ISD::OR, MVT::i64, Copy1, Tmp), Copy2.getValue(1)
4011 };
4012
4013 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4014 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2);
4015 }
4016
4017 SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4018 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::EDX,
4019 MVT::i32, Copy1.getValue(2));
4020 SDOperand Ops[] = { Copy1, Copy2, Copy2.getValue(1) };
4021 Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
4022 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 3);
4023}
4024
4025SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4026 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
4027
4028 if (!Subtarget->is64Bit()) {
4029 // vastart just stores the address of the VarArgsFrameIndex slot into the
4030 // memory location argument.
4031 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4032 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
4033 SV->getOffset());
4034 }
4035
4036 // __va_list_tag:
4037 // gp_offset (0 - 6 * 8)
4038 // fp_offset (48 - 48 + 8 * 16)
4039 // overflow_arg_area (point to parameters coming in memory).
4040 // reg_save_area
4041 SmallVector<SDOperand, 8> MemOps;
4042 SDOperand FIN = Op.getOperand(1);
4043 // Store gp_offset
4044 SDOperand Store = DAG.getStore(Op.getOperand(0),
4045 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4046 FIN, SV->getValue(), SV->getOffset());
4047 MemOps.push_back(Store);
4048
4049 // Store fp_offset
4050 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4051 DAG.getConstant(4, getPointerTy()));
4052 Store = DAG.getStore(Op.getOperand(0),
4053 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4054 FIN, SV->getValue(), SV->getOffset());
4055 MemOps.push_back(Store);
4056
4057 // Store ptr to overflow_arg_area
4058 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4059 DAG.getConstant(4, getPointerTy()));
4060 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4061 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
4062 SV->getOffset());
4063 MemOps.push_back(Store);
4064
4065 // Store ptr to reg_save_area.
4066 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4067 DAG.getConstant(8, getPointerTy()));
4068 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4069 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
4070 SV->getOffset());
4071 MemOps.push_back(Store);
4072 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4073}
4074
4075SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4076 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4077 SDOperand Chain = Op.getOperand(0);
4078 SDOperand DstPtr = Op.getOperand(1);
4079 SDOperand SrcPtr = Op.getOperand(2);
4080 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
4081 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
4082
4083 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
4084 SrcSV->getValue(), SrcSV->getOffset());
4085 Chain = SrcPtr.getValue(1);
4086 for (unsigned i = 0; i < 3; ++i) {
4087 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
4088 SrcSV->getValue(), SrcSV->getOffset());
4089 Chain = Val.getValue(1);
4090 Chain = DAG.getStore(Chain, Val, DstPtr,
4091 DstSV->getValue(), DstSV->getOffset());
4092 if (i == 2)
4093 break;
4094 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
4095 DAG.getConstant(8, getPointerTy()));
4096 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
4097 DAG.getConstant(8, getPointerTy()));
4098 }
4099 return Chain;
4100}
4101
4102SDOperand
4103X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4104 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4105 switch (IntNo) {
4106 default: return SDOperand(); // Don't custom lower most intrinsics.
4107 // Comparison intrinsics.
4108 case Intrinsic::x86_sse_comieq_ss:
4109 case Intrinsic::x86_sse_comilt_ss:
4110 case Intrinsic::x86_sse_comile_ss:
4111 case Intrinsic::x86_sse_comigt_ss:
4112 case Intrinsic::x86_sse_comige_ss:
4113 case Intrinsic::x86_sse_comineq_ss:
4114 case Intrinsic::x86_sse_ucomieq_ss:
4115 case Intrinsic::x86_sse_ucomilt_ss:
4116 case Intrinsic::x86_sse_ucomile_ss:
4117 case Intrinsic::x86_sse_ucomigt_ss:
4118 case Intrinsic::x86_sse_ucomige_ss:
4119 case Intrinsic::x86_sse_ucomineq_ss:
4120 case Intrinsic::x86_sse2_comieq_sd:
4121 case Intrinsic::x86_sse2_comilt_sd:
4122 case Intrinsic::x86_sse2_comile_sd:
4123 case Intrinsic::x86_sse2_comigt_sd:
4124 case Intrinsic::x86_sse2_comige_sd:
4125 case Intrinsic::x86_sse2_comineq_sd:
4126 case Intrinsic::x86_sse2_ucomieq_sd:
4127 case Intrinsic::x86_sse2_ucomilt_sd:
4128 case Intrinsic::x86_sse2_ucomile_sd:
4129 case Intrinsic::x86_sse2_ucomigt_sd:
4130 case Intrinsic::x86_sse2_ucomige_sd:
4131 case Intrinsic::x86_sse2_ucomineq_sd: {
4132 unsigned Opc = 0;
4133 ISD::CondCode CC = ISD::SETCC_INVALID;
4134 switch (IntNo) {
4135 default: break;
4136 case Intrinsic::x86_sse_comieq_ss:
4137 case Intrinsic::x86_sse2_comieq_sd:
4138 Opc = X86ISD::COMI;
4139 CC = ISD::SETEQ;
4140 break;
4141 case Intrinsic::x86_sse_comilt_ss:
4142 case Intrinsic::x86_sse2_comilt_sd:
4143 Opc = X86ISD::COMI;
4144 CC = ISD::SETLT;
4145 break;
4146 case Intrinsic::x86_sse_comile_ss:
4147 case Intrinsic::x86_sse2_comile_sd:
4148 Opc = X86ISD::COMI;
4149 CC = ISD::SETLE;
4150 break;
4151 case Intrinsic::x86_sse_comigt_ss:
4152 case Intrinsic::x86_sse2_comigt_sd:
4153 Opc = X86ISD::COMI;
4154 CC = ISD::SETGT;
4155 break;
4156 case Intrinsic::x86_sse_comige_ss:
4157 case Intrinsic::x86_sse2_comige_sd:
4158 Opc = X86ISD::COMI;
4159 CC = ISD::SETGE;
4160 break;
4161 case Intrinsic::x86_sse_comineq_ss:
4162 case Intrinsic::x86_sse2_comineq_sd:
4163 Opc = X86ISD::COMI;
4164 CC = ISD::SETNE;
4165 break;
4166 case Intrinsic::x86_sse_ucomieq_ss:
4167 case Intrinsic::x86_sse2_ucomieq_sd:
4168 Opc = X86ISD::UCOMI;
4169 CC = ISD::SETEQ;
4170 break;
4171 case Intrinsic::x86_sse_ucomilt_ss:
4172 case Intrinsic::x86_sse2_ucomilt_sd:
4173 Opc = X86ISD::UCOMI;
4174 CC = ISD::SETLT;
4175 break;
4176 case Intrinsic::x86_sse_ucomile_ss:
4177 case Intrinsic::x86_sse2_ucomile_sd:
4178 Opc = X86ISD::UCOMI;
4179 CC = ISD::SETLE;
4180 break;
4181 case Intrinsic::x86_sse_ucomigt_ss:
4182 case Intrinsic::x86_sse2_ucomigt_sd:
4183 Opc = X86ISD::UCOMI;
4184 CC = ISD::SETGT;
4185 break;
4186 case Intrinsic::x86_sse_ucomige_ss:
4187 case Intrinsic::x86_sse2_ucomige_sd:
4188 Opc = X86ISD::UCOMI;
4189 CC = ISD::SETGE;
4190 break;
4191 case Intrinsic::x86_sse_ucomineq_ss:
4192 case Intrinsic::x86_sse2_ucomineq_sd:
4193 Opc = X86ISD::UCOMI;
4194 CC = ISD::SETNE;
4195 break;
4196 }
4197
4198 unsigned X86CC;
4199 SDOperand LHS = Op.getOperand(1);
4200 SDOperand RHS = Op.getOperand(2);
4201 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4202
4203 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4204 SDOperand Ops1[] = { DAG.getEntryNode(), LHS, RHS };
4205 SDOperand Cond = DAG.getNode(Opc, VTs, 2, Ops1, 3);
4206 VTs = DAG.getNodeValueTypes(MVT::i8, MVT::Flag);
4207 SDOperand Ops2[] = { DAG.getConstant(X86CC, MVT::i8), Cond };
4208 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, VTs, 2, Ops2, 2);
4209 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
4210 }
4211 }
4212}
4213
4214SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4215 // Depths > 0 not supported yet!
4216 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4217 return SDOperand();
4218
4219 // Just load the return address
4220 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4221 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4222}
4223
4224SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4225 // Depths > 0 not supported yet!
4226 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4227 return SDOperand();
4228
4229 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4230 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
4231 DAG.getConstant(4, getPointerTy()));
4232}
4233
4234SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
4235 SelectionDAG &DAG) {
4236 // Is not yet supported on x86-64
4237 if (Subtarget->is64Bit())
4238 return SDOperand();
4239
4240 return DAG.getConstant(8, getPointerTy());
4241}
4242
4243SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
4244{
4245 assert(!Subtarget->is64Bit() &&
4246 "Lowering of eh_return builtin is not supported yet on x86-64");
4247
4248 MachineFunction &MF = DAG.getMachineFunction();
4249 SDOperand Chain = Op.getOperand(0);
4250 SDOperand Offset = Op.getOperand(1);
4251 SDOperand Handler = Op.getOperand(2);
4252
4253 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
4254 getPointerTy());
4255
4256 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
4257 DAG.getConstant(-4UL, getPointerTy()));
4258 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
4259 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
4260 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
4261 MF.addLiveOut(X86::ECX);
4262
4263 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
4264 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
4265}
4266
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004267SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
4268 SelectionDAG &DAG) {
4269 SDOperand Root = Op.getOperand(0);
4270 SDOperand Trmp = Op.getOperand(1); // trampoline
4271 SDOperand FPtr = Op.getOperand(2); // nested function
4272 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
4273
4274 SrcValueSDNode *TrmpSV = cast<SrcValueSDNode>(Op.getOperand(4));
4275
4276 if (Subtarget->is64Bit()) {
4277 return SDOperand(); // not yet supported
4278 } else {
4279 Function *Func = (Function *)
4280 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
4281 unsigned CC = Func->getCallingConv();
4282 unsigned char NestReg;
4283
4284 switch (CC) {
4285 default:
4286 assert(0 && "Unsupported calling convention");
4287 case CallingConv::C:
4288 case CallingConv::Fast:
4289 case CallingConv::X86_StdCall: {
4290 // Pass 'nest' parameter in ECX.
4291 // Must be kept in sync with X86CallingConv.td
4292 NestReg = N86::ECX;
4293
4294 // Check that ECX wasn't needed by an 'inreg' parameter.
4295 const FunctionType *FTy = Func->getFunctionType();
4296 const ParamAttrsList *Attrs = FTy->getParamAttrs();
4297
4298 if (Attrs && !Func->isVarArg()) {
4299 unsigned InRegCount = 0;
4300 unsigned Idx = 1;
4301
4302 for (FunctionType::param_iterator I = FTy->param_begin(),
4303 E = FTy->param_end(); I != E; ++I, ++Idx)
4304 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
4305 // FIXME: should only count parameters that are lowered to integers.
4306 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
4307
4308 if (InRegCount > 2) {
4309 cerr << "Nest register in use - reduce number of inreg parameters!\n";
4310 abort();
4311 }
4312 }
4313 break;
4314 }
4315 case CallingConv::X86_FastCall:
4316 // Pass 'nest' parameter in EAX.
4317 // Must be kept in sync with X86CallingConv.td
4318 NestReg = N86::EAX;
4319 break;
4320 }
4321
4322 SDOperand OutChains[4];
4323 SDOperand Addr, Disp;
4324
4325 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
4326 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
4327
4328 const unsigned char MOV32ri = 0xB8;
4329 const unsigned char JMP = 0xE9;
4330
4331 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|NestReg, MVT::i8),
4332 Trmp, TrmpSV->getValue(), TrmpSV->getOffset());
4333
4334 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
4335 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpSV->getValue(),
4336 TrmpSV->getOffset() + 1, false, 1);
4337
4338 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
4339 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
4340 TrmpSV->getValue() + 5, TrmpSV->getOffset());
4341
4342 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
4343 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpSV->getValue(),
4344 TrmpSV->getOffset() + 6, false, 1);
4345
4346 return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4);
4347 }
4348}
4349
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004350/// LowerOperation - Provide custom lowering hooks for some operations.
4351///
4352SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4353 switch (Op.getOpcode()) {
4354 default: assert(0 && "Should not custom lower this!");
4355 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
4356 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
4357 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4358 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
4359 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
4360 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
4361 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
4362 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
4363 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
4364 case ISD::SHL_PARTS:
4365 case ISD::SRA_PARTS:
4366 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
4367 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
4368 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
4369 case ISD::FABS: return LowerFABS(Op, DAG);
4370 case ISD::FNEG: return LowerFNEG(Op, DAG);
4371 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
4372 case ISD::SETCC: return LowerSETCC(Op, DAG, DAG.getEntryNode());
4373 case ISD::SELECT: return LowerSELECT(Op, DAG);
4374 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4375 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
4376 case ISD::CALL: return LowerCALL(Op, DAG);
4377 case ISD::RET: return LowerRET(Op, DAG);
4378 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
4379 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
4380 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
4381 case ISD::READCYCLECOUNTER: return LowerREADCYCLCECOUNTER(Op, DAG);
4382 case ISD::VASTART: return LowerVASTART(Op, DAG);
4383 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
4384 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4385 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4386 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
4387 case ISD::FRAME_TO_ARGS_OFFSET:
4388 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
4389 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
4390 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00004391 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004392 }
4393 return SDOperand();
4394}
4395
4396const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
4397 switch (Opcode) {
4398 default: return NULL;
4399 case X86ISD::SHLD: return "X86ISD::SHLD";
4400 case X86ISD::SHRD: return "X86ISD::SHRD";
4401 case X86ISD::FAND: return "X86ISD::FAND";
4402 case X86ISD::FOR: return "X86ISD::FOR";
4403 case X86ISD::FXOR: return "X86ISD::FXOR";
4404 case X86ISD::FSRL: return "X86ISD::FSRL";
4405 case X86ISD::FILD: return "X86ISD::FILD";
4406 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
4407 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
4408 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
4409 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
4410 case X86ISD::FLD: return "X86ISD::FLD";
4411 case X86ISD::FST: return "X86ISD::FST";
4412 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
4413 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
4414 case X86ISD::CALL: return "X86ISD::CALL";
4415 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
4416 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
4417 case X86ISD::CMP: return "X86ISD::CMP";
4418 case X86ISD::COMI: return "X86ISD::COMI";
4419 case X86ISD::UCOMI: return "X86ISD::UCOMI";
4420 case X86ISD::SETCC: return "X86ISD::SETCC";
4421 case X86ISD::CMOV: return "X86ISD::CMOV";
4422 case X86ISD::BRCOND: return "X86ISD::BRCOND";
4423 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
4424 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
4425 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004426 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
4427 case X86ISD::Wrapper: return "X86ISD::Wrapper";
4428 case X86ISD::S2VEC: return "X86ISD::S2VEC";
4429 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
4430 case X86ISD::PINSRW: return "X86ISD::PINSRW";
4431 case X86ISD::FMAX: return "X86ISD::FMAX";
4432 case X86ISD::FMIN: return "X86ISD::FMIN";
4433 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
4434 case X86ISD::FRCP: return "X86ISD::FRCP";
4435 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
4436 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
4437 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
4438 }
4439}
4440
4441// isLegalAddressingMode - Return true if the addressing mode represented
4442// by AM is legal for this target, for a load/store of the specified type.
4443bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
4444 const Type *Ty) const {
4445 // X86 supports extremely general addressing modes.
4446
4447 // X86 allows a sign-extended 32-bit immediate field as a displacement.
4448 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
4449 return false;
4450
4451 if (AM.BaseGV) {
4452 // X86-64 only supports addr of globals in small code model.
4453 if (Subtarget->is64Bit() &&
4454 getTargetMachine().getCodeModel() != CodeModel::Small)
4455 return false;
4456
4457 // We can only fold this if we don't need a load either.
4458 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
4459 return false;
4460 }
4461
4462 switch (AM.Scale) {
4463 case 0:
4464 case 1:
4465 case 2:
4466 case 4:
4467 case 8:
4468 // These scales always work.
4469 break;
4470 case 3:
4471 case 5:
4472 case 9:
4473 // These scales are formed with basereg+scalereg. Only accept if there is
4474 // no basereg yet.
4475 if (AM.HasBaseReg)
4476 return false;
4477 break;
4478 default: // Other stuff never works.
4479 return false;
4480 }
4481
4482 return true;
4483}
4484
4485
4486/// isShuffleMaskLegal - Targets can use this to indicate that they only
4487/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4488/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4489/// are assumed to be legal.
4490bool
4491X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
4492 // Only do shuffles on 128-bit vector types for now.
4493 if (MVT::getSizeInBits(VT) == 64) return false;
4494 return (Mask.Val->getNumOperands() <= 4 ||
4495 isIdentityMask(Mask.Val) ||
4496 isIdentityMask(Mask.Val, true) ||
4497 isSplatMask(Mask.Val) ||
4498 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
4499 X86::isUNPCKLMask(Mask.Val) ||
4500 X86::isUNPCKHMask(Mask.Val) ||
4501 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
4502 X86::isUNPCKH_v_undef_Mask(Mask.Val));
4503}
4504
4505bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
4506 MVT::ValueType EVT,
4507 SelectionDAG &DAG) const {
4508 unsigned NumElts = BVOps.size();
4509 // Only do shuffles on 128-bit vector types for now.
4510 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
4511 if (NumElts == 2) return true;
4512 if (NumElts == 4) {
4513 return (isMOVLMask(&BVOps[0], 4) ||
4514 isCommutedMOVL(&BVOps[0], 4, true) ||
4515 isSHUFPMask(&BVOps[0], 4) ||
4516 isCommutedSHUFP(&BVOps[0], 4));
4517 }
4518 return false;
4519}
4520
4521//===----------------------------------------------------------------------===//
4522// X86 Scheduler Hooks
4523//===----------------------------------------------------------------------===//
4524
4525MachineBasicBlock *
4526X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
4527 MachineBasicBlock *BB) {
4528 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4529 switch (MI->getOpcode()) {
4530 default: assert(false && "Unexpected instr type to insert");
4531 case X86::CMOV_FR32:
4532 case X86::CMOV_FR64:
4533 case X86::CMOV_V4F32:
4534 case X86::CMOV_V2F64:
4535 case X86::CMOV_V2I64: {
4536 // To "insert" a SELECT_CC instruction, we actually have to insert the
4537 // diamond control-flow pattern. The incoming instruction knows the
4538 // destination vreg to set, the condition code register to branch on, the
4539 // true/false values to select between, and a branch opcode to use.
4540 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4541 ilist<MachineBasicBlock>::iterator It = BB;
4542 ++It;
4543
4544 // thisMBB:
4545 // ...
4546 // TrueVal = ...
4547 // cmpTY ccX, r1, r2
4548 // bCC copy1MBB
4549 // fallthrough --> copy0MBB
4550 MachineBasicBlock *thisMBB = BB;
4551 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
4552 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
4553 unsigned Opc =
4554 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
4555 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
4556 MachineFunction *F = BB->getParent();
4557 F->getBasicBlockList().insert(It, copy0MBB);
4558 F->getBasicBlockList().insert(It, sinkMBB);
4559 // Update machine-CFG edges by first adding all successors of the current
4560 // block to the new block which will contain the Phi node for the select.
4561 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
4562 e = BB->succ_end(); i != e; ++i)
4563 sinkMBB->addSuccessor(*i);
4564 // Next, remove all successors of the current block, and add the true
4565 // and fallthrough blocks as its successors.
4566 while(!BB->succ_empty())
4567 BB->removeSuccessor(BB->succ_begin());
4568 BB->addSuccessor(copy0MBB);
4569 BB->addSuccessor(sinkMBB);
4570
4571 // copy0MBB:
4572 // %FalseValue = ...
4573 // # fallthrough to sinkMBB
4574 BB = copy0MBB;
4575
4576 // Update machine-CFG edges
4577 BB->addSuccessor(sinkMBB);
4578
4579 // sinkMBB:
4580 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
4581 // ...
4582 BB = sinkMBB;
4583 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
4584 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
4585 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
4586
4587 delete MI; // The pseudo instruction is gone now.
4588 return BB;
4589 }
4590
4591 case X86::FP32_TO_INT16_IN_MEM:
4592 case X86::FP32_TO_INT32_IN_MEM:
4593 case X86::FP32_TO_INT64_IN_MEM:
4594 case X86::FP64_TO_INT16_IN_MEM:
4595 case X86::FP64_TO_INT32_IN_MEM:
4596 case X86::FP64_TO_INT64_IN_MEM: {
4597 // Change the floating point control register to use "round towards zero"
4598 // mode when truncating to an integer value.
4599 MachineFunction *F = BB->getParent();
4600 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
4601 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
4602
4603 // Load the old value of the high byte of the control word...
4604 unsigned OldCW =
4605 F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
4606 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
4607
4608 // Set the high part to be round to zero...
4609 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
4610 .addImm(0xC7F);
4611
4612 // Reload the modified control word now...
4613 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
4614
4615 // Restore the memory image of control word to original value
4616 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
4617 .addReg(OldCW);
4618
4619 // Get the X86 opcode to use.
4620 unsigned Opc;
4621 switch (MI->getOpcode()) {
4622 default: assert(0 && "illegal opcode!");
4623 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
4624 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
4625 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
4626 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
4627 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
4628 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
4629 }
4630
4631 X86AddressMode AM;
4632 MachineOperand &Op = MI->getOperand(0);
4633 if (Op.isRegister()) {
4634 AM.BaseType = X86AddressMode::RegBase;
4635 AM.Base.Reg = Op.getReg();
4636 } else {
4637 AM.BaseType = X86AddressMode::FrameIndexBase;
4638 AM.Base.FrameIndex = Op.getFrameIndex();
4639 }
4640 Op = MI->getOperand(1);
4641 if (Op.isImmediate())
4642 AM.Scale = Op.getImm();
4643 Op = MI->getOperand(2);
4644 if (Op.isImmediate())
4645 AM.IndexReg = Op.getImm();
4646 Op = MI->getOperand(3);
4647 if (Op.isGlobalAddress()) {
4648 AM.GV = Op.getGlobal();
4649 } else {
4650 AM.Disp = Op.getImm();
4651 }
4652 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
4653 .addReg(MI->getOperand(4).getReg());
4654
4655 // Reload the original control word now.
4656 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
4657
4658 delete MI; // The pseudo instruction is gone now.
4659 return BB;
4660 }
4661 }
4662}
4663
4664//===----------------------------------------------------------------------===//
4665// X86 Optimization Hooks
4666//===----------------------------------------------------------------------===//
4667
4668void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
4669 uint64_t Mask,
4670 uint64_t &KnownZero,
4671 uint64_t &KnownOne,
4672 const SelectionDAG &DAG,
4673 unsigned Depth) const {
4674 unsigned Opc = Op.getOpcode();
4675 assert((Opc >= ISD::BUILTIN_OP_END ||
4676 Opc == ISD::INTRINSIC_WO_CHAIN ||
4677 Opc == ISD::INTRINSIC_W_CHAIN ||
4678 Opc == ISD::INTRINSIC_VOID) &&
4679 "Should use MaskedValueIsZero if you don't know whether Op"
4680 " is a target node!");
4681
4682 KnownZero = KnownOne = 0; // Don't know anything.
4683 switch (Opc) {
4684 default: break;
4685 case X86ISD::SETCC:
4686 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
4687 break;
4688 }
4689}
4690
4691/// getShuffleScalarElt - Returns the scalar element that will make up the ith
4692/// element of the result of the vector shuffle.
4693static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
4694 MVT::ValueType VT = N->getValueType(0);
4695 SDOperand PermMask = N->getOperand(2);
4696 unsigned NumElems = PermMask.getNumOperands();
4697 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
4698 i %= NumElems;
4699 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4700 return (i == 0)
4701 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
4702 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
4703 SDOperand Idx = PermMask.getOperand(i);
4704 if (Idx.getOpcode() == ISD::UNDEF)
4705 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
4706 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
4707 }
4708 return SDOperand();
4709}
4710
4711/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
4712/// node is a GlobalAddress + an offset.
4713static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
4714 unsigned Opc = N->getOpcode();
4715 if (Opc == X86ISD::Wrapper) {
4716 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
4717 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
4718 return true;
4719 }
4720 } else if (Opc == ISD::ADD) {
4721 SDOperand N1 = N->getOperand(0);
4722 SDOperand N2 = N->getOperand(1);
4723 if (isGAPlusOffset(N1.Val, GA, Offset)) {
4724 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
4725 if (V) {
4726 Offset += V->getSignExtended();
4727 return true;
4728 }
4729 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
4730 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
4731 if (V) {
4732 Offset += V->getSignExtended();
4733 return true;
4734 }
4735 }
4736 }
4737 return false;
4738}
4739
4740/// isConsecutiveLoad - Returns true if N is loading from an address of Base
4741/// + Dist * Size.
4742static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
4743 MachineFrameInfo *MFI) {
4744 if (N->getOperand(0).Val != Base->getOperand(0).Val)
4745 return false;
4746
4747 SDOperand Loc = N->getOperand(1);
4748 SDOperand BaseLoc = Base->getOperand(1);
4749 if (Loc.getOpcode() == ISD::FrameIndex) {
4750 if (BaseLoc.getOpcode() != ISD::FrameIndex)
4751 return false;
Dan Gohman53491e92007-07-23 20:24:29 +00004752 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
4753 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004754 int FS = MFI->getObjectSize(FI);
4755 int BFS = MFI->getObjectSize(BFI);
4756 if (FS != BFS || FS != Size) return false;
4757 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
4758 } else {
4759 GlobalValue *GV1 = NULL;
4760 GlobalValue *GV2 = NULL;
4761 int64_t Offset1 = 0;
4762 int64_t Offset2 = 0;
4763 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
4764 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
4765 if (isGA1 && isGA2 && GV1 == GV2)
4766 return Offset1 == (Offset2 + Dist*Size);
4767 }
4768
4769 return false;
4770}
4771
4772static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
4773 const X86Subtarget *Subtarget) {
4774 GlobalValue *GV;
4775 int64_t Offset;
4776 if (isGAPlusOffset(Base, GV, Offset))
4777 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
4778 else {
4779 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
Dan Gohman53491e92007-07-23 20:24:29 +00004780 int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004781 if (BFI < 0)
4782 // Fixed objects do not specify alignment, however the offsets are known.
4783 return ((Subtarget->getStackAlignment() % 16) == 0 &&
4784 (MFI->getObjectOffset(BFI) % 16) == 0);
4785 else
4786 return MFI->getObjectAlignment(BFI) >= 16;
4787 }
4788 return false;
4789}
4790
4791
4792/// PerformShuffleCombine - Combine a vector_shuffle that is equal to
4793/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
4794/// if the load addresses are consecutive, non-overlapping, and in the right
4795/// order.
4796static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
4797 const X86Subtarget *Subtarget) {
4798 MachineFunction &MF = DAG.getMachineFunction();
4799 MachineFrameInfo *MFI = MF.getFrameInfo();
4800 MVT::ValueType VT = N->getValueType(0);
4801 MVT::ValueType EVT = MVT::getVectorElementType(VT);
4802 SDOperand PermMask = N->getOperand(2);
4803 int NumElems = (int)PermMask.getNumOperands();
4804 SDNode *Base = NULL;
4805 for (int i = 0; i < NumElems; ++i) {
4806 SDOperand Idx = PermMask.getOperand(i);
4807 if (Idx.getOpcode() == ISD::UNDEF) {
4808 if (!Base) return SDOperand();
4809 } else {
4810 SDOperand Arg =
4811 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
4812 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
4813 return SDOperand();
4814 if (!Base)
4815 Base = Arg.Val;
4816 else if (!isConsecutiveLoad(Arg.Val, Base,
4817 i, MVT::getSizeInBits(EVT)/8,MFI))
4818 return SDOperand();
4819 }
4820 }
4821
4822 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
Dan Gohman11821702007-07-27 17:16:43 +00004823 LoadSDNode *LD = cast<LoadSDNode>(Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004824 if (isAlign16) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004825 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
Dan Gohman11821702007-07-27 17:16:43 +00004826 LD->getSrcValueOffset(), LD->isVolatile());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004827 } else {
Dan Gohman11821702007-07-27 17:16:43 +00004828 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
4829 LD->getSrcValueOffset(), LD->isVolatile(),
4830 LD->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004831 }
4832}
4833
4834/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
4835static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
4836 const X86Subtarget *Subtarget) {
4837 SDOperand Cond = N->getOperand(0);
4838
4839 // If we have SSE[12] support, try to form min/max nodes.
4840 if (Subtarget->hasSSE2() &&
4841 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
4842 if (Cond.getOpcode() == ISD::SETCC) {
4843 // Get the LHS/RHS of the select.
4844 SDOperand LHS = N->getOperand(1);
4845 SDOperand RHS = N->getOperand(2);
4846 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
4847
4848 unsigned Opcode = 0;
4849 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
4850 switch (CC) {
4851 default: break;
4852 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
4853 case ISD::SETULE:
4854 case ISD::SETLE:
4855 if (!UnsafeFPMath) break;
4856 // FALL THROUGH.
4857 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
4858 case ISD::SETLT:
4859 Opcode = X86ISD::FMIN;
4860 break;
4861
4862 case ISD::SETOGT: // (X > Y) ? X : Y -> max
4863 case ISD::SETUGT:
4864 case ISD::SETGT:
4865 if (!UnsafeFPMath) break;
4866 // FALL THROUGH.
4867 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
4868 case ISD::SETGE:
4869 Opcode = X86ISD::FMAX;
4870 break;
4871 }
4872 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
4873 switch (CC) {
4874 default: break;
4875 case ISD::SETOGT: // (X > Y) ? Y : X -> min
4876 case ISD::SETUGT:
4877 case ISD::SETGT:
4878 if (!UnsafeFPMath) break;
4879 // FALL THROUGH.
4880 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
4881 case ISD::SETGE:
4882 Opcode = X86ISD::FMIN;
4883 break;
4884
4885 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
4886 case ISD::SETULE:
4887 case ISD::SETLE:
4888 if (!UnsafeFPMath) break;
4889 // FALL THROUGH.
4890 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
4891 case ISD::SETLT:
4892 Opcode = X86ISD::FMAX;
4893 break;
4894 }
4895 }
4896
4897 if (Opcode)
4898 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
4899 }
4900
4901 }
4902
4903 return SDOperand();
4904}
4905
4906
4907SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
4908 DAGCombinerInfo &DCI) const {
4909 SelectionDAG &DAG = DCI.DAG;
4910 switch (N->getOpcode()) {
4911 default: break;
4912 case ISD::VECTOR_SHUFFLE:
4913 return PerformShuffleCombine(N, DAG, Subtarget);
4914 case ISD::SELECT:
4915 return PerformSELECTCombine(N, DAG, Subtarget);
4916 }
4917
4918 return SDOperand();
4919}
4920
4921//===----------------------------------------------------------------------===//
4922// X86 Inline Assembly Support
4923//===----------------------------------------------------------------------===//
4924
4925/// getConstraintType - Given a constraint letter, return the type of
4926/// constraint it is for this target.
4927X86TargetLowering::ConstraintType
4928X86TargetLowering::getConstraintType(const std::string &Constraint) const {
4929 if (Constraint.size() == 1) {
4930 switch (Constraint[0]) {
4931 case 'A':
4932 case 'r':
4933 case 'R':
4934 case 'l':
4935 case 'q':
4936 case 'Q':
4937 case 'x':
4938 case 'Y':
4939 return C_RegisterClass;
4940 default:
4941 break;
4942 }
4943 }
4944 return TargetLowering::getConstraintType(Constraint);
4945}
4946
4947/// isOperandValidForConstraint - Return the specified operand (possibly
4948/// modified) if the specified SDOperand is valid for the specified target
4949/// constraint letter, otherwise return null.
4950SDOperand X86TargetLowering::
4951isOperandValidForConstraint(SDOperand Op, char Constraint, SelectionDAG &DAG) {
4952 switch (Constraint) {
4953 default: break;
4954 case 'I':
4955 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4956 if (C->getValue() <= 31)
4957 return DAG.getTargetConstant(C->getValue(), Op.getValueType());
4958 }
4959 return SDOperand(0,0);
4960 case 'N':
4961 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4962 if (C->getValue() <= 255)
4963 return DAG.getTargetConstant(C->getValue(), Op.getValueType());
4964 }
4965 return SDOperand(0,0);
4966 case 'i': {
4967 // Literal immediates are always ok.
4968 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op))
4969 return DAG.getTargetConstant(CST->getValue(), Op.getValueType());
4970
4971 // If we are in non-pic codegen mode, we allow the address of a global (with
4972 // an optional displacement) to be used with 'i'.
4973 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
4974 int64_t Offset = 0;
4975
4976 // Match either (GA) or (GA+C)
4977 if (GA) {
4978 Offset = GA->getOffset();
4979 } else if (Op.getOpcode() == ISD::ADD) {
4980 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4981 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
4982 if (C && GA) {
4983 Offset = GA->getOffset()+C->getValue();
4984 } else {
4985 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4986 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
4987 if (C && GA)
4988 Offset = GA->getOffset()+C->getValue();
4989 else
4990 C = 0, GA = 0;
4991 }
4992 }
4993
4994 if (GA) {
4995 // If addressing this global requires a load (e.g. in PIC mode), we can't
4996 // match.
4997 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
4998 false))
4999 return SDOperand(0, 0);
5000
5001 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5002 Offset);
5003 return Op;
5004 }
5005
5006 // Otherwise, not valid for this mode.
5007 return SDOperand(0, 0);
5008 }
5009 }
5010 return TargetLowering::isOperandValidForConstraint(Op, Constraint, DAG);
5011}
5012
5013std::vector<unsigned> X86TargetLowering::
5014getRegClassForInlineAsmConstraint(const std::string &Constraint,
5015 MVT::ValueType VT) const {
5016 if (Constraint.size() == 1) {
5017 // FIXME: not handling fp-stack yet!
5018 switch (Constraint[0]) { // GCC X86 Constraint Letters
5019 default: break; // Unknown constraint letter
5020 case 'A': // EAX/EDX
5021 if (VT == MVT::i32 || VT == MVT::i64)
5022 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
5023 break;
5024 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
5025 case 'Q': // Q_REGS
5026 if (VT == MVT::i32)
5027 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
5028 else if (VT == MVT::i16)
5029 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
5030 else if (VT == MVT::i8)
5031 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::DL, 0);
5032 break;
5033 }
5034 }
5035
5036 return std::vector<unsigned>();
5037}
5038
5039std::pair<unsigned, const TargetRegisterClass*>
5040X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
5041 MVT::ValueType VT) const {
5042 // First, see if this is a constraint that directly corresponds to an LLVM
5043 // register class.
5044 if (Constraint.size() == 1) {
5045 // GCC Constraint Letters
5046 switch (Constraint[0]) {
5047 default: break;
5048 case 'r': // GENERAL_REGS
5049 case 'R': // LEGACY_REGS
5050 case 'l': // INDEX_REGS
5051 if (VT == MVT::i64 && Subtarget->is64Bit())
5052 return std::make_pair(0U, X86::GR64RegisterClass);
5053 if (VT == MVT::i32)
5054 return std::make_pair(0U, X86::GR32RegisterClass);
5055 else if (VT == MVT::i16)
5056 return std::make_pair(0U, X86::GR16RegisterClass);
5057 else if (VT == MVT::i8)
5058 return std::make_pair(0U, X86::GR8RegisterClass);
5059 break;
5060 case 'y': // MMX_REGS if MMX allowed.
5061 if (!Subtarget->hasMMX()) break;
5062 return std::make_pair(0U, X86::VR64RegisterClass);
5063 break;
5064 case 'Y': // SSE_REGS if SSE2 allowed
5065 if (!Subtarget->hasSSE2()) break;
5066 // FALL THROUGH.
5067 case 'x': // SSE_REGS if SSE1 allowed
5068 if (!Subtarget->hasSSE1()) break;
5069
5070 switch (VT) {
5071 default: break;
5072 // Scalar SSE types.
5073 case MVT::f32:
5074 case MVT::i32:
5075 return std::make_pair(0U, X86::FR32RegisterClass);
5076 case MVT::f64:
5077 case MVT::i64:
5078 return std::make_pair(0U, X86::FR64RegisterClass);
5079 // Vector types.
5080 case MVT::v16i8:
5081 case MVT::v8i16:
5082 case MVT::v4i32:
5083 case MVT::v2i64:
5084 case MVT::v4f32:
5085 case MVT::v2f64:
5086 return std::make_pair(0U, X86::VR128RegisterClass);
5087 }
5088 break;
5089 }
5090 }
5091
5092 // Use the default implementation in TargetLowering to convert the register
5093 // constraint into a member of a register class.
5094 std::pair<unsigned, const TargetRegisterClass*> Res;
5095 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
5096
5097 // Not found as a standard register?
5098 if (Res.second == 0) {
5099 // GCC calls "st(0)" just plain "st".
5100 if (StringsEqualNoCase("{st}", Constraint)) {
5101 Res.first = X86::ST0;
5102 Res.second = X86::RSTRegisterClass;
5103 }
5104
5105 return Res;
5106 }
5107
5108 // Otherwise, check to see if this is a register class of the wrong value
5109 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
5110 // turn into {ax},{dx}.
5111 if (Res.second->hasType(VT))
5112 return Res; // Correct type already, nothing to do.
5113
5114 // All of the single-register GCC register classes map their values onto
5115 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
5116 // really want an 8-bit or 32-bit register, map to the appropriate register
5117 // class and return the appropriate register.
5118 if (Res.second != X86::GR16RegisterClass)
5119 return Res;
5120
5121 if (VT == MVT::i8) {
5122 unsigned DestReg = 0;
5123 switch (Res.first) {
5124 default: break;
5125 case X86::AX: DestReg = X86::AL; break;
5126 case X86::DX: DestReg = X86::DL; break;
5127 case X86::CX: DestReg = X86::CL; break;
5128 case X86::BX: DestReg = X86::BL; break;
5129 }
5130 if (DestReg) {
5131 Res.first = DestReg;
5132 Res.second = Res.second = X86::GR8RegisterClass;
5133 }
5134 } else if (VT == MVT::i32) {
5135 unsigned DestReg = 0;
5136 switch (Res.first) {
5137 default: break;
5138 case X86::AX: DestReg = X86::EAX; break;
5139 case X86::DX: DestReg = X86::EDX; break;
5140 case X86::CX: DestReg = X86::ECX; break;
5141 case X86::BX: DestReg = X86::EBX; break;
5142 case X86::SI: DestReg = X86::ESI; break;
5143 case X86::DI: DestReg = X86::EDI; break;
5144 case X86::BP: DestReg = X86::EBP; break;
5145 case X86::SP: DestReg = X86::ESP; break;
5146 }
5147 if (DestReg) {
5148 Res.first = DestReg;
5149 Res.second = Res.second = X86::GR32RegisterClass;
5150 }
5151 } else if (VT == MVT::i64) {
5152 unsigned DestReg = 0;
5153 switch (Res.first) {
5154 default: break;
5155 case X86::AX: DestReg = X86::RAX; break;
5156 case X86::DX: DestReg = X86::RDX; break;
5157 case X86::CX: DestReg = X86::RCX; break;
5158 case X86::BX: DestReg = X86::RBX; break;
5159 case X86::SI: DestReg = X86::RSI; break;
5160 case X86::DI: DestReg = X86::RDI; break;
5161 case X86::BP: DestReg = X86::RBP; break;
5162 case X86::SP: DestReg = X86::RSP; break;
5163 }
5164 if (DestReg) {
5165 Res.first = DestReg;
5166 Res.second = Res.second = X86::GR64RegisterClass;
5167 }
5168 }
5169
5170 return Res;
5171}