1 //===-- X86isellowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/VectorExtras.h"
27 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/SSARegMap.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ParameterAttributes.h"
42 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
43 : TargetLowering(TM) {
44 Subtarget = &TM.getSubtarget<X86Subtarget>();
45 X86ScalarSSEf64 = Subtarget->hasSSE2();
46 X86ScalarSSEf32 = Subtarget->hasSSE1();
47 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
50 RegInfo = TM.getRegisterInfo();
52 // Set up the TargetLowering object.
54 // X86 is weird, it always uses i8 for shift amounts and setcc results.
55 setShiftAmountType(MVT::i8);
56 setSetCCResultType(MVT::i8);
57 setSetCCResultContents(ZeroOrOneSetCCResult);
58 setSchedulingPreference(SchedulingForRegPressure);
59 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
60 setStackPointerRegisterToSaveRestore(X86StackPtr);
62 if (Subtarget->isTargetDarwin()) {
63 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
64 setUseUnderscoreSetJmp(false);
65 setUseUnderscoreLongJmp(false);
66 } else if (Subtarget->isTargetMingw()) {
67 // MS runtime is weird: it exports _setjmp, but longjmp!
68 setUseUnderscoreSetJmp(true);
69 setUseUnderscoreLongJmp(false);
71 setUseUnderscoreSetJmp(true);
72 setUseUnderscoreLongJmp(true);
75 // Set up the register classes.
76 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
77 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
78 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
79 if (Subtarget->is64Bit())
80 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
82 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
84 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
86 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
87 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
88 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
90 if (Subtarget->is64Bit()) {
91 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
92 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
95 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
96 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
98 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
101 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
103 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
104 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
105 // SSE has no i16 to fp conversion, only i32
106 if (X86ScalarSSEf32) {
107 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
108 // f32 and f64 cases are Legal, f80 case is not
109 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
111 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
112 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
115 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
116 // are Legal, f80 is custom lowered.
117 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
118 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
120 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
122 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
123 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
125 if (X86ScalarSSEf32) {
126 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
127 // f32 and f64 cases are Legal, f80 case is not
128 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
130 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
131 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
134 // Handle FP_TO_UINT by promoting the destination to a larger signed
136 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
137 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
138 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
140 if (Subtarget->is64Bit()) {
141 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
142 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
144 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
145 // Expand FP_TO_UINT into a select.
146 // FIXME: We would like to use a Custom expander here eventually to do
147 // the optimal thing for SSE vs. the default expansion in the legalizer.
148 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
150 // With SSE3 we can use fisttpll to convert to a signed i64.
151 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
154 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
155 if (!X86ScalarSSEf64) {
156 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
157 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
160 // Scalar integer multiply, multiply-high, divide, and remainder are
161 // lowered to use operations that produce two results, to match the
162 // available instructions. This exposes the two-result form to trivial
163 // CSE, which is able to combine x/y and x%y into a single instruction,
164 // for example. The single-result multiply instructions are introduced
165 // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
167 setOperationAction(ISD::MUL , MVT::i8 , Expand);
168 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
169 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
170 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
171 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
172 setOperationAction(ISD::SREM , MVT::i8 , Expand);
173 setOperationAction(ISD::UREM , MVT::i8 , Expand);
174 setOperationAction(ISD::MUL , MVT::i16 , Expand);
175 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
176 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
177 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
178 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
179 setOperationAction(ISD::SREM , MVT::i16 , Expand);
180 setOperationAction(ISD::UREM , MVT::i16 , Expand);
181 setOperationAction(ISD::MUL , MVT::i32 , Expand);
182 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
183 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
184 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
185 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
186 setOperationAction(ISD::SREM , MVT::i32 , Expand);
187 setOperationAction(ISD::UREM , MVT::i32 , Expand);
188 setOperationAction(ISD::MUL , MVT::i64 , Expand);
189 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
190 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
191 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
192 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
193 setOperationAction(ISD::SREM , MVT::i64 , Expand);
194 setOperationAction(ISD::UREM , MVT::i64 , Expand);
196 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
197 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
198 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
199 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
200 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
201 if (Subtarget->is64Bit())
202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
206 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
207 setOperationAction(ISD::FREM , MVT::f64 , Expand);
209 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i8 , Expand);
211 setOperationAction(ISD::CTLZ , MVT::i8 , Expand);
212 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
213 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
214 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
215 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
216 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
217 setOperationAction(ISD::CTLZ , MVT::i32 , Expand);
218 if (Subtarget->is64Bit()) {
219 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
220 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
221 setOperationAction(ISD::CTLZ , MVT::i64 , Expand);
224 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
225 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
227 // These should be promoted to a larger select which is supported.
228 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
229 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
230 // X86 wants to expand cmov itself.
231 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
232 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
233 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
234 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
235 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
236 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
237 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
238 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
239 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
240 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
241 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
242 if (Subtarget->is64Bit()) {
243 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
244 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
246 // X86 ret instruction may pop stack.
247 setOperationAction(ISD::RET , MVT::Other, Custom);
248 if (!Subtarget->is64Bit())
249 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
252 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
253 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
254 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
255 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
256 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
257 if (Subtarget->is64Bit()) {
258 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
259 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
260 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
261 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
263 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
264 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
265 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
266 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
267 // X86 wants to expand memset / memcpy itself.
268 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
269 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
271 // Use the default ISD::LOCATION expansion.
272 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
273 // FIXME - use subtarget debug flags
274 if (!Subtarget->isTargetDarwin() &&
275 !Subtarget->isTargetELF() &&
276 !Subtarget->isTargetCygMing())
277 setOperationAction(ISD::LABEL, MVT::Other, Expand);
279 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
280 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
281 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
282 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
283 if (Subtarget->is64Bit()) {
285 setExceptionPointerRegister(X86::RAX);
286 setExceptionSelectorRegister(X86::RDX);
288 setExceptionPointerRegister(X86::EAX);
289 setExceptionSelectorRegister(X86::EDX);
291 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
293 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
295 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
296 setOperationAction(ISD::VASTART , MVT::Other, Custom);
297 setOperationAction(ISD::VAARG , MVT::Other, Expand);
298 setOperationAction(ISD::VAEND , MVT::Other, Expand);
299 if (Subtarget->is64Bit())
300 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
302 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
304 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
305 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
306 if (Subtarget->is64Bit())
307 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
308 if (Subtarget->isTargetCygMing())
309 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
311 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
313 if (X86ScalarSSEf64) {
314 // f32 and f64 use SSE.
315 // Set up the FP register classes.
316 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
317 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
319 // Use ANDPD to simulate FABS.
320 setOperationAction(ISD::FABS , MVT::f64, Custom);
321 setOperationAction(ISD::FABS , MVT::f32, Custom);
323 // Use XORP to simulate FNEG.
324 setOperationAction(ISD::FNEG , MVT::f64, Custom);
325 setOperationAction(ISD::FNEG , MVT::f32, Custom);
327 // Use ANDPD and ORPD to simulate FCOPYSIGN.
328 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
329 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
331 // We don't support sin/cos/fmod
332 setOperationAction(ISD::FSIN , MVT::f64, Expand);
333 setOperationAction(ISD::FCOS , MVT::f64, Expand);
334 setOperationAction(ISD::FREM , MVT::f64, Expand);
335 setOperationAction(ISD::FSIN , MVT::f32, Expand);
336 setOperationAction(ISD::FCOS , MVT::f32, Expand);
337 setOperationAction(ISD::FREM , MVT::f32, Expand);
339 // Expand FP immediates into loads from the stack, except for the special
341 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
342 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
343 addLegalFPImmediate(APFloat(+0.0)); // xorpd
344 addLegalFPImmediate(APFloat(+0.0f)); // xorps
346 // Conversions to long double (in X87) go through memory.
347 setConvertAction(MVT::f32, MVT::f80, Expand);
348 setConvertAction(MVT::f64, MVT::f80, Expand);
350 // Conversions from long double (in X87) go through memory.
351 setConvertAction(MVT::f80, MVT::f32, Expand);
352 setConvertAction(MVT::f80, MVT::f64, Expand);
353 } else if (X86ScalarSSEf32) {
354 // Use SSE for f32, x87 for f64.
355 // Set up the FP register classes.
356 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
357 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
359 // Use ANDPS to simulate FABS.
360 setOperationAction(ISD::FABS , MVT::f32, Custom);
362 // Use XORP to simulate FNEG.
363 setOperationAction(ISD::FNEG , MVT::f32, Custom);
365 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
367 // Use ANDPS and ORPS to simulate FCOPYSIGN.
368 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
369 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
371 // We don't support sin/cos/fmod
372 setOperationAction(ISD::FSIN , MVT::f32, Expand);
373 setOperationAction(ISD::FCOS , MVT::f32, Expand);
374 setOperationAction(ISD::FREM , MVT::f32, Expand);
376 // Expand FP immediates into loads from the stack, except for the special
378 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
379 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
380 addLegalFPImmediate(APFloat(+0.0f)); // xorps
381 addLegalFPImmediate(APFloat(+0.0)); // FLD0
382 addLegalFPImmediate(APFloat(+1.0)); // FLD1
383 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
384 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
386 // SSE->x87 conversions go through memory.
387 setConvertAction(MVT::f32, MVT::f64, Expand);
388 setConvertAction(MVT::f32, MVT::f80, Expand);
390 // x87->SSE truncations need to go through memory.
391 setConvertAction(MVT::f80, MVT::f32, Expand);
392 setConvertAction(MVT::f64, MVT::f32, Expand);
393 // And x87->x87 truncations also.
394 setConvertAction(MVT::f80, MVT::f64, Expand);
397 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
398 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
401 // f32 and f64 in x87.
402 // Set up the FP register classes.
403 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
404 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
406 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
407 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
408 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
409 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
411 // Floating truncations need to go through memory.
412 setConvertAction(MVT::f80, MVT::f32, Expand);
413 setConvertAction(MVT::f64, MVT::f32, Expand);
414 setConvertAction(MVT::f80, MVT::f64, Expand);
417 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
418 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
421 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
422 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
423 addLegalFPImmediate(APFloat(+0.0)); // FLD0
424 addLegalFPImmediate(APFloat(+1.0)); // FLD1
425 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
426 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
427 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
428 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
429 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
430 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
433 // Long double always uses X87.
434 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
435 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
436 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
437 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
439 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
440 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
443 // Always use a library call for pow.
444 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
445 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
446 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
448 // First set operation action for all vector types to expand. Then we
449 // will selectively turn on ones that can be effectively codegen'd.
450 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
451 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
452 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
453 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
454 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
455 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
456 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
457 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
458 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
459 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
460 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
461 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
462 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
463 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
464 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
465 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
466 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
467 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
468 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
469 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
470 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
471 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
472 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
473 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
474 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
475 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
476 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
477 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
478 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
479 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
480 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
481 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
482 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
485 if (Subtarget->hasMMX()) {
486 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
487 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
488 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
489 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
491 // FIXME: add MMX packed arithmetics
493 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
494 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
495 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
496 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
498 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
499 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
500 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
502 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
503 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
505 setOperationAction(ISD::AND, MVT::v8i8, Promote);
506 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
507 setOperationAction(ISD::AND, MVT::v4i16, Promote);
508 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
509 setOperationAction(ISD::AND, MVT::v2i32, Promote);
510 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
511 setOperationAction(ISD::AND, MVT::v1i64, Legal);
513 setOperationAction(ISD::OR, MVT::v8i8, Promote);
514 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
515 setOperationAction(ISD::OR, MVT::v4i16, Promote);
516 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
517 setOperationAction(ISD::OR, MVT::v2i32, Promote);
518 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
519 setOperationAction(ISD::OR, MVT::v1i64, Legal);
521 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
522 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
523 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
524 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
525 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
526 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
527 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
529 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
530 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
531 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
532 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
533 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
534 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
535 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
537 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
538 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
539 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
540 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
542 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
543 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
544 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
545 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
547 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
548 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
549 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
550 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
553 if (Subtarget->hasSSE1()) {
554 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
556 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
557 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
558 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
559 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
560 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
561 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
562 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
563 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
564 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
565 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
566 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
569 if (Subtarget->hasSSE2()) {
570 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
571 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
572 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
573 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
574 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
576 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
577 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
578 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
579 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
580 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
581 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
582 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
583 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
584 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
585 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
586 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
587 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
588 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
589 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
590 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
592 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
593 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
594 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
595 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
596 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
597 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
599 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
600 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
601 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
602 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
603 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
605 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
606 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
607 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
608 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
609 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
610 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
612 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
613 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
614 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
615 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
616 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
617 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
618 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
619 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
620 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
621 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
622 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
623 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
626 // Custom lower v2i64 and v2f64 selects.
627 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
628 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
629 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
630 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
633 // We want to custom lower some of our intrinsics.
634 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
636 // We have target-specific dag combine patterns for the following nodes:
637 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
638 setTargetDAGCombine(ISD::SELECT);
640 computeRegisterProperties();
642 // FIXME: These should be based on subtarget info. Plus, the values should
643 // be smaller when we are in optimizing for size mode.
644 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
645 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
646 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
647 allowUnalignedMemoryAccesses = true; // x86 supports it!
651 //===----------------------------------------------------------------------===//
652 // Return Value Calling Convention Implementation
653 //===----------------------------------------------------------------------===//
655 #include "X86GenCallingConv.inc"
657 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
658 /// exists skip possible ISD:TokenFactor.
659 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
660 if (Chain.getOpcode()==X86ISD::TAILCALL) {
662 } else if (Chain.getOpcode()==ISD::TokenFactor) {
663 if (Chain.getNumOperands() &&
664 Chain.getOperand(0).getOpcode()==X86ISD::TAILCALL)
665 return Chain.getOperand(0);
670 /// LowerRET - Lower an ISD::RET node.
671 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
672 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
674 SmallVector<CCValAssign, 16> RVLocs;
675 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
676 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
677 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
678 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
680 // If this is the first return lowered for this function, add the regs to the
681 // liveout set for the function.
682 if (DAG.getMachineFunction().liveout_empty()) {
683 for (unsigned i = 0; i != RVLocs.size(); ++i)
684 if (RVLocs[i].isRegLoc())
685 DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
687 SDOperand Chain = Op.getOperand(0);
689 // Handle tail call return.
690 Chain = GetPossiblePreceedingTailCall(Chain);
691 if (Chain.getOpcode() == X86ISD::TAILCALL) {
692 SDOperand TailCall = Chain;
693 SDOperand TargetAddress = TailCall.getOperand(1);
694 SDOperand StackAdjustment = TailCall.getOperand(2);
695 assert ( ((TargetAddress.getOpcode() == ISD::Register &&
696 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
697 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
698 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
699 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
700 "Expecting an global address, external symbol, or register");
701 assert( StackAdjustment.getOpcode() == ISD::Constant &&
702 "Expecting a const value");
704 SmallVector<SDOperand,8> Operands;
705 Operands.push_back(Chain.getOperand(0));
706 Operands.push_back(TargetAddress);
707 Operands.push_back(StackAdjustment);
708 // Copy registers used by the call. Last operand is a flag so it is not
710 for(unsigned i=3; i < TailCall.getNumOperands()-1;i++) {
711 Operands.push_back(Chain.getOperand(i));
713 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0], Operands.size());
719 // Copy the result values into the output registers.
720 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
721 RVLocs[0].getLocReg() != X86::ST0) {
722 for (unsigned i = 0; i != RVLocs.size(); ++i) {
723 CCValAssign &VA = RVLocs[i];
724 assert(VA.isRegLoc() && "Can only return in registers!");
725 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
727 Flag = Chain.getValue(1);
730 // We need to handle a destination of ST0 specially, because it isn't really
732 SDOperand Value = Op.getOperand(1);
734 // If this is an FP return with ScalarSSE, we need to move the value from
735 // an XMM register onto the fp-stack.
736 if ((X86ScalarSSEf32 && RVLocs[0].getValVT()==MVT::f32) ||
737 (X86ScalarSSEf64 && RVLocs[0].getValVT()==MVT::f64)) {
740 // If this is a load into a scalarsse value, don't store the loaded value
741 // back to the stack, only to reload it: just replace the scalar-sse load.
742 if (ISD::isNON_EXTLoad(Value.Val) &&
743 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
744 Chain = Value.getOperand(0);
745 MemLoc = Value.getOperand(1);
747 // Spill the value to memory and reload it into top of stack.
748 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
749 MachineFunction &MF = DAG.getMachineFunction();
750 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
751 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
752 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
754 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
755 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
756 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
757 Chain = Value.getValue(1);
760 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
761 SDOperand Ops[] = { Chain, Value };
762 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
763 Flag = Chain.getValue(1);
766 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
768 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
770 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
774 /// LowerCallResult - Lower the result values of an ISD::CALL into the
775 /// appropriate copies out of appropriate physical registers. This assumes that
776 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
777 /// being lowered. The returns a SDNode with the same number of values as the
779 SDNode *X86TargetLowering::
780 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
781 unsigned CallingConv, SelectionDAG &DAG) {
783 // Assign locations to each value returned by this call.
784 SmallVector<CCValAssign, 16> RVLocs;
785 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
786 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
787 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
790 SmallVector<SDOperand, 8> ResultVals;
792 // Copy all of the result registers out of their specified physreg.
793 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
794 for (unsigned i = 0; i != RVLocs.size(); ++i) {
795 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
796 RVLocs[i].getValVT(), InFlag).getValue(1);
797 InFlag = Chain.getValue(2);
798 ResultVals.push_back(Chain.getValue(0));
801 // Copies from the FP stack are special, as ST0 isn't a valid register
802 // before the fp stackifier runs.
804 // Copy ST0 into an RFP register with FP_GET_RESULT.
805 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
806 SDOperand GROps[] = { Chain, InFlag };
807 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
808 Chain = RetVal.getValue(1);
809 InFlag = RetVal.getValue(2);
811 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
813 if ((X86ScalarSSEf32 && RVLocs[0].getValVT() == MVT::f32) ||
814 (X86ScalarSSEf64 && RVLocs[0].getValVT() == MVT::f64)) {
815 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
816 // shouldn't be necessary except that RFP cannot be live across
817 // multiple blocks. When stackifier is fixed, they can be uncoupled.
818 MachineFunction &MF = DAG.getMachineFunction();
819 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
820 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
822 Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
824 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
825 RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
826 Chain = RetVal.getValue(1);
828 ResultVals.push_back(RetVal);
831 // Merge everything together with a MERGE_VALUES node.
832 ResultVals.push_back(Chain);
833 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
834 &ResultVals[0], ResultVals.size()).Val;
838 //===----------------------------------------------------------------------===//
839 // C & StdCall & Fast Calling Convention implementation
840 //===----------------------------------------------------------------------===//
841 // StdCall calling convention seems to be standard for many Windows' API
842 // routines and around. It differs from C calling convention just a little:
843 // callee should clean up the stack, not caller. Symbols should be also
844 // decorated in some fancy way :) It doesn't support any vector arguments.
845 // For info on fast calling convention see Fast Calling Convention (tail call)
846 // implementation LowerX86_32FastCCCallTo.
848 /// AddLiveIn - This helper function adds the specified physical register to the
849 /// MachineFunction as a live in value. It also creates a corresponding virtual
851 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
852 const TargetRegisterClass *RC) {
853 assert(RC->contains(PReg) && "Not the correct regclass!");
854 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
855 MF.addLiveIn(PReg, VReg);
859 // align stack arguments according to platform alignment needed for tail calls
860 unsigned GetAlignedArgumentStackSize(unsigned StackSize, SelectionDAG& DAG);
862 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
863 const CCValAssign &VA,
864 MachineFrameInfo *MFI,
865 SDOperand Root, unsigned i) {
866 // Create the nodes corresponding to a load from this parameter slot.
867 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
868 VA.getLocMemOffset());
869 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
871 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
873 if (Flags & ISD::ParamFlags::ByVal)
876 return DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0);
879 SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
881 unsigned NumArgs = Op.Val->getNumValues() - 1;
882 MachineFunction &MF = DAG.getMachineFunction();
883 MachineFrameInfo *MFI = MF.getFrameInfo();
884 SDOperand Root = Op.getOperand(0);
885 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
886 unsigned CC = MF.getFunction()->getCallingConv();
887 // Assign locations to all of the incoming arguments.
888 SmallVector<CCValAssign, 16> ArgLocs;
889 CCState CCInfo(CC, isVarArg,
890 getTargetMachine(), ArgLocs);
891 // Check for possible tail call calling convention.
892 if (CC == CallingConv::Fast && PerformTailCallOpt)
893 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_TailCall);
895 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
897 SmallVector<SDOperand, 8> ArgValues;
898 unsigned LastVal = ~0U;
899 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
900 CCValAssign &VA = ArgLocs[i];
901 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
903 assert(VA.getValNo() != LastVal &&
904 "Don't support value assigned to multiple locs yet");
905 LastVal = VA.getValNo();
908 MVT::ValueType RegVT = VA.getLocVT();
909 TargetRegisterClass *RC;
910 if (RegVT == MVT::i32)
911 RC = X86::GR32RegisterClass;
913 assert(MVT::isVector(RegVT));
914 RC = X86::VR128RegisterClass;
917 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
918 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
920 // If this is an 8 or 16-bit value, it is really passed promoted to 32
921 // bits. Insert an assert[sz]ext to capture this, then truncate to the
923 if (VA.getLocInfo() == CCValAssign::SExt)
924 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
925 DAG.getValueType(VA.getValVT()));
926 else if (VA.getLocInfo() == CCValAssign::ZExt)
927 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
928 DAG.getValueType(VA.getValVT()));
930 if (VA.getLocInfo() != CCValAssign::Full)
931 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
933 ArgValues.push_back(ArgValue);
935 assert(VA.isMemLoc());
936 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
940 unsigned StackSize = CCInfo.getNextStackOffset();
941 // align stack specially for tail calls
942 if (CC==CallingConv::Fast)
943 StackSize = GetAlignedArgumentStackSize(StackSize,DAG);
945 ArgValues.push_back(Root);
947 // If the function takes variable number of arguments, make a frame index for
948 // the start of the first vararg value... for expansion of llvm.va_start.
950 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
952 // Tail call calling convention (CallingConv::Fast) does not support varargs.
953 assert( !(isVarArg && CC == CallingConv::Fast) &&
954 "CallingConv::Fast does not support varargs.");
956 if (isStdCall && !isVarArg &&
957 (CC==CallingConv::Fast && PerformTailCallOpt || CC!=CallingConv::Fast)) {
958 BytesToPopOnReturn = StackSize; // Callee pops everything..
959 BytesCallerReserves = 0;
961 BytesToPopOnReturn = 0; // Callee pops nothing.
963 // If this is an sret function, the return should pop the hidden pointer.
965 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
966 ISD::ParamFlags::StructReturn))
967 BytesToPopOnReturn = 4;
969 BytesCallerReserves = StackSize;
972 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
974 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
975 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
977 // Return the new list of results.
978 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
979 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
982 SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
984 SDOperand Chain = Op.getOperand(0);
985 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
986 SDOperand Callee = Op.getOperand(4);
987 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
989 // Analyze operands of the call, assigning locations to each operand.
990 SmallVector<CCValAssign, 16> ArgLocs;
991 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
992 if(CC==CallingConv::Fast && PerformTailCallOpt)
993 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
995 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
997 // Get a count of how many bytes are to be pushed on the stack.
998 unsigned NumBytes = CCInfo.getNextStackOffset();
999 if (CC==CallingConv::Fast)
1000 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1002 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1004 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1005 SmallVector<SDOperand, 8> MemOpChains;
1009 // Walk the register/memloc assignments, inserting copies/loads.
1010 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1011 CCValAssign &VA = ArgLocs[i];
1012 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1014 // Promote the value if needed.
1015 switch (VA.getLocInfo()) {
1016 default: assert(0 && "Unknown loc info!");
1017 case CCValAssign::Full: break;
1018 case CCValAssign::SExt:
1019 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1021 case CCValAssign::ZExt:
1022 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1024 case CCValAssign::AExt:
1025 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1029 if (VA.isRegLoc()) {
1030 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1032 assert(VA.isMemLoc());
1033 if (StackPtr.Val == 0)
1034 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1036 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1041 // If the first argument is an sret pointer, remember it.
1042 bool isSRet = NumOps &&
1043 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
1044 ISD::ParamFlags::StructReturn);
1046 if (!MemOpChains.empty())
1047 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1048 &MemOpChains[0], MemOpChains.size());
1050 // Build a sequence of copy-to-reg nodes chained together with token chain
1051 // and flag operands which copy the outgoing args into registers.
1053 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1054 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1056 InFlag = Chain.getValue(1);
1059 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1061 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1062 Subtarget->isPICStyleGOT()) {
1063 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1064 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1066 InFlag = Chain.getValue(1);
1069 // If the callee is a GlobalAddress node (quite common, every direct call is)
1070 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1071 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1072 // We should use extra load for direct calls to dllimported functions in
1074 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1075 getTargetMachine(), true))
1076 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1077 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1078 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1080 // Returns a chain & a flag for retval copy to use.
1081 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1082 SmallVector<SDOperand, 8> Ops;
1083 Ops.push_back(Chain);
1084 Ops.push_back(Callee);
1086 // Add argument registers to the end of the list so that they are known live
1088 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1089 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1090 RegsToPass[i].second.getValueType()));
1092 // Add an implicit use GOT pointer in EBX.
1093 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1094 Subtarget->isPICStyleGOT())
1095 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1098 Ops.push_back(InFlag);
1100 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1101 InFlag = Chain.getValue(1);
1103 // Create the CALLSEQ_END node.
1104 unsigned NumBytesForCalleeToPush = 0;
1106 if (CC == CallingConv::X86_StdCall ||
1107 (CC == CallingConv::Fast && PerformTailCallOpt)) {
1109 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1111 NumBytesForCalleeToPush = NumBytes;
1112 assert(!(isVarArg && CC==CallingConv::Fast) &&
1113 "CallingConv::Fast does not support varargs.");
1115 // If this is is a call to a struct-return function, the callee
1116 // pops the hidden struct pointer, so we have to push it back.
1117 // This is common for Darwin/X86, Linux & Mingw32 targets.
1118 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1121 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1123 Ops.push_back(Chain);
1124 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1125 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
1126 Ops.push_back(InFlag);
1127 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1128 InFlag = Chain.getValue(1);
1130 // Handle result values, copying them out of physregs into vregs that we
1132 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1136 //===----------------------------------------------------------------------===//
1137 // FastCall Calling Convention implementation
1138 //===----------------------------------------------------------------------===//
1140 // The X86 'fastcall' calling convention passes up to two integer arguments in
1141 // registers (an appropriate portion of ECX/EDX), passes arguments in C order,
1142 // and requires that the callee pop its arguments off the stack (allowing proper
1143 // tail calls), and has the same return value conventions as C calling convs.
1145 // This calling convention always arranges for the callee pop value to be 8n+4
1146 // bytes, which is needed for tail recursion elimination and stack alignment
1149 X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
1150 MachineFunction &MF = DAG.getMachineFunction();
1151 MachineFrameInfo *MFI = MF.getFrameInfo();
1152 SDOperand Root = Op.getOperand(0);
1153 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1155 // Assign locations to all of the incoming arguments.
1156 SmallVector<CCValAssign, 16> ArgLocs;
1157 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
1158 getTargetMachine(), ArgLocs);
1159 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
1161 SmallVector<SDOperand, 8> ArgValues;
1162 unsigned LastVal = ~0U;
1163 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1164 CCValAssign &VA = ArgLocs[i];
1165 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1167 assert(VA.getValNo() != LastVal &&
1168 "Don't support value assigned to multiple locs yet");
1169 LastVal = VA.getValNo();
1171 if (VA.isRegLoc()) {
1172 MVT::ValueType RegVT = VA.getLocVT();
1173 TargetRegisterClass *RC;
1174 if (RegVT == MVT::i32)
1175 RC = X86::GR32RegisterClass;
1177 assert(MVT::isVector(RegVT));
1178 RC = X86::VR128RegisterClass;
1181 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1182 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1184 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1185 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1187 if (VA.getLocInfo() == CCValAssign::SExt)
1188 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1189 DAG.getValueType(VA.getValVT()));
1190 else if (VA.getLocInfo() == CCValAssign::ZExt)
1191 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1192 DAG.getValueType(VA.getValVT()));
1194 if (VA.getLocInfo() != CCValAssign::Full)
1195 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1197 ArgValues.push_back(ArgValue);
1199 assert(VA.isMemLoc());
1200 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1204 ArgValues.push_back(Root);
1206 unsigned StackSize = CCInfo.getNextStackOffset();
1208 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1209 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1210 // arguments and the arguments after the retaddr has been pushed are
1212 if ((StackSize & 7) == 0)
1216 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1217 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
1218 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
1219 BytesCallerReserves = 0;
1221 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1222 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1224 // Return the new list of results.
1225 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1226 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1230 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1231 const SDOperand &StackPtr,
1232 const CCValAssign &VA,
1235 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1236 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1237 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1238 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1239 if (Flags & ISD::ParamFlags::ByVal) {
1240 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1241 ISD::ParamFlags::ByValAlignOffs);
1243 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1244 ISD::ParamFlags::ByValSizeOffs;
1246 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1247 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1249 return DAG.getNode(ISD::MEMCPY, MVT::Other, Chain, PtrOff, Arg, SizeNode,
1252 return DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1256 SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1258 SDOperand Chain = Op.getOperand(0);
1259 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1260 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1261 SDOperand Callee = Op.getOperand(4);
1263 // Analyze operands of the call, assigning locations to each operand.
1264 SmallVector<CCValAssign, 16> ArgLocs;
1265 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1266 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1268 // Get a count of how many bytes are to be pushed on the stack.
1269 unsigned NumBytes = CCInfo.getNextStackOffset();
1271 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1272 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1273 // arguments and the arguments after the retaddr has been pushed are
1275 if ((NumBytes & 7) == 0)
1279 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1281 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1282 SmallVector<SDOperand, 8> MemOpChains;
1286 // Walk the register/memloc assignments, inserting copies/loads.
1287 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1288 CCValAssign &VA = ArgLocs[i];
1289 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1291 // Promote the value if needed.
1292 switch (VA.getLocInfo()) {
1293 default: assert(0 && "Unknown loc info!");
1294 case CCValAssign::Full: break;
1295 case CCValAssign::SExt:
1296 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1298 case CCValAssign::ZExt:
1299 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1301 case CCValAssign::AExt:
1302 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1306 if (VA.isRegLoc()) {
1307 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1309 assert(VA.isMemLoc());
1310 if (StackPtr.Val == 0)
1311 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1313 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1318 if (!MemOpChains.empty())
1319 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1320 &MemOpChains[0], MemOpChains.size());
1322 // Build a sequence of copy-to-reg nodes chained together with token chain
1323 // and flag operands which copy the outgoing args into registers.
1325 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1326 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1328 InFlag = Chain.getValue(1);
1331 // If the callee is a GlobalAddress node (quite common, every direct call is)
1332 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1333 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1334 // We should use extra load for direct calls to dllimported functions in
1336 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1337 getTargetMachine(), true))
1338 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1339 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1340 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1342 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1344 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1345 Subtarget->isPICStyleGOT()) {
1346 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1347 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1349 InFlag = Chain.getValue(1);
1352 // Returns a chain & a flag for retval copy to use.
1353 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1354 SmallVector<SDOperand, 8> Ops;
1355 Ops.push_back(Chain);
1356 Ops.push_back(Callee);
1358 // Add argument registers to the end of the list so that they are known live
1360 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1361 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1362 RegsToPass[i].second.getValueType()));
1364 // Add an implicit use GOT pointer in EBX.
1365 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1366 Subtarget->isPICStyleGOT())
1367 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1370 Ops.push_back(InFlag);
1372 assert(isTailCall==false && "no tail call here");
1373 Chain = DAG.getNode(X86ISD::CALL,
1374 NodeTys, &Ops[0], Ops.size());
1375 InFlag = Chain.getValue(1);
1377 // Returns a flag for retval copy to use.
1378 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1380 Ops.push_back(Chain);
1381 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1382 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1383 Ops.push_back(InFlag);
1384 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1385 InFlag = Chain.getValue(1);
1387 // Handle result values, copying them out of physregs into vregs that we
1389 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1392 //===----------------------------------------------------------------------===//
1393 // Fast Calling Convention (tail call) implementation
1394 //===----------------------------------------------------------------------===//
1396 // Like std call, callee cleans arguments, convention except that ECX is
1397 // reserved for storing the tail called function address. Only 2 registers are
1398 // free for argument passing (inreg). Tail call optimization is performed
1400 // * tailcallopt is enabled
1401 // * caller/callee are fastcc
1402 // * elf/pic is disabled OR
1403 // * elf/pic enabled + callee is in module + callee has
1404 // visibility protected or hidden
1405 // To keep the stack aligned according to platform abi the function
1406 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1407 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1408 // If a tail called function callee has more arguments than the caller the
1409 // caller needs to make sure that there is room to move the RETADDR to. This is
1410 // achieved by reserving an area the size of the argument delta right after the
1411 // original REtADDR, but before the saved framepointer or the spilled registers
1412 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1424 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1425 /// for a 16 byte align requirement.
1426 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1427 SelectionDAG& DAG) {
1428 if (PerformTailCallOpt) {
1429 MachineFunction &MF = DAG.getMachineFunction();
1430 const TargetMachine &TM = MF.getTarget();
1431 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1432 unsigned StackAlignment = TFI.getStackAlignment();
1433 uint64_t AlignMask = StackAlignment - 1;
1434 int64_t Offset = StackSize;
1435 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1436 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1437 // Number smaller than 12 so just add the difference.
1438 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1440 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1441 Offset = ((~AlignMask) & Offset) + StackAlignment +
1442 (StackAlignment-SlotSize);
1449 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1450 // following the call is a return. A function is eligible if caller/callee
1451 // calling conventions match, currently only fastcc supports tail calls, and the
1452 // function CALL is immediatly followed by a RET.
1453 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1455 SelectionDAG& DAG) const {
1456 bool IsEligible = false;
1458 // Check whether CALL node immediatly preceeds the RET node and whether the
1459 // return uses the result of the node or is a void return.
1460 if ((Ret.getNumOperands() == 1 &&
1461 (Ret.getOperand(0)== SDOperand(Call.Val,1) ||
1462 Ret.getOperand(0)== SDOperand(Call.Val,0))) ||
1463 (Ret.getOperand(0)== SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1464 Ret.getOperand(1)== SDOperand(Call.Val,0))) {
1465 MachineFunction &MF = DAG.getMachineFunction();
1466 unsigned CallerCC = MF.getFunction()->getCallingConv();
1467 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1468 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1469 SDOperand Callee = Call.getOperand(4);
1470 // On elf/pic %ebx needs to be livein.
1471 if(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1472 Subtarget->isPICStyleGOT()) {
1473 // Can only do local tail calls with PIC.
1474 GlobalValue * GV = 0;
1475 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1477 (GV = G->getGlobal()) &&
1478 (GV->hasHiddenVisibility() || GV->hasProtectedVisibility()))
1488 SDOperand X86TargetLowering::LowerX86_TailCallTo(SDOperand Op,
1491 SDOperand Chain = Op.getOperand(0);
1492 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1493 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1494 SDOperand Callee = Op.getOperand(4);
1495 bool is64Bit = Subtarget->is64Bit();
1497 assert(isTailCall && PerformTailCallOpt && "Should only emit tail calls.");
1499 // Analyze operands of the call, assigning locations to each operand.
1500 SmallVector<CCValAssign, 16> ArgLocs;
1501 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1503 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1505 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1508 // Lower arguments at fp - stackoffset + fpdiff.
1509 MachineFunction &MF = DAG.getMachineFunction();
1511 unsigned NumBytesToBePushed =
1512 GetAlignedArgumentStackSize(CCInfo.getNextStackOffset(), DAG);
1514 unsigned NumBytesCallerPushed =
1515 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1516 int FPDiff = NumBytesCallerPushed - NumBytesToBePushed;
1518 // Set the delta of movement of the returnaddr stackslot.
1519 // But only set if delta is greater than previous delta.
1520 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1521 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1523 // Adjust the ret address stack slot.
1525 MVT::ValueType VT = is64Bit ? MVT::i64 : MVT::i32;
1526 SDOperand RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1528 DAG.getLoad(VT, DAG.getEntryNode(),RetAddrFrIdx, NULL, 0);
1529 // Emit a store of the saved ret value to the new location.
1530 int SlotSize = is64Bit ? 8 : 4;
1531 int NewReturnAddrFI =
1532 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1533 SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1534 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1538 getCALLSEQ_START(Chain, DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1540 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1541 SmallVector<SDOperand, 8> MemOpChains;
1542 SmallVector<SDOperand, 8> MemOpChains2;
1543 SDOperand FramePtr, StackPtr;
1548 // Walk the register/memloc assignments, inserting copies/loads. Lower
1549 // arguments first to the stack slot where they would normally - in case of a
1550 // normal function call - be.
1551 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1552 CCValAssign &VA = ArgLocs[i];
1553 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1555 // Promote the value if needed.
1556 switch (VA.getLocInfo()) {
1557 default: assert(0 && "Unknown loc info!");
1558 case CCValAssign::Full: break;
1559 case CCValAssign::SExt:
1560 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1562 case CCValAssign::ZExt:
1563 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1565 case CCValAssign::AExt:
1566 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1570 if (VA.isRegLoc()) {
1571 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1573 assert(VA.isMemLoc());
1574 if (StackPtr.Val == 0)
1575 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1577 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1582 if (!MemOpChains.empty())
1583 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1584 &MemOpChains[0], MemOpChains.size());
1586 // Build a sequence of copy-to-reg nodes chained together with token chain
1587 // and flag operands which copy the outgoing args into registers.
1589 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1590 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1592 InFlag = Chain.getValue(1);
1594 InFlag = SDOperand();
1595 // Copy from stack slots to stack slot of a tail called function. This needs
1596 // to be done because if we would lower the arguments directly to their real
1597 // stack slot we might end up overwriting each other.
1598 // TODO: To make this more efficient (sometimes saving a store/load) we could
1599 // analyse the arguments and emit this store/load/store sequence only for
1600 // arguments which would be overwritten otherwise.
1601 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1602 CCValAssign &VA = ArgLocs[i];
1603 if (!VA.isRegLoc()) {
1604 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1605 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1607 // Get source stack slot.
1608 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1609 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1610 // Create frame index.
1611 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1612 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1613 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1614 FIN = DAG.getFrameIndex(FI, MVT::i32);
1615 if (Flags & ISD::ParamFlags::ByVal) {
1616 // Copy relative to framepointer.
1617 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1618 ISD::ParamFlags::ByValAlignOffs);
1620 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1621 ISD::ParamFlags::ByValSizeOffs;
1623 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1624 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1625 // Copy relative to framepointer.
1626 MemOpChains2.push_back(DAG.getNode(ISD::MEMCPY, MVT::Other, Chain, FIN,
1627 PtrOff, SizeNode, AlignNode));
1629 SDOperand LoadedArg = DAG.getLoad(VA.getValVT(), Chain, PtrOff, NULL,0);
1630 // Store relative to framepointer.
1631 MemOpChains2.push_back(DAG.getStore(Chain, LoadedArg, FIN, NULL, 0));
1636 if (!MemOpChains2.empty())
1637 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1638 &MemOpChains2[0], MemOpChains.size());
1640 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1642 // Does not work with tail call since ebx is not restored correctly by
1643 // tailcaller. TODO: at least for x86 - verify for x86-64
1645 // If the callee is a GlobalAddress node (quite common, every direct call is)
1646 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1647 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1648 // We should use extra load for direct calls to dllimported functions in
1650 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1651 getTargetMachine(), true))
1652 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1653 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1654 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1656 assert(Callee.getOpcode() == ISD::LOAD &&
1657 "Function destination must be loaded into virtual register");
1658 unsigned Opc = is64Bit ? X86::R9 : X86::ECX;
1660 Chain = DAG.getCopyToReg(Chain,
1661 DAG.getRegister(Opc, getPointerTy()) ,
1663 Callee = DAG.getRegister(Opc, getPointerTy());
1664 // Add register as live out.
1665 DAG.getMachineFunction().addLiveOut(Opc);
1668 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1669 SmallVector<SDOperand, 8> Ops;
1671 Ops.push_back(Chain);
1672 Ops.push_back(DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1673 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1675 Ops.push_back(InFlag);
1676 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1677 InFlag = Chain.getValue(1);
1679 // Returns a chain & a flag for retval copy to use.
1680 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1682 Ops.push_back(Chain);
1683 Ops.push_back(Callee);
1684 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1685 // Add argument registers to the end of the list so that they are known live
1687 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1688 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1689 RegsToPass[i].second.getValueType()));
1691 Ops.push_back(InFlag);
1692 assert(InFlag.Val &&
1693 "Flag must be set. Depend on flag being set in LowerRET");
1694 Chain = DAG.getNode(X86ISD::TAILCALL,
1695 Op.Val->getVTList(), &Ops[0], Ops.size());
1697 return SDOperand(Chain.Val, Op.ResNo);
1700 //===----------------------------------------------------------------------===//
1701 // X86-64 C Calling Convention implementation
1702 //===----------------------------------------------------------------------===//
1705 X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1706 MachineFunction &MF = DAG.getMachineFunction();
1707 MachineFrameInfo *MFI = MF.getFrameInfo();
1708 SDOperand Root = Op.getOperand(0);
1709 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1710 unsigned CC= MF.getFunction()->getCallingConv();
1712 static const unsigned GPR64ArgRegs[] = {
1713 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1715 static const unsigned XMMArgRegs[] = {
1716 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1717 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1721 // Assign locations to all of the incoming arguments.
1722 SmallVector<CCValAssign, 16> ArgLocs;
1723 CCState CCInfo(CC, isVarArg,
1724 getTargetMachine(), ArgLocs);
1725 if (CC == CallingConv::Fast && PerformTailCallOpt)
1726 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_TailCall);
1728 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
1730 SmallVector<SDOperand, 8> ArgValues;
1731 unsigned LastVal = ~0U;
1732 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1733 CCValAssign &VA = ArgLocs[i];
1734 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1736 assert(VA.getValNo() != LastVal &&
1737 "Don't support value assigned to multiple locs yet");
1738 LastVal = VA.getValNo();
1740 if (VA.isRegLoc()) {
1741 MVT::ValueType RegVT = VA.getLocVT();
1742 TargetRegisterClass *RC;
1743 if (RegVT == MVT::i32)
1744 RC = X86::GR32RegisterClass;
1745 else if (RegVT == MVT::i64)
1746 RC = X86::GR64RegisterClass;
1747 else if (RegVT == MVT::f32)
1748 RC = X86::FR32RegisterClass;
1749 else if (RegVT == MVT::f64)
1750 RC = X86::FR64RegisterClass;
1752 assert(MVT::isVector(RegVT));
1753 if (MVT::getSizeInBits(RegVT) == 64) {
1754 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1757 RC = X86::VR128RegisterClass;
1760 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1761 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1763 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1764 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1766 if (VA.getLocInfo() == CCValAssign::SExt)
1767 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1768 DAG.getValueType(VA.getValVT()));
1769 else if (VA.getLocInfo() == CCValAssign::ZExt)
1770 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1771 DAG.getValueType(VA.getValVT()));
1773 if (VA.getLocInfo() != CCValAssign::Full)
1774 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1776 // Handle MMX values passed in GPRs.
1777 if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1778 MVT::getSizeInBits(RegVT) == 64)
1779 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1781 ArgValues.push_back(ArgValue);
1783 assert(VA.isMemLoc());
1784 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1788 unsigned StackSize = CCInfo.getNextStackOffset();
1789 if (CC==CallingConv::Fast)
1790 StackSize =GetAlignedArgumentStackSize(StackSize, DAG);
1792 // If the function takes variable number of arguments, make a frame index for
1793 // the start of the first vararg value... for expansion of llvm.va_start.
1795 assert(CC!=CallingConv::Fast
1796 && "Var arg not supported with calling convention fastcc");
1797 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1798 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1800 // For X86-64, if there are vararg parameters that are passed via
1801 // registers, then we must store them to their spots on the stack so they
1802 // may be loaded by deferencing the result of va_next.
1803 VarArgsGPOffset = NumIntRegs * 8;
1804 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1805 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1806 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1808 // Store the integer parameter registers.
1809 SmallVector<SDOperand, 8> MemOps;
1810 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1811 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1812 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1813 for (; NumIntRegs != 6; ++NumIntRegs) {
1814 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1815 X86::GR64RegisterClass);
1816 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1817 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1818 MemOps.push_back(Store);
1819 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1820 DAG.getConstant(8, getPointerTy()));
1823 // Now store the XMM (fp + vector) parameter registers.
1824 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1825 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1826 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1827 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1828 X86::VR128RegisterClass);
1829 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1830 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1831 MemOps.push_back(Store);
1832 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1833 DAG.getConstant(16, getPointerTy()));
1835 if (!MemOps.empty())
1836 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1837 &MemOps[0], MemOps.size());
1840 ArgValues.push_back(Root);
1841 // Tail call convention (fastcc) needs callee pop.
1842 if (CC == CallingConv::Fast && PerformTailCallOpt){
1843 BytesToPopOnReturn = StackSize; // Callee pops everything.
1844 BytesCallerReserves = 0;
1846 BytesToPopOnReturn = 0; // Callee pops nothing.
1847 BytesCallerReserves = StackSize;
1849 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1850 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1852 // Return the new list of results.
1853 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1854 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1858 X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1860 SDOperand Chain = Op.getOperand(0);
1861 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1862 SDOperand Callee = Op.getOperand(4);
1864 // Analyze operands of the call, assigning locations to each operand.
1865 SmallVector<CCValAssign, 16> ArgLocs;
1866 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1867 if (CC==CallingConv::Fast)
1868 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1870 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
1872 // Get a count of how many bytes are to be pushed on the stack.
1873 unsigned NumBytes = CCInfo.getNextStackOffset();
1874 if (CC == CallingConv::Fast)
1875 NumBytes = GetAlignedArgumentStackSize(NumBytes,DAG);
1877 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1879 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1880 SmallVector<SDOperand, 8> MemOpChains;
1884 // Walk the register/memloc assignments, inserting copies/loads.
1885 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1886 CCValAssign &VA = ArgLocs[i];
1887 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1889 // Promote the value if needed.
1890 switch (VA.getLocInfo()) {
1891 default: assert(0 && "Unknown loc info!");
1892 case CCValAssign::Full: break;
1893 case CCValAssign::SExt:
1894 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1896 case CCValAssign::ZExt:
1897 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1899 case CCValAssign::AExt:
1900 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1904 if (VA.isRegLoc()) {
1905 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1907 assert(VA.isMemLoc());
1908 if (StackPtr.Val == 0)
1909 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1911 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1916 if (!MemOpChains.empty())
1917 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1918 &MemOpChains[0], MemOpChains.size());
1920 // Build a sequence of copy-to-reg nodes chained together with token chain
1921 // and flag operands which copy the outgoing args into registers.
1923 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1924 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1926 InFlag = Chain.getValue(1);
1930 assert ( CallingConv::Fast != CC &&
1931 "Var args not supported with calling convention fastcc");
1933 // From AMD64 ABI document:
1934 // For calls that may call functions that use varargs or stdargs
1935 // (prototype-less calls or calls to functions containing ellipsis (...) in
1936 // the declaration) %al is used as hidden argument to specify the number
1937 // of SSE registers used. The contents of %al do not need to match exactly
1938 // the number of registers, but must be an ubound on the number of SSE
1939 // registers used and is in the range 0 - 8 inclusive.
1941 // Count the number of XMM registers allocated.
1942 static const unsigned XMMArgRegs[] = {
1943 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1944 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1946 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1948 Chain = DAG.getCopyToReg(Chain, X86::AL,
1949 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1950 InFlag = Chain.getValue(1);
1953 // If the callee is a GlobalAddress node (quite common, every direct call is)
1954 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1955 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1956 // We should use extra load for direct calls to dllimported functions in
1958 if (getTargetMachine().getCodeModel() != CodeModel::Large
1959 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1960 getTargetMachine(), true))
1961 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1962 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1963 if (getTargetMachine().getCodeModel() != CodeModel::Large)
1964 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1966 // Returns a chain & a flag for retval copy to use.
1967 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1968 SmallVector<SDOperand, 8> Ops;
1969 Ops.push_back(Chain);
1970 Ops.push_back(Callee);
1972 // Add argument registers to the end of the list so that they are known live
1974 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1975 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1976 RegsToPass[i].second.getValueType()));
1979 Ops.push_back(InFlag);
1981 Chain = DAG.getNode(X86ISD::CALL,
1982 NodeTys, &Ops[0], Ops.size());
1983 InFlag = Chain.getValue(1);
1984 int NumBytesForCalleeToPush = 0;
1985 if (CC==CallingConv::Fast) {
1986 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1989 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1991 // Returns a flag for retval copy to use.
1992 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1994 Ops.push_back(Chain);
1995 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1996 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
1997 Ops.push_back(InFlag);
1998 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1999 InFlag = Chain.getValue(1);
2001 // Handle result values, copying them out of physregs into vregs that we
2003 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
2007 //===----------------------------------------------------------------------===//
2008 // Other Lowering Hooks
2009 //===----------------------------------------------------------------------===//
2012 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2013 MachineFunction &MF = DAG.getMachineFunction();
2014 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2015 int ReturnAddrIndex = FuncInfo->getRAIndex();
2017 if (ReturnAddrIndex == 0) {
2018 // Set up a frame object for the return address.
2019 if (Subtarget->is64Bit())
2020 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
2022 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
2024 FuncInfo->setRAIndex(ReturnAddrIndex);
2027 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2032 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
2033 /// specific condition code. It returns a false if it cannot do a direct
2034 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
2036 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2037 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
2038 SelectionDAG &DAG) {
2039 X86CC = X86::COND_INVALID;
2041 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2042 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2043 // X > -1 -> X == 0, jump !sign.
2044 RHS = DAG.getConstant(0, RHS.getValueType());
2045 X86CC = X86::COND_NS;
2047 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2048 // X < 0 -> X == 0, jump on sign.
2049 X86CC = X86::COND_S;
2051 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
2053 RHS = DAG.getConstant(0, RHS.getValueType());
2054 X86CC = X86::COND_LE;
2059 switch (SetCCOpcode) {
2061 case ISD::SETEQ: X86CC = X86::COND_E; break;
2062 case ISD::SETGT: X86CC = X86::COND_G; break;
2063 case ISD::SETGE: X86CC = X86::COND_GE; break;
2064 case ISD::SETLT: X86CC = X86::COND_L; break;
2065 case ISD::SETLE: X86CC = X86::COND_LE; break;
2066 case ISD::SETNE: X86CC = X86::COND_NE; break;
2067 case ISD::SETULT: X86CC = X86::COND_B; break;
2068 case ISD::SETUGT: X86CC = X86::COND_A; break;
2069 case ISD::SETULE: X86CC = X86::COND_BE; break;
2070 case ISD::SETUGE: X86CC = X86::COND_AE; break;
2073 // On a floating point condition, the flags are set as follows:
2075 // 0 | 0 | 0 | X > Y
2076 // 0 | 0 | 1 | X < Y
2077 // 1 | 0 | 0 | X == Y
2078 // 1 | 1 | 1 | unordered
2080 switch (SetCCOpcode) {
2083 case ISD::SETEQ: X86CC = X86::COND_E; break;
2084 case ISD::SETOLT: Flip = true; // Fallthrough
2086 case ISD::SETGT: X86CC = X86::COND_A; break;
2087 case ISD::SETOLE: Flip = true; // Fallthrough
2089 case ISD::SETGE: X86CC = X86::COND_AE; break;
2090 case ISD::SETUGT: Flip = true; // Fallthrough
2092 case ISD::SETLT: X86CC = X86::COND_B; break;
2093 case ISD::SETUGE: Flip = true; // Fallthrough
2095 case ISD::SETLE: X86CC = X86::COND_BE; break;
2097 case ISD::SETNE: X86CC = X86::COND_NE; break;
2098 case ISD::SETUO: X86CC = X86::COND_P; break;
2099 case ISD::SETO: X86CC = X86::COND_NP; break;
2102 std::swap(LHS, RHS);
2105 return X86CC != X86::COND_INVALID;
2108 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2109 /// code. Current x86 isa includes the following FP cmov instructions:
2110 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2111 static bool hasFPCMov(unsigned X86CC) {
2127 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2128 /// true if Op is undef or if its value falls within the specified range (L, H].
2129 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2130 if (Op.getOpcode() == ISD::UNDEF)
2133 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2134 return (Val >= Low && Val < Hi);
2137 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2138 /// true if Op is undef or if its value equal to the specified value.
2139 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2140 if (Op.getOpcode() == ISD::UNDEF)
2142 return cast<ConstantSDNode>(Op)->getValue() == Val;
2145 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2146 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2147 bool X86::isPSHUFDMask(SDNode *N) {
2148 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2150 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2153 // Check if the value doesn't reference the second vector.
2154 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2155 SDOperand Arg = N->getOperand(i);
2156 if (Arg.getOpcode() == ISD::UNDEF) continue;
2157 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2158 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2165 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2166 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2167 bool X86::isPSHUFHWMask(SDNode *N) {
2168 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2170 if (N->getNumOperands() != 8)
2173 // Lower quadword copied in order.
2174 for (unsigned i = 0; i != 4; ++i) {
2175 SDOperand Arg = N->getOperand(i);
2176 if (Arg.getOpcode() == ISD::UNDEF) continue;
2177 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2178 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2182 // Upper quadword shuffled.
2183 for (unsigned i = 4; i != 8; ++i) {
2184 SDOperand Arg = N->getOperand(i);
2185 if (Arg.getOpcode() == ISD::UNDEF) continue;
2186 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2187 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2188 if (Val < 4 || Val > 7)
2195 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2196 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2197 bool X86::isPSHUFLWMask(SDNode *N) {
2198 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2200 if (N->getNumOperands() != 8)
2203 // Upper quadword copied in order.
2204 for (unsigned i = 4; i != 8; ++i)
2205 if (!isUndefOrEqual(N->getOperand(i), i))
2208 // Lower quadword shuffled.
2209 for (unsigned i = 0; i != 4; ++i)
2210 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2216 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2217 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2218 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2219 if (NumElems != 2 && NumElems != 4) return false;
2221 unsigned Half = NumElems / 2;
2222 for (unsigned i = 0; i < Half; ++i)
2223 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2225 for (unsigned i = Half; i < NumElems; ++i)
2226 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2232 bool X86::isSHUFPMask(SDNode *N) {
2233 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2234 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2237 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2238 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2239 /// half elements to come from vector 1 (which would equal the dest.) and
2240 /// the upper half to come from vector 2.
2241 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2242 if (NumOps != 2 && NumOps != 4) return false;
2244 unsigned Half = NumOps / 2;
2245 for (unsigned i = 0; i < Half; ++i)
2246 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2248 for (unsigned i = Half; i < NumOps; ++i)
2249 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2254 static bool isCommutedSHUFP(SDNode *N) {
2255 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2256 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2259 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2260 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2261 bool X86::isMOVHLPSMask(SDNode *N) {
2262 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2264 if (N->getNumOperands() != 4)
2267 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2268 return isUndefOrEqual(N->getOperand(0), 6) &&
2269 isUndefOrEqual(N->getOperand(1), 7) &&
2270 isUndefOrEqual(N->getOperand(2), 2) &&
2271 isUndefOrEqual(N->getOperand(3), 3);
2274 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2275 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2277 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2278 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2280 if (N->getNumOperands() != 4)
2283 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2284 return isUndefOrEqual(N->getOperand(0), 2) &&
2285 isUndefOrEqual(N->getOperand(1), 3) &&
2286 isUndefOrEqual(N->getOperand(2), 2) &&
2287 isUndefOrEqual(N->getOperand(3), 3);
2290 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2291 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2292 bool X86::isMOVLPMask(SDNode *N) {
2293 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2295 unsigned NumElems = N->getNumOperands();
2296 if (NumElems != 2 && NumElems != 4)
2299 for (unsigned i = 0; i < NumElems/2; ++i)
2300 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2303 for (unsigned i = NumElems/2; i < NumElems; ++i)
2304 if (!isUndefOrEqual(N->getOperand(i), i))
2310 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2311 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2313 bool X86::isMOVHPMask(SDNode *N) {
2314 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2316 unsigned NumElems = N->getNumOperands();
2317 if (NumElems != 2 && NumElems != 4)
2320 for (unsigned i = 0; i < NumElems/2; ++i)
2321 if (!isUndefOrEqual(N->getOperand(i), i))
2324 for (unsigned i = 0; i < NumElems/2; ++i) {
2325 SDOperand Arg = N->getOperand(i + NumElems/2);
2326 if (!isUndefOrEqual(Arg, i + NumElems))
2333 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2334 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2335 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2336 bool V2IsSplat = false) {
2337 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2340 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2341 SDOperand BitI = Elts[i];
2342 SDOperand BitI1 = Elts[i+1];
2343 if (!isUndefOrEqual(BitI, j))
2346 if (isUndefOrEqual(BitI1, NumElts))
2349 if (!isUndefOrEqual(BitI1, j + NumElts))
2357 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2358 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2359 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2362 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2363 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2364 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2365 bool V2IsSplat = false) {
2366 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2369 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2370 SDOperand BitI = Elts[i];
2371 SDOperand BitI1 = Elts[i+1];
2372 if (!isUndefOrEqual(BitI, j + NumElts/2))
2375 if (isUndefOrEqual(BitI1, NumElts))
2378 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2386 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2387 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2388 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2391 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2392 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2394 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2395 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2397 unsigned NumElems = N->getNumOperands();
2398 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2401 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2402 SDOperand BitI = N->getOperand(i);
2403 SDOperand BitI1 = N->getOperand(i+1);
2405 if (!isUndefOrEqual(BitI, j))
2407 if (!isUndefOrEqual(BitI1, j))
2414 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2415 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2417 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2418 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2420 unsigned NumElems = N->getNumOperands();
2421 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2424 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2425 SDOperand BitI = N->getOperand(i);
2426 SDOperand BitI1 = N->getOperand(i + 1);
2428 if (!isUndefOrEqual(BitI, j))
2430 if (!isUndefOrEqual(BitI1, j))
2437 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2438 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2439 /// MOVSD, and MOVD, i.e. setting the lowest element.
2440 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2441 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2444 if (!isUndefOrEqual(Elts[0], NumElts))
2447 for (unsigned i = 1; i < NumElts; ++i) {
2448 if (!isUndefOrEqual(Elts[i], i))
2455 bool X86::isMOVLMask(SDNode *N) {
2456 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2457 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2460 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2461 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2462 /// element of vector 2 and the other elements to come from vector 1 in order.
2463 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2464 bool V2IsSplat = false,
2465 bool V2IsUndef = false) {
2466 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2469 if (!isUndefOrEqual(Ops[0], 0))
2472 for (unsigned i = 1; i < NumOps; ++i) {
2473 SDOperand Arg = Ops[i];
2474 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2475 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2476 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2483 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2484 bool V2IsUndef = false) {
2485 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2486 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2487 V2IsSplat, V2IsUndef);
2490 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2491 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2492 bool X86::isMOVSHDUPMask(SDNode *N) {
2493 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2495 if (N->getNumOperands() != 4)
2498 // Expect 1, 1, 3, 3
2499 for (unsigned i = 0; i < 2; ++i) {
2500 SDOperand Arg = N->getOperand(i);
2501 if (Arg.getOpcode() == ISD::UNDEF) continue;
2502 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2503 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2504 if (Val != 1) return false;
2508 for (unsigned i = 2; i < 4; ++i) {
2509 SDOperand Arg = N->getOperand(i);
2510 if (Arg.getOpcode() == ISD::UNDEF) continue;
2511 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2512 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2513 if (Val != 3) return false;
2517 // Don't use movshdup if it can be done with a shufps.
2521 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2522 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2523 bool X86::isMOVSLDUPMask(SDNode *N) {
2524 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2526 if (N->getNumOperands() != 4)
2529 // Expect 0, 0, 2, 2
2530 for (unsigned i = 0; i < 2; ++i) {
2531 SDOperand Arg = N->getOperand(i);
2532 if (Arg.getOpcode() == ISD::UNDEF) continue;
2533 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2534 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2535 if (Val != 0) return false;
2539 for (unsigned i = 2; i < 4; ++i) {
2540 SDOperand Arg = N->getOperand(i);
2541 if (Arg.getOpcode() == ISD::UNDEF) continue;
2542 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2543 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2544 if (Val != 2) return false;
2548 // Don't use movshdup if it can be done with a shufps.
2552 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2553 /// specifies a identity operation on the LHS or RHS.
2554 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2555 unsigned NumElems = N->getNumOperands();
2556 for (unsigned i = 0; i < NumElems; ++i)
2557 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2562 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2563 /// a splat of a single element.
2564 static bool isSplatMask(SDNode *N) {
2565 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2567 // This is a splat operation if each element of the permute is the same, and
2568 // if the value doesn't reference the second vector.
2569 unsigned NumElems = N->getNumOperands();
2570 SDOperand ElementBase;
2572 for (; i != NumElems; ++i) {
2573 SDOperand Elt = N->getOperand(i);
2574 if (isa<ConstantSDNode>(Elt)) {
2580 if (!ElementBase.Val)
2583 for (; i != NumElems; ++i) {
2584 SDOperand Arg = N->getOperand(i);
2585 if (Arg.getOpcode() == ISD::UNDEF) continue;
2586 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2587 if (Arg != ElementBase) return false;
2590 // Make sure it is a splat of the first vector operand.
2591 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2594 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2595 /// a splat of a single element and it's a 2 or 4 element mask.
2596 bool X86::isSplatMask(SDNode *N) {
2597 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2599 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2600 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2602 return ::isSplatMask(N);
2605 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2606 /// specifies a splat of zero element.
2607 bool X86::isSplatLoMask(SDNode *N) {
2608 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2610 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2611 if (!isUndefOrEqual(N->getOperand(i), 0))
2616 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2617 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2619 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2620 unsigned NumOperands = N->getNumOperands();
2621 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2623 for (unsigned i = 0; i < NumOperands; ++i) {
2625 SDOperand Arg = N->getOperand(NumOperands-i-1);
2626 if (Arg.getOpcode() != ISD::UNDEF)
2627 Val = cast<ConstantSDNode>(Arg)->getValue();
2628 if (Val >= NumOperands) Val -= NumOperands;
2630 if (i != NumOperands - 1)
2637 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2638 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2640 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2642 // 8 nodes, but we only care about the last 4.
2643 for (unsigned i = 7; i >= 4; --i) {
2645 SDOperand Arg = N->getOperand(i);
2646 if (Arg.getOpcode() != ISD::UNDEF)
2647 Val = cast<ConstantSDNode>(Arg)->getValue();
2656 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2657 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2659 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2661 // 8 nodes, but we only care about the first 4.
2662 for (int i = 3; i >= 0; --i) {
2664 SDOperand Arg = N->getOperand(i);
2665 if (Arg.getOpcode() != ISD::UNDEF)
2666 Val = cast<ConstantSDNode>(Arg)->getValue();
2675 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2676 /// specifies a 8 element shuffle that can be broken into a pair of
2677 /// PSHUFHW and PSHUFLW.
2678 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2679 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2681 if (N->getNumOperands() != 8)
2684 // Lower quadword shuffled.
2685 for (unsigned i = 0; i != 4; ++i) {
2686 SDOperand Arg = N->getOperand(i);
2687 if (Arg.getOpcode() == ISD::UNDEF) continue;
2688 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2689 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2694 // Upper quadword shuffled.
2695 for (unsigned i = 4; i != 8; ++i) {
2696 SDOperand Arg = N->getOperand(i);
2697 if (Arg.getOpcode() == ISD::UNDEF) continue;
2698 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2699 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2700 if (Val < 4 || Val > 7)
2707 /// CommuteVectorShuffle - Swap vector_shuffle operandsas well as
2708 /// values in ther permute mask.
2709 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2710 SDOperand &V2, SDOperand &Mask,
2711 SelectionDAG &DAG) {
2712 MVT::ValueType VT = Op.getValueType();
2713 MVT::ValueType MaskVT = Mask.getValueType();
2714 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2715 unsigned NumElems = Mask.getNumOperands();
2716 SmallVector<SDOperand, 8> MaskVec;
2718 for (unsigned i = 0; i != NumElems; ++i) {
2719 SDOperand Arg = Mask.getOperand(i);
2720 if (Arg.getOpcode() == ISD::UNDEF) {
2721 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2724 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2725 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2727 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2729 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2733 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2734 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2737 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2738 /// match movhlps. The lower half elements should come from upper half of
2739 /// V1 (and in order), and the upper half elements should come from the upper
2740 /// half of V2 (and in order).
2741 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2742 unsigned NumElems = Mask->getNumOperands();
2745 for (unsigned i = 0, e = 2; i != e; ++i)
2746 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2748 for (unsigned i = 2; i != 4; ++i)
2749 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2754 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2755 /// is promoted to a vector.
2756 static inline bool isScalarLoadToVector(SDNode *N) {
2757 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2758 N = N->getOperand(0).Val;
2759 return ISD::isNON_EXTLoad(N);
2764 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2765 /// match movlp{s|d}. The lower half elements should come from lower half of
2766 /// V1 (and in order), and the upper half elements should come from the upper
2767 /// half of V2 (and in order). And since V1 will become the source of the
2768 /// MOVLP, it must be either a vector load or a scalar load to vector.
2769 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2770 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2772 // Is V2 is a vector load, don't do this transformation. We will try to use
2773 // load folding shufps op.
2774 if (ISD::isNON_EXTLoad(V2))
2777 unsigned NumElems = Mask->getNumOperands();
2778 if (NumElems != 2 && NumElems != 4)
2780 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2781 if (!isUndefOrEqual(Mask->getOperand(i), i))
2783 for (unsigned i = NumElems/2; i != NumElems; ++i)
2784 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2789 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2791 static bool isSplatVector(SDNode *N) {
2792 if (N->getOpcode() != ISD::BUILD_VECTOR)
2795 SDOperand SplatValue = N->getOperand(0);
2796 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2797 if (N->getOperand(i) != SplatValue)
2802 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2804 static bool isUndefShuffle(SDNode *N) {
2805 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2808 SDOperand V1 = N->getOperand(0);
2809 SDOperand V2 = N->getOperand(1);
2810 SDOperand Mask = N->getOperand(2);
2811 unsigned NumElems = Mask.getNumOperands();
2812 for (unsigned i = 0; i != NumElems; ++i) {
2813 SDOperand Arg = Mask.getOperand(i);
2814 if (Arg.getOpcode() != ISD::UNDEF) {
2815 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2816 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2818 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2825 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2827 static inline bool isZeroNode(SDOperand Elt) {
2828 return ((isa<ConstantSDNode>(Elt) &&
2829 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2830 (isa<ConstantFPSDNode>(Elt) &&
2831 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2834 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2835 /// to an zero vector.
2836 static bool isZeroShuffle(SDNode *N) {
2837 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2840 SDOperand V1 = N->getOperand(0);
2841 SDOperand V2 = N->getOperand(1);
2842 SDOperand Mask = N->getOperand(2);
2843 unsigned NumElems = Mask.getNumOperands();
2844 for (unsigned i = 0; i != NumElems; ++i) {
2845 SDOperand Arg = Mask.getOperand(i);
2846 if (Arg.getOpcode() != ISD::UNDEF) {
2847 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2848 if (Idx < NumElems) {
2849 unsigned Opc = V1.Val->getOpcode();
2850 if (Opc == ISD::UNDEF)
2852 if (Opc != ISD::BUILD_VECTOR ||
2853 !isZeroNode(V1.Val->getOperand(Idx)))
2855 } else if (Idx >= NumElems) {
2856 unsigned Opc = V2.Val->getOpcode();
2857 if (Opc == ISD::UNDEF)
2859 if (Opc != ISD::BUILD_VECTOR ||
2860 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2868 /// getZeroVector - Returns a vector of specified type with all zero elements.
2870 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2871 assert(MVT::isVector(VT) && "Expected a vector type");
2872 unsigned NumElems = MVT::getVectorNumElements(VT);
2873 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2874 bool isFP = MVT::isFloatingPoint(EVT);
2875 SDOperand Zero = isFP ? DAG.getConstantFP(0.0, EVT) : DAG.getConstant(0, EVT);
2876 SmallVector<SDOperand, 8> ZeroVec(NumElems, Zero);
2877 return DAG.getNode(ISD::BUILD_VECTOR, VT, &ZeroVec[0], ZeroVec.size());
2880 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2881 /// that point to V2 points to its first element.
2882 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2883 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2885 bool Changed = false;
2886 SmallVector<SDOperand, 8> MaskVec;
2887 unsigned NumElems = Mask.getNumOperands();
2888 for (unsigned i = 0; i != NumElems; ++i) {
2889 SDOperand Arg = Mask.getOperand(i);
2890 if (Arg.getOpcode() != ISD::UNDEF) {
2891 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2892 if (Val > NumElems) {
2893 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2897 MaskVec.push_back(Arg);
2901 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2902 &MaskVec[0], MaskVec.size());
2906 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2907 /// operation of specified width.
2908 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2909 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2910 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2912 SmallVector<SDOperand, 8> MaskVec;
2913 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2914 for (unsigned i = 1; i != NumElems; ++i)
2915 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2916 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2919 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2920 /// of specified width.
2921 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2922 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2923 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2924 SmallVector<SDOperand, 8> MaskVec;
2925 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2926 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2927 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2929 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2932 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2933 /// of specified width.
2934 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2935 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2936 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2937 unsigned Half = NumElems/2;
2938 SmallVector<SDOperand, 8> MaskVec;
2939 for (unsigned i = 0; i != Half; ++i) {
2940 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2941 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2943 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2946 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2948 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2949 SDOperand V1 = Op.getOperand(0);
2950 SDOperand Mask = Op.getOperand(2);
2951 MVT::ValueType VT = Op.getValueType();
2952 unsigned NumElems = Mask.getNumOperands();
2953 Mask = getUnpacklMask(NumElems, DAG);
2954 while (NumElems != 4) {
2955 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2958 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2960 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2961 Mask = getZeroVector(MaskVT, DAG);
2962 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2963 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2964 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2967 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2968 /// vector of zero or undef vector.
2969 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2970 unsigned NumElems, unsigned Idx,
2971 bool isZero, SelectionDAG &DAG) {
2972 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2973 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2974 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2975 SDOperand Zero = DAG.getConstant(0, EVT);
2976 SmallVector<SDOperand, 8> MaskVec(NumElems, Zero);
2977 MaskVec[Idx] = DAG.getConstant(NumElems, EVT);
2978 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2979 &MaskVec[0], MaskVec.size());
2980 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2983 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2985 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2986 unsigned NumNonZero, unsigned NumZero,
2987 SelectionDAG &DAG, TargetLowering &TLI) {
2993 for (unsigned i = 0; i < 16; ++i) {
2994 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2995 if (ThisIsNonZero && First) {
2997 V = getZeroVector(MVT::v8i16, DAG);
2999 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3004 SDOperand ThisElt(0, 0), LastElt(0, 0);
3005 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3006 if (LastIsNonZero) {
3007 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3009 if (ThisIsNonZero) {
3010 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3011 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3012 ThisElt, DAG.getConstant(8, MVT::i8));
3014 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3019 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3020 DAG.getConstant(i/2, TLI.getPointerTy()));
3024 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3027 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3029 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3030 unsigned NumNonZero, unsigned NumZero,
3031 SelectionDAG &DAG, TargetLowering &TLI) {
3037 for (unsigned i = 0; i < 8; ++i) {
3038 bool isNonZero = (NonZeros & (1 << i)) != 0;
3042 V = getZeroVector(MVT::v8i16, DAG);
3044 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3047 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3048 DAG.getConstant(i, TLI.getPointerTy()));
3056 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3057 // All zero's are handled with pxor.
3058 if (ISD::isBuildVectorAllZeros(Op.Val))
3061 // All one's are handled with pcmpeqd.
3062 if (ISD::isBuildVectorAllOnes(Op.Val))
3065 MVT::ValueType VT = Op.getValueType();
3066 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3067 unsigned EVTBits = MVT::getSizeInBits(EVT);
3069 unsigned NumElems = Op.getNumOperands();
3070 unsigned NumZero = 0;
3071 unsigned NumNonZero = 0;
3072 unsigned NonZeros = 0;
3073 unsigned NumNonZeroImms = 0;
3074 std::set<SDOperand> Values;
3075 for (unsigned i = 0; i < NumElems; ++i) {
3076 SDOperand Elt = Op.getOperand(i);
3077 if (Elt.getOpcode() != ISD::UNDEF) {
3079 if (isZeroNode(Elt))
3082 NonZeros |= (1 << i);
3084 if (Elt.getOpcode() == ISD::Constant ||
3085 Elt.getOpcode() == ISD::ConstantFP)
3091 if (NumNonZero == 0) {
3093 // All undef vector. Return an UNDEF.
3094 return DAG.getNode(ISD::UNDEF, VT);
3096 // A mix of zero and undef. Return a zero vector.
3097 return getZeroVector(VT, DAG);
3100 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3101 if (Values.size() == 1)
3104 // Special case for single non-zero element.
3105 if (NumNonZero == 1) {
3106 unsigned Idx = CountTrailingZeros_32(NonZeros);
3107 SDOperand Item = Op.getOperand(Idx);
3108 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3110 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3111 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
3114 if (EVTBits == 32) {
3115 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3116 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
3118 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3119 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3120 SmallVector<SDOperand, 8> MaskVec;
3121 for (unsigned i = 0; i < NumElems; i++)
3122 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3123 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3124 &MaskVec[0], MaskVec.size());
3125 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3126 DAG.getNode(ISD::UNDEF, VT), Mask);
3130 // A vector full of immediates; various special cases are already
3131 // handled, so this is best done with a single constant-pool load.
3132 if (NumNonZero == NumNonZeroImms)
3135 // Let legalizer expand 2-wide build_vectors.
3139 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3140 if (EVTBits == 8 && NumElems == 16) {
3141 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3143 if (V.Val) return V;
3146 if (EVTBits == 16 && NumElems == 8) {
3147 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3149 if (V.Val) return V;
3152 // If element VT is == 32 bits, turn it into a number of shuffles.
3153 SmallVector<SDOperand, 8> V;
3155 if (NumElems == 4 && NumZero > 0) {
3156 for (unsigned i = 0; i < 4; ++i) {
3157 bool isZero = !(NonZeros & (1 << i));
3159 V[i] = getZeroVector(VT, DAG);
3161 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3164 for (unsigned i = 0; i < 2; ++i) {
3165 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3168 V[i] = V[i*2]; // Must be a zero vector.
3171 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3172 getMOVLMask(NumElems, DAG));
3175 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3176 getMOVLMask(NumElems, DAG));
3179 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3180 getUnpacklMask(NumElems, DAG));
3185 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3186 // clears the upper bits.
3187 // FIXME: we can do the same for v4f32 case when we know both parts of
3188 // the lower half come from scalar_to_vector (loadf32). We should do
3189 // that in post legalizer dag combiner with target specific hooks.
3190 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3192 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3193 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3194 SmallVector<SDOperand, 8> MaskVec;
3195 bool Reverse = (NonZeros & 0x3) == 2;
3196 for (unsigned i = 0; i < 2; ++i)
3198 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3200 MaskVec.push_back(DAG.getConstant(i, EVT));
3201 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3202 for (unsigned i = 0; i < 2; ++i)
3204 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3206 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3207 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3208 &MaskVec[0], MaskVec.size());
3209 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3212 if (Values.size() > 2) {
3213 // Expand into a number of unpckl*.
3215 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3216 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3217 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3218 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3219 for (unsigned i = 0; i < NumElems; ++i)
3220 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3222 while (NumElems != 0) {
3223 for (unsigned i = 0; i < NumElems; ++i)
3224 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3235 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3236 SDOperand V1 = Op.getOperand(0);
3237 SDOperand V2 = Op.getOperand(1);
3238 SDOperand PermMask = Op.getOperand(2);
3239 MVT::ValueType VT = Op.getValueType();
3240 unsigned NumElems = PermMask.getNumOperands();
3241 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3242 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3243 bool V1IsSplat = false;
3244 bool V2IsSplat = false;
3246 if (isUndefShuffle(Op.Val))
3247 return DAG.getNode(ISD::UNDEF, VT);
3249 if (isZeroShuffle(Op.Val))
3250 return getZeroVector(VT, DAG);
3252 if (isIdentityMask(PermMask.Val))
3254 else if (isIdentityMask(PermMask.Val, true))
3257 if (isSplatMask(PermMask.Val)) {
3258 if (NumElems <= 4) return Op;
3259 // Promote it to a v4i32 splat.
3260 return PromoteSplat(Op, DAG);
3263 if (X86::isMOVLMask(PermMask.Val))
3264 return (V1IsUndef) ? V2 : Op;
3266 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3267 X86::isMOVSLDUPMask(PermMask.Val) ||
3268 X86::isMOVHLPSMask(PermMask.Val) ||
3269 X86::isMOVHPMask(PermMask.Val) ||
3270 X86::isMOVLPMask(PermMask.Val))
3273 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3274 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3275 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3277 bool Commuted = false;
3278 V1IsSplat = isSplatVector(V1.Val);
3279 V2IsSplat = isSplatVector(V2.Val);
3280 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3281 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3282 std::swap(V1IsSplat, V2IsSplat);
3283 std::swap(V1IsUndef, V2IsUndef);
3287 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3288 if (V2IsUndef) return V1;
3289 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3291 // V2 is a splat, so the mask may be malformed. That is, it may point
3292 // to any V2 element. The instruction selectior won't like this. Get
3293 // a corrected mask and commute to form a proper MOVS{S|D}.
3294 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3295 if (NewMask.Val != PermMask.Val)
3296 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3301 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3302 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3303 X86::isUNPCKLMask(PermMask.Val) ||
3304 X86::isUNPCKHMask(PermMask.Val))
3308 // Normalize mask so all entries that point to V2 points to its first
3309 // element then try to match unpck{h|l} again. If match, return a
3310 // new vector_shuffle with the corrected mask.
3311 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3312 if (NewMask.Val != PermMask.Val) {
3313 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3314 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3315 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3316 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3317 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3318 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3323 // Normalize the node to match x86 shuffle ops if needed
3324 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3325 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3328 // Commute is back and try unpck* again.
3329 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3330 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3331 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3332 X86::isUNPCKLMask(PermMask.Val) ||
3333 X86::isUNPCKHMask(PermMask.Val))
3337 // If VT is integer, try PSHUF* first, then SHUFP*.
3338 if (MVT::isInteger(VT)) {
3339 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3340 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3341 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3342 X86::isPSHUFDMask(PermMask.Val)) ||
3343 X86::isPSHUFHWMask(PermMask.Val) ||
3344 X86::isPSHUFLWMask(PermMask.Val)) {
3345 if (V2.getOpcode() != ISD::UNDEF)
3346 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3347 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3351 if (X86::isSHUFPMask(PermMask.Val) &&
3352 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3355 // Handle v8i16 shuffle high / low shuffle node pair.
3356 if (VT == MVT::v8i16 && isPSHUFHW_PSHUFLWMask(PermMask.Val)) {
3357 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3358 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3359 SmallVector<SDOperand, 8> MaskVec;
3360 for (unsigned i = 0; i != 4; ++i)
3361 MaskVec.push_back(PermMask.getOperand(i));
3362 for (unsigned i = 4; i != 8; ++i)
3363 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3364 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3365 &MaskVec[0], MaskVec.size());
3366 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3368 for (unsigned i = 0; i != 4; ++i)
3369 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3370 for (unsigned i = 4; i != 8; ++i)
3371 MaskVec.push_back(PermMask.getOperand(i));
3372 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0],MaskVec.size());
3373 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3376 // Floating point cases in the other order.
3377 if (X86::isSHUFPMask(PermMask.Val))
3379 if (X86::isPSHUFDMask(PermMask.Val) ||
3380 X86::isPSHUFHWMask(PermMask.Val) ||
3381 X86::isPSHUFLWMask(PermMask.Val)) {
3382 if (V2.getOpcode() != ISD::UNDEF)
3383 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3384 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3389 if (NumElems == 4 &&
3390 // Don't do this for MMX.
3391 MVT::getSizeInBits(VT) != 64) {
3392 MVT::ValueType MaskVT = PermMask.getValueType();
3393 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3394 SmallVector<std::pair<int, int>, 8> Locs;
3395 Locs.reserve(NumElems);
3396 SmallVector<SDOperand, 8> Mask1(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3397 SmallVector<SDOperand, 8> Mask2(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3400 // If no more than two elements come from either vector. This can be
3401 // implemented with two shuffles. First shuffle gather the elements.
3402 // The second shuffle, which takes the first shuffle as both of its
3403 // vector operands, put the elements into the right order.
3404 for (unsigned i = 0; i != NumElems; ++i) {
3405 SDOperand Elt = PermMask.getOperand(i);
3406 if (Elt.getOpcode() == ISD::UNDEF) {
3407 Locs[i] = std::make_pair(-1, -1);
3409 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3410 if (Val < NumElems) {
3411 Locs[i] = std::make_pair(0, NumLo);
3415 Locs[i] = std::make_pair(1, NumHi);
3416 if (2+NumHi < NumElems)
3417 Mask1[2+NumHi] = Elt;
3422 if (NumLo <= 2 && NumHi <= 2) {
3423 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3424 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3425 &Mask1[0], Mask1.size()));
3426 for (unsigned i = 0; i != NumElems; ++i) {
3427 if (Locs[i].first == -1)
3430 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3431 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3432 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3436 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3437 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3438 &Mask2[0], Mask2.size()));
3441 // Break it into (shuffle shuffle_hi, shuffle_lo).
3443 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3444 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3445 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3446 unsigned MaskIdx = 0;
3448 unsigned HiIdx = NumElems/2;
3449 for (unsigned i = 0; i != NumElems; ++i) {
3450 if (i == NumElems/2) {
3456 SDOperand Elt = PermMask.getOperand(i);
3457 if (Elt.getOpcode() == ISD::UNDEF) {
3458 Locs[i] = std::make_pair(-1, -1);
3459 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3460 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3461 (*MaskPtr)[LoIdx] = Elt;
3464 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3465 (*MaskPtr)[HiIdx] = Elt;
3470 SDOperand LoShuffle =
3471 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3472 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3473 &LoMask[0], LoMask.size()));
3474 SDOperand HiShuffle =
3475 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3476 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3477 &HiMask[0], HiMask.size()));
3478 SmallVector<SDOperand, 8> MaskOps;
3479 for (unsigned i = 0; i != NumElems; ++i) {
3480 if (Locs[i].first == -1) {
3481 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3483 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3484 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3487 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3488 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3489 &MaskOps[0], MaskOps.size()));
3496 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3497 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3500 MVT::ValueType VT = Op.getValueType();
3501 // TODO: handle v16i8.
3502 if (MVT::getSizeInBits(VT) == 16) {
3503 // Transform it so it match pextrw which produces a 32-bit result.
3504 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3505 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3506 Op.getOperand(0), Op.getOperand(1));
3507 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3508 DAG.getValueType(VT));
3509 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3510 } else if (MVT::getSizeInBits(VT) == 32) {
3511 SDOperand Vec = Op.getOperand(0);
3512 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3515 // SHUFPS the element to the lowest double word, then movss.
3516 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3517 SmallVector<SDOperand, 8> IdxVec;
3519 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3521 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3523 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3525 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3526 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3527 &IdxVec[0], IdxVec.size());
3528 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3529 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3530 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3531 DAG.getConstant(0, getPointerTy()));
3532 } else if (MVT::getSizeInBits(VT) == 64) {
3533 SDOperand Vec = Op.getOperand(0);
3534 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3538 // UNPCKHPD the element to the lowest double word, then movsd.
3539 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3540 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3541 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3542 SmallVector<SDOperand, 8> IdxVec;
3543 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3545 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3546 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3547 &IdxVec[0], IdxVec.size());
3548 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3549 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3550 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3551 DAG.getConstant(0, getPointerTy()));
3558 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3559 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3560 // as its second argument.
3561 MVT::ValueType VT = Op.getValueType();
3562 MVT::ValueType BaseVT = MVT::getVectorElementType(VT);
3563 SDOperand N0 = Op.getOperand(0);
3564 SDOperand N1 = Op.getOperand(1);
3565 SDOperand N2 = Op.getOperand(2);
3566 if (MVT::getSizeInBits(BaseVT) == 16) {
3567 if (N1.getValueType() != MVT::i32)
3568 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3569 if (N2.getValueType() != MVT::i32)
3570 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
3571 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3572 } else if (MVT::getSizeInBits(BaseVT) == 32) {
3573 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
3576 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
3577 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3578 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3579 SmallVector<SDOperand, 8> MaskVec;
3580 MaskVec.push_back(DAG.getConstant(4, BaseVT));
3581 for (unsigned i = 1; i <= 3; ++i)
3582 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3583 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
3584 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3585 &MaskVec[0], MaskVec.size()));
3587 // Use two pinsrw instructions to insert a 32 bit value.
3589 if (MVT::isFloatingPoint(N1.getValueType())) {
3590 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
3591 N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
3592 N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
3593 DAG.getConstant(0, getPointerTy()));
3595 N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
3596 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3597 DAG.getConstant(Idx, getPointerTy()));
3598 N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
3599 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3600 DAG.getConstant(Idx+1, getPointerTy()));
3601 return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3609 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3610 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3611 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3614 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3615 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3616 // one of the above mentioned nodes. It has to be wrapped because otherwise
3617 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3618 // be used to form addressing mode. These wrapped nodes will be selected
3621 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3622 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3623 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3625 CP->getAlignment());
3626 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3627 // With PIC, the address is actually $g + Offset.
3628 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3629 !Subtarget->isPICStyleRIPRel()) {
3630 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3631 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3639 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3640 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3641 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3642 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3643 // With PIC, the address is actually $g + Offset.
3644 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3645 !Subtarget->isPICStyleRIPRel()) {
3646 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3647 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3651 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3652 // load the value at address GV, not the value of GV itself. This means that
3653 // the GlobalAddress must be in the base or index register of the address, not
3654 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3655 // The same applies for external symbols during PIC codegen
3656 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3657 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
3662 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3664 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3665 const MVT::ValueType PtrVT) {
3667 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3668 DAG.getNode(X86ISD::GlobalBaseReg,
3670 InFlag = Chain.getValue(1);
3672 // emit leal symbol@TLSGD(,%ebx,1), %eax
3673 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3674 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3675 GA->getValueType(0),
3677 SDOperand Ops[] = { Chain, TGA, InFlag };
3678 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3679 InFlag = Result.getValue(2);
3680 Chain = Result.getValue(1);
3682 // call ___tls_get_addr. This function receives its argument in
3683 // the register EAX.
3684 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3685 InFlag = Chain.getValue(1);
3687 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3688 SDOperand Ops1[] = { Chain,
3689 DAG.getTargetExternalSymbol("___tls_get_addr",
3691 DAG.getRegister(X86::EAX, PtrVT),
3692 DAG.getRegister(X86::EBX, PtrVT),
3694 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3695 InFlag = Chain.getValue(1);
3697 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3700 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3701 // "local exec" model.
3703 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3704 const MVT::ValueType PtrVT) {
3705 // Get the Thread Pointer
3706 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3707 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3709 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3710 GA->getValueType(0),
3712 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3714 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3715 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
3717 // The address of the thread local variable is the add of the thread
3718 // pointer with the offset of the variable.
3719 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3723 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3724 // TODO: implement the "local dynamic" model
3725 // TODO: implement the "initial exec"model for pic executables
3726 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3727 "TLS not implemented for non-ELF and 64-bit targets");
3728 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3729 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3730 // otherwise use the "Local Exec"TLS Model
3731 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3732 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3734 return LowerToTLSExecModel(GA, DAG, getPointerTy());
3738 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3739 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3740 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3741 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3742 // With PIC, the address is actually $g + Offset.
3743 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3744 !Subtarget->isPICStyleRIPRel()) {
3745 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3746 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3753 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3754 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3755 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3756 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3757 // With PIC, the address is actually $g + Offset.
3758 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3759 !Subtarget->isPICStyleRIPRel()) {
3760 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3761 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3768 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
3769 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
3770 "Not an i64 shift!");
3771 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
3772 SDOperand ShOpLo = Op.getOperand(0);
3773 SDOperand ShOpHi = Op.getOperand(1);
3774 SDOperand ShAmt = Op.getOperand(2);
3775 SDOperand Tmp1 = isSRA ?
3776 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
3777 DAG.getConstant(0, MVT::i32);
3779 SDOperand Tmp2, Tmp3;
3780 if (Op.getOpcode() == ISD::SHL_PARTS) {
3781 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
3782 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
3784 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
3785 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
3788 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3789 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
3790 DAG.getConstant(32, MVT::i8));
3791 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
3792 AndNode, DAG.getConstant(0, MVT::i8));
3795 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3796 unsigned Opc = X86ISD::CMOV;
3797 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
3798 SmallVector<SDOperand, 4> Ops;
3799 if (Op.getOpcode() == ISD::SHL_PARTS) {
3800 Ops.push_back(Tmp2);
3801 Ops.push_back(Tmp3);
3803 Ops.push_back(Cond);
3804 Hi = DAG.getNode(Opc, MVT::i32, &Ops[0], Ops.size());
3807 Ops.push_back(Tmp3);
3808 Ops.push_back(Tmp1);
3810 Ops.push_back(Cond);
3811 Lo = DAG.getNode(Opc, MVT::i32, &Ops[0], Ops.size());
3813 Ops.push_back(Tmp2);
3814 Ops.push_back(Tmp3);
3816 Ops.push_back(Cond);
3817 Lo = DAG.getNode(Opc, MVT::i32, &Ops[0], Ops.size());
3820 Ops.push_back(Tmp3);
3821 Ops.push_back(Tmp1);
3823 Ops.push_back(Cond);
3824 Hi = DAG.getNode(Opc, MVT::i32, &Ops[0], Ops.size());
3827 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
3831 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
3834 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
3835 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
3836 Op.getOperand(0).getValueType() >= MVT::i16 &&
3837 "Unknown SINT_TO_FP to lower!");
3840 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
3841 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
3842 MachineFunction &MF = DAG.getMachineFunction();
3843 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
3844 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3845 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
3846 StackSlot, NULL, 0);
3848 // These are really Legal; caller falls through into that case.
3849 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f32 && X86ScalarSSEf32)
3851 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f64 && X86ScalarSSEf64)
3853 if (SrcVT==MVT::i64 && Op.getValueType() != MVT::f80 &&
3854 Subtarget->is64Bit())
3859 bool useSSE = (X86ScalarSSEf32 && Op.getValueType() == MVT::f32) ||
3860 (X86ScalarSSEf64 && Op.getValueType() == MVT::f64);
3862 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
3864 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
3865 SmallVector<SDOperand, 8> Ops;
3866 Ops.push_back(Chain);
3867 Ops.push_back(StackSlot);
3868 Ops.push_back(DAG.getValueType(SrcVT));
3869 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
3870 Tys, &Ops[0], Ops.size());
3873 Chain = Result.getValue(1);
3874 SDOperand InFlag = Result.getValue(2);
3876 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
3877 // shouldn't be necessary except that RFP cannot be live across
3878 // multiple blocks. When stackifier is fixed, they can be uncoupled.
3879 MachineFunction &MF = DAG.getMachineFunction();
3880 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3881 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3882 Tys = DAG.getVTList(MVT::Other);
3883 SmallVector<SDOperand, 8> Ops;
3884 Ops.push_back(Chain);
3885 Ops.push_back(Result);
3886 Ops.push_back(StackSlot);
3887 Ops.push_back(DAG.getValueType(Op.getValueType()));
3888 Ops.push_back(InFlag);
3889 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
3890 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
3896 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
3897 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
3898 "Unknown FP_TO_SINT to lower!");
3899 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
3902 MachineFunction &MF = DAG.getMachineFunction();
3903 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
3904 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3905 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3907 // These are really Legal.
3908 if (Op.getValueType() == MVT::i32 &&
3909 X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32)
3911 if (Op.getValueType() == MVT::i32 &&
3912 X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)
3914 if (Subtarget->is64Bit() &&
3915 Op.getValueType() == MVT::i64 &&
3916 Op.getOperand(0).getValueType() != MVT::f80)
3920 switch (Op.getValueType()) {
3921 default: assert(0 && "Invalid FP_TO_SINT to lower!");
3922 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
3923 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
3924 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
3927 SDOperand Chain = DAG.getEntryNode();
3928 SDOperand Value = Op.getOperand(0);
3929 if ((X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32) ||
3930 (X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)) {
3931 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
3932 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
3933 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
3935 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
3937 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
3938 Chain = Value.getValue(1);
3939 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3940 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3943 // Build the FP_TO_INT*_IN_MEM
3944 SDOperand Ops[] = { Chain, Value, StackSlot };
3945 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
3948 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
3951 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
3952 MVT::ValueType VT = Op.getValueType();
3953 MVT::ValueType EltVT = VT;
3954 if (MVT::isVector(VT))
3955 EltVT = MVT::getVectorElementType(VT);
3956 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
3957 std::vector<Constant*> CV;
3958 if (EltVT == MVT::f64) {
3959 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
3963 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
3969 Constant *C = ConstantVector::get(CV);
3970 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
3971 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
3973 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
3976 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
3977 MVT::ValueType VT = Op.getValueType();
3978 MVT::ValueType EltVT = VT;
3979 unsigned EltNum = 1;
3980 if (MVT::isVector(VT)) {
3981 EltVT = MVT::getVectorElementType(VT);
3982 EltNum = MVT::getVectorNumElements(VT);
3984 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
3985 std::vector<Constant*> CV;
3986 if (EltVT == MVT::f64) {
3987 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
3991 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
3997 Constant *C = ConstantVector::get(CV);
3998 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
3999 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4001 if (MVT::isVector(VT)) {
4002 return DAG.getNode(ISD::BIT_CONVERT, VT,
4003 DAG.getNode(ISD::XOR, MVT::v2i64,
4004 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4005 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4007 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4011 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4012 SDOperand Op0 = Op.getOperand(0);
4013 SDOperand Op1 = Op.getOperand(1);
4014 MVT::ValueType VT = Op.getValueType();
4015 MVT::ValueType SrcVT = Op1.getValueType();
4016 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4018 // If second operand is smaller, extend it first.
4019 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4020 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4022 SrcTy = MVT::getTypeForValueType(SrcVT);
4025 // First get the sign bit of second operand.
4026 std::vector<Constant*> CV;
4027 if (SrcVT == MVT::f64) {
4028 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4029 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4031 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4032 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4033 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4034 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4036 Constant *C = ConstantVector::get(CV);
4037 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4038 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx, NULL, 0,
4040 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4042 // Shift sign bit right or left if the two operands have different types.
4043 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4044 // Op0 is MVT::f32, Op1 is MVT::f64.
4045 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4046 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4047 DAG.getConstant(32, MVT::i32));
4048 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4049 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4050 DAG.getConstant(0, getPointerTy()));
4053 // Clear first operand sign bit.
4055 if (VT == MVT::f64) {
4056 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4057 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4059 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4060 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4061 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4062 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4064 C = ConstantVector::get(CV);
4065 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4066 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4068 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4070 // Or the value with the sign bit.
4071 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4074 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4075 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4077 SDOperand Op0 = Op.getOperand(0);
4078 SDOperand Op1 = Op.getOperand(1);
4079 SDOperand CC = Op.getOperand(2);
4080 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4081 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4084 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4086 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4087 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4088 DAG.getConstant(X86CC, MVT::i8), Cond);
4091 assert(isFP && "Illegal integer SetCC!");
4093 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4094 switch (SetCCOpcode) {
4095 default: assert(false && "Illegal floating point SetCC!");
4096 case ISD::SETOEQ: { // !PF & ZF
4097 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4098 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4099 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4100 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4101 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4103 case ISD::SETUNE: { // PF | !ZF
4104 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4105 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4106 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4107 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4108 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4114 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4115 bool addTest = true;
4116 SDOperand Cond = Op.getOperand(0);
4119 if (Cond.getOpcode() == ISD::SETCC)
4120 Cond = LowerSETCC(Cond, DAG);
4122 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4123 // setting operand in place of the X86ISD::SETCC.
4124 if (Cond.getOpcode() == X86ISD::SETCC) {
4125 CC = Cond.getOperand(0);
4127 SDOperand Cmp = Cond.getOperand(1);
4128 unsigned Opc = Cmp.getOpcode();
4129 MVT::ValueType VT = Op.getValueType();
4130 bool IllegalFPCMov = false;
4131 if (VT == MVT::f32 && !X86ScalarSSEf32)
4132 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4133 else if (VT == MVT::f64 && !X86ScalarSSEf64)
4134 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4135 if ((Opc == X86ISD::CMP ||
4136 Opc == X86ISD::COMI ||
4137 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4144 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4145 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4148 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4150 SmallVector<SDOperand, 4> Ops;
4151 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4152 // condition is true.
4153 Ops.push_back(Op.getOperand(2));
4154 Ops.push_back(Op.getOperand(1));
4156 Ops.push_back(Cond);
4157 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4160 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4161 bool addTest = true;
4162 SDOperand Chain = Op.getOperand(0);
4163 SDOperand Cond = Op.getOperand(1);
4164 SDOperand Dest = Op.getOperand(2);
4167 if (Cond.getOpcode() == ISD::SETCC)
4168 Cond = LowerSETCC(Cond, DAG);
4170 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4171 // setting operand in place of the X86ISD::SETCC.
4172 if (Cond.getOpcode() == X86ISD::SETCC) {
4173 CC = Cond.getOperand(0);
4175 SDOperand Cmp = Cond.getOperand(1);
4176 unsigned Opc = Cmp.getOpcode();
4177 if (Opc == X86ISD::CMP ||
4178 Opc == X86ISD::COMI ||
4179 Opc == X86ISD::UCOMI) {
4186 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4187 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4189 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4190 Chain, Op.getOperand(2), CC, Cond);
4193 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
4194 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4195 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
4197 if (Subtarget->is64Bit())
4198 if(CallingConv==CallingConv::Fast && isTailCall && PerformTailCallOpt)
4199 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4201 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
4203 switch (CallingConv) {
4205 assert(0 && "Unsupported calling convention");
4206 case CallingConv::Fast:
4207 if (isTailCall && PerformTailCallOpt)
4208 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4210 return LowerCCCCallTo(Op,DAG, CallingConv);
4211 case CallingConv::C:
4212 case CallingConv::X86_StdCall:
4213 return LowerCCCCallTo(Op, DAG, CallingConv);
4214 case CallingConv::X86_FastCall:
4215 return LowerFastCCCallTo(Op, DAG, CallingConv);
4220 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4221 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4222 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4223 // that the guard pages used by the OS virtual memory manager are allocated in
4224 // correct sequence.
4226 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4227 SelectionDAG &DAG) {
4228 assert(Subtarget->isTargetCygMing() &&
4229 "This should be used only on Cygwin/Mingw targets");
4232 SDOperand Chain = Op.getOperand(0);
4233 SDOperand Size = Op.getOperand(1);
4234 // FIXME: Ensure alignment here
4238 MVT::ValueType IntPtr = getPointerTy();
4239 MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
4241 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4242 Flag = Chain.getValue(1);
4244 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4245 SDOperand Ops[] = { Chain,
4246 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4247 DAG.getRegister(X86::EAX, IntPtr),
4249 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4250 Flag = Chain.getValue(1);
4252 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4254 std::vector<MVT::ValueType> Tys;
4255 Tys.push_back(SPTy);
4256 Tys.push_back(MVT::Other);
4257 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4258 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4262 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
4263 MachineFunction &MF = DAG.getMachineFunction();
4264 const Function* Fn = MF.getFunction();
4265 if (Fn->hasExternalLinkage() &&
4266 Subtarget->isTargetCygMing() &&
4267 Fn->getName() == "main")
4268 MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
4270 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4271 if (Subtarget->is64Bit())
4272 return LowerX86_64CCCArguments(Op, DAG);
4276 assert(0 && "Unsupported calling convention");
4277 case CallingConv::Fast:
4278 return LowerCCCArguments(Op,DAG, true);
4280 case CallingConv::C:
4281 return LowerCCCArguments(Op, DAG);
4282 case CallingConv::X86_StdCall:
4283 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
4284 return LowerCCCArguments(Op, DAG, true);
4285 case CallingConv::X86_FastCall:
4286 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
4287 return LowerFastCCArguments(Op, DAG);
4291 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4292 SDOperand InFlag(0, 0);
4293 SDOperand Chain = Op.getOperand(0);
4295 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4296 if (Align == 0) Align = 1;
4298 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4299 // If not DWORD aligned or size is more than the threshold, call memset.
4300 // The libc version is likely to be faster for these cases. It can use the
4301 // address value and run time information about the CPU.
4302 if ((Align & 3) != 0 ||
4303 (I && I->getValue() > Subtarget->getMinRepStrSizeThreshold())) {
4304 MVT::ValueType IntPtr = getPointerTy();
4305 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4306 TargetLowering::ArgListTy Args;
4307 TargetLowering::ArgListEntry Entry;
4308 Entry.Node = Op.getOperand(1);
4309 Entry.Ty = IntPtrTy;
4310 Args.push_back(Entry);
4311 // Extend the unsigned i8 argument to be an int value for the call.
4312 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4313 Entry.Ty = IntPtrTy;
4314 Args.push_back(Entry);
4315 Entry.Node = Op.getOperand(3);
4316 Args.push_back(Entry);
4317 std::pair<SDOperand,SDOperand> CallResult =
4318 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4319 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4320 return CallResult.second;
4325 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4326 unsigned BytesLeft = 0;
4327 bool TwoRepStos = false;
4330 uint64_t Val = ValC->getValue() & 255;
4332 // If the value is a constant, then we can potentially use larger sets.
4333 switch (Align & 3) {
4334 case 2: // WORD aligned
4337 Val = (Val << 8) | Val;
4339 case 0: // DWORD aligned
4342 Val = (Val << 8) | Val;
4343 Val = (Val << 16) | Val;
4344 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4347 Val = (Val << 32) | Val;
4350 default: // Byte aligned
4353 Count = Op.getOperand(3);
4357 if (AVT > MVT::i8) {
4359 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4360 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
4361 BytesLeft = I->getValue() % UBytes;
4363 assert(AVT >= MVT::i32 &&
4364 "Do not use rep;stos if not at least DWORD aligned");
4365 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4366 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4371 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4373 InFlag = Chain.getValue(1);
4376 Count = Op.getOperand(3);
4377 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4378 InFlag = Chain.getValue(1);
4381 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4383 InFlag = Chain.getValue(1);
4384 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4385 Op.getOperand(1), InFlag);
4386 InFlag = Chain.getValue(1);
4388 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4389 SmallVector<SDOperand, 8> Ops;
4390 Ops.push_back(Chain);
4391 Ops.push_back(DAG.getValueType(AVT));
4392 Ops.push_back(InFlag);
4393 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4396 InFlag = Chain.getValue(1);
4397 Count = Op.getOperand(3);
4398 MVT::ValueType CVT = Count.getValueType();
4399 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4400 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4401 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4403 InFlag = Chain.getValue(1);
4404 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4406 Ops.push_back(Chain);
4407 Ops.push_back(DAG.getValueType(MVT::i8));
4408 Ops.push_back(InFlag);
4409 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4410 } else if (BytesLeft) {
4411 // Issue stores for the last 1 - 7 bytes.
4413 unsigned Val = ValC->getValue() & 255;
4414 unsigned Offset = I->getValue() - BytesLeft;
4415 SDOperand DstAddr = Op.getOperand(1);
4416 MVT::ValueType AddrVT = DstAddr.getValueType();
4417 if (BytesLeft >= 4) {
4418 Val = (Val << 8) | Val;
4419 Val = (Val << 16) | Val;
4420 Value = DAG.getConstant(Val, MVT::i32);
4421 Chain = DAG.getStore(Chain, Value,
4422 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4423 DAG.getConstant(Offset, AddrVT)),
4428 if (BytesLeft >= 2) {
4429 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4430 Chain = DAG.getStore(Chain, Value,
4431 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4432 DAG.getConstant(Offset, AddrVT)),
4437 if (BytesLeft == 1) {
4438 Value = DAG.getConstant(Val, MVT::i8);
4439 Chain = DAG.getStore(Chain, Value,
4440 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4441 DAG.getConstant(Offset, AddrVT)),
4449 SDOperand X86TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
4450 SDOperand ChainOp = Op.getOperand(0);
4451 SDOperand DestOp = Op.getOperand(1);
4452 SDOperand SourceOp = Op.getOperand(2);
4453 SDOperand CountOp = Op.getOperand(3);
4454 SDOperand AlignOp = Op.getOperand(4);
4455 unsigned Align = (unsigned)cast<ConstantSDNode>(AlignOp)->getValue();
4456 if (Align == 0) Align = 1;
4458 // The libc version is likely to be faster for the following cases. It can
4459 // use the address value and run time information about the CPU.
4460 // With glibc 2.6.1 on a core 2, coping an array of 100M longs was 30% faster
4462 // If not DWORD aligned, call memcpy.
4463 if ((Align & 3) != 0)
4464 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
4466 // If size is unknown, call memcpy.
4467 ConstantSDNode *I = dyn_cast<ConstantSDNode>(CountOp);
4469 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
4471 // If size is more than the threshold, call memcpy.
4472 unsigned Size = I->getValue();
4473 if (Size > Subtarget->getMinRepStrSizeThreshold())
4474 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
4476 return LowerMEMCPYInline(ChainOp, DestOp, SourceOp, Size, Align, DAG);
4479 SDOperand X86TargetLowering::LowerMEMCPYCall(SDOperand Chain,
4483 SelectionDAG &DAG) {
4484 MVT::ValueType IntPtr = getPointerTy();
4485 TargetLowering::ArgListTy Args;
4486 TargetLowering::ArgListEntry Entry;
4487 Entry.Ty = getTargetData()->getIntPtrType();
4488 Entry.Node = Dest; Args.push_back(Entry);
4489 Entry.Node = Source; Args.push_back(Entry);
4490 Entry.Node = Count; Args.push_back(Entry);
4491 std::pair<SDOperand,SDOperand> CallResult =
4492 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4493 DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
4494 return CallResult.second;
4497 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4502 SelectionDAG &DAG) {
4504 unsigned BytesLeft = 0;
4505 switch (Align & 3) {
4506 case 2: // WORD aligned
4509 case 0: // DWORD aligned
4511 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4514 default: // Byte aligned
4519 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4520 SDOperand Count = DAG.getConstant(Size / UBytes, getPointerTy());
4521 BytesLeft = Size % UBytes;
4523 SDOperand InFlag(0, 0);
4524 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4526 InFlag = Chain.getValue(1);
4527 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4529 InFlag = Chain.getValue(1);
4530 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4532 InFlag = Chain.getValue(1);
4534 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4535 SmallVector<SDOperand, 8> Ops;
4536 Ops.push_back(Chain);
4537 Ops.push_back(DAG.getValueType(AVT));
4538 Ops.push_back(InFlag);
4539 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4542 // Issue loads and stores for the last 1 - 7 bytes.
4543 unsigned Offset = Size - BytesLeft;
4544 SDOperand DstAddr = Dest;
4545 MVT::ValueType DstVT = DstAddr.getValueType();
4546 SDOperand SrcAddr = Source;
4547 MVT::ValueType SrcVT = SrcAddr.getValueType();
4549 if (BytesLeft >= 4) {
4550 Value = DAG.getLoad(MVT::i32, Chain,
4551 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4552 DAG.getConstant(Offset, SrcVT)),
4554 Chain = Value.getValue(1);
4555 Chain = DAG.getStore(Chain, Value,
4556 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4557 DAG.getConstant(Offset, DstVT)),
4562 if (BytesLeft >= 2) {
4563 Value = DAG.getLoad(MVT::i16, Chain,
4564 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4565 DAG.getConstant(Offset, SrcVT)),
4567 Chain = Value.getValue(1);
4568 Chain = DAG.getStore(Chain, Value,
4569 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4570 DAG.getConstant(Offset, DstVT)),
4576 if (BytesLeft == 1) {
4577 Value = DAG.getLoad(MVT::i8, Chain,
4578 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4579 DAG.getConstant(Offset, SrcVT)),
4581 Chain = Value.getValue(1);
4582 Chain = DAG.getStore(Chain, Value,
4583 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4584 DAG.getConstant(Offset, DstVT)),
4593 X86TargetLowering::LowerREADCYCLCECOUNTER(SDOperand Op, SelectionDAG &DAG) {
4594 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4595 SDOperand TheOp = Op.getOperand(0);
4596 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheOp, 1);
4597 if (Subtarget->is64Bit()) {
4599 DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4600 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::RDX,
4601 MVT::i64, Copy1.getValue(2));
4602 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, Copy2,
4603 DAG.getConstant(32, MVT::i8));
4605 DAG.getNode(ISD::OR, MVT::i64, Copy1, Tmp), Copy2.getValue(1)
4608 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4609 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2);
4612 SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4613 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::EDX,
4614 MVT::i32, Copy1.getValue(2));
4615 SDOperand Ops[] = { Copy1, Copy2, Copy2.getValue(1) };
4616 Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
4617 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 3);
4620 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4621 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
4623 if (!Subtarget->is64Bit()) {
4624 // vastart just stores the address of the VarArgsFrameIndex slot into the
4625 // memory location argument.
4626 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4627 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
4632 // gp_offset (0 - 6 * 8)
4633 // fp_offset (48 - 48 + 8 * 16)
4634 // overflow_arg_area (point to parameters coming in memory).
4636 SmallVector<SDOperand, 8> MemOps;
4637 SDOperand FIN = Op.getOperand(1);
4639 SDOperand Store = DAG.getStore(Op.getOperand(0),
4640 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4641 FIN, SV->getValue(), SV->getOffset());
4642 MemOps.push_back(Store);
4645 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4646 DAG.getConstant(4, getPointerTy()));
4647 Store = DAG.getStore(Op.getOperand(0),
4648 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4649 FIN, SV->getValue(), SV->getOffset());
4650 MemOps.push_back(Store);
4652 // Store ptr to overflow_arg_area
4653 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4654 DAG.getConstant(4, getPointerTy()));
4655 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4656 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
4658 MemOps.push_back(Store);
4660 // Store ptr to reg_save_area.
4661 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4662 DAG.getConstant(8, getPointerTy()));
4663 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4664 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
4666 MemOps.push_back(Store);
4667 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4670 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4671 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4672 SDOperand Chain = Op.getOperand(0);
4673 SDOperand DstPtr = Op.getOperand(1);
4674 SDOperand SrcPtr = Op.getOperand(2);
4675 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
4676 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
4678 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
4679 SrcSV->getValue(), SrcSV->getOffset());
4680 Chain = SrcPtr.getValue(1);
4681 for (unsigned i = 0; i < 3; ++i) {
4682 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
4683 SrcSV->getValue(), SrcSV->getOffset());
4684 Chain = Val.getValue(1);
4685 Chain = DAG.getStore(Chain, Val, DstPtr,
4686 DstSV->getValue(), DstSV->getOffset());
4689 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
4690 DAG.getConstant(8, getPointerTy()));
4691 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
4692 DAG.getConstant(8, getPointerTy()));
4698 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4699 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4701 default: return SDOperand(); // Don't custom lower most intrinsics.
4702 // Comparison intrinsics.
4703 case Intrinsic::x86_sse_comieq_ss:
4704 case Intrinsic::x86_sse_comilt_ss:
4705 case Intrinsic::x86_sse_comile_ss:
4706 case Intrinsic::x86_sse_comigt_ss:
4707 case Intrinsic::x86_sse_comige_ss:
4708 case Intrinsic::x86_sse_comineq_ss:
4709 case Intrinsic::x86_sse_ucomieq_ss:
4710 case Intrinsic::x86_sse_ucomilt_ss:
4711 case Intrinsic::x86_sse_ucomile_ss:
4712 case Intrinsic::x86_sse_ucomigt_ss:
4713 case Intrinsic::x86_sse_ucomige_ss:
4714 case Intrinsic::x86_sse_ucomineq_ss:
4715 case Intrinsic::x86_sse2_comieq_sd:
4716 case Intrinsic::x86_sse2_comilt_sd:
4717 case Intrinsic::x86_sse2_comile_sd:
4718 case Intrinsic::x86_sse2_comigt_sd:
4719 case Intrinsic::x86_sse2_comige_sd:
4720 case Intrinsic::x86_sse2_comineq_sd:
4721 case Intrinsic::x86_sse2_ucomieq_sd:
4722 case Intrinsic::x86_sse2_ucomilt_sd:
4723 case Intrinsic::x86_sse2_ucomile_sd:
4724 case Intrinsic::x86_sse2_ucomigt_sd:
4725 case Intrinsic::x86_sse2_ucomige_sd:
4726 case Intrinsic::x86_sse2_ucomineq_sd: {
4728 ISD::CondCode CC = ISD::SETCC_INVALID;
4731 case Intrinsic::x86_sse_comieq_ss:
4732 case Intrinsic::x86_sse2_comieq_sd:
4736 case Intrinsic::x86_sse_comilt_ss:
4737 case Intrinsic::x86_sse2_comilt_sd:
4741 case Intrinsic::x86_sse_comile_ss:
4742 case Intrinsic::x86_sse2_comile_sd:
4746 case Intrinsic::x86_sse_comigt_ss:
4747 case Intrinsic::x86_sse2_comigt_sd:
4751 case Intrinsic::x86_sse_comige_ss:
4752 case Intrinsic::x86_sse2_comige_sd:
4756 case Intrinsic::x86_sse_comineq_ss:
4757 case Intrinsic::x86_sse2_comineq_sd:
4761 case Intrinsic::x86_sse_ucomieq_ss:
4762 case Intrinsic::x86_sse2_ucomieq_sd:
4763 Opc = X86ISD::UCOMI;
4766 case Intrinsic::x86_sse_ucomilt_ss:
4767 case Intrinsic::x86_sse2_ucomilt_sd:
4768 Opc = X86ISD::UCOMI;
4771 case Intrinsic::x86_sse_ucomile_ss:
4772 case Intrinsic::x86_sse2_ucomile_sd:
4773 Opc = X86ISD::UCOMI;
4776 case Intrinsic::x86_sse_ucomigt_ss:
4777 case Intrinsic::x86_sse2_ucomigt_sd:
4778 Opc = X86ISD::UCOMI;
4781 case Intrinsic::x86_sse_ucomige_ss:
4782 case Intrinsic::x86_sse2_ucomige_sd:
4783 Opc = X86ISD::UCOMI;
4786 case Intrinsic::x86_sse_ucomineq_ss:
4787 case Intrinsic::x86_sse2_ucomineq_sd:
4788 Opc = X86ISD::UCOMI;
4794 SDOperand LHS = Op.getOperand(1);
4795 SDOperand RHS = Op.getOperand(2);
4796 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4798 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
4799 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
4800 DAG.getConstant(X86CC, MVT::i8), Cond);
4801 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
4806 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4807 // Depths > 0 not supported yet!
4808 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4811 // Just load the return address
4812 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4813 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4816 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4817 // Depths > 0 not supported yet!
4818 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4821 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4822 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
4823 DAG.getConstant(4, getPointerTy()));
4826 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
4827 SelectionDAG &DAG) {
4828 // Is not yet supported on x86-64
4829 if (Subtarget->is64Bit())
4832 return DAG.getConstant(8, getPointerTy());
4835 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
4837 assert(!Subtarget->is64Bit() &&
4838 "Lowering of eh_return builtin is not supported yet on x86-64");
4840 MachineFunction &MF = DAG.getMachineFunction();
4841 SDOperand Chain = Op.getOperand(0);
4842 SDOperand Offset = Op.getOperand(1);
4843 SDOperand Handler = Op.getOperand(2);
4845 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
4848 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
4849 DAG.getConstant(-4UL, getPointerTy()));
4850 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
4851 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
4852 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
4853 MF.addLiveOut(X86::ECX);
4855 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
4856 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
4859 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
4860 SelectionDAG &DAG) {
4861 SDOperand Root = Op.getOperand(0);
4862 SDOperand Trmp = Op.getOperand(1); // trampoline
4863 SDOperand FPtr = Op.getOperand(2); // nested function
4864 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
4866 SrcValueSDNode *TrmpSV = cast<SrcValueSDNode>(Op.getOperand(4));
4868 if (Subtarget->is64Bit()) {
4869 return SDOperand(); // not yet supported
4871 Function *Func = (Function *)
4872 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
4873 unsigned CC = Func->getCallingConv();
4878 assert(0 && "Unsupported calling convention");
4879 case CallingConv::C:
4880 case CallingConv::X86_StdCall: {
4881 // Pass 'nest' parameter in ECX.
4882 // Must be kept in sync with X86CallingConv.td
4885 // Check that ECX wasn't needed by an 'inreg' parameter.
4886 const FunctionType *FTy = Func->getFunctionType();
4887 const ParamAttrsList *Attrs = FTy->getParamAttrs();
4889 if (Attrs && !Func->isVarArg()) {
4890 unsigned InRegCount = 0;
4893 for (FunctionType::param_iterator I = FTy->param_begin(),
4894 E = FTy->param_end(); I != E; ++I, ++Idx)
4895 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
4896 // FIXME: should only count parameters that are lowered to integers.
4897 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
4899 if (InRegCount > 2) {
4900 cerr << "Nest register in use - reduce number of inreg parameters!\n";
4906 case CallingConv::X86_FastCall:
4907 // Pass 'nest' parameter in EAX.
4908 // Must be kept in sync with X86CallingConv.td
4913 const X86InstrInfo *TII =
4914 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
4916 SDOperand OutChains[4];
4917 SDOperand Addr, Disp;
4919 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
4920 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
4922 unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
4923 unsigned char N86Reg = ((X86RegisterInfo&)RegInfo).getX86RegNum(NestReg);
4924 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
4925 Trmp, TrmpSV->getValue(), TrmpSV->getOffset());
4927 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
4928 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpSV->getValue(),
4929 TrmpSV->getOffset() + 1, false, 1);
4931 unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
4932 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
4933 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
4934 TrmpSV->getValue() + 5, TrmpSV->getOffset());
4936 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
4937 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpSV->getValue(),
4938 TrmpSV->getOffset() + 6, false, 1);
4941 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
4942 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
4946 /// LowerOperation - Provide custom lowering hooks for some operations.
4948 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4949 switch (Op.getOpcode()) {
4950 default: assert(0 && "Should not custom lower this!");
4951 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
4952 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
4953 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4954 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
4955 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
4956 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
4957 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
4958 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
4959 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
4960 case ISD::SHL_PARTS:
4961 case ISD::SRA_PARTS:
4962 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
4963 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
4964 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
4965 case ISD::FABS: return LowerFABS(Op, DAG);
4966 case ISD::FNEG: return LowerFNEG(Op, DAG);
4967 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
4968 case ISD::SETCC: return LowerSETCC(Op, DAG);
4969 case ISD::SELECT: return LowerSELECT(Op, DAG);
4970 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4971 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
4972 case ISD::CALL: return LowerCALL(Op, DAG);
4973 case ISD::RET: return LowerRET(Op, DAG);
4974 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
4975 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
4976 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
4977 case ISD::READCYCLECOUNTER: return LowerREADCYCLCECOUNTER(Op, DAG);
4978 case ISD::VASTART: return LowerVASTART(Op, DAG);
4979 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
4980 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4981 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4982 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
4983 case ISD::FRAME_TO_ARGS_OFFSET:
4984 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
4985 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
4986 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
4987 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
4992 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
4994 default: return NULL;
4995 case X86ISD::SHLD: return "X86ISD::SHLD";
4996 case X86ISD::SHRD: return "X86ISD::SHRD";
4997 case X86ISD::FAND: return "X86ISD::FAND";
4998 case X86ISD::FOR: return "X86ISD::FOR";
4999 case X86ISD::FXOR: return "X86ISD::FXOR";
5000 case X86ISD::FSRL: return "X86ISD::FSRL";
5001 case X86ISD::FILD: return "X86ISD::FILD";
5002 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5003 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5004 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5005 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5006 case X86ISD::FLD: return "X86ISD::FLD";
5007 case X86ISD::FST: return "X86ISD::FST";
5008 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5009 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5010 case X86ISD::CALL: return "X86ISD::CALL";
5011 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5012 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5013 case X86ISD::CMP: return "X86ISD::CMP";
5014 case X86ISD::COMI: return "X86ISD::COMI";
5015 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5016 case X86ISD::SETCC: return "X86ISD::SETCC";
5017 case X86ISD::CMOV: return "X86ISD::CMOV";
5018 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5019 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5020 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5021 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5022 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5023 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5024 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5025 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5026 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5027 case X86ISD::FMAX: return "X86ISD::FMAX";
5028 case X86ISD::FMIN: return "X86ISD::FMIN";
5029 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5030 case X86ISD::FRCP: return "X86ISD::FRCP";
5031 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5032 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5033 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5034 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5038 // isLegalAddressingMode - Return true if the addressing mode represented
5039 // by AM is legal for this target, for a load/store of the specified type.
5040 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5041 const Type *Ty) const {
5042 // X86 supports extremely general addressing modes.
5044 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5045 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5049 // We can only fold this if we don't need an extra load.
5050 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5053 // X86-64 only supports addr of globals in small code model.
5054 if (Subtarget->is64Bit()) {
5055 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5057 // If lower 4G is not available, then we must use rip-relative addressing.
5058 if (AM.BaseOffs || AM.Scale > 1)
5069 // These scales always work.
5074 // These scales are formed with basereg+scalereg. Only accept if there is
5079 default: // Other stuff never works.
5087 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5088 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5089 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5090 /// are assumed to be legal.
5092 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5093 // Only do shuffles on 128-bit vector types for now.
5094 if (MVT::getSizeInBits(VT) == 64) return false;
5095 return (Mask.Val->getNumOperands() <= 4 ||
5096 isIdentityMask(Mask.Val) ||
5097 isIdentityMask(Mask.Val, true) ||
5098 isSplatMask(Mask.Val) ||
5099 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5100 X86::isUNPCKLMask(Mask.Val) ||
5101 X86::isUNPCKHMask(Mask.Val) ||
5102 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5103 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5106 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5108 SelectionDAG &DAG) const {
5109 unsigned NumElts = BVOps.size();
5110 // Only do shuffles on 128-bit vector types for now.
5111 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5112 if (NumElts == 2) return true;
5114 return (isMOVLMask(&BVOps[0], 4) ||
5115 isCommutedMOVL(&BVOps[0], 4, true) ||
5116 isSHUFPMask(&BVOps[0], 4) ||
5117 isCommutedSHUFP(&BVOps[0], 4));
5122 //===----------------------------------------------------------------------===//
5123 // X86 Scheduler Hooks
5124 //===----------------------------------------------------------------------===//
5127 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
5128 MachineBasicBlock *BB) {
5129 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5130 switch (MI->getOpcode()) {
5131 default: assert(false && "Unexpected instr type to insert");
5132 case X86::CMOV_FR32:
5133 case X86::CMOV_FR64:
5134 case X86::CMOV_V4F32:
5135 case X86::CMOV_V2F64:
5136 case X86::CMOV_V2I64: {
5137 // To "insert" a SELECT_CC instruction, we actually have to insert the
5138 // diamond control-flow pattern. The incoming instruction knows the
5139 // destination vreg to set, the condition code register to branch on, the
5140 // true/false values to select between, and a branch opcode to use.
5141 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5142 ilist<MachineBasicBlock>::iterator It = BB;
5148 // cmpTY ccX, r1, r2
5150 // fallthrough --> copy0MBB
5151 MachineBasicBlock *thisMBB = BB;
5152 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5153 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5155 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5156 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5157 MachineFunction *F = BB->getParent();
5158 F->getBasicBlockList().insert(It, copy0MBB);
5159 F->getBasicBlockList().insert(It, sinkMBB);
5160 // Update machine-CFG edges by first adding all successors of the current
5161 // block to the new block which will contain the Phi node for the select.
5162 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5163 e = BB->succ_end(); i != e; ++i)
5164 sinkMBB->addSuccessor(*i);
5165 // Next, remove all successors of the current block, and add the true
5166 // and fallthrough blocks as its successors.
5167 while(!BB->succ_empty())
5168 BB->removeSuccessor(BB->succ_begin());
5169 BB->addSuccessor(copy0MBB);
5170 BB->addSuccessor(sinkMBB);
5173 // %FalseValue = ...
5174 // # fallthrough to sinkMBB
5177 // Update machine-CFG edges
5178 BB->addSuccessor(sinkMBB);
5181 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5184 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5185 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5186 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5188 delete MI; // The pseudo instruction is gone now.
5192 case X86::FP32_TO_INT16_IN_MEM:
5193 case X86::FP32_TO_INT32_IN_MEM:
5194 case X86::FP32_TO_INT64_IN_MEM:
5195 case X86::FP64_TO_INT16_IN_MEM:
5196 case X86::FP64_TO_INT32_IN_MEM:
5197 case X86::FP64_TO_INT64_IN_MEM:
5198 case X86::FP80_TO_INT16_IN_MEM:
5199 case X86::FP80_TO_INT32_IN_MEM:
5200 case X86::FP80_TO_INT64_IN_MEM: {
5201 // Change the floating point control register to use "round towards zero"
5202 // mode when truncating to an integer value.
5203 MachineFunction *F = BB->getParent();
5204 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5205 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5207 // Load the old value of the high byte of the control word...
5209 F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
5210 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5212 // Set the high part to be round to zero...
5213 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5216 // Reload the modified control word now...
5217 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5219 // Restore the memory image of control word to original value
5220 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5223 // Get the X86 opcode to use.
5225 switch (MI->getOpcode()) {
5226 default: assert(0 && "illegal opcode!");
5227 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5228 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5229 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5230 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5231 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5232 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5233 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5234 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5235 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5239 MachineOperand &Op = MI->getOperand(0);
5240 if (Op.isRegister()) {
5241 AM.BaseType = X86AddressMode::RegBase;
5242 AM.Base.Reg = Op.getReg();
5244 AM.BaseType = X86AddressMode::FrameIndexBase;
5245 AM.Base.FrameIndex = Op.getFrameIndex();
5247 Op = MI->getOperand(1);
5248 if (Op.isImmediate())
5249 AM.Scale = Op.getImm();
5250 Op = MI->getOperand(2);
5251 if (Op.isImmediate())
5252 AM.IndexReg = Op.getImm();
5253 Op = MI->getOperand(3);
5254 if (Op.isGlobalAddress()) {
5255 AM.GV = Op.getGlobal();
5257 AM.Disp = Op.getImm();
5259 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5260 .addReg(MI->getOperand(4).getReg());
5262 // Reload the original control word now.
5263 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5265 delete MI; // The pseudo instruction is gone now.
5271 //===----------------------------------------------------------------------===//
5272 // X86 Optimization Hooks
5273 //===----------------------------------------------------------------------===//
5275 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5277 uint64_t &KnownZero,
5279 const SelectionDAG &DAG,
5280 unsigned Depth) const {
5281 unsigned Opc = Op.getOpcode();
5282 assert((Opc >= ISD::BUILTIN_OP_END ||
5283 Opc == ISD::INTRINSIC_WO_CHAIN ||
5284 Opc == ISD::INTRINSIC_W_CHAIN ||
5285 Opc == ISD::INTRINSIC_VOID) &&
5286 "Should use MaskedValueIsZero if you don't know whether Op"
5287 " is a target node!");
5289 KnownZero = KnownOne = 0; // Don't know anything.
5293 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5298 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5299 /// element of the result of the vector shuffle.
5300 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5301 MVT::ValueType VT = N->getValueType(0);
5302 SDOperand PermMask = N->getOperand(2);
5303 unsigned NumElems = PermMask.getNumOperands();
5304 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5306 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5308 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5309 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5310 SDOperand Idx = PermMask.getOperand(i);
5311 if (Idx.getOpcode() == ISD::UNDEF)
5312 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5313 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5318 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5319 /// node is a GlobalAddress + an offset.
5320 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5321 unsigned Opc = N->getOpcode();
5322 if (Opc == X86ISD::Wrapper) {
5323 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5324 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5327 } else if (Opc == ISD::ADD) {
5328 SDOperand N1 = N->getOperand(0);
5329 SDOperand N2 = N->getOperand(1);
5330 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5331 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5333 Offset += V->getSignExtended();
5336 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5337 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5339 Offset += V->getSignExtended();
5347 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5349 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5350 MachineFrameInfo *MFI) {
5351 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5354 SDOperand Loc = N->getOperand(1);
5355 SDOperand BaseLoc = Base->getOperand(1);
5356 if (Loc.getOpcode() == ISD::FrameIndex) {
5357 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5359 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5360 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5361 int FS = MFI->getObjectSize(FI);
5362 int BFS = MFI->getObjectSize(BFI);
5363 if (FS != BFS || FS != Size) return false;
5364 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5366 GlobalValue *GV1 = NULL;
5367 GlobalValue *GV2 = NULL;
5368 int64_t Offset1 = 0;
5369 int64_t Offset2 = 0;
5370 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5371 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5372 if (isGA1 && isGA2 && GV1 == GV2)
5373 return Offset1 == (Offset2 + Dist*Size);
5379 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5380 const X86Subtarget *Subtarget) {
5383 if (isGAPlusOffset(Base, GV, Offset))
5384 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5386 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
5387 int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
5389 // Fixed objects do not specify alignment, however the offsets are known.
5390 return ((Subtarget->getStackAlignment() % 16) == 0 &&
5391 (MFI->getObjectOffset(BFI) % 16) == 0);
5393 return MFI->getObjectAlignment(BFI) >= 16;
5399 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5400 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5401 /// if the load addresses are consecutive, non-overlapping, and in the right
5403 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5404 const X86Subtarget *Subtarget) {
5405 MachineFunction &MF = DAG.getMachineFunction();
5406 MachineFrameInfo *MFI = MF.getFrameInfo();
5407 MVT::ValueType VT = N->getValueType(0);
5408 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5409 SDOperand PermMask = N->getOperand(2);
5410 int NumElems = (int)PermMask.getNumOperands();
5411 SDNode *Base = NULL;
5412 for (int i = 0; i < NumElems; ++i) {
5413 SDOperand Idx = PermMask.getOperand(i);
5414 if (Idx.getOpcode() == ISD::UNDEF) {
5415 if (!Base) return SDOperand();
5418 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5419 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5423 else if (!isConsecutiveLoad(Arg.Val, Base,
5424 i, MVT::getSizeInBits(EVT)/8,MFI))
5429 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5430 LoadSDNode *LD = cast<LoadSDNode>(Base);
5432 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5433 LD->getSrcValueOffset(), LD->isVolatile());
5435 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5436 LD->getSrcValueOffset(), LD->isVolatile(),
5437 LD->getAlignment());
5441 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5442 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5443 const X86Subtarget *Subtarget) {
5444 SDOperand Cond = N->getOperand(0);
5446 // If we have SSE[12] support, try to form min/max nodes.
5447 if (Subtarget->hasSSE2() &&
5448 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5449 if (Cond.getOpcode() == ISD::SETCC) {
5450 // Get the LHS/RHS of the select.
5451 SDOperand LHS = N->getOperand(1);
5452 SDOperand RHS = N->getOperand(2);
5453 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5455 unsigned Opcode = 0;
5456 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5459 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5462 if (!UnsafeFPMath) break;
5464 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
5466 Opcode = X86ISD::FMIN;
5469 case ISD::SETOGT: // (X > Y) ? X : Y -> max
5472 if (!UnsafeFPMath) break;
5474 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
5476 Opcode = X86ISD::FMAX;
5479 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5482 case ISD::SETOGT: // (X > Y) ? Y : X -> min
5485 if (!UnsafeFPMath) break;
5487 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
5489 Opcode = X86ISD::FMIN;
5492 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
5495 if (!UnsafeFPMath) break;
5497 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
5499 Opcode = X86ISD::FMAX;
5505 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5514 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5515 DAGCombinerInfo &DCI) const {
5516 SelectionDAG &DAG = DCI.DAG;
5517 switch (N->getOpcode()) {
5519 case ISD::VECTOR_SHUFFLE:
5520 return PerformShuffleCombine(N, DAG, Subtarget);
5522 return PerformSELECTCombine(N, DAG, Subtarget);
5528 //===----------------------------------------------------------------------===//
5529 // X86 Inline Assembly Support
5530 //===----------------------------------------------------------------------===//
5532 /// getConstraintType - Given a constraint letter, return the type of
5533 /// constraint it is for this target.
5534 X86TargetLowering::ConstraintType
5535 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
5536 if (Constraint.size() == 1) {
5537 switch (Constraint[0]) {
5546 return C_RegisterClass;
5551 return TargetLowering::getConstraintType(Constraint);
5554 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5555 /// vector. If it is invalid, don't add anything to Ops.
5556 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
5558 std::vector<SDOperand>&Ops,
5559 SelectionDAG &DAG) {
5560 SDOperand Result(0, 0);
5562 switch (Constraint) {
5565 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5566 if (C->getValue() <= 31) {
5567 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5573 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5574 if (C->getValue() <= 255) {
5575 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5581 // Literal immediates are always ok.
5582 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
5583 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
5587 // If we are in non-pic codegen mode, we allow the address of a global (with
5588 // an optional displacement) to be used with 'i'.
5589 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
5592 // Match either (GA) or (GA+C)
5594 Offset = GA->getOffset();
5595 } else if (Op.getOpcode() == ISD::ADD) {
5596 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5597 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5599 Offset = GA->getOffset()+C->getValue();
5601 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5602 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5604 Offset = GA->getOffset()+C->getValue();
5611 // If addressing this global requires a load (e.g. in PIC mode), we can't
5613 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
5617 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5623 // Otherwise, not valid for this mode.
5629 Ops.push_back(Result);
5632 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5635 std::vector<unsigned> X86TargetLowering::
5636 getRegClassForInlineAsmConstraint(const std::string &Constraint,
5637 MVT::ValueType VT) const {
5638 if (Constraint.size() == 1) {
5639 // FIXME: not handling fp-stack yet!
5640 switch (Constraint[0]) { // GCC X86 Constraint Letters
5641 default: break; // Unknown constraint letter
5642 case 'A': // EAX/EDX
5643 if (VT == MVT::i32 || VT == MVT::i64)
5644 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
5646 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
5649 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
5650 else if (VT == MVT::i16)
5651 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
5652 else if (VT == MVT::i8)
5653 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
5658 return std::vector<unsigned>();
5661 std::pair<unsigned, const TargetRegisterClass*>
5662 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
5663 MVT::ValueType VT) const {
5664 // First, see if this is a constraint that directly corresponds to an LLVM
5666 if (Constraint.size() == 1) {
5667 // GCC Constraint Letters
5668 switch (Constraint[0]) {
5670 case 'r': // GENERAL_REGS
5671 case 'R': // LEGACY_REGS
5672 case 'l': // INDEX_REGS
5673 if (VT == MVT::i64 && Subtarget->is64Bit())
5674 return std::make_pair(0U, X86::GR64RegisterClass);
5676 return std::make_pair(0U, X86::GR32RegisterClass);
5677 else if (VT == MVT::i16)
5678 return std::make_pair(0U, X86::GR16RegisterClass);
5679 else if (VT == MVT::i8)
5680 return std::make_pair(0U, X86::GR8RegisterClass);
5682 case 'y': // MMX_REGS if MMX allowed.
5683 if (!Subtarget->hasMMX()) break;
5684 return std::make_pair(0U, X86::VR64RegisterClass);
5686 case 'Y': // SSE_REGS if SSE2 allowed
5687 if (!Subtarget->hasSSE2()) break;
5689 case 'x': // SSE_REGS if SSE1 allowed
5690 if (!Subtarget->hasSSE1()) break;
5694 // Scalar SSE types.
5697 return std::make_pair(0U, X86::FR32RegisterClass);
5700 return std::make_pair(0U, X86::FR64RegisterClass);
5708 return std::make_pair(0U, X86::VR128RegisterClass);
5714 // Use the default implementation in TargetLowering to convert the register
5715 // constraint into a member of a register class.
5716 std::pair<unsigned, const TargetRegisterClass*> Res;
5717 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
5719 // Not found as a standard register?
5720 if (Res.second == 0) {
5721 // GCC calls "st(0)" just plain "st".
5722 if (StringsEqualNoCase("{st}", Constraint)) {
5723 Res.first = X86::ST0;
5724 Res.second = X86::RFP80RegisterClass;
5730 // Otherwise, check to see if this is a register class of the wrong value
5731 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
5732 // turn into {ax},{dx}.
5733 if (Res.second->hasType(VT))
5734 return Res; // Correct type already, nothing to do.
5736 // All of the single-register GCC register classes map their values onto
5737 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
5738 // really want an 8-bit or 32-bit register, map to the appropriate register
5739 // class and return the appropriate register.
5740 if (Res.second != X86::GR16RegisterClass)
5743 if (VT == MVT::i8) {
5744 unsigned DestReg = 0;
5745 switch (Res.first) {
5747 case X86::AX: DestReg = X86::AL; break;
5748 case X86::DX: DestReg = X86::DL; break;
5749 case X86::CX: DestReg = X86::CL; break;
5750 case X86::BX: DestReg = X86::BL; break;
5753 Res.first = DestReg;
5754 Res.second = Res.second = X86::GR8RegisterClass;
5756 } else if (VT == MVT::i32) {
5757 unsigned DestReg = 0;
5758 switch (Res.first) {
5760 case X86::AX: DestReg = X86::EAX; break;
5761 case X86::DX: DestReg = X86::EDX; break;
5762 case X86::CX: DestReg = X86::ECX; break;
5763 case X86::BX: DestReg = X86::EBX; break;
5764 case X86::SI: DestReg = X86::ESI; break;
5765 case X86::DI: DestReg = X86::EDI; break;
5766 case X86::BP: DestReg = X86::EBP; break;
5767 case X86::SP: DestReg = X86::ESP; break;
5770 Res.first = DestReg;
5771 Res.second = Res.second = X86::GR32RegisterClass;
5773 } else if (VT == MVT::i64) {
5774 unsigned DestReg = 0;
5775 switch (Res.first) {
5777 case X86::AX: DestReg = X86::RAX; break;
5778 case X86::DX: DestReg = X86::RDX; break;
5779 case X86::CX: DestReg = X86::RCX; break;
5780 case X86::BX: DestReg = X86::RBX; break;
5781 case X86::SI: DestReg = X86::RSI; break;
5782 case X86::DI: DestReg = X86::RDI; break;
5783 case X86::BP: DestReg = X86::RBP; break;
5784 case X86::SP: DestReg = X86::RSP; break;
5787 Res.first = DestReg;
5788 Res.second = Res.second = X86::GR64RegisterClass;