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/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/CodeGen/SSARegMap.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/ParameterAttributes.h"
44 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
45 : TargetLowering(TM) {
46 Subtarget = &TM.getSubtarget<X86Subtarget>();
47 X86ScalarSSEf64 = Subtarget->hasSSE2();
48 X86ScalarSSEf32 = Subtarget->hasSSE1();
49 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
52 RegInfo = TM.getRegisterInfo();
54 // Set up the TargetLowering object.
56 // X86 is weird, it always uses i8 for shift amounts and setcc results.
57 setShiftAmountType(MVT::i8);
58 setSetCCResultType(MVT::i8);
59 setSetCCResultContents(ZeroOrOneSetCCResult);
60 setSchedulingPreference(SchedulingForRegPressure);
61 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
62 setStackPointerRegisterToSaveRestore(X86StackPtr);
64 if (Subtarget->isTargetDarwin()) {
65 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
66 setUseUnderscoreSetJmp(false);
67 setUseUnderscoreLongJmp(false);
68 } else if (Subtarget->isTargetMingw()) {
69 // MS runtime is weird: it exports _setjmp, but longjmp!
70 setUseUnderscoreSetJmp(true);
71 setUseUnderscoreLongJmp(false);
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(true);
77 // Set up the register classes.
78 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
79 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
80 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
81 if (Subtarget->is64Bit())
82 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
84 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
86 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
88 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
89 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
90 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
92 if (Subtarget->is64Bit()) {
93 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
94 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
97 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
98 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
100 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
103 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
105 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
106 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
107 // SSE has no i16 to fp conversion, only i32
108 if (X86ScalarSSEf32) {
109 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
110 // f32 and f64 cases are Legal, f80 case is not
111 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
113 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
114 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
117 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
118 // are Legal, f80 is custom lowered.
119 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
120 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
122 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
124 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
125 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
127 if (X86ScalarSSEf32) {
128 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
129 // f32 and f64 cases are Legal, f80 case is not
130 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
132 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
133 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
136 // Handle FP_TO_UINT by promoting the destination to a larger signed
138 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
139 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
140 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
142 if (Subtarget->is64Bit()) {
143 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
144 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
146 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
147 // Expand FP_TO_UINT into a select.
148 // FIXME: We would like to use a Custom expander here eventually to do
149 // the optimal thing for SSE vs. the default expansion in the legalizer.
150 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
152 // With SSE3 we can use fisttpll to convert to a signed i64.
153 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
156 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
157 if (!X86ScalarSSEf64) {
158 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
159 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
162 // Scalar integer multiply, multiply-high, divide, and remainder are
163 // lowered to use operations that produce two results, to match the
164 // available instructions. This exposes the two-result form to trivial
165 // CSE, which is able to combine x/y and x%y into a single instruction,
166 // for example. The single-result multiply instructions are introduced
167 // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
169 setOperationAction(ISD::MUL , MVT::i8 , Expand);
170 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
171 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
172 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
173 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
174 setOperationAction(ISD::SREM , MVT::i8 , Expand);
175 setOperationAction(ISD::UREM , MVT::i8 , Expand);
176 setOperationAction(ISD::MUL , MVT::i16 , Expand);
177 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
178 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
179 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
180 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
181 setOperationAction(ISD::SREM , MVT::i16 , Expand);
182 setOperationAction(ISD::UREM , MVT::i16 , Expand);
183 setOperationAction(ISD::MUL , MVT::i32 , Expand);
184 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
185 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
186 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
187 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
188 setOperationAction(ISD::SREM , MVT::i32 , Expand);
189 setOperationAction(ISD::UREM , MVT::i32 , Expand);
190 setOperationAction(ISD::MUL , MVT::i64 , Expand);
191 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
192 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
193 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
194 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
195 setOperationAction(ISD::SREM , MVT::i64 , Expand);
196 setOperationAction(ISD::UREM , MVT::i64 , Expand);
198 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
199 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
200 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
201 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
202 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
203 if (Subtarget->is64Bit())
204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
206 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
207 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
208 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
209 setOperationAction(ISD::FREM , MVT::f64 , Expand);
210 setOperationAction(ISD::FLT_ROUNDS , MVT::i32 , Custom);
212 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
213 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
214 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
215 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
216 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
217 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
218 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
219 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
220 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
221 if (Subtarget->is64Bit()) {
222 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
223 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
224 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
227 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
228 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
230 // These should be promoted to a larger select which is supported.
231 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
232 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
233 // X86 wants to expand cmov itself.
234 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
235 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
236 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
237 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
238 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
239 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
240 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
241 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
242 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
243 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
244 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
245 if (Subtarget->is64Bit()) {
246 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
247 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
249 // X86 ret instruction may pop stack.
250 setOperationAction(ISD::RET , MVT::Other, Custom);
251 if (!Subtarget->is64Bit())
252 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
255 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
256 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
257 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
258 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
259 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
260 if (Subtarget->is64Bit()) {
261 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
262 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
263 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
264 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
266 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
267 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
268 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
269 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
270 // X86 wants to expand memset / memcpy itself.
271 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
272 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
274 // Use the default ISD::LOCATION expansion.
275 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
276 // FIXME - use subtarget debug flags
277 if (!Subtarget->isTargetDarwin() &&
278 !Subtarget->isTargetELF() &&
279 !Subtarget->isTargetCygMing())
280 setOperationAction(ISD::LABEL, MVT::Other, Expand);
282 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
283 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
284 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
285 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
286 if (Subtarget->is64Bit()) {
288 setExceptionPointerRegister(X86::RAX);
289 setExceptionSelectorRegister(X86::RDX);
291 setExceptionPointerRegister(X86::EAX);
292 setExceptionSelectorRegister(X86::EDX);
294 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
296 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
298 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
299 setOperationAction(ISD::VASTART , MVT::Other, Custom);
300 setOperationAction(ISD::VAARG , MVT::Other, Expand);
301 setOperationAction(ISD::VAEND , MVT::Other, Expand);
302 if (Subtarget->is64Bit())
303 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
305 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
307 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
308 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
309 if (Subtarget->is64Bit())
310 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
311 if (Subtarget->isTargetCygMing())
312 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
314 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
316 if (X86ScalarSSEf64) {
317 // f32 and f64 use SSE.
318 // Set up the FP register classes.
319 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
320 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
322 // Use ANDPD to simulate FABS.
323 setOperationAction(ISD::FABS , MVT::f64, Custom);
324 setOperationAction(ISD::FABS , MVT::f32, Custom);
326 // Use XORP to simulate FNEG.
327 setOperationAction(ISD::FNEG , MVT::f64, Custom);
328 setOperationAction(ISD::FNEG , MVT::f32, Custom);
330 // Use ANDPD and ORPD to simulate FCOPYSIGN.
331 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
332 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
334 // We don't support sin/cos/fmod
335 setOperationAction(ISD::FSIN , MVT::f64, Expand);
336 setOperationAction(ISD::FCOS , MVT::f64, Expand);
337 setOperationAction(ISD::FREM , MVT::f64, Expand);
338 setOperationAction(ISD::FSIN , MVT::f32, Expand);
339 setOperationAction(ISD::FCOS , MVT::f32, Expand);
340 setOperationAction(ISD::FREM , MVT::f32, Expand);
342 // Expand FP immediates into loads from the stack, except for the special
344 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
345 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
346 addLegalFPImmediate(APFloat(+0.0)); // xorpd
347 addLegalFPImmediate(APFloat(+0.0f)); // xorps
349 // Conversions to long double (in X87) go through memory.
350 setConvertAction(MVT::f32, MVT::f80, Expand);
351 setConvertAction(MVT::f64, MVT::f80, Expand);
353 // Conversions from long double (in X87) go through memory.
354 setConvertAction(MVT::f80, MVT::f32, Expand);
355 setConvertAction(MVT::f80, MVT::f64, Expand);
356 } else if (X86ScalarSSEf32) {
357 // Use SSE for f32, x87 for f64.
358 // Set up the FP register classes.
359 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
360 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
362 // Use ANDPS to simulate FABS.
363 setOperationAction(ISD::FABS , MVT::f32, Custom);
365 // Use XORP to simulate FNEG.
366 setOperationAction(ISD::FNEG , MVT::f32, Custom);
368 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
370 // Use ANDPS and ORPS to simulate FCOPYSIGN.
371 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
372 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
374 // We don't support sin/cos/fmod
375 setOperationAction(ISD::FSIN , MVT::f32, Expand);
376 setOperationAction(ISD::FCOS , MVT::f32, Expand);
377 setOperationAction(ISD::FREM , MVT::f32, Expand);
379 // Expand FP immediates into loads from the stack, except for the special
381 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
382 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
383 addLegalFPImmediate(APFloat(+0.0f)); // xorps
384 addLegalFPImmediate(APFloat(+0.0)); // FLD0
385 addLegalFPImmediate(APFloat(+1.0)); // FLD1
386 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
387 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
389 // SSE->x87 conversions go through memory.
390 setConvertAction(MVT::f32, MVT::f64, Expand);
391 setConvertAction(MVT::f32, MVT::f80, Expand);
393 // x87->SSE truncations need to go through memory.
394 setConvertAction(MVT::f80, MVT::f32, Expand);
395 setConvertAction(MVT::f64, MVT::f32, Expand);
396 // And x87->x87 truncations also.
397 setConvertAction(MVT::f80, MVT::f64, Expand);
400 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
401 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
404 // f32 and f64 in x87.
405 // Set up the FP register classes.
406 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
407 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
409 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
410 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
411 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
412 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
414 // Floating truncations need to go through memory.
415 setConvertAction(MVT::f80, MVT::f32, Expand);
416 setConvertAction(MVT::f64, MVT::f32, Expand);
417 setConvertAction(MVT::f80, MVT::f64, Expand);
420 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
421 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
424 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
425 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
426 addLegalFPImmediate(APFloat(+0.0)); // FLD0
427 addLegalFPImmediate(APFloat(+1.0)); // FLD1
428 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
429 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
430 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
431 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
432 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
433 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
436 // Long double always uses X87.
437 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
438 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
439 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
440 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
442 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
443 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
446 // Always use a library call for pow.
447 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
448 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
449 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
451 // First set operation action for all vector types to expand. Then we
452 // will selectively turn on ones that can be effectively codegen'd.
453 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
454 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
455 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
456 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
457 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
458 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
459 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
460 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
461 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
462 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
463 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
464 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
465 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
466 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
467 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
468 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
469 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
470 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
471 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
472 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
473 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
474 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
475 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
476 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
477 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
478 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
479 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
480 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
481 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
482 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
483 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
484 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
485 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
486 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
487 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
488 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
489 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
490 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
491 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
494 if (Subtarget->hasMMX()) {
495 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
496 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
497 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
498 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
500 // FIXME: add MMX packed arithmetics
502 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
503 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
504 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
505 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
507 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
508 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
509 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
510 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
512 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
513 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
515 setOperationAction(ISD::AND, MVT::v8i8, Promote);
516 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
517 setOperationAction(ISD::AND, MVT::v4i16, Promote);
518 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
519 setOperationAction(ISD::AND, MVT::v2i32, Promote);
520 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
521 setOperationAction(ISD::AND, MVT::v1i64, Legal);
523 setOperationAction(ISD::OR, MVT::v8i8, Promote);
524 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
525 setOperationAction(ISD::OR, MVT::v4i16, Promote);
526 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
527 setOperationAction(ISD::OR, MVT::v2i32, Promote);
528 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
529 setOperationAction(ISD::OR, MVT::v1i64, Legal);
531 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
532 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
533 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
534 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
535 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
536 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
537 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
539 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
540 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
541 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
542 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
543 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
544 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
545 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
547 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
548 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
549 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
550 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
552 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
553 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
554 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
555 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
557 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
558 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
559 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
560 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
563 if (Subtarget->hasSSE1()) {
564 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
566 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
567 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
568 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
569 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
570 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
571 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
572 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
573 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
574 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
575 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
576 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
579 if (Subtarget->hasSSE2()) {
580 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
581 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
582 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
583 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
584 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
586 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
587 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
588 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
589 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
590 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
591 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
592 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
593 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
594 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
595 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
596 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
597 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
598 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
599 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
600 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
602 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
603 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
604 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
605 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
606 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
607 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
609 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
610 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
611 // Do not attempt to custom lower non-power-of-2 vectors
612 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
614 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
615 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
616 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
618 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
619 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
620 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
621 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
622 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
623 if (Subtarget->is64Bit())
624 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
626 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
627 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
628 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
629 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
630 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
631 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
632 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
633 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
634 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
635 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
636 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
637 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
640 // Custom lower v2i64 and v2f64 selects.
641 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
642 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
643 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
644 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
647 // We want to custom lower some of our intrinsics.
648 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
650 // We have target-specific dag combine patterns for the following nodes:
651 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
652 setTargetDAGCombine(ISD::SELECT);
654 computeRegisterProperties();
656 // FIXME: These should be based on subtarget info. Plus, the values should
657 // be smaller when we are in optimizing for size mode.
658 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
659 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
660 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
661 allowUnalignedMemoryAccesses = true; // x86 supports it!
665 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
667 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
668 SelectionDAG &DAG) const {
669 if (usesGlobalOffsetTable())
670 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
671 if (!Subtarget->isPICStyleRIPRel())
672 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
676 //===----------------------------------------------------------------------===//
677 // Return Value Calling Convention Implementation
678 //===----------------------------------------------------------------------===//
680 #include "X86GenCallingConv.inc"
682 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
683 /// exists skip possible ISD:TokenFactor.
684 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
685 if (Chain.getOpcode()==X86ISD::TAILCALL) {
687 } else if (Chain.getOpcode()==ISD::TokenFactor) {
688 if (Chain.getNumOperands() &&
689 Chain.getOperand(0).getOpcode()==X86ISD::TAILCALL)
690 return Chain.getOperand(0);
695 /// LowerRET - Lower an ISD::RET node.
696 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
697 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
699 SmallVector<CCValAssign, 16> RVLocs;
700 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
701 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
702 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
703 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
705 // If this is the first return lowered for this function, add the regs to the
706 // liveout set for the function.
707 if (DAG.getMachineFunction().liveout_empty()) {
708 for (unsigned i = 0; i != RVLocs.size(); ++i)
709 if (RVLocs[i].isRegLoc())
710 DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
712 SDOperand Chain = Op.getOperand(0);
714 // Handle tail call return.
715 Chain = GetPossiblePreceedingTailCall(Chain);
716 if (Chain.getOpcode() == X86ISD::TAILCALL) {
717 SDOperand TailCall = Chain;
718 SDOperand TargetAddress = TailCall.getOperand(1);
719 SDOperand StackAdjustment = TailCall.getOperand(2);
720 assert ( ((TargetAddress.getOpcode() == ISD::Register &&
721 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
722 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
723 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
724 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
725 "Expecting an global address, external symbol, or register");
726 assert( StackAdjustment.getOpcode() == ISD::Constant &&
727 "Expecting a const value");
729 SmallVector<SDOperand,8> Operands;
730 Operands.push_back(Chain.getOperand(0));
731 Operands.push_back(TargetAddress);
732 Operands.push_back(StackAdjustment);
733 // Copy registers used by the call. Last operand is a flag so it is not
735 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
736 Operands.push_back(Chain.getOperand(i));
738 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
745 // Copy the result values into the output registers.
746 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
747 RVLocs[0].getLocReg() != X86::ST0) {
748 for (unsigned i = 0; i != RVLocs.size(); ++i) {
749 CCValAssign &VA = RVLocs[i];
750 assert(VA.isRegLoc() && "Can only return in registers!");
751 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
753 Flag = Chain.getValue(1);
756 // We need to handle a destination of ST0 specially, because it isn't really
758 SDOperand Value = Op.getOperand(1);
760 // If this is an FP return with ScalarSSE, we need to move the value from
761 // an XMM register onto the fp-stack.
762 if ((X86ScalarSSEf32 && RVLocs[0].getValVT()==MVT::f32) ||
763 (X86ScalarSSEf64 && RVLocs[0].getValVT()==MVT::f64)) {
766 // If this is a load into a scalarsse value, don't store the loaded value
767 // back to the stack, only to reload it: just replace the scalar-sse load.
768 if (ISD::isNON_EXTLoad(Value.Val) &&
769 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
770 Chain = Value.getOperand(0);
771 MemLoc = Value.getOperand(1);
773 // Spill the value to memory and reload it into top of stack.
774 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
775 MachineFunction &MF = DAG.getMachineFunction();
776 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
777 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
778 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
780 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
781 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
782 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
783 Chain = Value.getValue(1);
786 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
787 SDOperand Ops[] = { Chain, Value };
788 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
789 Flag = Chain.getValue(1);
792 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
794 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
796 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
800 /// LowerCallResult - Lower the result values of an ISD::CALL into the
801 /// appropriate copies out of appropriate physical registers. This assumes that
802 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
803 /// being lowered. The returns a SDNode with the same number of values as the
805 SDNode *X86TargetLowering::
806 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
807 unsigned CallingConv, SelectionDAG &DAG) {
809 // Assign locations to each value returned by this call.
810 SmallVector<CCValAssign, 16> RVLocs;
811 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
812 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
813 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
816 SmallVector<SDOperand, 8> ResultVals;
818 // Copy all of the result registers out of their specified physreg.
819 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
820 for (unsigned i = 0; i != RVLocs.size(); ++i) {
821 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
822 RVLocs[i].getValVT(), InFlag).getValue(1);
823 InFlag = Chain.getValue(2);
824 ResultVals.push_back(Chain.getValue(0));
827 // Copies from the FP stack are special, as ST0 isn't a valid register
828 // before the fp stackifier runs.
830 // Copy ST0 into an RFP register with FP_GET_RESULT.
831 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
832 SDOperand GROps[] = { Chain, InFlag };
833 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
834 Chain = RetVal.getValue(1);
835 InFlag = RetVal.getValue(2);
837 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
839 if ((X86ScalarSSEf32 && RVLocs[0].getValVT() == MVT::f32) ||
840 (X86ScalarSSEf64 && RVLocs[0].getValVT() == MVT::f64)) {
841 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
842 // shouldn't be necessary except that RFP cannot be live across
843 // multiple blocks. When stackifier is fixed, they can be uncoupled.
844 MachineFunction &MF = DAG.getMachineFunction();
845 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
846 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
848 Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
850 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
851 RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
852 Chain = RetVal.getValue(1);
854 ResultVals.push_back(RetVal);
857 // Merge everything together with a MERGE_VALUES node.
858 ResultVals.push_back(Chain);
859 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
860 &ResultVals[0], ResultVals.size()).Val;
864 //===----------------------------------------------------------------------===//
865 // C & StdCall & Fast Calling Convention implementation
866 //===----------------------------------------------------------------------===//
867 // StdCall calling convention seems to be standard for many Windows' API
868 // routines and around. It differs from C calling convention just a little:
869 // callee should clean up the stack, not caller. Symbols should be also
870 // decorated in some fancy way :) It doesn't support any vector arguments.
871 // For info on fast calling convention see Fast Calling Convention (tail call)
872 // implementation LowerX86_32FastCCCallTo.
874 /// AddLiveIn - This helper function adds the specified physical register to the
875 /// MachineFunction as a live in value. It also creates a corresponding virtual
877 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
878 const TargetRegisterClass *RC) {
879 assert(RC->contains(PReg) && "Not the correct regclass!");
880 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
881 MF.addLiveIn(PReg, VReg);
885 // align stack arguments according to platform alignment needed for tail calls
886 unsigned GetAlignedArgumentStackSize(unsigned StackSize, SelectionDAG& DAG);
888 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
889 const CCValAssign &VA,
890 MachineFrameInfo *MFI,
891 SDOperand Root, unsigned i) {
892 // Create the nodes corresponding to a load from this parameter slot.
893 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
894 VA.getLocMemOffset());
895 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
897 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
899 if (Flags & ISD::ParamFlags::ByVal)
902 return DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0);
905 SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
907 unsigned NumArgs = Op.Val->getNumValues() - 1;
908 MachineFunction &MF = DAG.getMachineFunction();
909 MachineFrameInfo *MFI = MF.getFrameInfo();
910 SDOperand Root = Op.getOperand(0);
911 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
912 unsigned CC = MF.getFunction()->getCallingConv();
913 // Assign locations to all of the incoming arguments.
914 SmallVector<CCValAssign, 16> ArgLocs;
915 CCState CCInfo(CC, isVarArg,
916 getTargetMachine(), ArgLocs);
917 // Check for possible tail call calling convention.
918 if (CC == CallingConv::Fast && PerformTailCallOpt)
919 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_TailCall);
921 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
923 SmallVector<SDOperand, 8> ArgValues;
924 unsigned LastVal = ~0U;
925 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
926 CCValAssign &VA = ArgLocs[i];
927 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
929 assert(VA.getValNo() != LastVal &&
930 "Don't support value assigned to multiple locs yet");
931 LastVal = VA.getValNo();
934 MVT::ValueType RegVT = VA.getLocVT();
935 TargetRegisterClass *RC;
936 if (RegVT == MVT::i32)
937 RC = X86::GR32RegisterClass;
939 assert(MVT::isVector(RegVT));
940 RC = X86::VR128RegisterClass;
943 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
944 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
946 // If this is an 8 or 16-bit value, it is really passed promoted to 32
947 // bits. Insert an assert[sz]ext to capture this, then truncate to the
949 if (VA.getLocInfo() == CCValAssign::SExt)
950 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
951 DAG.getValueType(VA.getValVT()));
952 else if (VA.getLocInfo() == CCValAssign::ZExt)
953 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
954 DAG.getValueType(VA.getValVT()));
956 if (VA.getLocInfo() != CCValAssign::Full)
957 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
959 ArgValues.push_back(ArgValue);
961 assert(VA.isMemLoc());
962 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
966 unsigned StackSize = CCInfo.getNextStackOffset();
967 // align stack specially for tail calls
968 if (CC==CallingConv::Fast)
969 StackSize = GetAlignedArgumentStackSize(StackSize,DAG);
971 ArgValues.push_back(Root);
973 // If the function takes variable number of arguments, make a frame index for
974 // the start of the first vararg value... for expansion of llvm.va_start.
976 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
978 // Tail call calling convention (CallingConv::Fast) does not support varargs.
979 assert( !(isVarArg && CC == CallingConv::Fast) &&
980 "CallingConv::Fast does not support varargs.");
982 if (isStdCall && !isVarArg &&
983 (CC==CallingConv::Fast && PerformTailCallOpt || CC!=CallingConv::Fast)) {
984 BytesToPopOnReturn = StackSize; // Callee pops everything..
985 BytesCallerReserves = 0;
987 BytesToPopOnReturn = 0; // Callee pops nothing.
989 // If this is an sret function, the return should pop the hidden pointer.
991 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
992 ISD::ParamFlags::StructReturn))
993 BytesToPopOnReturn = 4;
995 BytesCallerReserves = StackSize;
998 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
1000 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1001 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1003 // Return the new list of results.
1004 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1005 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1008 SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
1010 SDOperand Chain = Op.getOperand(0);
1011 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1012 SDOperand Callee = Op.getOperand(4);
1013 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1015 // Analyze operands of the call, assigning locations to each operand.
1016 SmallVector<CCValAssign, 16> ArgLocs;
1017 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1018 if(CC==CallingConv::Fast && PerformTailCallOpt)
1019 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1021 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
1023 // Get a count of how many bytes are to be pushed on the stack.
1024 unsigned NumBytes = CCInfo.getNextStackOffset();
1025 if (CC==CallingConv::Fast)
1026 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1028 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1030 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1031 SmallVector<SDOperand, 8> MemOpChains;
1035 // Walk the register/memloc assignments, inserting copies/loads.
1036 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1037 CCValAssign &VA = ArgLocs[i];
1038 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1040 // Promote the value if needed.
1041 switch (VA.getLocInfo()) {
1042 default: assert(0 && "Unknown loc info!");
1043 case CCValAssign::Full: break;
1044 case CCValAssign::SExt:
1045 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1047 case CCValAssign::ZExt:
1048 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1050 case CCValAssign::AExt:
1051 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1055 if (VA.isRegLoc()) {
1056 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1058 assert(VA.isMemLoc());
1059 if (StackPtr.Val == 0)
1060 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1062 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1067 // If the first argument is an sret pointer, remember it.
1068 bool isSRet = NumOps &&
1069 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
1070 ISD::ParamFlags::StructReturn);
1072 if (!MemOpChains.empty())
1073 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1074 &MemOpChains[0], MemOpChains.size());
1076 // Build a sequence of copy-to-reg nodes chained together with token chain
1077 // and flag operands which copy the outgoing args into registers.
1079 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1080 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1082 InFlag = Chain.getValue(1);
1085 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1087 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1088 Subtarget->isPICStyleGOT()) {
1089 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1090 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1092 InFlag = Chain.getValue(1);
1095 // If the callee is a GlobalAddress node (quite common, every direct call is)
1096 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1097 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1098 // We should use extra load for direct calls to dllimported functions in
1100 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1101 getTargetMachine(), true))
1102 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1103 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1104 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1106 // Returns a chain & a flag for retval copy to use.
1107 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1108 SmallVector<SDOperand, 8> Ops;
1109 Ops.push_back(Chain);
1110 Ops.push_back(Callee);
1112 // Add argument registers to the end of the list so that they are known live
1114 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1115 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1116 RegsToPass[i].second.getValueType()));
1118 // Add an implicit use GOT pointer in EBX.
1119 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1120 Subtarget->isPICStyleGOT())
1121 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1124 Ops.push_back(InFlag);
1126 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1127 InFlag = Chain.getValue(1);
1129 // Create the CALLSEQ_END node.
1130 unsigned NumBytesForCalleeToPush = 0;
1132 if (CC == CallingConv::X86_StdCall ||
1133 (CC == CallingConv::Fast && PerformTailCallOpt)) {
1135 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1137 NumBytesForCalleeToPush = NumBytes;
1138 assert(!(isVarArg && CC==CallingConv::Fast) &&
1139 "CallingConv::Fast does not support varargs.");
1141 // If this is is a call to a struct-return function, the callee
1142 // pops the hidden struct pointer, so we have to push it back.
1143 // This is common for Darwin/X86, Linux & Mingw32 targets.
1144 NumBytesForCalleeToPush = isSRet ? 4 : 0;
1147 Chain = DAG.getCALLSEQ_END(Chain,
1148 DAG.getConstant(NumBytes, getPointerTy()),
1149 DAG.getConstant(NumBytesForCalleeToPush,
1152 InFlag = Chain.getValue(1);
1154 // Handle result values, copying them out of physregs into vregs that we
1156 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1160 //===----------------------------------------------------------------------===//
1161 // FastCall Calling Convention implementation
1162 //===----------------------------------------------------------------------===//
1164 // The X86 'fastcall' calling convention passes up to two integer arguments in
1165 // registers (an appropriate portion of ECX/EDX), passes arguments in C order,
1166 // and requires that the callee pop its arguments off the stack (allowing proper
1167 // tail calls), and has the same return value conventions as C calling convs.
1169 // This calling convention always arranges for the callee pop value to be 8n+4
1170 // bytes, which is needed for tail recursion elimination and stack alignment
1173 X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
1174 MachineFunction &MF = DAG.getMachineFunction();
1175 MachineFrameInfo *MFI = MF.getFrameInfo();
1176 SDOperand Root = Op.getOperand(0);
1177 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1179 // Assign locations to all of the incoming arguments.
1180 SmallVector<CCValAssign, 16> ArgLocs;
1181 CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
1182 getTargetMachine(), ArgLocs);
1183 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
1185 SmallVector<SDOperand, 8> ArgValues;
1186 unsigned LastVal = ~0U;
1187 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1188 CCValAssign &VA = ArgLocs[i];
1189 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1191 assert(VA.getValNo() != LastVal &&
1192 "Don't support value assigned to multiple locs yet");
1193 LastVal = VA.getValNo();
1195 if (VA.isRegLoc()) {
1196 MVT::ValueType RegVT = VA.getLocVT();
1197 TargetRegisterClass *RC;
1198 if (RegVT == MVT::i32)
1199 RC = X86::GR32RegisterClass;
1201 assert(MVT::isVector(RegVT));
1202 RC = X86::VR128RegisterClass;
1205 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1206 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1208 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1209 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1211 if (VA.getLocInfo() == CCValAssign::SExt)
1212 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1213 DAG.getValueType(VA.getValVT()));
1214 else if (VA.getLocInfo() == CCValAssign::ZExt)
1215 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1216 DAG.getValueType(VA.getValVT()));
1218 if (VA.getLocInfo() != CCValAssign::Full)
1219 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1221 ArgValues.push_back(ArgValue);
1223 assert(VA.isMemLoc());
1224 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1228 ArgValues.push_back(Root);
1230 unsigned StackSize = CCInfo.getNextStackOffset();
1232 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1233 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1234 // arguments and the arguments after the retaddr has been pushed are
1236 if ((StackSize & 7) == 0)
1240 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1241 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
1242 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
1243 BytesCallerReserves = 0;
1245 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1246 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1248 // Return the new list of results.
1249 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1250 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1254 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1255 const SDOperand &StackPtr,
1256 const CCValAssign &VA,
1259 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1260 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1261 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1262 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1263 if (Flags & ISD::ParamFlags::ByVal) {
1264 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1265 ISD::ParamFlags::ByValAlignOffs);
1267 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1268 ISD::ParamFlags::ByValSizeOffs;
1270 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1271 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1272 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1274 return DAG.getMemcpy(Chain, PtrOff, Arg, SizeNode, AlignNode,
1277 return DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1281 SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1283 SDOperand Chain = Op.getOperand(0);
1284 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1285 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1286 SDOperand Callee = Op.getOperand(4);
1288 // Analyze operands of the call, assigning locations to each operand.
1289 SmallVector<CCValAssign, 16> ArgLocs;
1290 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1291 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1293 // Get a count of how many bytes are to be pushed on the stack.
1294 unsigned NumBytes = CCInfo.getNextStackOffset();
1296 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1297 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1298 // arguments and the arguments after the retaddr has been pushed are
1300 if ((NumBytes & 7) == 0)
1304 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1306 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1307 SmallVector<SDOperand, 8> MemOpChains;
1311 // Walk the register/memloc assignments, inserting copies/loads.
1312 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1313 CCValAssign &VA = ArgLocs[i];
1314 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1316 // Promote the value if needed.
1317 switch (VA.getLocInfo()) {
1318 default: assert(0 && "Unknown loc info!");
1319 case CCValAssign::Full: break;
1320 case CCValAssign::SExt:
1321 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1323 case CCValAssign::ZExt:
1324 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1326 case CCValAssign::AExt:
1327 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1331 if (VA.isRegLoc()) {
1332 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1334 assert(VA.isMemLoc());
1335 if (StackPtr.Val == 0)
1336 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1338 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1343 if (!MemOpChains.empty())
1344 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1345 &MemOpChains[0], MemOpChains.size());
1347 // Build a sequence of copy-to-reg nodes chained together with token chain
1348 // and flag operands which copy the outgoing args into registers.
1350 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1351 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1353 InFlag = Chain.getValue(1);
1356 // If the callee is a GlobalAddress node (quite common, every direct call is)
1357 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1358 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1359 // We should use extra load for direct calls to dllimported functions in
1361 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1362 getTargetMachine(), true))
1363 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1364 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1365 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1367 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1369 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1370 Subtarget->isPICStyleGOT()) {
1371 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1372 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1374 InFlag = Chain.getValue(1);
1377 // Returns a chain & a flag for retval copy to use.
1378 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1379 SmallVector<SDOperand, 8> Ops;
1380 Ops.push_back(Chain);
1381 Ops.push_back(Callee);
1383 // Add argument registers to the end of the list so that they are known live
1385 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1386 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1387 RegsToPass[i].second.getValueType()));
1389 // Add an implicit use GOT pointer in EBX.
1390 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1391 Subtarget->isPICStyleGOT())
1392 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1395 Ops.push_back(InFlag);
1397 assert(isTailCall==false && "no tail call here");
1398 Chain = DAG.getNode(X86ISD::CALL,
1399 NodeTys, &Ops[0], Ops.size());
1400 InFlag = Chain.getValue(1);
1402 // Returns a flag for retval copy to use.
1403 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1405 Ops.push_back(Chain);
1406 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1407 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1408 Ops.push_back(InFlag);
1409 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1410 InFlag = Chain.getValue(1);
1412 // Handle result values, copying them out of physregs into vregs that we
1414 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1417 //===----------------------------------------------------------------------===//
1418 // Fast Calling Convention (tail call) implementation
1419 //===----------------------------------------------------------------------===//
1421 // Like std call, callee cleans arguments, convention except that ECX is
1422 // reserved for storing the tail called function address. Only 2 registers are
1423 // free for argument passing (inreg). Tail call optimization is performed
1425 // * tailcallopt is enabled
1426 // * caller/callee are fastcc
1427 // * elf/pic is disabled OR
1428 // * elf/pic enabled + callee is in module + callee has
1429 // visibility protected or hidden
1430 // To keep the stack aligned according to platform abi the function
1431 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1432 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1433 // If a tail called function callee has more arguments than the caller the
1434 // caller needs to make sure that there is room to move the RETADDR to. This is
1435 // achieved by reserving an area the size of the argument delta right after the
1436 // original REtADDR, but before the saved framepointer or the spilled registers
1437 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1449 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1450 /// for a 16 byte align requirement.
1451 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1452 SelectionDAG& DAG) {
1453 if (PerformTailCallOpt) {
1454 MachineFunction &MF = DAG.getMachineFunction();
1455 const TargetMachine &TM = MF.getTarget();
1456 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1457 unsigned StackAlignment = TFI.getStackAlignment();
1458 uint64_t AlignMask = StackAlignment - 1;
1459 int64_t Offset = StackSize;
1460 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1461 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1462 // Number smaller than 12 so just add the difference.
1463 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1465 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1466 Offset = ((~AlignMask) & Offset) + StackAlignment +
1467 (StackAlignment-SlotSize);
1474 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1475 /// following the call is a return. A function is eligible if caller/callee
1476 /// calling conventions match, currently only fastcc supports tail calls, and
1477 /// the function CALL is immediatly followed by a RET.
1478 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1480 SelectionDAG& DAG) const {
1481 if (!PerformTailCallOpt)
1484 // Check whether CALL node immediatly preceeds the RET node and whether the
1485 // return uses the result of the node or is a void return.
1486 unsigned NumOps = Ret.getNumOperands();
1488 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1489 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1491 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1492 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1493 MachineFunction &MF = DAG.getMachineFunction();
1494 unsigned CallerCC = MF.getFunction()->getCallingConv();
1495 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1496 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1497 SDOperand Callee = Call.getOperand(4);
1498 // On elf/pic %ebx needs to be livein.
1499 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1500 !Subtarget->isPICStyleGOT())
1503 // Can only do local tail calls with PIC.
1504 GlobalValue * GV = 0;
1505 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1507 (GV = G->getGlobal()) &&
1508 (GV->hasHiddenVisibility() || GV->hasProtectedVisibility()))
1516 SDOperand X86TargetLowering::LowerX86_TailCallTo(SDOperand Op,
1519 SDOperand Chain = Op.getOperand(0);
1520 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1521 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1522 SDOperand Callee = Op.getOperand(4);
1523 bool is64Bit = Subtarget->is64Bit();
1525 assert(isTailCall && PerformTailCallOpt && "Should only emit tail calls.");
1527 // Analyze operands of the call, assigning locations to each operand.
1528 SmallVector<CCValAssign, 16> ArgLocs;
1529 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1531 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1533 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1536 // Lower arguments at fp - stackoffset + fpdiff.
1537 MachineFunction &MF = DAG.getMachineFunction();
1539 unsigned NumBytesToBePushed =
1540 GetAlignedArgumentStackSize(CCInfo.getNextStackOffset(), DAG);
1542 unsigned NumBytesCallerPushed =
1543 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1544 int FPDiff = NumBytesCallerPushed - NumBytesToBePushed;
1546 // Set the delta of movement of the returnaddr stackslot.
1547 // But only set if delta is greater than previous delta.
1548 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1549 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1552 getCALLSEQ_START(Chain, DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1554 // Adjust the Return address stack slot.
1555 SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
1557 MVT::ValueType VT = is64Bit ? MVT::i64 : MVT::i32;
1558 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1559 // Load the "old" Return address.
1561 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1562 // Calculate the new stack slot for the return address.
1563 int SlotSize = is64Bit ? 8 : 4;
1564 int NewReturnAddrFI =
1565 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1566 NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1567 Chain = SDOperand(RetAddrFrIdx.Val, 1);
1570 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1571 SmallVector<SDOperand, 8> MemOpChains;
1572 SmallVector<SDOperand, 8> MemOpChains2;
1573 SDOperand FramePtr, StackPtr;
1578 // Walk the register/memloc assignments, inserting copies/loads. Lower
1579 // arguments first to the stack slot where they would normally - in case of a
1580 // normal function call - be.
1581 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1582 CCValAssign &VA = ArgLocs[i];
1583 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1585 // Promote the value if needed.
1586 switch (VA.getLocInfo()) {
1587 default: assert(0 && "Unknown loc info!");
1588 case CCValAssign::Full: break;
1589 case CCValAssign::SExt:
1590 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1592 case CCValAssign::ZExt:
1593 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1595 case CCValAssign::AExt:
1596 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1600 if (VA.isRegLoc()) {
1601 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1603 assert(VA.isMemLoc());
1604 if (StackPtr.Val == 0)
1605 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1607 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1612 if (!MemOpChains.empty())
1613 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1614 &MemOpChains[0], MemOpChains.size());
1616 // Build a sequence of copy-to-reg nodes chained together with token chain
1617 // and flag operands which copy the outgoing args into registers.
1619 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1620 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1622 InFlag = Chain.getValue(1);
1624 InFlag = SDOperand();
1626 // Copy from stack slots to stack slot of a tail called function. This needs
1627 // to be done because if we would lower the arguments directly to their real
1628 // stack slot we might end up overwriting each other.
1629 // TODO: To make this more efficient (sometimes saving a store/load) we could
1630 // analyse the arguments and emit this store/load/store sequence only for
1631 // arguments which would be overwritten otherwise.
1632 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1633 CCValAssign &VA = ArgLocs[i];
1634 if (!VA.isRegLoc()) {
1635 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1636 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1638 // Get source stack slot.
1639 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1640 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1641 // Create frame index.
1642 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1643 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1644 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1645 FIN = DAG.getFrameIndex(FI, MVT::i32);
1646 if (Flags & ISD::ParamFlags::ByVal) {
1647 // Copy relative to framepointer.
1648 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1649 ISD::ParamFlags::ByValAlignOffs);
1651 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1652 ISD::ParamFlags::ByValSizeOffs;
1654 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1655 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1656 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i1);
1658 MemOpChains2.push_back(DAG.getMemcpy(Chain, FIN, PtrOff, SizeNode,
1659 AlignNode,AlwaysInline));
1661 SDOperand LoadedArg = DAG.getLoad(VA.getValVT(), Chain, PtrOff, NULL,0);
1662 // Store relative to framepointer.
1663 MemOpChains2.push_back(DAG.getStore(Chain, LoadedArg, FIN, NULL, 0));
1668 if (!MemOpChains2.empty())
1669 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1670 &MemOpChains2[0], MemOpChains.size());
1672 // Store the return address to the appropriate stack slot.
1674 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1676 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1678 // Does not work with tail call since ebx is not restored correctly by
1679 // tailcaller. TODO: at least for x86 - verify for x86-64
1681 // If the callee is a GlobalAddress node (quite common, every direct call is)
1682 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1683 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1684 // We should use extra load for direct calls to dllimported functions in
1686 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1687 getTargetMachine(), true))
1688 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1689 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1690 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1692 assert(Callee.getOpcode() == ISD::LOAD &&
1693 "Function destination must be loaded into virtual register");
1694 unsigned Opc = is64Bit ? X86::R9 : X86::ECX;
1696 Chain = DAG.getCopyToReg(Chain,
1697 DAG.getRegister(Opc, getPointerTy()) ,
1699 Callee = DAG.getRegister(Opc, getPointerTy());
1700 // Add register as live out.
1701 DAG.getMachineFunction().addLiveOut(Opc);
1704 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1705 SmallVector<SDOperand, 8> Ops;
1707 Ops.push_back(Chain);
1708 Ops.push_back(DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1709 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1711 Ops.push_back(InFlag);
1712 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1713 InFlag = Chain.getValue(1);
1715 // Returns a chain & a flag for retval copy to use.
1716 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1718 Ops.push_back(Chain);
1719 Ops.push_back(Callee);
1720 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1721 // Add argument registers to the end of the list so that they are known live
1723 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1724 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1725 RegsToPass[i].second.getValueType()));
1727 Ops.push_back(InFlag);
1728 assert(InFlag.Val &&
1729 "Flag must be set. Depend on flag being set in LowerRET");
1730 Chain = DAG.getNode(X86ISD::TAILCALL,
1731 Op.Val->getVTList(), &Ops[0], Ops.size());
1733 return SDOperand(Chain.Val, Op.ResNo);
1736 //===----------------------------------------------------------------------===//
1737 // X86-64 C Calling Convention implementation
1738 //===----------------------------------------------------------------------===//
1741 X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1742 MachineFunction &MF = DAG.getMachineFunction();
1743 MachineFrameInfo *MFI = MF.getFrameInfo();
1744 SDOperand Root = Op.getOperand(0);
1745 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1746 unsigned CC= MF.getFunction()->getCallingConv();
1748 static const unsigned GPR64ArgRegs[] = {
1749 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1751 static const unsigned XMMArgRegs[] = {
1752 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1753 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1757 // Assign locations to all of the incoming arguments.
1758 SmallVector<CCValAssign, 16> ArgLocs;
1759 CCState CCInfo(CC, isVarArg,
1760 getTargetMachine(), ArgLocs);
1761 if (CC == CallingConv::Fast && PerformTailCallOpt)
1762 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_TailCall);
1764 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
1766 SmallVector<SDOperand, 8> ArgValues;
1767 unsigned LastVal = ~0U;
1768 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1769 CCValAssign &VA = ArgLocs[i];
1770 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1772 assert(VA.getValNo() != LastVal &&
1773 "Don't support value assigned to multiple locs yet");
1774 LastVal = VA.getValNo();
1776 if (VA.isRegLoc()) {
1777 MVT::ValueType RegVT = VA.getLocVT();
1778 TargetRegisterClass *RC;
1779 if (RegVT == MVT::i32)
1780 RC = X86::GR32RegisterClass;
1781 else if (RegVT == MVT::i64)
1782 RC = X86::GR64RegisterClass;
1783 else if (RegVT == MVT::f32)
1784 RC = X86::FR32RegisterClass;
1785 else if (RegVT == MVT::f64)
1786 RC = X86::FR64RegisterClass;
1788 assert(MVT::isVector(RegVT));
1789 if (MVT::getSizeInBits(RegVT) == 64) {
1790 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1793 RC = X86::VR128RegisterClass;
1796 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1797 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1799 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1800 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1802 if (VA.getLocInfo() == CCValAssign::SExt)
1803 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1804 DAG.getValueType(VA.getValVT()));
1805 else if (VA.getLocInfo() == CCValAssign::ZExt)
1806 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1807 DAG.getValueType(VA.getValVT()));
1809 if (VA.getLocInfo() != CCValAssign::Full)
1810 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1812 // Handle MMX values passed in GPRs.
1813 if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1814 MVT::getSizeInBits(RegVT) == 64)
1815 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1817 ArgValues.push_back(ArgValue);
1819 assert(VA.isMemLoc());
1820 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1824 unsigned StackSize = CCInfo.getNextStackOffset();
1825 if (CC==CallingConv::Fast)
1826 StackSize =GetAlignedArgumentStackSize(StackSize, DAG);
1828 // If the function takes variable number of arguments, make a frame index for
1829 // the start of the first vararg value... for expansion of llvm.va_start.
1831 assert(CC!=CallingConv::Fast
1832 && "Var arg not supported with calling convention fastcc");
1833 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1834 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1836 // For X86-64, if there are vararg parameters that are passed via
1837 // registers, then we must store them to their spots on the stack so they
1838 // may be loaded by deferencing the result of va_next.
1839 VarArgsGPOffset = NumIntRegs * 8;
1840 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1841 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1842 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1844 // Store the integer parameter registers.
1845 SmallVector<SDOperand, 8> MemOps;
1846 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1847 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1848 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1849 for (; NumIntRegs != 6; ++NumIntRegs) {
1850 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1851 X86::GR64RegisterClass);
1852 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1853 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1854 MemOps.push_back(Store);
1855 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1856 DAG.getConstant(8, getPointerTy()));
1859 // Now store the XMM (fp + vector) parameter registers.
1860 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1861 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1862 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1863 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1864 X86::VR128RegisterClass);
1865 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1866 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1867 MemOps.push_back(Store);
1868 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1869 DAG.getConstant(16, getPointerTy()));
1871 if (!MemOps.empty())
1872 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1873 &MemOps[0], MemOps.size());
1876 ArgValues.push_back(Root);
1877 // Tail call convention (fastcc) needs callee pop.
1878 if (CC == CallingConv::Fast && PerformTailCallOpt) {
1879 BytesToPopOnReturn = StackSize; // Callee pops everything.
1880 BytesCallerReserves = 0;
1882 BytesToPopOnReturn = 0; // Callee pops nothing.
1883 BytesCallerReserves = StackSize;
1885 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1886 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1888 // Return the new list of results.
1889 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1890 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1894 X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1896 SDOperand Chain = Op.getOperand(0);
1897 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1898 SDOperand Callee = Op.getOperand(4);
1900 // Analyze operands of the call, assigning locations to each operand.
1901 SmallVector<CCValAssign, 16> ArgLocs;
1902 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1903 if (CC==CallingConv::Fast && PerformTailCallOpt)
1904 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1906 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
1908 // Get a count of how many bytes are to be pushed on the stack.
1909 unsigned NumBytes = CCInfo.getNextStackOffset();
1910 if (CC == CallingConv::Fast)
1911 NumBytes = GetAlignedArgumentStackSize(NumBytes,DAG);
1913 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1915 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1916 SmallVector<SDOperand, 8> MemOpChains;
1920 // Walk the register/memloc assignments, inserting copies/loads.
1921 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1922 CCValAssign &VA = ArgLocs[i];
1923 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1925 // Promote the value if needed.
1926 switch (VA.getLocInfo()) {
1927 default: assert(0 && "Unknown loc info!");
1928 case CCValAssign::Full: break;
1929 case CCValAssign::SExt:
1930 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1932 case CCValAssign::ZExt:
1933 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1935 case CCValAssign::AExt:
1936 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1940 if (VA.isRegLoc()) {
1941 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1943 assert(VA.isMemLoc());
1944 if (StackPtr.Val == 0)
1945 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1947 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1952 if (!MemOpChains.empty())
1953 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1954 &MemOpChains[0], MemOpChains.size());
1956 // Build a sequence of copy-to-reg nodes chained together with token chain
1957 // and flag operands which copy the outgoing args into registers.
1959 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1960 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1962 InFlag = Chain.getValue(1);
1966 assert ( CallingConv::Fast != CC &&
1967 "Var args not supported with calling convention fastcc");
1969 // From AMD64 ABI document:
1970 // For calls that may call functions that use varargs or stdargs
1971 // (prototype-less calls or calls to functions containing ellipsis (...) in
1972 // the declaration) %al is used as hidden argument to specify the number
1973 // of SSE registers used. The contents of %al do not need to match exactly
1974 // the number of registers, but must be an ubound on the number of SSE
1975 // registers used and is in the range 0 - 8 inclusive.
1977 // Count the number of XMM registers allocated.
1978 static const unsigned XMMArgRegs[] = {
1979 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1980 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1982 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1984 Chain = DAG.getCopyToReg(Chain, X86::AL,
1985 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1986 InFlag = Chain.getValue(1);
1989 // If the callee is a GlobalAddress node (quite common, every direct call is)
1990 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1991 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1992 // We should use extra load for direct calls to dllimported functions in
1994 if (getTargetMachine().getCodeModel() != CodeModel::Large
1995 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1996 getTargetMachine(), true))
1997 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1998 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1999 if (getTargetMachine().getCodeModel() != CodeModel::Large)
2000 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
2002 // Returns a chain & a flag for retval copy to use.
2003 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2004 SmallVector<SDOperand, 8> Ops;
2005 Ops.push_back(Chain);
2006 Ops.push_back(Callee);
2008 // Add argument registers to the end of the list so that they are known live
2010 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2011 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2012 RegsToPass[i].second.getValueType()));
2015 Ops.push_back(InFlag);
2017 Chain = DAG.getNode(X86ISD::CALL,
2018 NodeTys, &Ops[0], Ops.size());
2019 InFlag = Chain.getValue(1);
2020 int NumBytesForCalleeToPush = 0;
2021 if (CC==CallingConv::Fast && PerformTailCallOpt) {
2022 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2024 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2026 // Returns a flag for retval copy to use.
2027 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2029 Ops.push_back(Chain);
2030 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
2031 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
2032 Ops.push_back(InFlag);
2033 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
2034 InFlag = Chain.getValue(1);
2036 // Handle result values, copying them out of physregs into vregs that we
2038 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
2042 //===----------------------------------------------------------------------===//
2043 // Other Lowering Hooks
2044 //===----------------------------------------------------------------------===//
2047 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2048 MachineFunction &MF = DAG.getMachineFunction();
2049 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2050 int ReturnAddrIndex = FuncInfo->getRAIndex();
2052 if (ReturnAddrIndex == 0) {
2053 // Set up a frame object for the return address.
2054 if (Subtarget->is64Bit())
2055 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
2057 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
2059 FuncInfo->setRAIndex(ReturnAddrIndex);
2062 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2067 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
2068 /// specific condition code. It returns a false if it cannot do a direct
2069 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
2071 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2072 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
2073 SelectionDAG &DAG) {
2074 X86CC = X86::COND_INVALID;
2076 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2077 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2078 // X > -1 -> X == 0, jump !sign.
2079 RHS = DAG.getConstant(0, RHS.getValueType());
2080 X86CC = X86::COND_NS;
2082 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2083 // X < 0 -> X == 0, jump on sign.
2084 X86CC = X86::COND_S;
2086 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
2088 RHS = DAG.getConstant(0, RHS.getValueType());
2089 X86CC = X86::COND_LE;
2094 switch (SetCCOpcode) {
2096 case ISD::SETEQ: X86CC = X86::COND_E; break;
2097 case ISD::SETGT: X86CC = X86::COND_G; break;
2098 case ISD::SETGE: X86CC = X86::COND_GE; break;
2099 case ISD::SETLT: X86CC = X86::COND_L; break;
2100 case ISD::SETLE: X86CC = X86::COND_LE; break;
2101 case ISD::SETNE: X86CC = X86::COND_NE; break;
2102 case ISD::SETULT: X86CC = X86::COND_B; break;
2103 case ISD::SETUGT: X86CC = X86::COND_A; break;
2104 case ISD::SETULE: X86CC = X86::COND_BE; break;
2105 case ISD::SETUGE: X86CC = X86::COND_AE; break;
2108 // On a floating point condition, the flags are set as follows:
2110 // 0 | 0 | 0 | X > Y
2111 // 0 | 0 | 1 | X < Y
2112 // 1 | 0 | 0 | X == Y
2113 // 1 | 1 | 1 | unordered
2115 switch (SetCCOpcode) {
2118 case ISD::SETEQ: X86CC = X86::COND_E; break;
2119 case ISD::SETOLT: Flip = true; // Fallthrough
2121 case ISD::SETGT: X86CC = X86::COND_A; break;
2122 case ISD::SETOLE: Flip = true; // Fallthrough
2124 case ISD::SETGE: X86CC = X86::COND_AE; break;
2125 case ISD::SETUGT: Flip = true; // Fallthrough
2127 case ISD::SETLT: X86CC = X86::COND_B; break;
2128 case ISD::SETUGE: Flip = true; // Fallthrough
2130 case ISD::SETLE: X86CC = X86::COND_BE; break;
2132 case ISD::SETNE: X86CC = X86::COND_NE; break;
2133 case ISD::SETUO: X86CC = X86::COND_P; break;
2134 case ISD::SETO: X86CC = X86::COND_NP; break;
2137 std::swap(LHS, RHS);
2140 return X86CC != X86::COND_INVALID;
2143 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2144 /// code. Current x86 isa includes the following FP cmov instructions:
2145 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2146 static bool hasFPCMov(unsigned X86CC) {
2162 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2163 /// true if Op is undef or if its value falls within the specified range (L, H].
2164 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2165 if (Op.getOpcode() == ISD::UNDEF)
2168 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2169 return (Val >= Low && Val < Hi);
2172 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2173 /// true if Op is undef or if its value equal to the specified value.
2174 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2175 if (Op.getOpcode() == ISD::UNDEF)
2177 return cast<ConstantSDNode>(Op)->getValue() == Val;
2180 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2181 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2182 bool X86::isPSHUFDMask(SDNode *N) {
2183 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2185 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2188 // Check if the value doesn't reference the second vector.
2189 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2190 SDOperand Arg = N->getOperand(i);
2191 if (Arg.getOpcode() == ISD::UNDEF) continue;
2192 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2193 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2200 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2201 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2202 bool X86::isPSHUFHWMask(SDNode *N) {
2203 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2205 if (N->getNumOperands() != 8)
2208 // Lower quadword copied in order.
2209 for (unsigned i = 0; i != 4; ++i) {
2210 SDOperand Arg = N->getOperand(i);
2211 if (Arg.getOpcode() == ISD::UNDEF) continue;
2212 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2213 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2217 // Upper quadword shuffled.
2218 for (unsigned i = 4; i != 8; ++i) {
2219 SDOperand Arg = N->getOperand(i);
2220 if (Arg.getOpcode() == ISD::UNDEF) continue;
2221 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2222 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2223 if (Val < 4 || Val > 7)
2230 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2231 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2232 bool X86::isPSHUFLWMask(SDNode *N) {
2233 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2235 if (N->getNumOperands() != 8)
2238 // Upper quadword copied in order.
2239 for (unsigned i = 4; i != 8; ++i)
2240 if (!isUndefOrEqual(N->getOperand(i), i))
2243 // Lower quadword shuffled.
2244 for (unsigned i = 0; i != 4; ++i)
2245 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2251 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2252 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2253 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2254 if (NumElems != 2 && NumElems != 4) return false;
2256 unsigned Half = NumElems / 2;
2257 for (unsigned i = 0; i < Half; ++i)
2258 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2260 for (unsigned i = Half; i < NumElems; ++i)
2261 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2267 bool X86::isSHUFPMask(SDNode *N) {
2268 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2269 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2272 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2273 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2274 /// half elements to come from vector 1 (which would equal the dest.) and
2275 /// the upper half to come from vector 2.
2276 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2277 if (NumOps != 2 && NumOps != 4) return false;
2279 unsigned Half = NumOps / 2;
2280 for (unsigned i = 0; i < Half; ++i)
2281 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2283 for (unsigned i = Half; i < NumOps; ++i)
2284 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2289 static bool isCommutedSHUFP(SDNode *N) {
2290 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2291 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2294 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2295 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2296 bool X86::isMOVHLPSMask(SDNode *N) {
2297 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2299 if (N->getNumOperands() != 4)
2302 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2303 return isUndefOrEqual(N->getOperand(0), 6) &&
2304 isUndefOrEqual(N->getOperand(1), 7) &&
2305 isUndefOrEqual(N->getOperand(2), 2) &&
2306 isUndefOrEqual(N->getOperand(3), 3);
2309 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2310 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2312 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2313 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2315 if (N->getNumOperands() != 4)
2318 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2319 return isUndefOrEqual(N->getOperand(0), 2) &&
2320 isUndefOrEqual(N->getOperand(1), 3) &&
2321 isUndefOrEqual(N->getOperand(2), 2) &&
2322 isUndefOrEqual(N->getOperand(3), 3);
2325 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2326 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2327 bool X86::isMOVLPMask(SDNode *N) {
2328 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2330 unsigned NumElems = N->getNumOperands();
2331 if (NumElems != 2 && NumElems != 4)
2334 for (unsigned i = 0; i < NumElems/2; ++i)
2335 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2338 for (unsigned i = NumElems/2; i < NumElems; ++i)
2339 if (!isUndefOrEqual(N->getOperand(i), i))
2345 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2346 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2348 bool X86::isMOVHPMask(SDNode *N) {
2349 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2351 unsigned NumElems = N->getNumOperands();
2352 if (NumElems != 2 && NumElems != 4)
2355 for (unsigned i = 0; i < NumElems/2; ++i)
2356 if (!isUndefOrEqual(N->getOperand(i), i))
2359 for (unsigned i = 0; i < NumElems/2; ++i) {
2360 SDOperand Arg = N->getOperand(i + NumElems/2);
2361 if (!isUndefOrEqual(Arg, i + NumElems))
2368 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2369 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2370 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2371 bool V2IsSplat = false) {
2372 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2375 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2376 SDOperand BitI = Elts[i];
2377 SDOperand BitI1 = Elts[i+1];
2378 if (!isUndefOrEqual(BitI, j))
2381 if (isUndefOrEqual(BitI1, NumElts))
2384 if (!isUndefOrEqual(BitI1, j + NumElts))
2392 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2393 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2394 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2397 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2398 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2399 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2400 bool V2IsSplat = false) {
2401 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2404 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2405 SDOperand BitI = Elts[i];
2406 SDOperand BitI1 = Elts[i+1];
2407 if (!isUndefOrEqual(BitI, j + NumElts/2))
2410 if (isUndefOrEqual(BitI1, NumElts))
2413 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2421 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2422 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2423 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2426 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2427 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2429 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2430 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2432 unsigned NumElems = N->getNumOperands();
2433 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2436 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2437 SDOperand BitI = N->getOperand(i);
2438 SDOperand BitI1 = N->getOperand(i+1);
2440 if (!isUndefOrEqual(BitI, j))
2442 if (!isUndefOrEqual(BitI1, j))
2449 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2450 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2452 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2453 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2455 unsigned NumElems = N->getNumOperands();
2456 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2459 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2460 SDOperand BitI = N->getOperand(i);
2461 SDOperand BitI1 = N->getOperand(i + 1);
2463 if (!isUndefOrEqual(BitI, j))
2465 if (!isUndefOrEqual(BitI1, j))
2472 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2473 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2474 /// MOVSD, and MOVD, i.e. setting the lowest element.
2475 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2476 if (NumElts != 2 && NumElts != 4)
2479 if (!isUndefOrEqual(Elts[0], NumElts))
2482 for (unsigned i = 1; i < NumElts; ++i) {
2483 if (!isUndefOrEqual(Elts[i], i))
2490 bool X86::isMOVLMask(SDNode *N) {
2491 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2492 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2495 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2496 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2497 /// element of vector 2 and the other elements to come from vector 1 in order.
2498 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2499 bool V2IsSplat = false,
2500 bool V2IsUndef = false) {
2501 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2504 if (!isUndefOrEqual(Ops[0], 0))
2507 for (unsigned i = 1; i < NumOps; ++i) {
2508 SDOperand Arg = Ops[i];
2509 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2510 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2511 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2518 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2519 bool V2IsUndef = false) {
2520 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2521 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2522 V2IsSplat, V2IsUndef);
2525 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2526 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2527 bool X86::isMOVSHDUPMask(SDNode *N) {
2528 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2530 if (N->getNumOperands() != 4)
2533 // Expect 1, 1, 3, 3
2534 for (unsigned i = 0; i < 2; ++i) {
2535 SDOperand Arg = N->getOperand(i);
2536 if (Arg.getOpcode() == ISD::UNDEF) continue;
2537 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2538 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2539 if (Val != 1) return false;
2543 for (unsigned i = 2; i < 4; ++i) {
2544 SDOperand Arg = N->getOperand(i);
2545 if (Arg.getOpcode() == ISD::UNDEF) continue;
2546 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2547 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2548 if (Val != 3) return false;
2552 // Don't use movshdup if it can be done with a shufps.
2556 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2557 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2558 bool X86::isMOVSLDUPMask(SDNode *N) {
2559 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2561 if (N->getNumOperands() != 4)
2564 // Expect 0, 0, 2, 2
2565 for (unsigned i = 0; i < 2; ++i) {
2566 SDOperand Arg = N->getOperand(i);
2567 if (Arg.getOpcode() == ISD::UNDEF) continue;
2568 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2569 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2570 if (Val != 0) return false;
2574 for (unsigned i = 2; i < 4; ++i) {
2575 SDOperand Arg = N->getOperand(i);
2576 if (Arg.getOpcode() == ISD::UNDEF) continue;
2577 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2578 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2579 if (Val != 2) return false;
2583 // Don't use movshdup if it can be done with a shufps.
2587 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2588 /// specifies a identity operation on the LHS or RHS.
2589 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2590 unsigned NumElems = N->getNumOperands();
2591 for (unsigned i = 0; i < NumElems; ++i)
2592 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2597 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2598 /// a splat of a single element.
2599 static bool isSplatMask(SDNode *N) {
2600 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2602 // This is a splat operation if each element of the permute is the same, and
2603 // if the value doesn't reference the second vector.
2604 unsigned NumElems = N->getNumOperands();
2605 SDOperand ElementBase;
2607 for (; i != NumElems; ++i) {
2608 SDOperand Elt = N->getOperand(i);
2609 if (isa<ConstantSDNode>(Elt)) {
2615 if (!ElementBase.Val)
2618 for (; i != NumElems; ++i) {
2619 SDOperand Arg = N->getOperand(i);
2620 if (Arg.getOpcode() == ISD::UNDEF) continue;
2621 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2622 if (Arg != ElementBase) return false;
2625 // Make sure it is a splat of the first vector operand.
2626 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2629 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2630 /// a splat of a single element and it's a 2 or 4 element mask.
2631 bool X86::isSplatMask(SDNode *N) {
2632 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2634 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2635 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2637 return ::isSplatMask(N);
2640 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2641 /// specifies a splat of zero element.
2642 bool X86::isSplatLoMask(SDNode *N) {
2643 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2645 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2646 if (!isUndefOrEqual(N->getOperand(i), 0))
2651 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2652 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2654 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2655 unsigned NumOperands = N->getNumOperands();
2656 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2658 for (unsigned i = 0; i < NumOperands; ++i) {
2660 SDOperand Arg = N->getOperand(NumOperands-i-1);
2661 if (Arg.getOpcode() != ISD::UNDEF)
2662 Val = cast<ConstantSDNode>(Arg)->getValue();
2663 if (Val >= NumOperands) Val -= NumOperands;
2665 if (i != NumOperands - 1)
2672 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2673 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2675 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2677 // 8 nodes, but we only care about the last 4.
2678 for (unsigned i = 7; i >= 4; --i) {
2680 SDOperand Arg = N->getOperand(i);
2681 if (Arg.getOpcode() != ISD::UNDEF)
2682 Val = cast<ConstantSDNode>(Arg)->getValue();
2691 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2692 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2694 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2696 // 8 nodes, but we only care about the first 4.
2697 for (int i = 3; i >= 0; --i) {
2699 SDOperand Arg = N->getOperand(i);
2700 if (Arg.getOpcode() != ISD::UNDEF)
2701 Val = cast<ConstantSDNode>(Arg)->getValue();
2710 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2711 /// specifies a 8 element shuffle that can be broken into a pair of
2712 /// PSHUFHW and PSHUFLW.
2713 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2714 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2716 if (N->getNumOperands() != 8)
2719 // Lower quadword shuffled.
2720 for (unsigned i = 0; i != 4; ++i) {
2721 SDOperand Arg = N->getOperand(i);
2722 if (Arg.getOpcode() == ISD::UNDEF) continue;
2723 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2724 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2729 // Upper quadword shuffled.
2730 for (unsigned i = 4; i != 8; ++i) {
2731 SDOperand Arg = N->getOperand(i);
2732 if (Arg.getOpcode() == ISD::UNDEF) continue;
2733 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2734 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2735 if (Val < 4 || Val > 7)
2742 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2743 /// values in ther permute mask.
2744 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2745 SDOperand &V2, SDOperand &Mask,
2746 SelectionDAG &DAG) {
2747 MVT::ValueType VT = Op.getValueType();
2748 MVT::ValueType MaskVT = Mask.getValueType();
2749 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2750 unsigned NumElems = Mask.getNumOperands();
2751 SmallVector<SDOperand, 8> MaskVec;
2753 for (unsigned i = 0; i != NumElems; ++i) {
2754 SDOperand Arg = Mask.getOperand(i);
2755 if (Arg.getOpcode() == ISD::UNDEF) {
2756 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2759 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2760 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2762 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2764 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2768 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2769 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2772 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2773 /// the two vector operands have swapped position.
2775 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2776 MVT::ValueType MaskVT = Mask.getValueType();
2777 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2778 unsigned NumElems = Mask.getNumOperands();
2779 SmallVector<SDOperand, 8> MaskVec;
2780 for (unsigned i = 0; i != NumElems; ++i) {
2781 SDOperand Arg = Mask.getOperand(i);
2782 if (Arg.getOpcode() == ISD::UNDEF) {
2783 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2786 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2787 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2789 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2791 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2793 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2797 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2798 /// match movhlps. The lower half elements should come from upper half of
2799 /// V1 (and in order), and the upper half elements should come from the upper
2800 /// half of V2 (and in order).
2801 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2802 unsigned NumElems = Mask->getNumOperands();
2805 for (unsigned i = 0, e = 2; i != e; ++i)
2806 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2808 for (unsigned i = 2; i != 4; ++i)
2809 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2814 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2815 /// is promoted to a vector.
2816 static inline bool isScalarLoadToVector(SDNode *N) {
2817 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2818 N = N->getOperand(0).Val;
2819 return ISD::isNON_EXTLoad(N);
2824 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2825 /// match movlp{s|d}. The lower half elements should come from lower half of
2826 /// V1 (and in order), and the upper half elements should come from the upper
2827 /// half of V2 (and in order). And since V1 will become the source of the
2828 /// MOVLP, it must be either a vector load or a scalar load to vector.
2829 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2830 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2832 // Is V2 is a vector load, don't do this transformation. We will try to use
2833 // load folding shufps op.
2834 if (ISD::isNON_EXTLoad(V2))
2837 unsigned NumElems = Mask->getNumOperands();
2838 if (NumElems != 2 && NumElems != 4)
2840 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2841 if (!isUndefOrEqual(Mask->getOperand(i), i))
2843 for (unsigned i = NumElems/2; i != NumElems; ++i)
2844 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2849 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2851 static bool isSplatVector(SDNode *N) {
2852 if (N->getOpcode() != ISD::BUILD_VECTOR)
2855 SDOperand SplatValue = N->getOperand(0);
2856 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2857 if (N->getOperand(i) != SplatValue)
2862 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2864 static bool isUndefShuffle(SDNode *N) {
2865 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2868 SDOperand V1 = N->getOperand(0);
2869 SDOperand V2 = N->getOperand(1);
2870 SDOperand Mask = N->getOperand(2);
2871 unsigned NumElems = Mask.getNumOperands();
2872 for (unsigned i = 0; i != NumElems; ++i) {
2873 SDOperand Arg = Mask.getOperand(i);
2874 if (Arg.getOpcode() != ISD::UNDEF) {
2875 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2876 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2878 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2885 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2887 static inline bool isZeroNode(SDOperand Elt) {
2888 return ((isa<ConstantSDNode>(Elt) &&
2889 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2890 (isa<ConstantFPSDNode>(Elt) &&
2891 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2894 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2895 /// to an zero vector.
2896 static bool isZeroShuffle(SDNode *N) {
2897 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2900 SDOperand V1 = N->getOperand(0);
2901 SDOperand V2 = N->getOperand(1);
2902 SDOperand Mask = N->getOperand(2);
2903 unsigned NumElems = Mask.getNumOperands();
2904 for (unsigned i = 0; i != NumElems; ++i) {
2905 SDOperand Arg = Mask.getOperand(i);
2906 if (Arg.getOpcode() == ISD::UNDEF)
2909 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2910 if (Idx < NumElems) {
2911 unsigned Opc = V1.Val->getOpcode();
2912 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2914 if (Opc != ISD::BUILD_VECTOR ||
2915 !isZeroNode(V1.Val->getOperand(Idx)))
2917 } else if (Idx >= NumElems) {
2918 unsigned Opc = V2.Val->getOpcode();
2919 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2921 if (Opc != ISD::BUILD_VECTOR ||
2922 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2929 /// getZeroVector - Returns a vector of specified type with all zero elements.
2931 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2932 assert(MVT::isVector(VT) && "Expected a vector type");
2934 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2935 // type. This ensures they get CSE'd.
2936 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2938 if (MVT::getSizeInBits(VT) == 64) // MMX
2939 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2941 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2942 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2945 /// getOnesVector - Returns a vector of specified type with all bits set.
2947 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2948 assert(MVT::isVector(VT) && "Expected a vector type");
2950 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2951 // type. This ensures they get CSE'd.
2952 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2954 if (MVT::getSizeInBits(VT) == 64) // MMX
2955 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2957 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2958 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2962 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2963 /// that point to V2 points to its first element.
2964 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2965 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2967 bool Changed = false;
2968 SmallVector<SDOperand, 8> MaskVec;
2969 unsigned NumElems = Mask.getNumOperands();
2970 for (unsigned i = 0; i != NumElems; ++i) {
2971 SDOperand Arg = Mask.getOperand(i);
2972 if (Arg.getOpcode() != ISD::UNDEF) {
2973 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2974 if (Val > NumElems) {
2975 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2979 MaskVec.push_back(Arg);
2983 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2984 &MaskVec[0], MaskVec.size());
2988 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2989 /// operation of specified width.
2990 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2991 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2992 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2994 SmallVector<SDOperand, 8> MaskVec;
2995 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2996 for (unsigned i = 1; i != NumElems; ++i)
2997 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2998 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3001 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
3002 /// of specified width.
3003 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
3004 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3005 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3006 SmallVector<SDOperand, 8> MaskVec;
3007 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3008 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3009 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
3011 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3014 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3015 /// of specified width.
3016 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
3017 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3018 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3019 unsigned Half = NumElems/2;
3020 SmallVector<SDOperand, 8> MaskVec;
3021 for (unsigned i = 0; i != Half; ++i) {
3022 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3023 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3025 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3028 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
3030 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
3031 SDOperand V1 = Op.getOperand(0);
3032 SDOperand Mask = Op.getOperand(2);
3033 MVT::ValueType VT = Op.getValueType();
3034 unsigned NumElems = Mask.getNumOperands();
3035 Mask = getUnpacklMask(NumElems, DAG);
3036 while (NumElems != 4) {
3037 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
3040 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
3042 Mask = getZeroVector(MVT::v4i32, DAG);
3043 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
3044 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
3045 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3048 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3049 /// vector of zero or undef vector. This produces a shuffle where the low
3050 /// element of V2 is swizzled into the zero/undef vector, landing at element
3051 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3052 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
3053 unsigned NumElems, unsigned Idx,
3054 bool isZero, SelectionDAG &DAG) {
3055 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
3056 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3057 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3058 SmallVector<SDOperand, 16> MaskVec;
3059 for (unsigned i = 0; i != NumElems; ++i)
3060 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3061 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3063 MaskVec.push_back(DAG.getConstant(i, EVT));
3064 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3065 &MaskVec[0], MaskVec.size());
3066 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3069 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3071 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
3072 unsigned NumNonZero, unsigned NumZero,
3073 SelectionDAG &DAG, TargetLowering &TLI) {
3079 for (unsigned i = 0; i < 16; ++i) {
3080 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3081 if (ThisIsNonZero && First) {
3083 V = getZeroVector(MVT::v8i16, DAG);
3085 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3090 SDOperand ThisElt(0, 0), LastElt(0, 0);
3091 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3092 if (LastIsNonZero) {
3093 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3095 if (ThisIsNonZero) {
3096 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3097 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3098 ThisElt, DAG.getConstant(8, MVT::i8));
3100 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3105 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3106 DAG.getConstant(i/2, TLI.getPointerTy()));
3110 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3113 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3115 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3116 unsigned NumNonZero, unsigned NumZero,
3117 SelectionDAG &DAG, TargetLowering &TLI) {
3123 for (unsigned i = 0; i < 8; ++i) {
3124 bool isNonZero = (NonZeros & (1 << i)) != 0;
3128 V = getZeroVector(MVT::v8i16, DAG);
3130 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3133 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3134 DAG.getConstant(i, TLI.getPointerTy()));
3142 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3143 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3144 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3145 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3146 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3147 // eliminated on x86-32 hosts.
3148 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3151 if (ISD::isBuildVectorAllOnes(Op.Val))
3152 return getOnesVector(Op.getValueType(), DAG);
3153 return getZeroVector(Op.getValueType(), DAG);
3156 MVT::ValueType VT = Op.getValueType();
3157 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3158 unsigned EVTBits = MVT::getSizeInBits(EVT);
3160 unsigned NumElems = Op.getNumOperands();
3161 unsigned NumZero = 0;
3162 unsigned NumNonZero = 0;
3163 unsigned NonZeros = 0;
3164 bool HasNonImms = false;
3165 SmallSet<SDOperand, 8> Values;
3166 for (unsigned i = 0; i < NumElems; ++i) {
3167 SDOperand Elt = Op.getOperand(i);
3168 if (Elt.getOpcode() == ISD::UNDEF)
3171 if (Elt.getOpcode() != ISD::Constant &&
3172 Elt.getOpcode() != ISD::ConstantFP)
3174 if (isZeroNode(Elt))
3177 NonZeros |= (1 << i);
3182 if (NumNonZero == 0) {
3183 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3184 return DAG.getNode(ISD::UNDEF, VT);
3187 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3188 if (Values.size() == 1)
3191 // Special case for single non-zero element.
3192 if (NumNonZero == 1 && NumElems <= 4) {
3193 unsigned Idx = CountTrailingZeros_32(NonZeros);
3194 SDOperand Item = Op.getOperand(Idx);
3195 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3197 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3198 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
3200 else if (!HasNonImms) // Otherwise, it's better to do a constpool load.
3203 if (EVTBits == 32) {
3204 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3205 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
3207 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3208 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3209 SmallVector<SDOperand, 8> MaskVec;
3210 for (unsigned i = 0; i < NumElems; i++)
3211 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3212 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3213 &MaskVec[0], MaskVec.size());
3214 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3215 DAG.getNode(ISD::UNDEF, VT), Mask);
3219 // A vector full of immediates; various special cases are already
3220 // handled, so this is best done with a single constant-pool load.
3224 // Let legalizer expand 2-wide build_vectors.
3228 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3229 if (EVTBits == 8 && NumElems == 16) {
3230 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3232 if (V.Val) return V;
3235 if (EVTBits == 16 && NumElems == 8) {
3236 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3238 if (V.Val) return V;
3241 // If element VT is == 32 bits, turn it into a number of shuffles.
3242 SmallVector<SDOperand, 8> V;
3244 if (NumElems == 4 && NumZero > 0) {
3245 for (unsigned i = 0; i < 4; ++i) {
3246 bool isZero = !(NonZeros & (1 << i));
3248 V[i] = getZeroVector(VT, DAG);
3250 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3253 for (unsigned i = 0; i < 2; ++i) {
3254 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3257 V[i] = V[i*2]; // Must be a zero vector.
3260 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3261 getMOVLMask(NumElems, DAG));
3264 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3265 getMOVLMask(NumElems, DAG));
3268 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3269 getUnpacklMask(NumElems, DAG));
3274 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3275 // clears the upper bits.
3276 // FIXME: we can do the same for v4f32 case when we know both parts of
3277 // the lower half come from scalar_to_vector (loadf32). We should do
3278 // that in post legalizer dag combiner with target specific hooks.
3279 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3281 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3282 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3283 SmallVector<SDOperand, 8> MaskVec;
3284 bool Reverse = (NonZeros & 0x3) == 2;
3285 for (unsigned i = 0; i < 2; ++i)
3287 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3289 MaskVec.push_back(DAG.getConstant(i, EVT));
3290 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3291 for (unsigned i = 0; i < 2; ++i)
3293 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3295 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3296 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3297 &MaskVec[0], MaskVec.size());
3298 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3301 if (Values.size() > 2) {
3302 // Expand into a number of unpckl*.
3304 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3305 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3306 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3307 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3308 for (unsigned i = 0; i < NumElems; ++i)
3309 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3311 while (NumElems != 0) {
3312 for (unsigned i = 0; i < NumElems; ++i)
3313 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3324 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3325 SDOperand PermMask, SelectionDAG &DAG,
3326 TargetLowering &TLI) {
3328 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3329 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3330 MVT::ValueType PtrVT = TLI.getPointerTy();
3331 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3332 PermMask.Val->op_end());
3334 // First record which half of which vector the low elements come from.
3335 SmallVector<unsigned, 4> LowQuad(4);
3336 for (unsigned i = 0; i < 4; ++i) {
3337 SDOperand Elt = MaskElts[i];
3338 if (Elt.getOpcode() == ISD::UNDEF)
3340 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3341 int QuadIdx = EltIdx / 4;
3344 int BestLowQuad = -1;
3345 unsigned MaxQuad = 1;
3346 for (unsigned i = 0; i < 4; ++i) {
3347 if (LowQuad[i] > MaxQuad) {
3349 MaxQuad = LowQuad[i];
3353 // Record which half of which vector the high elements come from.
3354 SmallVector<unsigned, 4> HighQuad(4);
3355 for (unsigned i = 4; i < 8; ++i) {
3356 SDOperand Elt = MaskElts[i];
3357 if (Elt.getOpcode() == ISD::UNDEF)
3359 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3360 int QuadIdx = EltIdx / 4;
3361 ++HighQuad[QuadIdx];
3363 int BestHighQuad = -1;
3365 for (unsigned i = 0; i < 4; ++i) {
3366 if (HighQuad[i] > MaxQuad) {
3368 MaxQuad = HighQuad[i];
3372 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3373 if (BestLowQuad != -1 || BestHighQuad != -1) {
3374 // First sort the 4 chunks in order using shufpd.
3375 SmallVector<SDOperand, 8> MaskVec;
3376 if (BestLowQuad != -1)
3377 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3379 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3380 if (BestHighQuad != -1)
3381 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3383 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3384 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3385 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3386 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3387 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3388 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3390 // Now sort high and low parts separately.
3391 BitVector InOrder(8);
3392 if (BestLowQuad != -1) {
3393 // Sort lower half in order using PSHUFLW.
3395 bool AnyOutOrder = false;
3396 for (unsigned i = 0; i != 4; ++i) {
3397 SDOperand Elt = MaskElts[i];
3398 if (Elt.getOpcode() == ISD::UNDEF) {
3399 MaskVec.push_back(Elt);
3402 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3405 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3406 // If this element is in the right place after this shuffle, then
3408 if ((int)(EltIdx / 4) == BestLowQuad)
3413 for (unsigned i = 4; i != 8; ++i)
3414 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3415 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3416 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3420 if (BestHighQuad != -1) {
3421 // Sort high half in order using PSHUFHW if possible.
3423 for (unsigned i = 0; i != 4; ++i)
3424 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3425 bool AnyOutOrder = false;
3426 for (unsigned i = 4; i != 8; ++i) {
3427 SDOperand Elt = MaskElts[i];
3428 if (Elt.getOpcode() == ISD::UNDEF) {
3429 MaskVec.push_back(Elt);
3432 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3435 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3436 // If this element is in the right place after this shuffle, then
3438 if ((int)(EltIdx / 4) == BestHighQuad)
3443 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3444 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3448 // The other elements are put in the right place using pextrw and pinsrw.
3449 for (unsigned i = 0; i != 8; ++i) {
3452 SDOperand Elt = MaskElts[i];
3453 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3456 SDOperand ExtOp = (EltIdx < 8)
3457 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3458 DAG.getConstant(EltIdx, PtrVT))
3459 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3460 DAG.getConstant(EltIdx - 8, PtrVT));
3461 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3462 DAG.getConstant(i, PtrVT));
3467 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3468 ///as few as possible.
3469 // First, let's find out how many elements are already in the right order.
3470 unsigned V1InOrder = 0;
3471 unsigned V1FromV1 = 0;
3472 unsigned V2InOrder = 0;
3473 unsigned V2FromV2 = 0;
3474 SmallVector<SDOperand, 8> V1Elts;
3475 SmallVector<SDOperand, 8> V2Elts;
3476 for (unsigned i = 0; i < 8; ++i) {
3477 SDOperand Elt = MaskElts[i];
3478 if (Elt.getOpcode() == ISD::UNDEF) {
3479 V1Elts.push_back(Elt);
3480 V2Elts.push_back(Elt);
3485 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3487 V1Elts.push_back(Elt);
3488 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3490 } else if (EltIdx == i+8) {
3491 V1Elts.push_back(Elt);
3492 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3494 } else if (EltIdx < 8) {
3495 V1Elts.push_back(Elt);
3498 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3503 if (V2InOrder > V1InOrder) {
3504 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3506 std::swap(V1Elts, V2Elts);
3507 std::swap(V1FromV1, V2FromV2);
3510 if ((V1FromV1 + V1InOrder) != 8) {
3511 // Some elements are from V2.
3513 // If there are elements that are from V1 but out of place,
3514 // then first sort them in place
3515 SmallVector<SDOperand, 8> MaskVec;
3516 for (unsigned i = 0; i < 8; ++i) {
3517 SDOperand Elt = V1Elts[i];
3518 if (Elt.getOpcode() == ISD::UNDEF) {
3519 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3522 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3524 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3526 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3528 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3529 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3533 for (unsigned i = 0; i < 8; ++i) {
3534 SDOperand Elt = V1Elts[i];
3535 if (Elt.getOpcode() == ISD::UNDEF)
3537 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3540 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3541 DAG.getConstant(EltIdx - 8, PtrVT));
3542 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3543 DAG.getConstant(i, PtrVT));
3547 // All elements are from V1.
3549 for (unsigned i = 0; i < 8; ++i) {
3550 SDOperand Elt = V1Elts[i];
3551 if (Elt.getOpcode() == ISD::UNDEF)
3553 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3554 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3555 DAG.getConstant(EltIdx, PtrVT));
3556 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3557 DAG.getConstant(i, PtrVT));
3563 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3564 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3565 /// done when every pair / quad of shuffle mask elements point to elements in
3566 /// the right sequence. e.g.
3567 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3569 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3571 SDOperand PermMask, SelectionDAG &DAG,
3572 TargetLowering &TLI) {
3573 unsigned NumElems = PermMask.getNumOperands();
3574 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3575 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3576 MVT::ValueType NewVT = MaskVT;
3578 case MVT::v4f32: NewVT = MVT::v2f64; break;
3579 case MVT::v4i32: NewVT = MVT::v2i64; break;
3580 case MVT::v8i16: NewVT = MVT::v4i32; break;
3581 case MVT::v16i8: NewVT = MVT::v4i32; break;
3582 default: assert(false && "Unexpected!");
3586 if (MVT::isInteger(VT))
3590 unsigned Scale = NumElems / NewWidth;
3591 SmallVector<SDOperand, 8> MaskVec;
3592 for (unsigned i = 0; i < NumElems; i += Scale) {
3593 unsigned StartIdx = ~0U;
3594 for (unsigned j = 0; j < Scale; ++j) {
3595 SDOperand Elt = PermMask.getOperand(i+j);
3596 if (Elt.getOpcode() == ISD::UNDEF)
3598 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3599 if (StartIdx == ~0U)
3600 StartIdx = EltIdx - (EltIdx % Scale);
3601 if (EltIdx != StartIdx + j)
3604 if (StartIdx == ~0U)
3605 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3607 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3610 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3611 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3612 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3613 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3614 &MaskVec[0], MaskVec.size()));
3618 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3619 SDOperand V1 = Op.getOperand(0);
3620 SDOperand V2 = Op.getOperand(1);
3621 SDOperand PermMask = Op.getOperand(2);
3622 MVT::ValueType VT = Op.getValueType();
3623 unsigned NumElems = PermMask.getNumOperands();
3624 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3625 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3626 bool V1IsSplat = false;
3627 bool V2IsSplat = false;
3629 if (isUndefShuffle(Op.Val))
3630 return DAG.getNode(ISD::UNDEF, VT);
3632 if (isZeroShuffle(Op.Val))
3633 return getZeroVector(VT, DAG);
3635 if (isIdentityMask(PermMask.Val))
3637 else if (isIdentityMask(PermMask.Val, true))
3640 if (isSplatMask(PermMask.Val)) {
3641 if (NumElems <= 4) return Op;
3642 // Promote it to a v4i32 splat.
3643 return PromoteSplat(Op, DAG);
3646 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3648 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3649 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3651 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3652 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3653 // FIXME: Figure out a cleaner way to do this.
3654 // Try to make use of movq to zero out the top part.
3655 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3656 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3658 SDOperand NewV1 = NewOp.getOperand(0);
3659 SDOperand NewV2 = NewOp.getOperand(1);
3660 SDOperand NewMask = NewOp.getOperand(2);
3661 if (isCommutedMOVL(NewMask.Val, true, false)) {
3662 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3663 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3664 NewV1, NewV2, getMOVLMask(2, DAG));
3665 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3668 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3669 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3670 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3671 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3675 if (X86::isMOVLMask(PermMask.Val))
3676 return (V1IsUndef) ? V2 : Op;
3678 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3679 X86::isMOVSLDUPMask(PermMask.Val) ||
3680 X86::isMOVHLPSMask(PermMask.Val) ||
3681 X86::isMOVHPMask(PermMask.Val) ||
3682 X86::isMOVLPMask(PermMask.Val))
3685 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3686 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3687 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3689 bool Commuted = false;
3690 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3691 // 1,1,1,1 -> v8i16 though.
3692 V1IsSplat = isSplatVector(V1.Val);
3693 V2IsSplat = isSplatVector(V2.Val);
3695 // Canonicalize the splat or undef, if present, to be on the RHS.
3696 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3697 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3698 std::swap(V1IsSplat, V2IsSplat);
3699 std::swap(V1IsUndef, V2IsUndef);
3703 // FIXME: Figure out a cleaner way to do this.
3704 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3705 if (V2IsUndef) return V1;
3706 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3708 // V2 is a splat, so the mask may be malformed. That is, it may point
3709 // to any V2 element. The instruction selectior won't like this. Get
3710 // a corrected mask and commute to form a proper MOVS{S|D}.
3711 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3712 if (NewMask.Val != PermMask.Val)
3713 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3718 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3719 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3720 X86::isUNPCKLMask(PermMask.Val) ||
3721 X86::isUNPCKHMask(PermMask.Val))
3725 // Normalize mask so all entries that point to V2 points to its first
3726 // element then try to match unpck{h|l} again. If match, return a
3727 // new vector_shuffle with the corrected mask.
3728 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3729 if (NewMask.Val != PermMask.Val) {
3730 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3731 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3732 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3733 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3734 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3735 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3740 // Normalize the node to match x86 shuffle ops if needed
3741 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3742 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3745 // Commute is back and try unpck* again.
3746 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3747 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3748 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3749 X86::isUNPCKLMask(PermMask.Val) ||
3750 X86::isUNPCKHMask(PermMask.Val))
3754 // If VT is integer, try PSHUF* first, then SHUFP*.
3755 if (MVT::isInteger(VT)) {
3756 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3757 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3758 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3759 X86::isPSHUFDMask(PermMask.Val)) ||
3760 X86::isPSHUFHWMask(PermMask.Val) ||
3761 X86::isPSHUFLWMask(PermMask.Val)) {
3762 if (V2.getOpcode() != ISD::UNDEF)
3763 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3764 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3768 if (X86::isSHUFPMask(PermMask.Val) &&
3769 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3772 // Floating point cases in the other order.
3773 if (X86::isSHUFPMask(PermMask.Val))
3775 if (X86::isPSHUFDMask(PermMask.Val) ||
3776 X86::isPSHUFHWMask(PermMask.Val) ||
3777 X86::isPSHUFLWMask(PermMask.Val)) {
3778 if (V2.getOpcode() != ISD::UNDEF)
3779 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3780 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3785 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3786 if (VT == MVT::v8i16) {
3787 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3792 // Handle all 4 wide cases with a number of shuffles.
3793 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3794 // Don't do this for MMX.
3795 MVT::ValueType MaskVT = PermMask.getValueType();
3796 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3797 SmallVector<std::pair<int, int>, 8> Locs;
3798 Locs.reserve(NumElems);
3799 SmallVector<SDOperand, 8> Mask1(NumElems,
3800 DAG.getNode(ISD::UNDEF, MaskEVT));
3801 SmallVector<SDOperand, 8> Mask2(NumElems,
3802 DAG.getNode(ISD::UNDEF, MaskEVT));
3805 // If no more than two elements come from either vector. This can be
3806 // implemented with two shuffles. First shuffle gather the elements.
3807 // The second shuffle, which takes the first shuffle as both of its
3808 // vector operands, put the elements into the right order.
3809 for (unsigned i = 0; i != NumElems; ++i) {
3810 SDOperand Elt = PermMask.getOperand(i);
3811 if (Elt.getOpcode() == ISD::UNDEF) {
3812 Locs[i] = std::make_pair(-1, -1);
3814 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3815 if (Val < NumElems) {
3816 Locs[i] = std::make_pair(0, NumLo);
3820 Locs[i] = std::make_pair(1, NumHi);
3821 if (2+NumHi < NumElems)
3822 Mask1[2+NumHi] = Elt;
3827 if (NumLo <= 2 && NumHi <= 2) {
3828 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3829 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3830 &Mask1[0], Mask1.size()));
3831 for (unsigned i = 0; i != NumElems; ++i) {
3832 if (Locs[i].first == -1)
3835 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3836 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3837 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3841 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3842 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3843 &Mask2[0], Mask2.size()));
3846 // Break it into (shuffle shuffle_hi, shuffle_lo).
3848 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3849 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3850 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3851 unsigned MaskIdx = 0;
3853 unsigned HiIdx = NumElems/2;
3854 for (unsigned i = 0; i != NumElems; ++i) {
3855 if (i == NumElems/2) {
3861 SDOperand Elt = PermMask.getOperand(i);
3862 if (Elt.getOpcode() == ISD::UNDEF) {
3863 Locs[i] = std::make_pair(-1, -1);
3864 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3865 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3866 (*MaskPtr)[LoIdx] = Elt;
3869 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3870 (*MaskPtr)[HiIdx] = Elt;
3875 SDOperand LoShuffle =
3876 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3877 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3878 &LoMask[0], LoMask.size()));
3879 SDOperand HiShuffle =
3880 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3881 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3882 &HiMask[0], HiMask.size()));
3883 SmallVector<SDOperand, 8> MaskOps;
3884 for (unsigned i = 0; i != NumElems; ++i) {
3885 if (Locs[i].first == -1) {
3886 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3888 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3889 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3892 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3893 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3894 &MaskOps[0], MaskOps.size()));
3901 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3902 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3905 MVT::ValueType VT = Op.getValueType();
3906 // TODO: handle v16i8.
3907 if (MVT::getSizeInBits(VT) == 16) {
3908 SDOperand Vec = Op.getOperand(0);
3909 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3911 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3912 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3913 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3915 // Transform it so it match pextrw which produces a 32-bit result.
3916 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3917 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3918 Op.getOperand(0), Op.getOperand(1));
3919 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3920 DAG.getValueType(VT));
3921 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3922 } else if (MVT::getSizeInBits(VT) == 32) {
3923 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3926 // SHUFPS the element to the lowest double word, then movss.
3927 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3928 SmallVector<SDOperand, 8> IdxVec;
3930 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3932 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3934 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3936 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3937 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3938 &IdxVec[0], IdxVec.size());
3939 SDOperand Vec = Op.getOperand(0);
3940 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3941 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3942 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3943 DAG.getConstant(0, getPointerTy()));
3944 } else if (MVT::getSizeInBits(VT) == 64) {
3945 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3949 // UNPCKHPD the element to the lowest double word, then movsd.
3950 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3951 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3952 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3953 SmallVector<SDOperand, 8> IdxVec;
3954 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3956 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3957 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3958 &IdxVec[0], IdxVec.size());
3959 SDOperand Vec = Op.getOperand(0);
3960 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3961 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3962 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3963 DAG.getConstant(0, getPointerTy()));
3970 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3971 MVT::ValueType VT = Op.getValueType();
3972 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3976 SDOperand N0 = Op.getOperand(0);
3977 SDOperand N1 = Op.getOperand(1);
3978 SDOperand N2 = Op.getOperand(2);
3980 if (MVT::getSizeInBits(EVT) == 16) {
3981 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3982 // as its second argument.
3983 if (N1.getValueType() != MVT::i32)
3984 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3985 if (N2.getValueType() != MVT::i32)
3986 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
3987 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3990 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
3991 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
3992 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3993 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3994 SmallVector<SDOperand, 4> MaskVec;
3995 for (unsigned i = 0; i < 4; ++i)
3996 MaskVec.push_back(DAG.getConstant((i == Idx) ? i+4 : i, MaskEVT));
3997 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
3998 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3999 &MaskVec[0], MaskVec.size()));
4003 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
4004 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4005 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
4008 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4009 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4010 // one of the above mentioned nodes. It has to be wrapped because otherwise
4011 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4012 // be used to form addressing mode. These wrapped nodes will be selected
4015 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
4016 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4017 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
4019 CP->getAlignment());
4020 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4021 // With PIC, the address is actually $g + Offset.
4022 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4023 !Subtarget->isPICStyleRIPRel()) {
4024 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4025 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4033 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4034 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4035 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4036 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4037 // With PIC, the address is actually $g + Offset.
4038 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4039 !Subtarget->isPICStyleRIPRel()) {
4040 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4041 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4045 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4046 // load the value at address GV, not the value of GV itself. This means that
4047 // the GlobalAddress must be in the base or index register of the address, not
4048 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4049 // The same applies for external symbols during PIC codegen
4050 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4051 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
4056 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
4058 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4059 const MVT::ValueType PtrVT) {
4061 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4062 DAG.getNode(X86ISD::GlobalBaseReg,
4064 InFlag = Chain.getValue(1);
4066 // emit leal symbol@TLSGD(,%ebx,1), %eax
4067 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4068 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4069 GA->getValueType(0),
4071 SDOperand Ops[] = { Chain, TGA, InFlag };
4072 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4073 InFlag = Result.getValue(2);
4074 Chain = Result.getValue(1);
4076 // call ___tls_get_addr. This function receives its argument in
4077 // the register EAX.
4078 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4079 InFlag = Chain.getValue(1);
4081 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4082 SDOperand Ops1[] = { Chain,
4083 DAG.getTargetExternalSymbol("___tls_get_addr",
4085 DAG.getRegister(X86::EAX, PtrVT),
4086 DAG.getRegister(X86::EBX, PtrVT),
4088 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4089 InFlag = Chain.getValue(1);
4091 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4094 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4095 // "local exec" model.
4097 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4098 const MVT::ValueType PtrVT) {
4099 // Get the Thread Pointer
4100 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4101 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4103 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4104 GA->getValueType(0),
4106 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4108 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4109 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
4111 // The address of the thread local variable is the add of the thread
4112 // pointer with the offset of the variable.
4113 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4117 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4118 // TODO: implement the "local dynamic" model
4119 // TODO: implement the "initial exec"model for pic executables
4120 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4121 "TLS not implemented for non-ELF and 64-bit targets");
4122 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4123 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4124 // otherwise use the "Local Exec"TLS Model
4125 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4126 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4128 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4132 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4133 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4134 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4135 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4136 // With PIC, the address is actually $g + Offset.
4137 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4138 !Subtarget->isPICStyleRIPRel()) {
4139 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4140 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4147 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4148 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4149 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4150 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4151 // With PIC, the address is actually $g + Offset.
4152 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4153 !Subtarget->isPICStyleRIPRel()) {
4154 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4155 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4162 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4163 /// take a 2 x i32 value to shift plus a shift amount.
4164 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4165 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
4166 "Not an i64 shift!");
4167 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4168 SDOperand ShOpLo = Op.getOperand(0);
4169 SDOperand ShOpHi = Op.getOperand(1);
4170 SDOperand ShAmt = Op.getOperand(2);
4171 SDOperand Tmp1 = isSRA ?
4172 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
4173 DAG.getConstant(0, MVT::i32);
4175 SDOperand Tmp2, Tmp3;
4176 if (Op.getOpcode() == ISD::SHL_PARTS) {
4177 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
4178 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
4180 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
4181 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
4184 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4185 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4186 DAG.getConstant(32, MVT::i8));
4187 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
4188 AndNode, DAG.getConstant(0, MVT::i8));
4191 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4192 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
4193 SmallVector<SDOperand, 4> Ops;
4194 if (Op.getOpcode() == ISD::SHL_PARTS) {
4195 Ops.push_back(Tmp2);
4196 Ops.push_back(Tmp3);
4198 Ops.push_back(Cond);
4199 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4202 Ops.push_back(Tmp3);
4203 Ops.push_back(Tmp1);
4205 Ops.push_back(Cond);
4206 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4208 Ops.push_back(Tmp2);
4209 Ops.push_back(Tmp3);
4211 Ops.push_back(Cond);
4212 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4215 Ops.push_back(Tmp3);
4216 Ops.push_back(Tmp1);
4218 Ops.push_back(Cond);
4219 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4222 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
4226 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4229 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4230 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
4231 Op.getOperand(0).getValueType() >= MVT::i16 &&
4232 "Unknown SINT_TO_FP to lower!");
4235 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4236 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4237 MachineFunction &MF = DAG.getMachineFunction();
4238 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4239 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4240 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4241 StackSlot, NULL, 0);
4243 // These are really Legal; caller falls through into that case.
4244 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f32 && X86ScalarSSEf32)
4246 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f64 && X86ScalarSSEf64)
4248 if (SrcVT==MVT::i64 && Op.getValueType() != MVT::f80 &&
4249 Subtarget->is64Bit())
4254 bool useSSE = (X86ScalarSSEf32 && Op.getValueType() == MVT::f32) ||
4255 (X86ScalarSSEf64 && Op.getValueType() == MVT::f64);
4257 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4259 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4260 SmallVector<SDOperand, 8> Ops;
4261 Ops.push_back(Chain);
4262 Ops.push_back(StackSlot);
4263 Ops.push_back(DAG.getValueType(SrcVT));
4264 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
4265 Tys, &Ops[0], Ops.size());
4268 Chain = Result.getValue(1);
4269 SDOperand InFlag = Result.getValue(2);
4271 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4272 // shouldn't be necessary except that RFP cannot be live across
4273 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4274 MachineFunction &MF = DAG.getMachineFunction();
4275 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4276 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4277 Tys = DAG.getVTList(MVT::Other);
4278 SmallVector<SDOperand, 8> Ops;
4279 Ops.push_back(Chain);
4280 Ops.push_back(Result);
4281 Ops.push_back(StackSlot);
4282 Ops.push_back(DAG.getValueType(Op.getValueType()));
4283 Ops.push_back(InFlag);
4284 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4285 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
4291 std::pair<SDOperand,SDOperand> X86TargetLowering::
4292 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4293 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4294 "Unknown FP_TO_SINT to lower!");
4296 // These are really Legal.
4297 if (Op.getValueType() == MVT::i32 &&
4298 X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32)
4299 return std::make_pair(SDOperand(), SDOperand());
4300 if (Op.getValueType() == MVT::i32 &&
4301 X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)
4302 return std::make_pair(SDOperand(), SDOperand());
4303 if (Subtarget->is64Bit() &&
4304 Op.getValueType() == MVT::i64 &&
4305 Op.getOperand(0).getValueType() != MVT::f80)
4306 return std::make_pair(SDOperand(), SDOperand());
4308 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4310 MachineFunction &MF = DAG.getMachineFunction();
4311 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4312 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4313 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4315 switch (Op.getValueType()) {
4316 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4317 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4318 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4319 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4322 SDOperand Chain = DAG.getEntryNode();
4323 SDOperand Value = Op.getOperand(0);
4324 if ((X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32) ||
4325 (X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)) {
4326 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4327 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
4328 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4330 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4332 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4333 Chain = Value.getValue(1);
4334 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4335 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4338 // Build the FP_TO_INT*_IN_MEM
4339 SDOperand Ops[] = { Chain, Value, StackSlot };
4340 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4342 return std::make_pair(FIST, StackSlot);
4345 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4346 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4347 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4348 if (FIST.Val == 0) return SDOperand();
4351 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4354 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4355 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4356 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4357 if (FIST.Val == 0) return 0;
4359 // Return an i64 load from the stack slot.
4360 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4362 // Use a MERGE_VALUES node to drop the chain result value.
4363 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4366 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4367 MVT::ValueType VT = Op.getValueType();
4368 MVT::ValueType EltVT = VT;
4369 if (MVT::isVector(VT))
4370 EltVT = MVT::getVectorElementType(VT);
4371 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4372 std::vector<Constant*> CV;
4373 if (EltVT == MVT::f64) {
4374 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4378 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4384 Constant *C = ConstantVector::get(CV);
4385 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4386 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4388 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4391 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4392 MVT::ValueType VT = Op.getValueType();
4393 MVT::ValueType EltVT = VT;
4394 unsigned EltNum = 1;
4395 if (MVT::isVector(VT)) {
4396 EltVT = MVT::getVectorElementType(VT);
4397 EltNum = MVT::getVectorNumElements(VT);
4399 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4400 std::vector<Constant*> CV;
4401 if (EltVT == MVT::f64) {
4402 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4406 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4412 Constant *C = ConstantVector::get(CV);
4413 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4414 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4416 if (MVT::isVector(VT)) {
4417 return DAG.getNode(ISD::BIT_CONVERT, VT,
4418 DAG.getNode(ISD::XOR, MVT::v2i64,
4419 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4420 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4422 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4426 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4427 SDOperand Op0 = Op.getOperand(0);
4428 SDOperand Op1 = Op.getOperand(1);
4429 MVT::ValueType VT = Op.getValueType();
4430 MVT::ValueType SrcVT = Op1.getValueType();
4431 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4433 // If second operand is smaller, extend it first.
4434 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4435 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4437 SrcTy = MVT::getTypeForValueType(SrcVT);
4439 // And if it is bigger, shrink it first.
4440 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4441 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1);
4443 SrcTy = MVT::getTypeForValueType(SrcVT);
4446 // At this point the operands and the result should have the same
4447 // type, and that won't be f80 since that is not custom lowered.
4449 // First get the sign bit of second operand.
4450 std::vector<Constant*> CV;
4451 if (SrcVT == MVT::f64) {
4452 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4453 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4455 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4456 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4457 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4458 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4460 Constant *C = ConstantVector::get(CV);
4461 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4462 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx, NULL, 0,
4464 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4466 // Shift sign bit right or left if the two operands have different types.
4467 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4468 // Op0 is MVT::f32, Op1 is MVT::f64.
4469 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4470 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4471 DAG.getConstant(32, MVT::i32));
4472 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4473 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4474 DAG.getConstant(0, getPointerTy()));
4477 // Clear first operand sign bit.
4479 if (VT == MVT::f64) {
4480 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4481 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4483 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4484 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4485 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4486 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4488 C = ConstantVector::get(CV);
4489 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4490 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4492 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4494 // Or the value with the sign bit.
4495 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4498 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4499 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4501 SDOperand Op0 = Op.getOperand(0);
4502 SDOperand Op1 = Op.getOperand(1);
4503 SDOperand CC = Op.getOperand(2);
4504 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4505 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4508 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4510 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4511 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4512 DAG.getConstant(X86CC, MVT::i8), Cond);
4515 assert(isFP && "Illegal integer SetCC!");
4517 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4518 switch (SetCCOpcode) {
4519 default: assert(false && "Illegal floating point SetCC!");
4520 case ISD::SETOEQ: { // !PF & ZF
4521 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4522 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4523 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4524 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4525 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4527 case ISD::SETUNE: { // PF | !ZF
4528 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4529 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4530 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4531 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4532 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4538 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4539 bool addTest = true;
4540 SDOperand Cond = Op.getOperand(0);
4543 if (Cond.getOpcode() == ISD::SETCC)
4544 Cond = LowerSETCC(Cond, DAG);
4546 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4547 // setting operand in place of the X86ISD::SETCC.
4548 if (Cond.getOpcode() == X86ISD::SETCC) {
4549 CC = Cond.getOperand(0);
4551 SDOperand Cmp = Cond.getOperand(1);
4552 unsigned Opc = Cmp.getOpcode();
4553 MVT::ValueType VT = Op.getValueType();
4554 bool IllegalFPCMov = false;
4555 if (VT == MVT::f32 && !X86ScalarSSEf32)
4556 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4557 else if (VT == MVT::f64 && !X86ScalarSSEf64)
4558 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4559 else if (VT == MVT::f80)
4560 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4561 if ((Opc == X86ISD::CMP ||
4562 Opc == X86ISD::COMI ||
4563 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4570 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4571 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4574 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4576 SmallVector<SDOperand, 4> Ops;
4577 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4578 // condition is true.
4579 Ops.push_back(Op.getOperand(2));
4580 Ops.push_back(Op.getOperand(1));
4582 Ops.push_back(Cond);
4583 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4586 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4587 bool addTest = true;
4588 SDOperand Chain = Op.getOperand(0);
4589 SDOperand Cond = Op.getOperand(1);
4590 SDOperand Dest = Op.getOperand(2);
4593 if (Cond.getOpcode() == ISD::SETCC)
4594 Cond = LowerSETCC(Cond, DAG);
4596 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4597 // setting operand in place of the X86ISD::SETCC.
4598 if (Cond.getOpcode() == X86ISD::SETCC) {
4599 CC = Cond.getOperand(0);
4601 SDOperand Cmp = Cond.getOperand(1);
4602 unsigned Opc = Cmp.getOpcode();
4603 if (Opc == X86ISD::CMP ||
4604 Opc == X86ISD::COMI ||
4605 Opc == X86ISD::UCOMI) {
4612 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4613 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4615 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4616 Chain, Op.getOperand(2), CC, Cond);
4619 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
4620 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4621 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
4623 if (Subtarget->is64Bit())
4624 if(CallingConv==CallingConv::Fast && isTailCall && PerformTailCallOpt)
4625 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4627 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
4629 switch (CallingConv) {
4631 assert(0 && "Unsupported calling convention");
4632 case CallingConv::Fast:
4633 if (isTailCall && PerformTailCallOpt)
4634 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4636 return LowerCCCCallTo(Op,DAG, CallingConv);
4637 case CallingConv::C:
4638 case CallingConv::X86_StdCall:
4639 return LowerCCCCallTo(Op, DAG, CallingConv);
4640 case CallingConv::X86_FastCall:
4641 return LowerFastCCCallTo(Op, DAG, CallingConv);
4646 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4647 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4648 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4649 // that the guard pages used by the OS virtual memory manager are allocated in
4650 // correct sequence.
4652 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4653 SelectionDAG &DAG) {
4654 assert(Subtarget->isTargetCygMing() &&
4655 "This should be used only on Cygwin/Mingw targets");
4658 SDOperand Chain = Op.getOperand(0);
4659 SDOperand Size = Op.getOperand(1);
4660 // FIXME: Ensure alignment here
4664 MVT::ValueType IntPtr = getPointerTy();
4665 MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
4667 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4668 Flag = Chain.getValue(1);
4670 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4671 SDOperand Ops[] = { Chain,
4672 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4673 DAG.getRegister(X86::EAX, IntPtr),
4675 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4676 Flag = Chain.getValue(1);
4678 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4680 std::vector<MVT::ValueType> Tys;
4681 Tys.push_back(SPTy);
4682 Tys.push_back(MVT::Other);
4683 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4684 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4688 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
4689 MachineFunction &MF = DAG.getMachineFunction();
4690 const Function* Fn = MF.getFunction();
4691 if (Fn->hasExternalLinkage() &&
4692 Subtarget->isTargetCygMing() &&
4693 Fn->getName() == "main")
4694 MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
4696 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4697 if (Subtarget->is64Bit())
4698 return LowerX86_64CCCArguments(Op, DAG);
4702 assert(0 && "Unsupported calling convention");
4703 case CallingConv::Fast:
4704 return LowerCCCArguments(Op,DAG, true);
4706 case CallingConv::C:
4707 return LowerCCCArguments(Op, DAG);
4708 case CallingConv::X86_StdCall:
4709 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
4710 return LowerCCCArguments(Op, DAG, true);
4711 case CallingConv::X86_FastCall:
4712 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
4713 return LowerFastCCArguments(Op, DAG);
4717 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4718 SDOperand InFlag(0, 0);
4719 SDOperand Chain = Op.getOperand(0);
4721 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4722 if (Align == 0) Align = 1;
4724 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4725 // If not DWORD aligned or size is more than the threshold, call memset.
4726 // The libc version is likely to be faster for these cases. It can use the
4727 // address value and run time information about the CPU.
4728 if ((Align & 3) != 0 ||
4729 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4730 MVT::ValueType IntPtr = getPointerTy();
4731 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4732 TargetLowering::ArgListTy Args;
4733 TargetLowering::ArgListEntry Entry;
4734 Entry.Node = Op.getOperand(1);
4735 Entry.Ty = IntPtrTy;
4736 Args.push_back(Entry);
4737 // Extend the unsigned i8 argument to be an int value for the call.
4738 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4739 Entry.Ty = IntPtrTy;
4740 Args.push_back(Entry);
4741 Entry.Node = Op.getOperand(3);
4742 Args.push_back(Entry);
4743 std::pair<SDOperand,SDOperand> CallResult =
4744 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4745 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4746 return CallResult.second;
4751 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4752 unsigned BytesLeft = 0;
4753 bool TwoRepStos = false;
4756 uint64_t Val = ValC->getValue() & 255;
4758 // If the value is a constant, then we can potentially use larger sets.
4759 switch (Align & 3) {
4760 case 2: // WORD aligned
4763 Val = (Val << 8) | Val;
4765 case 0: // DWORD aligned
4768 Val = (Val << 8) | Val;
4769 Val = (Val << 16) | Val;
4770 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4773 Val = (Val << 32) | Val;
4776 default: // Byte aligned
4779 Count = Op.getOperand(3);
4783 if (AVT > MVT::i8) {
4785 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4786 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
4787 BytesLeft = I->getValue() % UBytes;
4789 assert(AVT >= MVT::i32 &&
4790 "Do not use rep;stos if not at least DWORD aligned");
4791 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4792 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4797 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4799 InFlag = Chain.getValue(1);
4802 Count = Op.getOperand(3);
4803 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4804 InFlag = Chain.getValue(1);
4807 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4809 InFlag = Chain.getValue(1);
4810 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4811 Op.getOperand(1), InFlag);
4812 InFlag = Chain.getValue(1);
4814 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4815 SmallVector<SDOperand, 8> Ops;
4816 Ops.push_back(Chain);
4817 Ops.push_back(DAG.getValueType(AVT));
4818 Ops.push_back(InFlag);
4819 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4822 InFlag = Chain.getValue(1);
4823 Count = Op.getOperand(3);
4824 MVT::ValueType CVT = Count.getValueType();
4825 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4826 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4827 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4829 InFlag = Chain.getValue(1);
4830 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4832 Ops.push_back(Chain);
4833 Ops.push_back(DAG.getValueType(MVT::i8));
4834 Ops.push_back(InFlag);
4835 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4836 } else if (BytesLeft) {
4837 // Issue stores for the last 1 - 7 bytes.
4839 unsigned Val = ValC->getValue() & 255;
4840 unsigned Offset = I->getValue() - BytesLeft;
4841 SDOperand DstAddr = Op.getOperand(1);
4842 MVT::ValueType AddrVT = DstAddr.getValueType();
4843 if (BytesLeft >= 4) {
4844 Val = (Val << 8) | Val;
4845 Val = (Val << 16) | Val;
4846 Value = DAG.getConstant(Val, MVT::i32);
4847 Chain = DAG.getStore(Chain, Value,
4848 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4849 DAG.getConstant(Offset, AddrVT)),
4854 if (BytesLeft >= 2) {
4855 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4856 Chain = DAG.getStore(Chain, Value,
4857 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4858 DAG.getConstant(Offset, AddrVT)),
4863 if (BytesLeft == 1) {
4864 Value = DAG.getConstant(Val, MVT::i8);
4865 Chain = DAG.getStore(Chain, Value,
4866 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4867 DAG.getConstant(Offset, AddrVT)),
4875 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4880 SelectionDAG &DAG) {
4882 unsigned BytesLeft = 0;
4883 switch (Align & 3) {
4884 case 2: // WORD aligned
4887 case 0: // DWORD aligned
4889 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4892 default: // Byte aligned
4897 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4898 SDOperand Count = DAG.getConstant(Size / UBytes, getPointerTy());
4899 BytesLeft = Size % UBytes;
4901 SDOperand InFlag(0, 0);
4902 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4904 InFlag = Chain.getValue(1);
4905 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4907 InFlag = Chain.getValue(1);
4908 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4910 InFlag = Chain.getValue(1);
4912 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4913 SmallVector<SDOperand, 8> Ops;
4914 Ops.push_back(Chain);
4915 Ops.push_back(DAG.getValueType(AVT));
4916 Ops.push_back(InFlag);
4917 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4920 // Issue loads and stores for the last 1 - 7 bytes.
4921 unsigned Offset = Size - BytesLeft;
4922 SDOperand DstAddr = Dest;
4923 MVT::ValueType DstVT = DstAddr.getValueType();
4924 SDOperand SrcAddr = Source;
4925 MVT::ValueType SrcVT = SrcAddr.getValueType();
4927 if (BytesLeft >= 4) {
4928 Value = DAG.getLoad(MVT::i32, Chain,
4929 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4930 DAG.getConstant(Offset, SrcVT)),
4932 Chain = Value.getValue(1);
4933 Chain = DAG.getStore(Chain, Value,
4934 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4935 DAG.getConstant(Offset, DstVT)),
4940 if (BytesLeft >= 2) {
4941 Value = DAG.getLoad(MVT::i16, Chain,
4942 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4943 DAG.getConstant(Offset, SrcVT)),
4945 Chain = Value.getValue(1);
4946 Chain = DAG.getStore(Chain, Value,
4947 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4948 DAG.getConstant(Offset, DstVT)),
4954 if (BytesLeft == 1) {
4955 Value = DAG.getLoad(MVT::i8, Chain,
4956 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4957 DAG.getConstant(Offset, SrcVT)),
4959 Chain = Value.getValue(1);
4960 Chain = DAG.getStore(Chain, Value,
4961 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4962 DAG.getConstant(Offset, DstVT)),
4970 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4971 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4972 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4973 SDOperand TheChain = N->getOperand(0);
4974 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4975 if (Subtarget->is64Bit()) {
4976 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4977 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4978 MVT::i64, rax.getValue(2));
4979 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4980 DAG.getConstant(32, MVT::i8));
4982 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4985 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4986 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4989 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4990 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4991 MVT::i32, eax.getValue(2));
4992 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4993 SDOperand Ops[] = { eax, edx };
4994 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4996 // Use a MERGE_VALUES to return the value and chain.
4997 Ops[1] = edx.getValue(1);
4998 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4999 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
5002 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
5003 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
5005 if (!Subtarget->is64Bit()) {
5006 // vastart just stores the address of the VarArgsFrameIndex slot into the
5007 // memory location argument.
5008 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5009 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
5014 // gp_offset (0 - 6 * 8)
5015 // fp_offset (48 - 48 + 8 * 16)
5016 // overflow_arg_area (point to parameters coming in memory).
5018 SmallVector<SDOperand, 8> MemOps;
5019 SDOperand FIN = Op.getOperand(1);
5021 SDOperand Store = DAG.getStore(Op.getOperand(0),
5022 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5023 FIN, SV->getValue(), SV->getOffset());
5024 MemOps.push_back(Store);
5027 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5028 DAG.getConstant(4, getPointerTy()));
5029 Store = DAG.getStore(Op.getOperand(0),
5030 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5031 FIN, SV->getValue(), SV->getOffset());
5032 MemOps.push_back(Store);
5034 // Store ptr to overflow_arg_area
5035 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5036 DAG.getConstant(4, getPointerTy()));
5037 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5038 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
5040 MemOps.push_back(Store);
5042 // Store ptr to reg_save_area.
5043 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5044 DAG.getConstant(8, getPointerTy()));
5045 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5046 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
5048 MemOps.push_back(Store);
5049 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5052 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
5053 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5054 SDOperand Chain = Op.getOperand(0);
5055 SDOperand DstPtr = Op.getOperand(1);
5056 SDOperand SrcPtr = Op.getOperand(2);
5057 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
5058 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
5060 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
5061 SrcSV->getValue(), SrcSV->getOffset());
5062 Chain = SrcPtr.getValue(1);
5063 for (unsigned i = 0; i < 3; ++i) {
5064 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
5065 SrcSV->getValue(), SrcSV->getOffset());
5066 Chain = Val.getValue(1);
5067 Chain = DAG.getStore(Chain, Val, DstPtr,
5068 DstSV->getValue(), DstSV->getOffset());
5071 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
5072 DAG.getConstant(8, getPointerTy()));
5073 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
5074 DAG.getConstant(8, getPointerTy()));
5080 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5081 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5083 default: return SDOperand(); // Don't custom lower most intrinsics.
5084 // Comparison intrinsics.
5085 case Intrinsic::x86_sse_comieq_ss:
5086 case Intrinsic::x86_sse_comilt_ss:
5087 case Intrinsic::x86_sse_comile_ss:
5088 case Intrinsic::x86_sse_comigt_ss:
5089 case Intrinsic::x86_sse_comige_ss:
5090 case Intrinsic::x86_sse_comineq_ss:
5091 case Intrinsic::x86_sse_ucomieq_ss:
5092 case Intrinsic::x86_sse_ucomilt_ss:
5093 case Intrinsic::x86_sse_ucomile_ss:
5094 case Intrinsic::x86_sse_ucomigt_ss:
5095 case Intrinsic::x86_sse_ucomige_ss:
5096 case Intrinsic::x86_sse_ucomineq_ss:
5097 case Intrinsic::x86_sse2_comieq_sd:
5098 case Intrinsic::x86_sse2_comilt_sd:
5099 case Intrinsic::x86_sse2_comile_sd:
5100 case Intrinsic::x86_sse2_comigt_sd:
5101 case Intrinsic::x86_sse2_comige_sd:
5102 case Intrinsic::x86_sse2_comineq_sd:
5103 case Intrinsic::x86_sse2_ucomieq_sd:
5104 case Intrinsic::x86_sse2_ucomilt_sd:
5105 case Intrinsic::x86_sse2_ucomile_sd:
5106 case Intrinsic::x86_sse2_ucomigt_sd:
5107 case Intrinsic::x86_sse2_ucomige_sd:
5108 case Intrinsic::x86_sse2_ucomineq_sd: {
5110 ISD::CondCode CC = ISD::SETCC_INVALID;
5113 case Intrinsic::x86_sse_comieq_ss:
5114 case Intrinsic::x86_sse2_comieq_sd:
5118 case Intrinsic::x86_sse_comilt_ss:
5119 case Intrinsic::x86_sse2_comilt_sd:
5123 case Intrinsic::x86_sse_comile_ss:
5124 case Intrinsic::x86_sse2_comile_sd:
5128 case Intrinsic::x86_sse_comigt_ss:
5129 case Intrinsic::x86_sse2_comigt_sd:
5133 case Intrinsic::x86_sse_comige_ss:
5134 case Intrinsic::x86_sse2_comige_sd:
5138 case Intrinsic::x86_sse_comineq_ss:
5139 case Intrinsic::x86_sse2_comineq_sd:
5143 case Intrinsic::x86_sse_ucomieq_ss:
5144 case Intrinsic::x86_sse2_ucomieq_sd:
5145 Opc = X86ISD::UCOMI;
5148 case Intrinsic::x86_sse_ucomilt_ss:
5149 case Intrinsic::x86_sse2_ucomilt_sd:
5150 Opc = X86ISD::UCOMI;
5153 case Intrinsic::x86_sse_ucomile_ss:
5154 case Intrinsic::x86_sse2_ucomile_sd:
5155 Opc = X86ISD::UCOMI;
5158 case Intrinsic::x86_sse_ucomigt_ss:
5159 case Intrinsic::x86_sse2_ucomigt_sd:
5160 Opc = X86ISD::UCOMI;
5163 case Intrinsic::x86_sse_ucomige_ss:
5164 case Intrinsic::x86_sse2_ucomige_sd:
5165 Opc = X86ISD::UCOMI;
5168 case Intrinsic::x86_sse_ucomineq_ss:
5169 case Intrinsic::x86_sse2_ucomineq_sd:
5170 Opc = X86ISD::UCOMI;
5176 SDOperand LHS = Op.getOperand(1);
5177 SDOperand RHS = Op.getOperand(2);
5178 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5180 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5181 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5182 DAG.getConstant(X86CC, MVT::i8), Cond);
5183 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5188 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5189 // Depths > 0 not supported yet!
5190 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5193 // Just load the return address
5194 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5195 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5198 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5199 // Depths > 0 not supported yet!
5200 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5203 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5204 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5205 DAG.getConstant(4, getPointerTy()));
5208 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5209 SelectionDAG &DAG) {
5210 // Is not yet supported on x86-64
5211 if (Subtarget->is64Bit())
5214 return DAG.getConstant(8, getPointerTy());
5217 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5219 assert(!Subtarget->is64Bit() &&
5220 "Lowering of eh_return builtin is not supported yet on x86-64");
5222 MachineFunction &MF = DAG.getMachineFunction();
5223 SDOperand Chain = Op.getOperand(0);
5224 SDOperand Offset = Op.getOperand(1);
5225 SDOperand Handler = Op.getOperand(2);
5227 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5230 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5231 DAG.getConstant(-4UL, getPointerTy()));
5232 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5233 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5234 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5235 MF.addLiveOut(X86::ECX);
5237 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5238 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5241 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5242 SelectionDAG &DAG) {
5243 SDOperand Root = Op.getOperand(0);
5244 SDOperand Trmp = Op.getOperand(1); // trampoline
5245 SDOperand FPtr = Op.getOperand(2); // nested function
5246 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5248 SrcValueSDNode *TrmpSV = cast<SrcValueSDNode>(Op.getOperand(4));
5250 if (Subtarget->is64Bit()) {
5251 return SDOperand(); // not yet supported
5253 Function *Func = (Function *)
5254 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5255 unsigned CC = Func->getCallingConv();
5260 assert(0 && "Unsupported calling convention");
5261 case CallingConv::C:
5262 case CallingConv::X86_StdCall: {
5263 // Pass 'nest' parameter in ECX.
5264 // Must be kept in sync with X86CallingConv.td
5267 // Check that ECX wasn't needed by an 'inreg' parameter.
5268 const FunctionType *FTy = Func->getFunctionType();
5269 const ParamAttrsList *Attrs = Func->getParamAttrs();
5271 if (Attrs && !Func->isVarArg()) {
5272 unsigned InRegCount = 0;
5275 for (FunctionType::param_iterator I = FTy->param_begin(),
5276 E = FTy->param_end(); I != E; ++I, ++Idx)
5277 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5278 // FIXME: should only count parameters that are lowered to integers.
5279 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5281 if (InRegCount > 2) {
5282 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5288 case CallingConv::X86_FastCall:
5289 // Pass 'nest' parameter in EAX.
5290 // Must be kept in sync with X86CallingConv.td
5295 const X86InstrInfo *TII =
5296 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5298 SDOperand OutChains[4];
5299 SDOperand Addr, Disp;
5301 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5302 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5304 unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5305 unsigned char N86Reg = ((X86RegisterInfo&)RegInfo).getX86RegNum(NestReg);
5306 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5307 Trmp, TrmpSV->getValue(), TrmpSV->getOffset());
5309 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5310 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpSV->getValue(),
5311 TrmpSV->getOffset() + 1, false, 1);
5313 unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5314 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5315 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5316 TrmpSV->getValue() + 5, TrmpSV->getOffset());
5318 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5319 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpSV->getValue(),
5320 TrmpSV->getOffset() + 6, false, 1);
5323 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5324 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5328 SDOperand X86TargetLowering::LowerFLT_ROUNDS(SDOperand Op, SelectionDAG &DAG) {
5330 The rounding mode is in bits 11:10 of FPSR, and has the following
5337 FLT_ROUNDS, on the other hand, expects the following:
5344 To perform the conversion, we do:
5345 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5348 MachineFunction &MF = DAG.getMachineFunction();
5349 const TargetMachine &TM = MF.getTarget();
5350 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5351 unsigned StackAlignment = TFI.getStackAlignment();
5352 MVT::ValueType VT = Op.getValueType();
5354 // Save FP Control Word to stack slot
5355 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5356 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5358 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5359 DAG.getEntryNode(), StackSlot);
5361 // Load FP Control Word from stack slot
5362 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5364 // Transform as necessary
5366 DAG.getNode(ISD::SRL, MVT::i16,
5367 DAG.getNode(ISD::AND, MVT::i16,
5368 CWD, DAG.getConstant(0x800, MVT::i16)),
5369 DAG.getConstant(11, MVT::i8));
5371 DAG.getNode(ISD::SRL, MVT::i16,
5372 DAG.getNode(ISD::AND, MVT::i16,
5373 CWD, DAG.getConstant(0x400, MVT::i16)),
5374 DAG.getConstant(9, MVT::i8));
5377 DAG.getNode(ISD::AND, MVT::i16,
5378 DAG.getNode(ISD::ADD, MVT::i16,
5379 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5380 DAG.getConstant(1, MVT::i16)),
5381 DAG.getConstant(3, MVT::i16));
5384 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5385 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5388 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5389 MVT::ValueType VT = Op.getValueType();
5390 MVT::ValueType OpVT = VT;
5391 unsigned NumBits = MVT::getSizeInBits(VT);
5393 Op = Op.getOperand(0);
5394 if (VT == MVT::i8) {
5395 // Zero extend to i32 since there is not an i8 bsr.
5397 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5400 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5401 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5402 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5404 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5405 SmallVector<SDOperand, 4> Ops;
5407 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5408 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5409 Ops.push_back(Op.getValue(1));
5410 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5412 // Finally xor with NumBits-1.
5413 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5416 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5420 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5421 MVT::ValueType VT = Op.getValueType();
5422 MVT::ValueType OpVT = VT;
5423 unsigned NumBits = MVT::getSizeInBits(VT);
5425 Op = Op.getOperand(0);
5426 if (VT == MVT::i8) {
5428 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5431 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5432 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5433 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5435 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5436 SmallVector<SDOperand, 4> Ops;
5438 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5439 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5440 Ops.push_back(Op.getValue(1));
5441 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5444 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5448 /// LowerOperation - Provide custom lowering hooks for some operations.
5450 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5451 switch (Op.getOpcode()) {
5452 default: assert(0 && "Should not custom lower this!");
5453 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5454 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5455 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5456 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5457 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5458 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5459 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5460 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5461 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5462 case ISD::SHL_PARTS:
5463 case ISD::SRA_PARTS:
5464 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5465 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5466 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5467 case ISD::FABS: return LowerFABS(Op, DAG);
5468 case ISD::FNEG: return LowerFNEG(Op, DAG);
5469 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5470 case ISD::SETCC: return LowerSETCC(Op, DAG);
5471 case ISD::SELECT: return LowerSELECT(Op, DAG);
5472 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5473 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5474 case ISD::CALL: return LowerCALL(Op, DAG);
5475 case ISD::RET: return LowerRET(Op, DAG);
5476 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5477 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5478 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
5479 case ISD::VASTART: return LowerVASTART(Op, DAG);
5480 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5481 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5482 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5483 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5484 case ISD::FRAME_TO_ARGS_OFFSET:
5485 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5486 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5487 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5488 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5489 case ISD::FLT_ROUNDS: return LowerFLT_ROUNDS(Op, DAG);
5490 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5491 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5493 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5494 case ISD::READCYCLECOUNTER:
5495 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5499 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5500 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5501 switch (N->getOpcode()) {
5502 default: assert(0 && "Should not custom lower this!");
5503 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5504 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5508 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5510 default: return NULL;
5511 case X86ISD::BSF: return "X86ISD::BSF";
5512 case X86ISD::BSR: return "X86ISD::BSR";
5513 case X86ISD::SHLD: return "X86ISD::SHLD";
5514 case X86ISD::SHRD: return "X86ISD::SHRD";
5515 case X86ISD::FAND: return "X86ISD::FAND";
5516 case X86ISD::FOR: return "X86ISD::FOR";
5517 case X86ISD::FXOR: return "X86ISD::FXOR";
5518 case X86ISD::FSRL: return "X86ISD::FSRL";
5519 case X86ISD::FILD: return "X86ISD::FILD";
5520 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5521 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5522 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5523 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5524 case X86ISD::FLD: return "X86ISD::FLD";
5525 case X86ISD::FST: return "X86ISD::FST";
5526 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5527 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5528 case X86ISD::CALL: return "X86ISD::CALL";
5529 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5530 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5531 case X86ISD::CMP: return "X86ISD::CMP";
5532 case X86ISD::COMI: return "X86ISD::COMI";
5533 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5534 case X86ISD::SETCC: return "X86ISD::SETCC";
5535 case X86ISD::CMOV: return "X86ISD::CMOV";
5536 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5537 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5538 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5539 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5540 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5541 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5542 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5543 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5544 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5545 case X86ISD::FMAX: return "X86ISD::FMAX";
5546 case X86ISD::FMIN: return "X86ISD::FMIN";
5547 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5548 case X86ISD::FRCP: return "X86ISD::FRCP";
5549 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5550 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5551 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5552 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5553 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5557 // isLegalAddressingMode - Return true if the addressing mode represented
5558 // by AM is legal for this target, for a load/store of the specified type.
5559 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5560 const Type *Ty) const {
5561 // X86 supports extremely general addressing modes.
5563 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5564 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5568 // We can only fold this if we don't need an extra load.
5569 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5572 // X86-64 only supports addr of globals in small code model.
5573 if (Subtarget->is64Bit()) {
5574 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5576 // If lower 4G is not available, then we must use rip-relative addressing.
5577 if (AM.BaseOffs || AM.Scale > 1)
5588 // These scales always work.
5593 // These scales are formed with basereg+scalereg. Only accept if there is
5598 default: // Other stuff never works.
5606 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5607 if (!Ty1->isInteger() || !Ty2->isInteger())
5609 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5610 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5611 if (NumBits1 <= NumBits2)
5613 return Subtarget->is64Bit() || NumBits1 < 64;
5616 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5617 MVT::ValueType VT2) const {
5618 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5620 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5621 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5622 if (NumBits1 <= NumBits2)
5624 return Subtarget->is64Bit() || NumBits1 < 64;
5627 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5628 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5629 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5630 /// are assumed to be legal.
5632 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5633 // Only do shuffles on 128-bit vector types for now.
5634 if (MVT::getSizeInBits(VT) == 64) return false;
5635 return (Mask.Val->getNumOperands() <= 4 ||
5636 isIdentityMask(Mask.Val) ||
5637 isIdentityMask(Mask.Val, true) ||
5638 isSplatMask(Mask.Val) ||
5639 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5640 X86::isUNPCKLMask(Mask.Val) ||
5641 X86::isUNPCKHMask(Mask.Val) ||
5642 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5643 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5646 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5648 SelectionDAG &DAG) const {
5649 unsigned NumElts = BVOps.size();
5650 // Only do shuffles on 128-bit vector types for now.
5651 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5652 if (NumElts == 2) return true;
5654 return (isMOVLMask(&BVOps[0], 4) ||
5655 isCommutedMOVL(&BVOps[0], 4, true) ||
5656 isSHUFPMask(&BVOps[0], 4) ||
5657 isCommutedSHUFP(&BVOps[0], 4));
5662 //===----------------------------------------------------------------------===//
5663 // X86 Scheduler Hooks
5664 //===----------------------------------------------------------------------===//
5667 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
5668 MachineBasicBlock *BB) {
5669 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5670 switch (MI->getOpcode()) {
5671 default: assert(false && "Unexpected instr type to insert");
5672 case X86::CMOV_FR32:
5673 case X86::CMOV_FR64:
5674 case X86::CMOV_V4F32:
5675 case X86::CMOV_V2F64:
5676 case X86::CMOV_V2I64: {
5677 // To "insert" a SELECT_CC instruction, we actually have to insert the
5678 // diamond control-flow pattern. The incoming instruction knows the
5679 // destination vreg to set, the condition code register to branch on, the
5680 // true/false values to select between, and a branch opcode to use.
5681 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5682 ilist<MachineBasicBlock>::iterator It = BB;
5688 // cmpTY ccX, r1, r2
5690 // fallthrough --> copy0MBB
5691 MachineBasicBlock *thisMBB = BB;
5692 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5693 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5695 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5696 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5697 MachineFunction *F = BB->getParent();
5698 F->getBasicBlockList().insert(It, copy0MBB);
5699 F->getBasicBlockList().insert(It, sinkMBB);
5700 // Update machine-CFG edges by first adding all successors of the current
5701 // block to the new block which will contain the Phi node for the select.
5702 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5703 e = BB->succ_end(); i != e; ++i)
5704 sinkMBB->addSuccessor(*i);
5705 // Next, remove all successors of the current block, and add the true
5706 // and fallthrough blocks as its successors.
5707 while(!BB->succ_empty())
5708 BB->removeSuccessor(BB->succ_begin());
5709 BB->addSuccessor(copy0MBB);
5710 BB->addSuccessor(sinkMBB);
5713 // %FalseValue = ...
5714 // # fallthrough to sinkMBB
5717 // Update machine-CFG edges
5718 BB->addSuccessor(sinkMBB);
5721 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5724 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5725 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5726 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5728 delete MI; // The pseudo instruction is gone now.
5732 case X86::FP32_TO_INT16_IN_MEM:
5733 case X86::FP32_TO_INT32_IN_MEM:
5734 case X86::FP32_TO_INT64_IN_MEM:
5735 case X86::FP64_TO_INT16_IN_MEM:
5736 case X86::FP64_TO_INT32_IN_MEM:
5737 case X86::FP64_TO_INT64_IN_MEM:
5738 case X86::FP80_TO_INT16_IN_MEM:
5739 case X86::FP80_TO_INT32_IN_MEM:
5740 case X86::FP80_TO_INT64_IN_MEM: {
5741 // Change the floating point control register to use "round towards zero"
5742 // mode when truncating to an integer value.
5743 MachineFunction *F = BB->getParent();
5744 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5745 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5747 // Load the old value of the high byte of the control word...
5749 F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
5750 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5752 // Set the high part to be round to zero...
5753 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5756 // Reload the modified control word now...
5757 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5759 // Restore the memory image of control word to original value
5760 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5763 // Get the X86 opcode to use.
5765 switch (MI->getOpcode()) {
5766 default: assert(0 && "illegal opcode!");
5767 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5768 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5769 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5770 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5771 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5772 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5773 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5774 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5775 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5779 MachineOperand &Op = MI->getOperand(0);
5780 if (Op.isRegister()) {
5781 AM.BaseType = X86AddressMode::RegBase;
5782 AM.Base.Reg = Op.getReg();
5784 AM.BaseType = X86AddressMode::FrameIndexBase;
5785 AM.Base.FrameIndex = Op.getFrameIndex();
5787 Op = MI->getOperand(1);
5788 if (Op.isImmediate())
5789 AM.Scale = Op.getImm();
5790 Op = MI->getOperand(2);
5791 if (Op.isImmediate())
5792 AM.IndexReg = Op.getImm();
5793 Op = MI->getOperand(3);
5794 if (Op.isGlobalAddress()) {
5795 AM.GV = Op.getGlobal();
5797 AM.Disp = Op.getImm();
5799 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5800 .addReg(MI->getOperand(4).getReg());
5802 // Reload the original control word now.
5803 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5805 delete MI; // The pseudo instruction is gone now.
5811 //===----------------------------------------------------------------------===//
5812 // X86 Optimization Hooks
5813 //===----------------------------------------------------------------------===//
5815 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5817 uint64_t &KnownZero,
5819 const SelectionDAG &DAG,
5820 unsigned Depth) const {
5821 unsigned Opc = Op.getOpcode();
5822 assert((Opc >= ISD::BUILTIN_OP_END ||
5823 Opc == ISD::INTRINSIC_WO_CHAIN ||
5824 Opc == ISD::INTRINSIC_W_CHAIN ||
5825 Opc == ISD::INTRINSIC_VOID) &&
5826 "Should use MaskedValueIsZero if you don't know whether Op"
5827 " is a target node!");
5829 KnownZero = KnownOne = 0; // Don't know anything.
5833 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5838 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5839 /// element of the result of the vector shuffle.
5840 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5841 MVT::ValueType VT = N->getValueType(0);
5842 SDOperand PermMask = N->getOperand(2);
5843 unsigned NumElems = PermMask.getNumOperands();
5844 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5846 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5848 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5849 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5850 SDOperand Idx = PermMask.getOperand(i);
5851 if (Idx.getOpcode() == ISD::UNDEF)
5852 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5853 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5858 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5859 /// node is a GlobalAddress + an offset.
5860 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5861 unsigned Opc = N->getOpcode();
5862 if (Opc == X86ISD::Wrapper) {
5863 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5864 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5867 } else if (Opc == ISD::ADD) {
5868 SDOperand N1 = N->getOperand(0);
5869 SDOperand N2 = N->getOperand(1);
5870 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5871 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5873 Offset += V->getSignExtended();
5876 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5877 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5879 Offset += V->getSignExtended();
5887 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5889 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5890 MachineFrameInfo *MFI) {
5891 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5894 SDOperand Loc = N->getOperand(1);
5895 SDOperand BaseLoc = Base->getOperand(1);
5896 if (Loc.getOpcode() == ISD::FrameIndex) {
5897 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5899 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5900 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5901 int FS = MFI->getObjectSize(FI);
5902 int BFS = MFI->getObjectSize(BFI);
5903 if (FS != BFS || FS != Size) return false;
5904 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5906 GlobalValue *GV1 = NULL;
5907 GlobalValue *GV2 = NULL;
5908 int64_t Offset1 = 0;
5909 int64_t Offset2 = 0;
5910 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5911 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5912 if (isGA1 && isGA2 && GV1 == GV2)
5913 return Offset1 == (Offset2 + Dist*Size);
5919 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5920 const X86Subtarget *Subtarget) {
5923 if (isGAPlusOffset(Base, GV, Offset))
5924 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5926 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
5927 int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
5929 // Fixed objects do not specify alignment, however the offsets are known.
5930 return ((Subtarget->getStackAlignment() % 16) == 0 &&
5931 (MFI->getObjectOffset(BFI) % 16) == 0);
5933 return MFI->getObjectAlignment(BFI) >= 16;
5939 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5940 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5941 /// if the load addresses are consecutive, non-overlapping, and in the right
5943 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5944 const X86Subtarget *Subtarget) {
5945 MachineFunction &MF = DAG.getMachineFunction();
5946 MachineFrameInfo *MFI = MF.getFrameInfo();
5947 MVT::ValueType VT = N->getValueType(0);
5948 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5949 SDOperand PermMask = N->getOperand(2);
5950 int NumElems = (int)PermMask.getNumOperands();
5951 SDNode *Base = NULL;
5952 for (int i = 0; i < NumElems; ++i) {
5953 SDOperand Idx = PermMask.getOperand(i);
5954 if (Idx.getOpcode() == ISD::UNDEF) {
5955 if (!Base) return SDOperand();
5958 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5959 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5963 else if (!isConsecutiveLoad(Arg.Val, Base,
5964 i, MVT::getSizeInBits(EVT)/8,MFI))
5969 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5970 LoadSDNode *LD = cast<LoadSDNode>(Base);
5972 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5973 LD->getSrcValueOffset(), LD->isVolatile());
5975 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5976 LD->getSrcValueOffset(), LD->isVolatile(),
5977 LD->getAlignment());
5981 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5982 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5983 const X86Subtarget *Subtarget) {
5984 SDOperand Cond = N->getOperand(0);
5986 // If we have SSE[12] support, try to form min/max nodes.
5987 if (Subtarget->hasSSE2() &&
5988 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5989 if (Cond.getOpcode() == ISD::SETCC) {
5990 // Get the LHS/RHS of the select.
5991 SDOperand LHS = N->getOperand(1);
5992 SDOperand RHS = N->getOperand(2);
5993 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5995 unsigned Opcode = 0;
5996 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5999 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6002 if (!UnsafeFPMath) break;
6004 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6006 Opcode = X86ISD::FMIN;
6009 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6012 if (!UnsafeFPMath) break;
6014 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6016 Opcode = X86ISD::FMAX;
6019 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6022 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6025 if (!UnsafeFPMath) break;
6027 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6029 Opcode = X86ISD::FMIN;
6032 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6035 if (!UnsafeFPMath) break;
6037 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6039 Opcode = X86ISD::FMAX;
6045 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6054 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6055 DAGCombinerInfo &DCI) const {
6056 SelectionDAG &DAG = DCI.DAG;
6057 switch (N->getOpcode()) {
6059 case ISD::VECTOR_SHUFFLE:
6060 return PerformShuffleCombine(N, DAG, Subtarget);
6062 return PerformSELECTCombine(N, DAG, Subtarget);
6068 //===----------------------------------------------------------------------===//
6069 // X86 Inline Assembly Support
6070 //===----------------------------------------------------------------------===//
6072 /// getConstraintType - Given a constraint letter, return the type of
6073 /// constraint it is for this target.
6074 X86TargetLowering::ConstraintType
6075 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6076 if (Constraint.size() == 1) {
6077 switch (Constraint[0]) {
6086 return C_RegisterClass;
6091 return TargetLowering::getConstraintType(Constraint);
6094 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6095 /// vector. If it is invalid, don't add anything to Ops.
6096 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6098 std::vector<SDOperand>&Ops,
6099 SelectionDAG &DAG) {
6100 SDOperand Result(0, 0);
6102 switch (Constraint) {
6105 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6106 if (C->getValue() <= 31) {
6107 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6113 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6114 if (C->getValue() <= 255) {
6115 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6121 // Literal immediates are always ok.
6122 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6123 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6127 // If we are in non-pic codegen mode, we allow the address of a global (with
6128 // an optional displacement) to be used with 'i'.
6129 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6132 // Match either (GA) or (GA+C)
6134 Offset = GA->getOffset();
6135 } else if (Op.getOpcode() == ISD::ADD) {
6136 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6137 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6139 Offset = GA->getOffset()+C->getValue();
6141 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6142 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6144 Offset = GA->getOffset()+C->getValue();
6151 // If addressing this global requires a load (e.g. in PIC mode), we can't
6153 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6157 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6163 // Otherwise, not valid for this mode.
6169 Ops.push_back(Result);
6172 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6175 std::vector<unsigned> X86TargetLowering::
6176 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6177 MVT::ValueType VT) const {
6178 if (Constraint.size() == 1) {
6179 // FIXME: not handling fp-stack yet!
6180 switch (Constraint[0]) { // GCC X86 Constraint Letters
6181 default: break; // Unknown constraint letter
6182 case 'A': // EAX/EDX
6183 if (VT == MVT::i32 || VT == MVT::i64)
6184 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6186 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6189 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6190 else if (VT == MVT::i16)
6191 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6192 else if (VT == MVT::i8)
6193 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6194 else if (VT == MVT::i64)
6195 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6200 return std::vector<unsigned>();
6203 std::pair<unsigned, const TargetRegisterClass*>
6204 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6205 MVT::ValueType VT) const {
6206 // First, see if this is a constraint that directly corresponds to an LLVM
6208 if (Constraint.size() == 1) {
6209 // GCC Constraint Letters
6210 switch (Constraint[0]) {
6212 case 'r': // GENERAL_REGS
6213 case 'R': // LEGACY_REGS
6214 case 'l': // INDEX_REGS
6215 if (VT == MVT::i64 && Subtarget->is64Bit())
6216 return std::make_pair(0U, X86::GR64RegisterClass);
6218 return std::make_pair(0U, X86::GR32RegisterClass);
6219 else if (VT == MVT::i16)
6220 return std::make_pair(0U, X86::GR16RegisterClass);
6221 else if (VT == MVT::i8)
6222 return std::make_pair(0U, X86::GR8RegisterClass);
6224 case 'y': // MMX_REGS if MMX allowed.
6225 if (!Subtarget->hasMMX()) break;
6226 return std::make_pair(0U, X86::VR64RegisterClass);
6228 case 'Y': // SSE_REGS if SSE2 allowed
6229 if (!Subtarget->hasSSE2()) break;
6231 case 'x': // SSE_REGS if SSE1 allowed
6232 if (!Subtarget->hasSSE1()) break;
6236 // Scalar SSE types.
6239 return std::make_pair(0U, X86::FR32RegisterClass);
6242 return std::make_pair(0U, X86::FR64RegisterClass);
6250 return std::make_pair(0U, X86::VR128RegisterClass);
6256 // Use the default implementation in TargetLowering to convert the register
6257 // constraint into a member of a register class.
6258 std::pair<unsigned, const TargetRegisterClass*> Res;
6259 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6261 // Not found as a standard register?
6262 if (Res.second == 0) {
6263 // GCC calls "st(0)" just plain "st".
6264 if (StringsEqualNoCase("{st}", Constraint)) {
6265 Res.first = X86::ST0;
6266 Res.second = X86::RFP80RegisterClass;
6272 // Otherwise, check to see if this is a register class of the wrong value
6273 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6274 // turn into {ax},{dx}.
6275 if (Res.second->hasType(VT))
6276 return Res; // Correct type already, nothing to do.
6278 // All of the single-register GCC register classes map their values onto
6279 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6280 // really want an 8-bit or 32-bit register, map to the appropriate register
6281 // class and return the appropriate register.
6282 if (Res.second != X86::GR16RegisterClass)
6285 if (VT == MVT::i8) {
6286 unsigned DestReg = 0;
6287 switch (Res.first) {
6289 case X86::AX: DestReg = X86::AL; break;
6290 case X86::DX: DestReg = X86::DL; break;
6291 case X86::CX: DestReg = X86::CL; break;
6292 case X86::BX: DestReg = X86::BL; break;
6295 Res.first = DestReg;
6296 Res.second = Res.second = X86::GR8RegisterClass;
6298 } else if (VT == MVT::i32) {
6299 unsigned DestReg = 0;
6300 switch (Res.first) {
6302 case X86::AX: DestReg = X86::EAX; break;
6303 case X86::DX: DestReg = X86::EDX; break;
6304 case X86::CX: DestReg = X86::ECX; break;
6305 case X86::BX: DestReg = X86::EBX; break;
6306 case X86::SI: DestReg = X86::ESI; break;
6307 case X86::DI: DestReg = X86::EDI; break;
6308 case X86::BP: DestReg = X86::EBP; break;
6309 case X86::SP: DestReg = X86::ESP; break;
6312 Res.first = DestReg;
6313 Res.second = Res.second = X86::GR32RegisterClass;
6315 } else if (VT == MVT::i64) {
6316 unsigned DestReg = 0;
6317 switch (Res.first) {
6319 case X86::AX: DestReg = X86::RAX; break;
6320 case X86::DX: DestReg = X86::RDX; break;
6321 case X86::CX: DestReg = X86::RCX; break;
6322 case X86::BX: DestReg = X86::RBX; break;
6323 case X86::SI: DestReg = X86::RSI; break;
6324 case X86::DI: DestReg = X86::RDI; break;
6325 case X86::BP: DestReg = X86::RBP; break;
6326 case X86::SP: DestReg = X86::RSP; break;
6329 Res.first = DestReg;
6330 Res.second = Res.second = X86::GR64RegisterClass;