1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/SmallSet.h"
41 #include "llvm/ADT/StringExtras.h"
42 #include "llvm/ParamAttrsList.h"
45 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
46 : TargetLowering(TM) {
47 Subtarget = &TM.getSubtarget<X86Subtarget>();
48 X86ScalarSSEf64 = Subtarget->hasSSE2();
49 X86ScalarSSEf32 = Subtarget->hasSSE1();
50 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
54 RegInfo = TM.getRegisterInfo();
56 // Set up the TargetLowering object.
58 // X86 is weird, it always uses i8 for shift amounts and setcc results.
59 setShiftAmountType(MVT::i8);
60 setSetCCResultContents(ZeroOrOneSetCCResult);
61 setSchedulingPreference(SchedulingForRegPressure);
62 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
63 setStackPointerRegisterToSaveRestore(X86StackPtr);
65 if (Subtarget->isTargetDarwin()) {
66 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
67 setUseUnderscoreSetJmp(false);
68 setUseUnderscoreLongJmp(false);
69 } else if (Subtarget->isTargetMingw()) {
70 // MS runtime is weird: it exports _setjmp, but longjmp!
71 setUseUnderscoreSetJmp(true);
72 setUseUnderscoreLongJmp(false);
74 setUseUnderscoreSetJmp(true);
75 setUseUnderscoreLongJmp(true);
78 // Set up the register classes.
79 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
80 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
81 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
82 if (Subtarget->is64Bit())
83 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
85 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
87 // We don't accept any truncstore of integer registers.
88 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
89 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
90 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
91 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
92 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
93 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
95 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
97 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
98 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
99 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
101 if (Subtarget->is64Bit()) {
102 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
103 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
106 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
107 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
109 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
112 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
114 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
115 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
116 // SSE has no i16 to fp conversion, only i32
117 if (X86ScalarSSEf32) {
118 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
119 // f32 and f64 cases are Legal, f80 case is not
120 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
122 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
123 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
126 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
127 // are Legal, f80 is custom lowered.
128 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
129 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
131 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
133 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
134 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
136 if (X86ScalarSSEf32) {
137 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
138 // f32 and f64 cases are Legal, f80 case is not
139 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
141 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
142 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
145 // Handle FP_TO_UINT by promoting the destination to a larger signed
147 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
148 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
149 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
151 if (Subtarget->is64Bit()) {
152 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
153 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
155 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
156 // Expand FP_TO_UINT into a select.
157 // FIXME: We would like to use a Custom expander here eventually to do
158 // the optimal thing for SSE vs. the default expansion in the legalizer.
159 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
161 // With SSE3 we can use fisttpll to convert to a signed i64.
162 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
165 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
166 if (!X86ScalarSSEf64) {
167 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
168 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
171 // Scalar integer divide and remainder are lowered to use operations that
172 // produce two results, to match the available instructions. This exposes
173 // the two-result form to trivial CSE, which is able to combine x/y and x%y
174 // into a single instruction.
176 // Scalar integer multiply-high is also lowered to use two-result
177 // operations, to match the available instructions. However, plain multiply
178 // (low) operations are left as Legal, as there are single-result
179 // instructions for this in x86. Using the two-result multiply instructions
180 // when both high and low results are needed must be arranged by dagcombine.
181 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
182 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
183 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
184 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
185 setOperationAction(ISD::SREM , MVT::i8 , Expand);
186 setOperationAction(ISD::UREM , MVT::i8 , Expand);
187 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
188 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
189 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
190 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
191 setOperationAction(ISD::SREM , MVT::i16 , Expand);
192 setOperationAction(ISD::UREM , MVT::i16 , Expand);
193 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
194 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
195 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
196 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
197 setOperationAction(ISD::SREM , MVT::i32 , Expand);
198 setOperationAction(ISD::UREM , MVT::i32 , Expand);
199 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
200 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
201 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
202 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
203 setOperationAction(ISD::SREM , MVT::i64 , Expand);
204 setOperationAction(ISD::UREM , MVT::i64 , Expand);
206 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
207 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
208 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
209 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
210 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
211 if (Subtarget->is64Bit())
212 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
216 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
217 setOperationAction(ISD::FREM , MVT::f32 , Expand);
218 setOperationAction(ISD::FREM , MVT::f64 , Expand);
219 setOperationAction(ISD::FREM , MVT::f80 , Expand);
220 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
222 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
223 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
224 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
225 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
226 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
227 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
228 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
229 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
230 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
231 if (Subtarget->is64Bit()) {
232 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
233 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
234 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
237 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
238 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
240 // These should be promoted to a larger select which is supported.
241 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
242 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
243 // X86 wants to expand cmov itself.
244 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
245 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
246 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
247 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
248 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
249 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
250 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
251 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
252 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
253 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
254 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
255 if (Subtarget->is64Bit()) {
256 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
257 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
259 // X86 ret instruction may pop stack.
260 setOperationAction(ISD::RET , MVT::Other, Custom);
261 if (!Subtarget->is64Bit())
262 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
265 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
266 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
267 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
268 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
269 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
270 if (Subtarget->is64Bit()) {
271 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
272 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
273 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
274 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
276 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
277 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
278 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
279 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
280 if (Subtarget->is64Bit()) {
281 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
282 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
283 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
285 // X86 wants to expand memset / memcpy itself.
286 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
287 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
289 if (Subtarget->hasSSE1())
290 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
292 if (!Subtarget->hasSSE2())
293 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
295 setOperationAction(ISD::ATOMIC_LCS , MVT::i8, Custom);
296 setOperationAction(ISD::ATOMIC_LCS , MVT::i16, Custom);
297 setOperationAction(ISD::ATOMIC_LCS , MVT::i32, Custom);
298 setOperationAction(ISD::ATOMIC_LCS , MVT::i64, Custom);
300 // Use the default ISD::LOCATION, ISD::DECLARE expansion.
301 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
302 // FIXME - use subtarget debug flags
303 if (!Subtarget->isTargetDarwin() &&
304 !Subtarget->isTargetELF() &&
305 !Subtarget->isTargetCygMing())
306 setOperationAction(ISD::LABEL, MVT::Other, Expand);
308 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
309 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
310 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
311 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
312 if (Subtarget->is64Bit()) {
314 setExceptionPointerRegister(X86::RAX);
315 setExceptionSelectorRegister(X86::RDX);
317 setExceptionPointerRegister(X86::EAX);
318 setExceptionSelectorRegister(X86::EDX);
320 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
322 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
324 setOperationAction(ISD::TRAP, MVT::Other, Legal);
326 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
327 setOperationAction(ISD::VASTART , MVT::Other, Custom);
328 setOperationAction(ISD::VAARG , MVT::Other, Expand);
329 setOperationAction(ISD::VAEND , MVT::Other, Expand);
330 if (Subtarget->is64Bit())
331 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
333 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
335 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
336 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
337 if (Subtarget->is64Bit())
338 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
339 if (Subtarget->isTargetCygMing())
340 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
342 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
344 if (X86ScalarSSEf64) {
345 // f32 and f64 use SSE.
346 // Set up the FP register classes.
347 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
348 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
350 // Use ANDPD to simulate FABS.
351 setOperationAction(ISD::FABS , MVT::f64, Custom);
352 setOperationAction(ISD::FABS , MVT::f32, Custom);
354 // Use XORP to simulate FNEG.
355 setOperationAction(ISD::FNEG , MVT::f64, Custom);
356 setOperationAction(ISD::FNEG , MVT::f32, Custom);
358 // Use ANDPD and ORPD to simulate FCOPYSIGN.
359 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
360 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
362 // We don't support sin/cos/fmod
363 setOperationAction(ISD::FSIN , MVT::f64, Expand);
364 setOperationAction(ISD::FCOS , MVT::f64, Expand);
365 setOperationAction(ISD::FSIN , MVT::f32, Expand);
366 setOperationAction(ISD::FCOS , MVT::f32, Expand);
368 // Expand FP immediates into loads from the stack, except for the special
370 addLegalFPImmediate(APFloat(+0.0)); // xorpd
371 addLegalFPImmediate(APFloat(+0.0f)); // xorps
373 // Floating truncations from f80 and extensions to f80 go through memory.
374 // If optimizing, we lie about this though and handle it in
375 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
377 setConvertAction(MVT::f32, MVT::f80, Expand);
378 setConvertAction(MVT::f64, MVT::f80, Expand);
379 setConvertAction(MVT::f80, MVT::f32, Expand);
380 setConvertAction(MVT::f80, MVT::f64, Expand);
382 } else if (X86ScalarSSEf32) {
383 // Use SSE for f32, x87 for f64.
384 // Set up the FP register classes.
385 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
386 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
388 // Use ANDPS to simulate FABS.
389 setOperationAction(ISD::FABS , MVT::f32, Custom);
391 // Use XORP to simulate FNEG.
392 setOperationAction(ISD::FNEG , MVT::f32, Custom);
394 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
396 // Use ANDPS and ORPS to simulate FCOPYSIGN.
397 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
398 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
400 // We don't support sin/cos/fmod
401 setOperationAction(ISD::FSIN , MVT::f32, Expand);
402 setOperationAction(ISD::FCOS , MVT::f32, Expand);
404 // Special cases we handle for FP constants.
405 addLegalFPImmediate(APFloat(+0.0f)); // xorps
406 addLegalFPImmediate(APFloat(+0.0)); // FLD0
407 addLegalFPImmediate(APFloat(+1.0)); // FLD1
408 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
409 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
411 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
412 // this though and handle it in InstructionSelectPreprocess so that
413 // dagcombine2 can hack on these.
415 setConvertAction(MVT::f32, MVT::f64, Expand);
416 setConvertAction(MVT::f32, MVT::f80, Expand);
417 setConvertAction(MVT::f80, MVT::f32, Expand);
418 setConvertAction(MVT::f64, MVT::f32, Expand);
419 // And x87->x87 truncations also.
420 setConvertAction(MVT::f80, MVT::f64, Expand);
424 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
425 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
428 // f32 and f64 in x87.
429 // Set up the FP register classes.
430 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
431 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
433 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
434 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
435 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
436 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
438 // Floating truncations go through memory. If optimizing, we lie about
439 // this though and handle it in InstructionSelectPreprocess so that
440 // dagcombine2 can hack on these.
442 setConvertAction(MVT::f80, MVT::f32, Expand);
443 setConvertAction(MVT::f64, MVT::f32, Expand);
444 setConvertAction(MVT::f80, MVT::f64, Expand);
448 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
449 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
451 addLegalFPImmediate(APFloat(+0.0)); // FLD0
452 addLegalFPImmediate(APFloat(+1.0)); // FLD1
453 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
454 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
455 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
456 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
457 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
458 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
461 // Long double always uses X87.
462 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
463 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
464 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
466 APFloat TmpFlt(+0.0);
467 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
468 addLegalFPImmediate(TmpFlt); // FLD0
470 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
471 APFloat TmpFlt2(+1.0);
472 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
473 addLegalFPImmediate(TmpFlt2); // FLD1
474 TmpFlt2.changeSign();
475 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
479 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
480 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
483 // Always use a library call for pow.
484 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
485 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
486 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
488 // First set operation action for all vector types to expand. Then we
489 // will selectively turn on ones that can be effectively codegen'd.
490 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
491 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
492 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
493 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
494 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
495 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
496 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
497 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
498 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
499 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
500 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
501 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
502 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
503 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
504 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
505 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
506 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
507 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
508 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
509 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
510 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
511 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
512 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
513 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
514 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
515 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
516 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
517 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
518 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
519 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
520 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
521 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
522 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
523 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
524 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
525 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
526 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
527 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
528 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
531 if (Subtarget->hasMMX()) {
532 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
533 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
534 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
535 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
537 // FIXME: add MMX packed arithmetics
539 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
540 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
541 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
542 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
544 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
545 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
546 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
547 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
549 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
550 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
552 setOperationAction(ISD::AND, MVT::v8i8, Promote);
553 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
554 setOperationAction(ISD::AND, MVT::v4i16, Promote);
555 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
556 setOperationAction(ISD::AND, MVT::v2i32, Promote);
557 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
558 setOperationAction(ISD::AND, MVT::v1i64, Legal);
560 setOperationAction(ISD::OR, MVT::v8i8, Promote);
561 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
562 setOperationAction(ISD::OR, MVT::v4i16, Promote);
563 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
564 setOperationAction(ISD::OR, MVT::v2i32, Promote);
565 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
566 setOperationAction(ISD::OR, MVT::v1i64, Legal);
568 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
569 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
570 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
571 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
572 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
573 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
574 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
576 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
577 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
578 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
579 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
580 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
581 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
582 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
584 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
585 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
586 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
587 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
589 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
590 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
591 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
592 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
594 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
595 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
596 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
599 if (Subtarget->hasSSE1()) {
600 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
602 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
603 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
604 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
605 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
606 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
607 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
608 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
609 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
610 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
611 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
612 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
615 if (Subtarget->hasSSE2()) {
616 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
617 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
618 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
619 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
620 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
622 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
623 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
624 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
625 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
626 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
627 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
628 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
629 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
630 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
631 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
632 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
633 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
634 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
635 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
636 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
638 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
639 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
640 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
641 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
642 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
644 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
645 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
646 // Do not attempt to custom lower non-power-of-2 vectors
647 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
649 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
650 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
651 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
653 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
654 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
655 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
656 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
657 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
658 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
659 if (Subtarget->is64Bit()) {
660 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
661 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
664 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
665 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
666 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
667 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
668 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
669 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
670 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
671 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
672 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
673 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
674 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
675 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
678 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
680 // Custom lower v2i64 and v2f64 selects.
681 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
682 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
683 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
684 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
687 if (Subtarget->hasSSE41()) {
688 // FIXME: Do we need to handle scalar-to-vector here?
689 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
691 // i8 and i16 vectors are custom , because the source register and source
692 // source memory operand types are not the same width. f32 vectors are
693 // custom since the immediate controlling the insert encodes additional
695 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
696 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
697 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
698 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
700 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
701 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
702 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
703 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
705 if (Subtarget->is64Bit()) {
706 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
707 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
711 // We want to custom lower some of our intrinsics.
712 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
714 // We have target-specific dag combine patterns for the following nodes:
715 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
716 setTargetDAGCombine(ISD::SELECT);
717 setTargetDAGCombine(ISD::STORE);
719 computeRegisterProperties();
721 // FIXME: These should be based on subtarget info. Plus, the values should
722 // be smaller when we are in optimizing for size mode.
723 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
724 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
725 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
726 allowUnalignedMemoryAccesses = true; // x86 supports it!
727 setPrefLoopAlignment(16);
732 X86TargetLowering::getSetCCResultType(const SDOperand &) const {
737 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
738 /// the desired ByVal argument alignment.
739 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
742 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
743 if (VTy->getBitWidth() == 128)
745 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
746 unsigned EltAlign = 0;
747 getMaxByValAlign(ATy->getElementType(), EltAlign);
748 if (EltAlign > MaxAlign)
750 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
751 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
752 unsigned EltAlign = 0;
753 getMaxByValAlign(STy->getElementType(i), EltAlign);
754 if (EltAlign > MaxAlign)
763 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
764 /// function arguments in the caller parameter area. For X86, aggregates
765 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
766 /// are at 4-byte boundaries.
767 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
768 if (Subtarget->is64Bit())
769 return getTargetData()->getABITypeAlignment(Ty);
771 if (Subtarget->hasSSE1())
772 getMaxByValAlign(Ty, Align);
776 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
778 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
779 SelectionDAG &DAG) const {
780 if (usesGlobalOffsetTable())
781 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
782 if (!Subtarget->isPICStyleRIPRel())
783 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
787 //===----------------------------------------------------------------------===//
788 // Return Value Calling Convention Implementation
789 //===----------------------------------------------------------------------===//
791 #include "X86GenCallingConv.inc"
793 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
794 /// exists skip possible ISD:TokenFactor.
795 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
796 if (Chain.getOpcode() == X86ISD::TAILCALL) {
798 } else if (Chain.getOpcode() == ISD::TokenFactor) {
799 if (Chain.getNumOperands() &&
800 Chain.getOperand(0).getOpcode() == X86ISD::TAILCALL)
801 return Chain.getOperand(0);
806 /// LowerRET - Lower an ISD::RET node.
807 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
808 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
810 SmallVector<CCValAssign, 16> RVLocs;
811 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
812 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
813 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
814 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
816 // If this is the first return lowered for this function, add the regs to the
817 // liveout set for the function.
818 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
819 for (unsigned i = 0; i != RVLocs.size(); ++i)
820 if (RVLocs[i].isRegLoc())
821 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
823 SDOperand Chain = Op.getOperand(0);
825 // Handle tail call return.
826 Chain = GetPossiblePreceedingTailCall(Chain);
827 if (Chain.getOpcode() == X86ISD::TAILCALL) {
828 SDOperand TailCall = Chain;
829 SDOperand TargetAddress = TailCall.getOperand(1);
830 SDOperand StackAdjustment = TailCall.getOperand(2);
831 assert(((TargetAddress.getOpcode() == ISD::Register &&
832 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
833 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
834 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
835 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
836 "Expecting an global address, external symbol, or register");
837 assert(StackAdjustment.getOpcode() == ISD::Constant &&
838 "Expecting a const value");
840 SmallVector<SDOperand,8> Operands;
841 Operands.push_back(Chain.getOperand(0));
842 Operands.push_back(TargetAddress);
843 Operands.push_back(StackAdjustment);
844 // Copy registers used by the call. Last operand is a flag so it is not
846 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
847 Operands.push_back(Chain.getOperand(i));
849 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
856 // Copy the result values into the output registers.
857 for (unsigned i = 0; i != RVLocs.size(); ++i) {
858 CCValAssign &VA = RVLocs[i];
859 assert(VA.isRegLoc() && "Can only return in registers!");
860 SDOperand ValToCopy = Op.getOperand(i*2+1);
862 // If this is a copy from an xmm register to ST(0), use an FPExtend to
863 // change the value to the FP stack register class.
864 if (RVLocs[i].getLocReg() == X86::ST0 &&
865 isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
866 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
868 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
869 Flag = Chain.getValue(1);
872 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
874 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
876 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
880 /// LowerCallResult - Lower the result values of an ISD::CALL into the
881 /// appropriate copies out of appropriate physical registers. This assumes that
882 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
883 /// being lowered. The returns a SDNode with the same number of values as the
885 SDNode *X86TargetLowering::
886 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
887 unsigned CallingConv, SelectionDAG &DAG) {
889 // Assign locations to each value returned by this call.
890 SmallVector<CCValAssign, 16> RVLocs;
891 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
892 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
893 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
895 SmallVector<SDOperand, 8> ResultVals;
897 // Copy all of the result registers out of their specified physreg.
898 for (unsigned i = 0; i != RVLocs.size(); ++i) {
899 MVT::ValueType CopyVT = RVLocs[i].getValVT();
901 // If this is a call to a function that returns an fp value on the floating
902 // point stack, but where we prefer to use the value in xmm registers, copy
903 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
904 if (RVLocs[i].getLocReg() == X86::ST0 &&
905 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
909 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
910 CopyVT, InFlag).getValue(1);
911 SDOperand Val = Chain.getValue(0);
912 InFlag = Chain.getValue(2);
914 if (CopyVT != RVLocs[i].getValVT()) {
915 // Round the F80 the right size, which also moves to the appropriate xmm
917 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
918 // This truncation won't change the value.
919 DAG.getIntPtrConstant(1));
922 ResultVals.push_back(Val);
925 // Merge everything together with a MERGE_VALUES node.
926 ResultVals.push_back(Chain);
927 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
928 &ResultVals[0], ResultVals.size()).Val;
931 /// LowerCallResultToTwo64BitRegs - Lower the result values of an x86-64
932 /// ISD::CALL where the results are known to be in two 64-bit registers,
933 /// e.g. XMM0 and XMM1. This simplify store the two values back to the
934 /// fixed stack slot allocated for StructRet.
935 SDNode *X86TargetLowering::
936 LowerCallResultToTwo64BitRegs(SDOperand Chain, SDOperand InFlag,
937 SDNode *TheCall, unsigned Reg1, unsigned Reg2,
938 MVT::ValueType VT, SelectionDAG &DAG) {
939 SDOperand RetVal1 = DAG.getCopyFromReg(Chain, Reg1, VT, InFlag);
940 Chain = RetVal1.getValue(1);
941 InFlag = RetVal1.getValue(2);
942 SDOperand RetVal2 = DAG.getCopyFromReg(Chain, Reg2, VT, InFlag);
943 Chain = RetVal2.getValue(1);
944 InFlag = RetVal2.getValue(2);
945 SDOperand FIN = TheCall->getOperand(5);
946 Chain = DAG.getStore(Chain, RetVal1, FIN, NULL, 0);
947 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
948 Chain = DAG.getStore(Chain, RetVal2, FIN, NULL, 0);
952 /// LowerCallResultToTwoX87Regs - Lower the result values of an x86-64 ISD::CALL
953 /// where the results are known to be in ST0 and ST1.
954 SDNode *X86TargetLowering::
955 LowerCallResultToTwoX87Regs(SDOperand Chain, SDOperand InFlag,
956 SDNode *TheCall, SelectionDAG &DAG) {
957 SmallVector<SDOperand, 8> ResultVals;
958 const MVT::ValueType VTs[] = { MVT::f80, MVT::f80, MVT::Other, MVT::Flag };
959 SDVTList Tys = DAG.getVTList(VTs, 4);
960 SDOperand Ops[] = { Chain, InFlag };
961 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_ST0_ST1, Tys, Ops, 2);
962 Chain = RetVal.getValue(2);
963 SDOperand FIN = TheCall->getOperand(5);
964 Chain = DAG.getStore(Chain, RetVal.getValue(1), FIN, NULL, 0);
965 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(16));
966 Chain = DAG.getStore(Chain, RetVal, FIN, NULL, 0);
970 //===----------------------------------------------------------------------===//
971 // C & StdCall & Fast Calling Convention implementation
972 //===----------------------------------------------------------------------===//
973 // StdCall calling convention seems to be standard for many Windows' API
974 // routines and around. It differs from C calling convention just a little:
975 // callee should clean up the stack, not caller. Symbols should be also
976 // decorated in some fancy way :) It doesn't support any vector arguments.
977 // For info on fast calling convention see Fast Calling Convention (tail call)
978 // implementation LowerX86_32FastCCCallTo.
980 /// AddLiveIn - This helper function adds the specified physical register to the
981 /// MachineFunction as a live in value. It also creates a corresponding virtual
983 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
984 const TargetRegisterClass *RC) {
985 assert(RC->contains(PReg) && "Not the correct regclass!");
986 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
987 MF.getRegInfo().addLiveIn(PReg, VReg);
991 /// CallIsStructReturn - Determines whether a CALL node uses struct return
993 static bool CallIsStructReturn(SDOperand Op) {
994 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
998 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(6));
999 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1002 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1003 /// return semantics.
1004 static bool ArgsAreStructReturn(SDOperand Op) {
1005 unsigned NumArgs = Op.Val->getNumValues() - 1;
1009 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(3));
1010 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1013 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires the
1014 /// callee to pop its own arguments. Callee pop is necessary to support tail
1016 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1017 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1021 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1024 case CallingConv::X86_StdCall:
1025 return !Subtarget->is64Bit();
1026 case CallingConv::X86_FastCall:
1027 return !Subtarget->is64Bit();
1028 case CallingConv::Fast:
1029 return PerformTailCallOpt;
1033 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1034 /// FORMAL_ARGUMENTS node.
1035 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1036 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1038 if (Subtarget->is64Bit()) {
1039 if (CC == CallingConv::Fast && PerformTailCallOpt)
1040 return CC_X86_64_TailCall;
1045 if (CC == CallingConv::X86_FastCall)
1046 return CC_X86_32_FastCall;
1047 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1048 return CC_X86_32_TailCall;
1053 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1054 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1056 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1057 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1058 if (CC == CallingConv::X86_FastCall)
1060 else if (CC == CallingConv::X86_StdCall)
1065 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
1066 /// possibly be overwritten when lowering the outgoing arguments in a tail
1067 /// call. Currently the implementation of this call is very conservative and
1068 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
1069 /// virtual registers would be overwritten by direct lowering.
1070 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
1071 MachineFrameInfo * MFI) {
1072 RegisterSDNode * OpReg = NULL;
1073 FrameIndexSDNode * FrameIdxNode = NULL;
1075 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
1076 (Op.getOpcode()== ISD::CopyFromReg &&
1077 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
1078 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
1079 (Op.getOpcode() == ISD::LOAD &&
1080 (FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op.getOperand(1))) &&
1081 (MFI->isFixedObjectIndex((FrameIdx = FrameIdxNode->getIndex()))) &&
1082 (MFI->getObjectOffset(FrameIdx) >= 0)))
1087 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1088 /// in a register before calling.
1089 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1090 return !IsTailCall && !Is64Bit &&
1091 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1092 Subtarget->isPICStyleGOT();
1096 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1097 /// address to be loaded in a register.
1099 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1100 return !Is64Bit && IsTailCall &&
1101 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1102 Subtarget->isPICStyleGOT();
1105 /// CopyTailCallClobberedArgumentsToVRegs - Create virtual registers for all
1106 /// arguments to force loading and guarantee that arguments sourcing from
1107 /// incomming parameters are not overwriting each other.
1109 CopyTailCallClobberedArgumentsToVRegs(SDOperand Chain,
1110 SmallVector<std::pair<unsigned, SDOperand>, 8> &TailCallClobberedVRegs,
1112 MachineFunction &MF,
1113 const TargetLowering * TL) {
1116 for (unsigned i = 0, e = TailCallClobberedVRegs.size(); i != e; i++) {
1117 SDOperand Arg = TailCallClobberedVRegs[i].second;
1118 unsigned Idx = TailCallClobberedVRegs[i].first;
1121 createVirtualRegister(TL->getRegClassFor(Arg.getValueType()));
1122 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
1123 InFlag = Chain.getValue(1);
1124 Arg = DAG.getCopyFromReg(Chain, VReg, Arg.getValueType(), InFlag);
1125 TailCallClobberedVRegs[i] = std::make_pair(Idx, Arg);
1126 Chain = Arg.getValue(1);
1127 InFlag = Arg.getValue(2);
1132 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1133 /// by "Src" to address "Dst" with size and alignment information specified by
1134 /// the specific parameter attribute. The copy will be passed as a byval function
1137 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1138 ISD::ParamFlags::ParamFlagsTy Flags,
1139 SelectionDAG &DAG) {
1140 unsigned Align = ISD::ParamFlags::One <<
1141 ((Flags & ISD::ParamFlags::ByValAlign) >> ISD::ParamFlags::ByValAlignOffs);
1142 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1143 ISD::ParamFlags::ByValSizeOffs;
1144 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1145 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1146 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1147 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, AlignNode, AlwaysInline);
1150 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1151 const CCValAssign &VA,
1152 MachineFrameInfo *MFI,
1154 SDOperand Root, unsigned i) {
1155 // Create the nodes corresponding to a load from this parameter slot.
1156 ISD::ParamFlags::ParamFlagsTy Flags =
1157 cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
1158 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1159 bool isByVal = Flags & ISD::ParamFlags::ByVal;
1160 bool isImmutable = !AlwaysUseMutable && !isByVal;
1162 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1163 // changed with more analysis.
1164 // In case of tail call optimization mark all arguments mutable. Since they
1165 // could be overwritten by lowering of arguments in case of a tail call.
1166 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1167 VA.getLocMemOffset(), isImmutable);
1168 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1171 return DAG.getLoad(VA.getValVT(), Root, FIN,
1172 PseudoSourceValue::getFixedStack(), FI);
1176 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1177 MachineFunction &MF = DAG.getMachineFunction();
1178 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1180 const Function* Fn = MF.getFunction();
1181 if (Fn->hasExternalLinkage() &&
1182 Subtarget->isTargetCygMing() &&
1183 Fn->getName() == "main")
1184 FuncInfo->setForceFramePointer(true);
1186 // Decorate the function name.
1187 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1189 MachineFrameInfo *MFI = MF.getFrameInfo();
1190 SDOperand Root = Op.getOperand(0);
1191 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1192 unsigned CC = MF.getFunction()->getCallingConv();
1193 bool Is64Bit = Subtarget->is64Bit();
1195 assert(!(isVarArg && CC == CallingConv::Fast) &&
1196 "Var args not supported with calling convention fastcc");
1198 // Assign locations to all of the incoming arguments.
1199 SmallVector<CCValAssign, 16> ArgLocs;
1200 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1201 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1203 SmallVector<SDOperand, 8> ArgValues;
1204 unsigned LastVal = ~0U;
1205 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1206 CCValAssign &VA = ArgLocs[i];
1207 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1209 assert(VA.getValNo() != LastVal &&
1210 "Don't support value assigned to multiple locs yet");
1211 LastVal = VA.getValNo();
1213 if (VA.isRegLoc()) {
1214 MVT::ValueType RegVT = VA.getLocVT();
1215 TargetRegisterClass *RC;
1216 if (RegVT == MVT::i32)
1217 RC = X86::GR32RegisterClass;
1218 else if (Is64Bit && RegVT == MVT::i64)
1219 RC = X86::GR64RegisterClass;
1220 else if (RegVT == MVT::f32)
1221 RC = X86::FR32RegisterClass;
1222 else if (RegVT == MVT::f64)
1223 RC = X86::FR64RegisterClass;
1225 assert(MVT::isVector(RegVT));
1226 if (Is64Bit && MVT::getSizeInBits(RegVT) == 64) {
1227 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1230 RC = X86::VR128RegisterClass;
1233 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1234 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1236 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1237 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1239 if (VA.getLocInfo() == CCValAssign::SExt)
1240 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1241 DAG.getValueType(VA.getValVT()));
1242 else if (VA.getLocInfo() == CCValAssign::ZExt)
1243 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1244 DAG.getValueType(VA.getValVT()));
1246 if (VA.getLocInfo() != CCValAssign::Full)
1247 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1249 // Handle MMX values passed in GPRs.
1250 if (Is64Bit && RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1251 MVT::getSizeInBits(RegVT) == 64)
1252 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1254 ArgValues.push_back(ArgValue);
1256 assert(VA.isMemLoc());
1257 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1261 unsigned StackSize = CCInfo.getNextStackOffset();
1262 // align stack specially for tail calls
1263 if (CC == CallingConv::Fast)
1264 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1266 // If the function takes variable number of arguments, make a frame index for
1267 // the start of the first vararg value... for expansion of llvm.va_start.
1269 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1270 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1273 static const unsigned GPR64ArgRegs[] = {
1274 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1276 static const unsigned XMMArgRegs[] = {
1277 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1278 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1281 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1282 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1284 // For X86-64, if there are vararg parameters that are passed via
1285 // registers, then we must store them to their spots on the stack so they
1286 // may be loaded by deferencing the result of va_next.
1287 VarArgsGPOffset = NumIntRegs * 8;
1288 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1289 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1291 // Store the integer parameter registers.
1292 SmallVector<SDOperand, 8> MemOps;
1293 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1294 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1295 DAG.getIntPtrConstant(VarArgsGPOffset));
1296 for (; NumIntRegs != 6; ++NumIntRegs) {
1297 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1298 X86::GR64RegisterClass);
1299 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1301 DAG.getStore(Val.getValue(1), Val, FIN,
1302 PseudoSourceValue::getFixedStack(),
1304 MemOps.push_back(Store);
1305 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1306 DAG.getIntPtrConstant(8));
1309 // Now store the XMM (fp + vector) parameter registers.
1310 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1311 DAG.getIntPtrConstant(VarArgsFPOffset));
1312 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1313 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1314 X86::VR128RegisterClass);
1315 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1317 DAG.getStore(Val.getValue(1), Val, FIN,
1318 PseudoSourceValue::getFixedStack(),
1320 MemOps.push_back(Store);
1321 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1322 DAG.getIntPtrConstant(16));
1324 if (!MemOps.empty())
1325 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1326 &MemOps[0], MemOps.size());
1330 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1331 // arguments and the arguments after the retaddr has been pushed are
1333 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1334 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1335 (StackSize & 7) == 0)
1338 ArgValues.push_back(Root);
1340 // Some CCs need callee pop.
1341 if (IsCalleePop(Op)) {
1342 BytesToPopOnReturn = StackSize; // Callee pops everything.
1343 BytesCallerReserves = 0;
1345 BytesToPopOnReturn = 0; // Callee pops nothing.
1346 // If this is an sret function, the return should pop the hidden pointer.
1347 if (!Is64Bit && ArgsAreStructReturn(Op))
1348 BytesToPopOnReturn = 4;
1349 BytesCallerReserves = StackSize;
1353 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1354 if (CC == CallingConv::X86_FastCall)
1355 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1358 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1360 // Return the new list of results.
1361 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1362 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1366 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1367 const SDOperand &StackPtr,
1368 const CCValAssign &VA,
1371 unsigned LocMemOffset = VA.getLocMemOffset();
1372 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1373 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1374 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1375 ISD::ParamFlags::ParamFlagsTy Flags =
1376 cast<ConstantSDNode>(FlagsOp)->getValue();
1377 if (Flags & ISD::ParamFlags::ByVal) {
1378 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1380 return DAG.getStore(Chain, Arg, PtrOff,
1381 PseudoSourceValue::getStack(), LocMemOffset);
1384 /// ClassifyX86_64SRetCallReturn - Classify how to implement a x86-64
1385 /// struct return call to the specified function. X86-64 ABI specifies
1386 /// some SRet calls are actually returned in registers. Since current
1387 /// LLVM cannot represent multi-value calls, they are represent as
1388 /// calls where the results are passed in a hidden struct provided by
1389 /// the caller. This function examines the type of the struct to
1390 /// determine the correct way to implement the call.
1392 X86TargetLowering::ClassifyX86_64SRetCallReturn(const Function *Fn) {
1393 // FIXME: Disabled for now.
1394 return X86::InMemory;
1396 const PointerType *PTy = cast<PointerType>(Fn->arg_begin()->getType());
1397 const Type *RTy = PTy->getElementType();
1398 unsigned Size = getTargetData()->getABITypeSize(RTy);
1399 if (Size != 16 && Size != 32)
1400 return X86::InMemory;
1403 const StructType *STy = dyn_cast<StructType>(RTy);
1404 if (!STy) return X86::InMemory;
1405 if (STy->getNumElements() == 2 &&
1406 STy->getElementType(0) == Type::X86_FP80Ty &&
1407 STy->getElementType(1) == Type::X86_FP80Ty)
1412 for (Type::subtype_iterator I = RTy->subtype_begin(), E = RTy->subtype_end();
1414 const Type *STy = I->get();
1415 if (!STy->isFPOrFPVector()) {
1423 return X86::InGPR64;
1426 void X86TargetLowering::X86_64AnalyzeSRetCallOperands(SDNode *TheCall,
1429 unsigned NumOps = (TheCall->getNumOperands() - 5) / 2;
1430 for (unsigned i = 1; i != NumOps; ++i) {
1431 MVT::ValueType ArgVT = TheCall->getOperand(5+2*i).getValueType();
1432 SDOperand FlagOp = TheCall->getOperand(5+2*i+1);
1433 unsigned ArgFlags =cast<ConstantSDNode>(FlagOp)->getValue();
1434 if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo)) {
1435 cerr << "Call operand #" << i << " has unhandled type "
1436 << MVT::getValueTypeString(ArgVT) << "\n";
1442 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1443 MachineFunction &MF = DAG.getMachineFunction();
1444 MachineFrameInfo * MFI = MF.getFrameInfo();
1445 SDOperand Chain = Op.getOperand(0);
1446 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1447 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1448 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1449 && CC == CallingConv::Fast && PerformTailCallOpt;
1450 SDOperand Callee = Op.getOperand(4);
1451 bool Is64Bit = Subtarget->is64Bit();
1452 bool IsStructRet = CallIsStructReturn(Op);
1454 assert(!(isVarArg && CC == CallingConv::Fast) &&
1455 "Var args not supported with calling convention fastcc");
1457 // Analyze operands of the call, assigning locations to each operand.
1458 SmallVector<CCValAssign, 16> ArgLocs;
1459 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1460 CCAssignFn *CCFn = CCAssignFnForNode(Op);
1462 X86::X86_64SRet SRetMethod = X86::InMemory;
1463 if (Is64Bit && IsStructRet)
1464 // FIXME: We can't figure out type of the sret structure for indirect
1465 // calls. We need to copy more information from CallSite to the ISD::CALL
1467 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1469 ClassifyX86_64SRetCallReturn(dyn_cast<Function>(G->getGlobal()));
1471 // UGLY HACK! For x86-64, some 128-bit aggregates are returns in a pair of
1472 // registers. Unfortunately, llvm does not support i128 yet so we pretend it's
1474 if (SRetMethod != X86::InMemory)
1475 X86_64AnalyzeSRetCallOperands(Op.Val, CCFn, CCInfo);
1477 CCInfo.AnalyzeCallOperands(Op.Val, CCFn);
1479 // Get a count of how many bytes are to be pushed on the stack.
1480 unsigned NumBytes = CCInfo.getNextStackOffset();
1481 if (CC == CallingConv::Fast)
1482 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1484 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1485 // arguments and the arguments after the retaddr has been pushed are aligned.
1486 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1487 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1488 (NumBytes & 7) == 0)
1493 // Lower arguments at fp - stackoffset + fpdiff.
1494 unsigned NumBytesCallerPushed =
1495 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1496 FPDiff = NumBytesCallerPushed - NumBytes;
1498 // Set the delta of movement of the returnaddr stackslot.
1499 // But only set if delta is greater than previous delta.
1500 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1501 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1504 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1506 SDOperand RetAddrFrIdx;
1508 // Adjust the Return address stack slot.
1510 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1511 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1512 // Load the "old" Return address.
1514 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1515 Chain = SDOperand(RetAddrFrIdx.Val, 1);
1519 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1520 SmallVector<std::pair<unsigned, SDOperand>, 8> TailCallClobberedVRegs;
1521 SmallVector<SDOperand, 8> MemOpChains;
1525 // Walk the register/memloc assignments, inserting copies/loads. For tail
1526 // calls, remember all arguments for later special lowering.
1527 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1528 CCValAssign &VA = ArgLocs[i];
1529 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1531 // Promote the value if needed.
1532 switch (VA.getLocInfo()) {
1533 default: assert(0 && "Unknown loc info!");
1534 case CCValAssign::Full: break;
1535 case CCValAssign::SExt:
1536 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1538 case CCValAssign::ZExt:
1539 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1541 case CCValAssign::AExt:
1542 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1546 if (VA.isRegLoc()) {
1547 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1550 assert(VA.isMemLoc());
1551 if (StackPtr.Val == 0)
1552 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1554 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1556 } else if (IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
1557 TailCallClobberedVRegs.push_back(std::make_pair(i,Arg));
1562 if (!MemOpChains.empty())
1563 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1564 &MemOpChains[0], MemOpChains.size());
1566 // Build a sequence of copy-to-reg nodes chained together with token chain
1567 // and flag operands which copy the outgoing args into registers.
1569 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1570 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1572 InFlag = Chain.getValue(1);
1575 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1577 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1578 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1579 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1581 InFlag = Chain.getValue(1);
1583 // If we are tail calling and generating PIC/GOT style code load the address
1584 // of the callee into ecx. The value in ecx is used as target of the tail
1585 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1586 // calls on PIC/GOT architectures. Normally we would just put the address of
1587 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1588 // restored (since ebx is callee saved) before jumping to the target@PLT.
1589 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1590 // Note: The actual moving to ecx is done further down.
1591 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1592 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1593 !G->getGlobal()->hasProtectedVisibility())
1594 Callee = LowerGlobalAddress(Callee, DAG);
1595 else if (isa<ExternalSymbolSDNode>(Callee))
1596 Callee = LowerExternalSymbol(Callee,DAG);
1599 if (Is64Bit && isVarArg) {
1600 // From AMD64 ABI document:
1601 // For calls that may call functions that use varargs or stdargs
1602 // (prototype-less calls or calls to functions containing ellipsis (...) in
1603 // the declaration) %al is used as hidden argument to specify the number
1604 // of SSE registers used. The contents of %al do not need to match exactly
1605 // the number of registers, but must be an ubound on the number of SSE
1606 // registers used and is in the range 0 - 8 inclusive.
1608 // Count the number of XMM registers allocated.
1609 static const unsigned XMMArgRegs[] = {
1610 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1611 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1613 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1615 Chain = DAG.getCopyToReg(Chain, X86::AL,
1616 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1617 InFlag = Chain.getValue(1);
1621 // For tail calls lower the arguments to the 'real' stack slot.
1623 SmallVector<SDOperand, 8> MemOpChains2;
1626 // Do not flag preceeding copytoreg stuff together with the following stuff.
1627 InFlag = SDOperand();
1629 Chain = CopyTailCallClobberedArgumentsToVRegs(Chain, TailCallClobberedVRegs,
1632 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1633 CCValAssign &VA = ArgLocs[i];
1634 if (!VA.isRegLoc()) {
1635 assert(VA.isMemLoc());
1636 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1637 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1638 ISD::ParamFlags::ParamFlagsTy Flags =
1639 cast<ConstantSDNode>(FlagsOp)->getValue();
1640 // Create frame index.
1641 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1642 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1643 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1644 FIN = DAG.getFrameIndex(FI, MVT::i32);
1646 // Find virtual register for this argument.
1648 for (unsigned idx=0, e= TailCallClobberedVRegs.size(); idx < e; idx++)
1649 if (TailCallClobberedVRegs[idx].first==i) {
1650 Arg = TailCallClobberedVRegs[idx].second;
1654 assert(IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)==false ||
1655 (Found==true && "No corresponding Argument was found"));
1657 if (Flags & ISD::ParamFlags::ByVal) {
1658 // Copy relative to framepointer.
1659 MemOpChains2.push_back(CreateCopyOfByValArgument(Arg, FIN, Chain,
1662 // Store relative to framepointer.
1663 MemOpChains2.push_back(
1664 DAG.getStore(Chain, Arg, FIN,
1665 PseudoSourceValue::getFixedStack(), FI));
1670 if (!MemOpChains2.empty())
1671 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1672 &MemOpChains2[0], MemOpChains2.size());
1674 // Store the return address to the appropriate stack slot.
1676 // Calculate the new stack slot for the return address.
1677 int SlotSize = Is64Bit ? 8 : 4;
1678 int NewReturnAddrFI =
1679 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1680 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1681 SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1682 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1683 PseudoSourceValue::getFixedStack(), NewReturnAddrFI);
1687 // If the callee is a GlobalAddress node (quite common, every direct call is)
1688 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1689 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1690 // We should use extra load for direct calls to dllimported functions in
1692 if ((IsTailCall || !Is64Bit ||
1693 getTargetMachine().getCodeModel() != CodeModel::Large)
1694 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1695 getTargetMachine(), true))
1696 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1697 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1698 if (IsTailCall || !Is64Bit ||
1699 getTargetMachine().getCodeModel() != CodeModel::Large)
1700 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1701 } else if (IsTailCall) {
1702 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1704 Chain = DAG.getCopyToReg(Chain,
1705 DAG.getRegister(Opc, getPointerTy()),
1707 Callee = DAG.getRegister(Opc, getPointerTy());
1708 // Add register as live out.
1709 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1712 // Returns a chain & a flag for retval copy to use.
1713 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1714 SmallVector<SDOperand, 8> Ops;
1717 Ops.push_back(Chain);
1718 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1719 Ops.push_back(DAG.getIntPtrConstant(0));
1721 Ops.push_back(InFlag);
1722 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1723 InFlag = Chain.getValue(1);
1725 // Returns a chain & a flag for retval copy to use.
1726 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1730 Ops.push_back(Chain);
1731 Ops.push_back(Callee);
1734 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1736 // Add an implicit use GOT pointer in EBX.
1737 if (!IsTailCall && !Is64Bit &&
1738 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1739 Subtarget->isPICStyleGOT())
1740 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1742 // Add argument registers to the end of the list so that they are known live
1744 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1745 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1746 RegsToPass[i].second.getValueType()));
1749 Ops.push_back(InFlag);
1752 assert(InFlag.Val &&
1753 "Flag must be set. Depend on flag being set in LowerRET");
1754 Chain = DAG.getNode(X86ISD::TAILCALL,
1755 Op.Val->getVTList(), &Ops[0], Ops.size());
1757 return SDOperand(Chain.Val, Op.ResNo);
1760 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1761 InFlag = Chain.getValue(1);
1763 // Create the CALLSEQ_END node.
1764 unsigned NumBytesForCalleeToPush;
1765 if (IsCalleePop(Op))
1766 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1767 else if (!Is64Bit && IsStructRet)
1768 // If this is is a call to a struct-return function, the callee
1769 // pops the hidden struct pointer, so we have to push it back.
1770 // This is common for Darwin/X86, Linux & Mingw32 targets.
1771 NumBytesForCalleeToPush = 4;
1773 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1775 // Returns a flag for retval copy to use.
1776 Chain = DAG.getCALLSEQ_END(Chain,
1777 DAG.getIntPtrConstant(NumBytes),
1778 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1780 InFlag = Chain.getValue(1);
1782 // Handle result values, copying them out of physregs into vregs that we
1784 switch (SRetMethod) {
1786 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1788 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1790 MVT::i64, DAG), Op.ResNo);
1792 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1793 X86::XMM0, X86::XMM1,
1794 MVT::f64, DAG), Op.ResNo);
1796 return SDOperand(LowerCallResultToTwoX87Regs(Chain, InFlag, Op.Val, DAG),
1802 //===----------------------------------------------------------------------===//
1803 // Fast Calling Convention (tail call) implementation
1804 //===----------------------------------------------------------------------===//
1806 // Like std call, callee cleans arguments, convention except that ECX is
1807 // reserved for storing the tail called function address. Only 2 registers are
1808 // free for argument passing (inreg). Tail call optimization is performed
1810 // * tailcallopt is enabled
1811 // * caller/callee are fastcc
1812 // On X86_64 architecture with GOT-style position independent code only local
1813 // (within module) calls are supported at the moment.
1814 // To keep the stack aligned according to platform abi the function
1815 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1816 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1817 // If a tail called function callee has more arguments than the caller the
1818 // caller needs to make sure that there is room to move the RETADDR to. This is
1819 // achieved by reserving an area the size of the argument delta right after the
1820 // original REtADDR, but before the saved framepointer or the spilled registers
1821 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1833 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1834 /// for a 16 byte align requirement.
1835 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1836 SelectionDAG& DAG) {
1837 if (PerformTailCallOpt) {
1838 MachineFunction &MF = DAG.getMachineFunction();
1839 const TargetMachine &TM = MF.getTarget();
1840 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1841 unsigned StackAlignment = TFI.getStackAlignment();
1842 uint64_t AlignMask = StackAlignment - 1;
1843 int64_t Offset = StackSize;
1844 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1845 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1846 // Number smaller than 12 so just add the difference.
1847 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1849 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1850 Offset = ((~AlignMask) & Offset) + StackAlignment +
1851 (StackAlignment-SlotSize);
1858 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1859 /// following the call is a return. A function is eligible if caller/callee
1860 /// calling conventions match, currently only fastcc supports tail calls, and
1861 /// the function CALL is immediatly followed by a RET.
1862 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1864 SelectionDAG& DAG) const {
1865 if (!PerformTailCallOpt)
1868 // Check whether CALL node immediatly preceeds the RET node and whether the
1869 // return uses the result of the node or is a void return.
1870 unsigned NumOps = Ret.getNumOperands();
1872 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1873 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1875 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1876 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1877 MachineFunction &MF = DAG.getMachineFunction();
1878 unsigned CallerCC = MF.getFunction()->getCallingConv();
1879 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1880 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1881 SDOperand Callee = Call.getOperand(4);
1882 // On x86/32Bit PIC/GOT tail calls are supported.
1883 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1884 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1887 // Can only do local tail calls (in same module, hidden or protected) on
1888 // x86_64 PIC/GOT at the moment.
1889 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1890 return G->getGlobal()->hasHiddenVisibility()
1891 || G->getGlobal()->hasProtectedVisibility();
1898 //===----------------------------------------------------------------------===//
1899 // Other Lowering Hooks
1900 //===----------------------------------------------------------------------===//
1903 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1904 MachineFunction &MF = DAG.getMachineFunction();
1905 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1906 int ReturnAddrIndex = FuncInfo->getRAIndex();
1908 if (ReturnAddrIndex == 0) {
1909 // Set up a frame object for the return address.
1910 if (Subtarget->is64Bit())
1911 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1913 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1915 FuncInfo->setRAIndex(ReturnAddrIndex);
1918 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1923 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1924 /// specific condition code. It returns a false if it cannot do a direct
1925 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1927 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1928 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1929 SelectionDAG &DAG) {
1930 X86CC = X86::COND_INVALID;
1932 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1933 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1934 // X > -1 -> X == 0, jump !sign.
1935 RHS = DAG.getConstant(0, RHS.getValueType());
1936 X86CC = X86::COND_NS;
1938 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1939 // X < 0 -> X == 0, jump on sign.
1940 X86CC = X86::COND_S;
1942 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1944 RHS = DAG.getConstant(0, RHS.getValueType());
1945 X86CC = X86::COND_LE;
1950 switch (SetCCOpcode) {
1952 case ISD::SETEQ: X86CC = X86::COND_E; break;
1953 case ISD::SETGT: X86CC = X86::COND_G; break;
1954 case ISD::SETGE: X86CC = X86::COND_GE; break;
1955 case ISD::SETLT: X86CC = X86::COND_L; break;
1956 case ISD::SETLE: X86CC = X86::COND_LE; break;
1957 case ISD::SETNE: X86CC = X86::COND_NE; break;
1958 case ISD::SETULT: X86CC = X86::COND_B; break;
1959 case ISD::SETUGT: X86CC = X86::COND_A; break;
1960 case ISD::SETULE: X86CC = X86::COND_BE; break;
1961 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1964 // On a floating point condition, the flags are set as follows:
1966 // 0 | 0 | 0 | X > Y
1967 // 0 | 0 | 1 | X < Y
1968 // 1 | 0 | 0 | X == Y
1969 // 1 | 1 | 1 | unordered
1971 switch (SetCCOpcode) {
1974 case ISD::SETEQ: X86CC = X86::COND_E; break;
1975 case ISD::SETOLT: Flip = true; // Fallthrough
1977 case ISD::SETGT: X86CC = X86::COND_A; break;
1978 case ISD::SETOLE: Flip = true; // Fallthrough
1980 case ISD::SETGE: X86CC = X86::COND_AE; break;
1981 case ISD::SETUGT: Flip = true; // Fallthrough
1983 case ISD::SETLT: X86CC = X86::COND_B; break;
1984 case ISD::SETUGE: Flip = true; // Fallthrough
1986 case ISD::SETLE: X86CC = X86::COND_BE; break;
1988 case ISD::SETNE: X86CC = X86::COND_NE; break;
1989 case ISD::SETUO: X86CC = X86::COND_P; break;
1990 case ISD::SETO: X86CC = X86::COND_NP; break;
1993 std::swap(LHS, RHS);
1996 return X86CC != X86::COND_INVALID;
1999 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2000 /// code. Current x86 isa includes the following FP cmov instructions:
2001 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2002 static bool hasFPCMov(unsigned X86CC) {
2018 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2019 /// true if Op is undef or if its value falls within the specified range (L, H].
2020 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2021 if (Op.getOpcode() == ISD::UNDEF)
2024 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2025 return (Val >= Low && Val < Hi);
2028 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2029 /// true if Op is undef or if its value equal to the specified value.
2030 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2031 if (Op.getOpcode() == ISD::UNDEF)
2033 return cast<ConstantSDNode>(Op)->getValue() == Val;
2036 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2037 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2038 bool X86::isPSHUFDMask(SDNode *N) {
2039 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2041 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2044 // Check if the value doesn't reference the second vector.
2045 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2046 SDOperand Arg = N->getOperand(i);
2047 if (Arg.getOpcode() == ISD::UNDEF) continue;
2048 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2049 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2056 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2057 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2058 bool X86::isPSHUFHWMask(SDNode *N) {
2059 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2061 if (N->getNumOperands() != 8)
2064 // Lower quadword copied in order.
2065 for (unsigned i = 0; i != 4; ++i) {
2066 SDOperand Arg = N->getOperand(i);
2067 if (Arg.getOpcode() == ISD::UNDEF) continue;
2068 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2069 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2073 // Upper quadword shuffled.
2074 for (unsigned i = 4; i != 8; ++i) {
2075 SDOperand Arg = N->getOperand(i);
2076 if (Arg.getOpcode() == ISD::UNDEF) continue;
2077 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2078 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2079 if (Val < 4 || Val > 7)
2086 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2087 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2088 bool X86::isPSHUFLWMask(SDNode *N) {
2089 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2091 if (N->getNumOperands() != 8)
2094 // Upper quadword copied in order.
2095 for (unsigned i = 4; i != 8; ++i)
2096 if (!isUndefOrEqual(N->getOperand(i), i))
2099 // Lower quadword shuffled.
2100 for (unsigned i = 0; i != 4; ++i)
2101 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2107 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2108 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2109 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2110 if (NumElems != 2 && NumElems != 4) return false;
2112 unsigned Half = NumElems / 2;
2113 for (unsigned i = 0; i < Half; ++i)
2114 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2116 for (unsigned i = Half; i < NumElems; ++i)
2117 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2123 bool X86::isSHUFPMask(SDNode *N) {
2124 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2125 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2128 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2129 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2130 /// half elements to come from vector 1 (which would equal the dest.) and
2131 /// the upper half to come from vector 2.
2132 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2133 if (NumOps != 2 && NumOps != 4) return false;
2135 unsigned Half = NumOps / 2;
2136 for (unsigned i = 0; i < Half; ++i)
2137 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2139 for (unsigned i = Half; i < NumOps; ++i)
2140 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2145 static bool isCommutedSHUFP(SDNode *N) {
2146 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2147 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2150 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2151 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2152 bool X86::isMOVHLPSMask(SDNode *N) {
2153 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2155 if (N->getNumOperands() != 4)
2158 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2159 return isUndefOrEqual(N->getOperand(0), 6) &&
2160 isUndefOrEqual(N->getOperand(1), 7) &&
2161 isUndefOrEqual(N->getOperand(2), 2) &&
2162 isUndefOrEqual(N->getOperand(3), 3);
2165 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2166 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2168 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2169 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2171 if (N->getNumOperands() != 4)
2174 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2175 return isUndefOrEqual(N->getOperand(0), 2) &&
2176 isUndefOrEqual(N->getOperand(1), 3) &&
2177 isUndefOrEqual(N->getOperand(2), 2) &&
2178 isUndefOrEqual(N->getOperand(3), 3);
2181 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2182 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2183 bool X86::isMOVLPMask(SDNode *N) {
2184 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2186 unsigned NumElems = N->getNumOperands();
2187 if (NumElems != 2 && NumElems != 4)
2190 for (unsigned i = 0; i < NumElems/2; ++i)
2191 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2194 for (unsigned i = NumElems/2; i < NumElems; ++i)
2195 if (!isUndefOrEqual(N->getOperand(i), i))
2201 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2202 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2204 bool X86::isMOVHPMask(SDNode *N) {
2205 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2207 unsigned NumElems = N->getNumOperands();
2208 if (NumElems != 2 && NumElems != 4)
2211 for (unsigned i = 0; i < NumElems/2; ++i)
2212 if (!isUndefOrEqual(N->getOperand(i), i))
2215 for (unsigned i = 0; i < NumElems/2; ++i) {
2216 SDOperand Arg = N->getOperand(i + NumElems/2);
2217 if (!isUndefOrEqual(Arg, i + NumElems))
2224 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2225 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2226 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2227 bool V2IsSplat = false) {
2228 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2231 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2232 SDOperand BitI = Elts[i];
2233 SDOperand BitI1 = Elts[i+1];
2234 if (!isUndefOrEqual(BitI, j))
2237 if (isUndefOrEqual(BitI1, NumElts))
2240 if (!isUndefOrEqual(BitI1, j + NumElts))
2248 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2249 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2250 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2253 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2254 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2255 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2256 bool V2IsSplat = false) {
2257 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2260 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2261 SDOperand BitI = Elts[i];
2262 SDOperand BitI1 = Elts[i+1];
2263 if (!isUndefOrEqual(BitI, j + NumElts/2))
2266 if (isUndefOrEqual(BitI1, NumElts))
2269 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2277 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2278 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2279 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2282 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2283 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2285 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2286 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2288 unsigned NumElems = N->getNumOperands();
2289 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2292 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2293 SDOperand BitI = N->getOperand(i);
2294 SDOperand BitI1 = N->getOperand(i+1);
2296 if (!isUndefOrEqual(BitI, j))
2298 if (!isUndefOrEqual(BitI1, j))
2305 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2306 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2308 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2309 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2311 unsigned NumElems = N->getNumOperands();
2312 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2315 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2316 SDOperand BitI = N->getOperand(i);
2317 SDOperand BitI1 = N->getOperand(i + 1);
2319 if (!isUndefOrEqual(BitI, j))
2321 if (!isUndefOrEqual(BitI1, j))
2328 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2329 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2330 /// MOVSD, and MOVD, i.e. setting the lowest element.
2331 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2332 if (NumElts != 2 && NumElts != 4)
2335 if (!isUndefOrEqual(Elts[0], NumElts))
2338 for (unsigned i = 1; i < NumElts; ++i) {
2339 if (!isUndefOrEqual(Elts[i], i))
2346 bool X86::isMOVLMask(SDNode *N) {
2347 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2348 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2351 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2352 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2353 /// element of vector 2 and the other elements to come from vector 1 in order.
2354 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2355 bool V2IsSplat = false,
2356 bool V2IsUndef = false) {
2357 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2360 if (!isUndefOrEqual(Ops[0], 0))
2363 for (unsigned i = 1; i < NumOps; ++i) {
2364 SDOperand Arg = Ops[i];
2365 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2366 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2367 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2374 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2375 bool V2IsUndef = false) {
2376 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2377 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2378 V2IsSplat, V2IsUndef);
2381 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2382 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2383 bool X86::isMOVSHDUPMask(SDNode *N) {
2384 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2386 if (N->getNumOperands() != 4)
2389 // Expect 1, 1, 3, 3
2390 for (unsigned i = 0; i < 2; ++i) {
2391 SDOperand Arg = N->getOperand(i);
2392 if (Arg.getOpcode() == ISD::UNDEF) continue;
2393 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2394 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2395 if (Val != 1) return false;
2399 for (unsigned i = 2; i < 4; ++i) {
2400 SDOperand Arg = N->getOperand(i);
2401 if (Arg.getOpcode() == ISD::UNDEF) continue;
2402 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2403 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2404 if (Val != 3) return false;
2408 // Don't use movshdup if it can be done with a shufps.
2412 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2413 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2414 bool X86::isMOVSLDUPMask(SDNode *N) {
2415 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2417 if (N->getNumOperands() != 4)
2420 // Expect 0, 0, 2, 2
2421 for (unsigned i = 0; i < 2; ++i) {
2422 SDOperand Arg = N->getOperand(i);
2423 if (Arg.getOpcode() == ISD::UNDEF) continue;
2424 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2425 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2426 if (Val != 0) return false;
2430 for (unsigned i = 2; i < 4; ++i) {
2431 SDOperand Arg = N->getOperand(i);
2432 if (Arg.getOpcode() == ISD::UNDEF) continue;
2433 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2434 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2435 if (Val != 2) return false;
2439 // Don't use movshdup if it can be done with a shufps.
2443 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2444 /// specifies a identity operation on the LHS or RHS.
2445 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2446 unsigned NumElems = N->getNumOperands();
2447 for (unsigned i = 0; i < NumElems; ++i)
2448 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2453 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2454 /// a splat of a single element.
2455 static bool isSplatMask(SDNode *N) {
2456 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2458 // This is a splat operation if each element of the permute is the same, and
2459 // if the value doesn't reference the second vector.
2460 unsigned NumElems = N->getNumOperands();
2461 SDOperand ElementBase;
2463 for (; i != NumElems; ++i) {
2464 SDOperand Elt = N->getOperand(i);
2465 if (isa<ConstantSDNode>(Elt)) {
2471 if (!ElementBase.Val)
2474 for (; i != NumElems; ++i) {
2475 SDOperand Arg = N->getOperand(i);
2476 if (Arg.getOpcode() == ISD::UNDEF) continue;
2477 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2478 if (Arg != ElementBase) return false;
2481 // Make sure it is a splat of the first vector operand.
2482 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2485 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2486 /// a splat of a single element and it's a 2 or 4 element mask.
2487 bool X86::isSplatMask(SDNode *N) {
2488 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2490 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2491 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2493 return ::isSplatMask(N);
2496 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2497 /// specifies a splat of zero element.
2498 bool X86::isSplatLoMask(SDNode *N) {
2499 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2501 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2502 if (!isUndefOrEqual(N->getOperand(i), 0))
2507 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2508 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2510 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2511 unsigned NumOperands = N->getNumOperands();
2512 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2514 for (unsigned i = 0; i < NumOperands; ++i) {
2516 SDOperand Arg = N->getOperand(NumOperands-i-1);
2517 if (Arg.getOpcode() != ISD::UNDEF)
2518 Val = cast<ConstantSDNode>(Arg)->getValue();
2519 if (Val >= NumOperands) Val -= NumOperands;
2521 if (i != NumOperands - 1)
2528 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2529 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2531 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2533 // 8 nodes, but we only care about the last 4.
2534 for (unsigned i = 7; i >= 4; --i) {
2536 SDOperand Arg = N->getOperand(i);
2537 if (Arg.getOpcode() != ISD::UNDEF)
2538 Val = cast<ConstantSDNode>(Arg)->getValue();
2547 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2548 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2550 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2552 // 8 nodes, but we only care about the first 4.
2553 for (int i = 3; i >= 0; --i) {
2555 SDOperand Arg = N->getOperand(i);
2556 if (Arg.getOpcode() != ISD::UNDEF)
2557 Val = cast<ConstantSDNode>(Arg)->getValue();
2566 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2567 /// specifies a 8 element shuffle that can be broken into a pair of
2568 /// PSHUFHW and PSHUFLW.
2569 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2570 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2572 if (N->getNumOperands() != 8)
2575 // Lower quadword shuffled.
2576 for (unsigned i = 0; i != 4; ++i) {
2577 SDOperand Arg = N->getOperand(i);
2578 if (Arg.getOpcode() == ISD::UNDEF) continue;
2579 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2580 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2585 // Upper quadword shuffled.
2586 for (unsigned i = 4; i != 8; ++i) {
2587 SDOperand Arg = N->getOperand(i);
2588 if (Arg.getOpcode() == ISD::UNDEF) continue;
2589 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2590 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2591 if (Val < 4 || Val > 7)
2598 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2599 /// values in ther permute mask.
2600 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2601 SDOperand &V2, SDOperand &Mask,
2602 SelectionDAG &DAG) {
2603 MVT::ValueType VT = Op.getValueType();
2604 MVT::ValueType MaskVT = Mask.getValueType();
2605 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2606 unsigned NumElems = Mask.getNumOperands();
2607 SmallVector<SDOperand, 8> MaskVec;
2609 for (unsigned i = 0; i != NumElems; ++i) {
2610 SDOperand Arg = Mask.getOperand(i);
2611 if (Arg.getOpcode() == ISD::UNDEF) {
2612 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2615 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2616 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2618 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2620 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2624 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2625 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2628 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2629 /// the two vector operands have swapped position.
2631 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2632 MVT::ValueType MaskVT = Mask.getValueType();
2633 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2634 unsigned NumElems = Mask.getNumOperands();
2635 SmallVector<SDOperand, 8> MaskVec;
2636 for (unsigned i = 0; i != NumElems; ++i) {
2637 SDOperand Arg = Mask.getOperand(i);
2638 if (Arg.getOpcode() == ISD::UNDEF) {
2639 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2642 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2643 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2645 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2647 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2649 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2653 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2654 /// match movhlps. The lower half elements should come from upper half of
2655 /// V1 (and in order), and the upper half elements should come from the upper
2656 /// half of V2 (and in order).
2657 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2658 unsigned NumElems = Mask->getNumOperands();
2661 for (unsigned i = 0, e = 2; i != e; ++i)
2662 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2664 for (unsigned i = 2; i != 4; ++i)
2665 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2670 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2671 /// is promoted to a vector.
2672 static inline bool isScalarLoadToVector(SDNode *N) {
2673 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2674 N = N->getOperand(0).Val;
2675 return ISD::isNON_EXTLoad(N);
2680 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2681 /// match movlp{s|d}. The lower half elements should come from lower half of
2682 /// V1 (and in order), and the upper half elements should come from the upper
2683 /// half of V2 (and in order). And since V1 will become the source of the
2684 /// MOVLP, it must be either a vector load or a scalar load to vector.
2685 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2686 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2688 // Is V2 is a vector load, don't do this transformation. We will try to use
2689 // load folding shufps op.
2690 if (ISD::isNON_EXTLoad(V2))
2693 unsigned NumElems = Mask->getNumOperands();
2694 if (NumElems != 2 && NumElems != 4)
2696 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2697 if (!isUndefOrEqual(Mask->getOperand(i), i))
2699 for (unsigned i = NumElems/2; i != NumElems; ++i)
2700 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2705 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2707 static bool isSplatVector(SDNode *N) {
2708 if (N->getOpcode() != ISD::BUILD_VECTOR)
2711 SDOperand SplatValue = N->getOperand(0);
2712 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2713 if (N->getOperand(i) != SplatValue)
2718 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2720 static bool isUndefShuffle(SDNode *N) {
2721 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2724 SDOperand V1 = N->getOperand(0);
2725 SDOperand V2 = N->getOperand(1);
2726 SDOperand Mask = N->getOperand(2);
2727 unsigned NumElems = Mask.getNumOperands();
2728 for (unsigned i = 0; i != NumElems; ++i) {
2729 SDOperand Arg = Mask.getOperand(i);
2730 if (Arg.getOpcode() != ISD::UNDEF) {
2731 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2732 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2734 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2741 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2743 static inline bool isZeroNode(SDOperand Elt) {
2744 return ((isa<ConstantSDNode>(Elt) &&
2745 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2746 (isa<ConstantFPSDNode>(Elt) &&
2747 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2750 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2751 /// to an zero vector.
2752 static bool isZeroShuffle(SDNode *N) {
2753 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2756 SDOperand V1 = N->getOperand(0);
2757 SDOperand V2 = N->getOperand(1);
2758 SDOperand Mask = N->getOperand(2);
2759 unsigned NumElems = Mask.getNumOperands();
2760 for (unsigned i = 0; i != NumElems; ++i) {
2761 SDOperand Arg = Mask.getOperand(i);
2762 if (Arg.getOpcode() == ISD::UNDEF)
2765 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2766 if (Idx < NumElems) {
2767 unsigned Opc = V1.Val->getOpcode();
2768 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2770 if (Opc != ISD::BUILD_VECTOR ||
2771 !isZeroNode(V1.Val->getOperand(Idx)))
2773 } else if (Idx >= NumElems) {
2774 unsigned Opc = V2.Val->getOpcode();
2775 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2777 if (Opc != ISD::BUILD_VECTOR ||
2778 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2785 /// getZeroVector - Returns a vector of specified type with all zero elements.
2787 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2788 assert(MVT::isVector(VT) && "Expected a vector type");
2790 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2791 // type. This ensures they get CSE'd.
2792 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2794 if (MVT::getSizeInBits(VT) == 64) // MMX
2795 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2797 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2798 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2801 /// getOnesVector - Returns a vector of specified type with all bits set.
2803 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2804 assert(MVT::isVector(VT) && "Expected a vector type");
2806 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2807 // type. This ensures they get CSE'd.
2808 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2810 if (MVT::getSizeInBits(VT) == 64) // MMX
2811 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2813 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2814 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2818 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2819 /// that point to V2 points to its first element.
2820 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2821 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2823 bool Changed = false;
2824 SmallVector<SDOperand, 8> MaskVec;
2825 unsigned NumElems = Mask.getNumOperands();
2826 for (unsigned i = 0; i != NumElems; ++i) {
2827 SDOperand Arg = Mask.getOperand(i);
2828 if (Arg.getOpcode() != ISD::UNDEF) {
2829 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2830 if (Val > NumElems) {
2831 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2835 MaskVec.push_back(Arg);
2839 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2840 &MaskVec[0], MaskVec.size());
2844 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2845 /// operation of specified width.
2846 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2847 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2848 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2850 SmallVector<SDOperand, 8> MaskVec;
2851 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2852 for (unsigned i = 1; i != NumElems; ++i)
2853 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2854 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2857 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2858 /// of specified width.
2859 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2860 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2861 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2862 SmallVector<SDOperand, 8> MaskVec;
2863 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2864 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2865 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2867 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2870 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2871 /// of specified width.
2872 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2873 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2874 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2875 unsigned Half = NumElems/2;
2876 SmallVector<SDOperand, 8> MaskVec;
2877 for (unsigned i = 0; i != Half; ++i) {
2878 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2879 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2881 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2884 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2885 /// element #0 of a vector with the specified index, leaving the rest of the
2886 /// elements in place.
2887 static SDOperand getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2888 SelectionDAG &DAG) {
2889 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2890 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2891 SmallVector<SDOperand, 8> MaskVec;
2892 // Element #0 of the result gets the elt we are replacing.
2893 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2894 for (unsigned i = 1; i != NumElems; ++i)
2895 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2896 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2899 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2901 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2902 SDOperand V1 = Op.getOperand(0);
2903 SDOperand Mask = Op.getOperand(2);
2904 MVT::ValueType VT = Op.getValueType();
2905 unsigned NumElems = Mask.getNumOperands();
2906 Mask = getUnpacklMask(NumElems, DAG);
2907 while (NumElems != 4) {
2908 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2911 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2913 Mask = getZeroVector(MVT::v4i32, DAG);
2914 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2915 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2916 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2919 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2920 /// vector of zero or undef vector. This produces a shuffle where the low
2921 /// element of V2 is swizzled into the zero/undef vector, landing at element
2922 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2923 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, unsigned Idx,
2924 bool isZero, SelectionDAG &DAG) {
2925 MVT::ValueType VT = V2.getValueType();
2926 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2927 unsigned NumElems = MVT::getVectorNumElements(V2.getValueType());
2928 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2929 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2930 SmallVector<SDOperand, 16> MaskVec;
2931 for (unsigned i = 0; i != NumElems; ++i)
2932 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2933 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2935 MaskVec.push_back(DAG.getConstant(i, EVT));
2936 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2937 &MaskVec[0], MaskVec.size());
2938 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2941 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2943 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2944 unsigned NumNonZero, unsigned NumZero,
2945 SelectionDAG &DAG, TargetLowering &TLI) {
2951 for (unsigned i = 0; i < 16; ++i) {
2952 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2953 if (ThisIsNonZero && First) {
2955 V = getZeroVector(MVT::v8i16, DAG);
2957 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2962 SDOperand ThisElt(0, 0), LastElt(0, 0);
2963 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2964 if (LastIsNonZero) {
2965 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2967 if (ThisIsNonZero) {
2968 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2969 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2970 ThisElt, DAG.getConstant(8, MVT::i8));
2972 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2977 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2978 DAG.getIntPtrConstant(i/2));
2982 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2985 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2987 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2988 unsigned NumNonZero, unsigned NumZero,
2989 SelectionDAG &DAG, TargetLowering &TLI) {
2995 for (unsigned i = 0; i < 8; ++i) {
2996 bool isNonZero = (NonZeros & (1 << i)) != 0;
3000 V = getZeroVector(MVT::v8i16, DAG);
3002 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3005 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3006 DAG.getIntPtrConstant(i));
3014 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3015 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3016 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3017 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3018 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3019 // eliminated on x86-32 hosts.
3020 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3023 if (ISD::isBuildVectorAllOnes(Op.Val))
3024 return getOnesVector(Op.getValueType(), DAG);
3025 return getZeroVector(Op.getValueType(), DAG);
3028 MVT::ValueType VT = Op.getValueType();
3029 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3030 unsigned EVTBits = MVT::getSizeInBits(EVT);
3032 unsigned NumElems = Op.getNumOperands();
3033 unsigned NumZero = 0;
3034 unsigned NumNonZero = 0;
3035 unsigned NonZeros = 0;
3036 bool IsAllConstants = true;
3037 SmallSet<SDOperand, 8> Values;
3038 for (unsigned i = 0; i < NumElems; ++i) {
3039 SDOperand Elt = Op.getOperand(i);
3040 if (Elt.getOpcode() == ISD::UNDEF)
3043 if (Elt.getOpcode() != ISD::Constant &&
3044 Elt.getOpcode() != ISD::ConstantFP)
3045 IsAllConstants = false;
3046 if (isZeroNode(Elt))
3049 NonZeros |= (1 << i);
3054 if (NumNonZero == 0) {
3055 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3056 return DAG.getNode(ISD::UNDEF, VT);
3059 // Special case for single non-zero, non-undef, element.
3060 if (NumNonZero == 1 && NumElems <= 4) {
3061 unsigned Idx = CountTrailingZeros_32(NonZeros);
3062 SDOperand Item = Op.getOperand(Idx);
3064 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3065 // the value are obviously zero, truncate the value to i32 and do the
3066 // insertion that way. Only do this if the value is non-constant or if the
3067 // value is a constant being inserted into element 0. It is cheaper to do
3068 // a constant pool load than it is to do a movd + shuffle.
3069 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3070 (!IsAllConstants || Idx == 0)) {
3071 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3072 // Handle MMX and SSE both.
3073 MVT::ValueType VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3074 MVT::ValueType VecElts = VT == MVT::v2i64 ? 4 : 2;
3076 // Truncate the value (which may itself be a constant) to i32, and
3077 // convert it to a vector with movd (S2V+shuffle to zero extend).
3078 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3079 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3080 Item = getShuffleVectorZeroOrUndef(Item, 0, true, DAG);
3082 // Now we have our 32-bit value zero extended in the low element of
3083 // a vector. If Idx != 0, swizzle it into place.
3086 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3087 getSwapEltZeroMask(VecElts, Idx, DAG)
3089 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3091 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3095 // If we have a constant or non-constant insertion into the low element of
3096 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3097 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3098 // depending on what the source datatype is. Because we can only get here
3099 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3101 // Don't do this for i64 values on x86-32.
3102 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3103 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3104 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3105 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3108 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3111 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3112 // is a non-constant being inserted into an element other than the low one,
3113 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3114 // movd/movss) to move this into the low element, then shuffle it into
3116 if (EVTBits == 32) {
3117 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3119 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3120 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3121 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3122 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3123 SmallVector<SDOperand, 8> MaskVec;
3124 for (unsigned i = 0; i < NumElems; i++)
3125 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3126 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3127 &MaskVec[0], MaskVec.size());
3128 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3129 DAG.getNode(ISD::UNDEF, VT), Mask);
3133 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3134 if (Values.size() == 1)
3137 // A vector full of immediates; various special cases are already
3138 // handled, so this is best done with a single constant-pool load.
3142 // Let legalizer expand 2-wide build_vectors.
3146 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3147 if (EVTBits == 8 && NumElems == 16) {
3148 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3150 if (V.Val) return V;
3153 if (EVTBits == 16 && NumElems == 8) {
3154 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3156 if (V.Val) return V;
3159 // If element VT is == 32 bits, turn it into a number of shuffles.
3160 SmallVector<SDOperand, 8> V;
3162 if (NumElems == 4 && NumZero > 0) {
3163 for (unsigned i = 0; i < 4; ++i) {
3164 bool isZero = !(NonZeros & (1 << i));
3166 V[i] = getZeroVector(VT, DAG);
3168 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3171 for (unsigned i = 0; i < 2; ++i) {
3172 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3175 V[i] = V[i*2]; // Must be a zero vector.
3178 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3179 getMOVLMask(NumElems, DAG));
3182 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3183 getMOVLMask(NumElems, DAG));
3186 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3187 getUnpacklMask(NumElems, DAG));
3192 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3193 // clears the upper bits.
3194 // FIXME: we can do the same for v4f32 case when we know both parts of
3195 // the lower half come from scalar_to_vector (loadf32). We should do
3196 // that in post legalizer dag combiner with target specific hooks.
3197 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3199 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3200 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3201 SmallVector<SDOperand, 8> MaskVec;
3202 bool Reverse = (NonZeros & 0x3) == 2;
3203 for (unsigned i = 0; i < 2; ++i)
3205 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3207 MaskVec.push_back(DAG.getConstant(i, EVT));
3208 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3209 for (unsigned i = 0; i < 2; ++i)
3211 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3213 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3214 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3215 &MaskVec[0], MaskVec.size());
3216 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3219 if (Values.size() > 2) {
3220 // Expand into a number of unpckl*.
3222 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3223 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3224 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3225 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3226 for (unsigned i = 0; i < NumElems; ++i)
3227 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3229 while (NumElems != 0) {
3230 for (unsigned i = 0; i < NumElems; ++i)
3231 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3242 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3243 SDOperand PermMask, SelectionDAG &DAG,
3244 TargetLowering &TLI) {
3246 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3247 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3248 MVT::ValueType PtrVT = TLI.getPointerTy();
3249 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3250 PermMask.Val->op_end());
3252 // First record which half of which vector the low elements come from.
3253 SmallVector<unsigned, 4> LowQuad(4);
3254 for (unsigned i = 0; i < 4; ++i) {
3255 SDOperand Elt = MaskElts[i];
3256 if (Elt.getOpcode() == ISD::UNDEF)
3258 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3259 int QuadIdx = EltIdx / 4;
3262 int BestLowQuad = -1;
3263 unsigned MaxQuad = 1;
3264 for (unsigned i = 0; i < 4; ++i) {
3265 if (LowQuad[i] > MaxQuad) {
3267 MaxQuad = LowQuad[i];
3271 // Record which half of which vector the high elements come from.
3272 SmallVector<unsigned, 4> HighQuad(4);
3273 for (unsigned i = 4; i < 8; ++i) {
3274 SDOperand Elt = MaskElts[i];
3275 if (Elt.getOpcode() == ISD::UNDEF)
3277 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3278 int QuadIdx = EltIdx / 4;
3279 ++HighQuad[QuadIdx];
3281 int BestHighQuad = -1;
3283 for (unsigned i = 0; i < 4; ++i) {
3284 if (HighQuad[i] > MaxQuad) {
3286 MaxQuad = HighQuad[i];
3290 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3291 if (BestLowQuad != -1 || BestHighQuad != -1) {
3292 // First sort the 4 chunks in order using shufpd.
3293 SmallVector<SDOperand, 8> MaskVec;
3294 if (BestLowQuad != -1)
3295 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3297 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3298 if (BestHighQuad != -1)
3299 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3301 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3302 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3303 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3304 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3305 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3306 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3308 // Now sort high and low parts separately.
3309 BitVector InOrder(8);
3310 if (BestLowQuad != -1) {
3311 // Sort lower half in order using PSHUFLW.
3313 bool AnyOutOrder = false;
3314 for (unsigned i = 0; i != 4; ++i) {
3315 SDOperand Elt = MaskElts[i];
3316 if (Elt.getOpcode() == ISD::UNDEF) {
3317 MaskVec.push_back(Elt);
3320 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3323 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3324 // If this element is in the right place after this shuffle, then
3326 if ((int)(EltIdx / 4) == BestLowQuad)
3331 for (unsigned i = 4; i != 8; ++i)
3332 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3333 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3334 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3338 if (BestHighQuad != -1) {
3339 // Sort high half in order using PSHUFHW if possible.
3341 for (unsigned i = 0; i != 4; ++i)
3342 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3343 bool AnyOutOrder = false;
3344 for (unsigned i = 4; i != 8; ++i) {
3345 SDOperand Elt = MaskElts[i];
3346 if (Elt.getOpcode() == ISD::UNDEF) {
3347 MaskVec.push_back(Elt);
3350 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3353 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3354 // If this element is in the right place after this shuffle, then
3356 if ((int)(EltIdx / 4) == BestHighQuad)
3361 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3362 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3366 // The other elements are put in the right place using pextrw and pinsrw.
3367 for (unsigned i = 0; i != 8; ++i) {
3370 SDOperand Elt = MaskElts[i];
3371 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3374 SDOperand ExtOp = (EltIdx < 8)
3375 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3376 DAG.getConstant(EltIdx, PtrVT))
3377 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3378 DAG.getConstant(EltIdx - 8, PtrVT));
3379 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3380 DAG.getConstant(i, PtrVT));
3385 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3386 ///as few as possible.
3387 // First, let's find out how many elements are already in the right order.
3388 unsigned V1InOrder = 0;
3389 unsigned V1FromV1 = 0;
3390 unsigned V2InOrder = 0;
3391 unsigned V2FromV2 = 0;
3392 SmallVector<SDOperand, 8> V1Elts;
3393 SmallVector<SDOperand, 8> V2Elts;
3394 for (unsigned i = 0; i < 8; ++i) {
3395 SDOperand Elt = MaskElts[i];
3396 if (Elt.getOpcode() == ISD::UNDEF) {
3397 V1Elts.push_back(Elt);
3398 V2Elts.push_back(Elt);
3403 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3405 V1Elts.push_back(Elt);
3406 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3408 } else if (EltIdx == i+8) {
3409 V1Elts.push_back(Elt);
3410 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3412 } else if (EltIdx < 8) {
3413 V1Elts.push_back(Elt);
3416 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3421 if (V2InOrder > V1InOrder) {
3422 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3424 std::swap(V1Elts, V2Elts);
3425 std::swap(V1FromV1, V2FromV2);
3428 if ((V1FromV1 + V1InOrder) != 8) {
3429 // Some elements are from V2.
3431 // If there are elements that are from V1 but out of place,
3432 // then first sort them in place
3433 SmallVector<SDOperand, 8> MaskVec;
3434 for (unsigned i = 0; i < 8; ++i) {
3435 SDOperand Elt = V1Elts[i];
3436 if (Elt.getOpcode() == ISD::UNDEF) {
3437 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3440 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3442 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3444 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3446 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3447 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3451 for (unsigned i = 0; i < 8; ++i) {
3452 SDOperand Elt = V1Elts[i];
3453 if (Elt.getOpcode() == ISD::UNDEF)
3455 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3458 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3459 DAG.getConstant(EltIdx - 8, PtrVT));
3460 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3461 DAG.getConstant(i, PtrVT));
3465 // All elements are from V1.
3467 for (unsigned i = 0; i < 8; ++i) {
3468 SDOperand Elt = V1Elts[i];
3469 if (Elt.getOpcode() == ISD::UNDEF)
3471 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3472 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3473 DAG.getConstant(EltIdx, PtrVT));
3474 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3475 DAG.getConstant(i, PtrVT));
3481 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3482 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3483 /// done when every pair / quad of shuffle mask elements point to elements in
3484 /// the right sequence. e.g.
3485 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3487 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3489 SDOperand PermMask, SelectionDAG &DAG,
3490 TargetLowering &TLI) {
3491 unsigned NumElems = PermMask.getNumOperands();
3492 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3493 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3494 MVT::ValueType NewVT = MaskVT;
3496 case MVT::v4f32: NewVT = MVT::v2f64; break;
3497 case MVT::v4i32: NewVT = MVT::v2i64; break;
3498 case MVT::v8i16: NewVT = MVT::v4i32; break;
3499 case MVT::v16i8: NewVT = MVT::v4i32; break;
3500 default: assert(false && "Unexpected!");
3503 if (NewWidth == 2) {
3504 if (MVT::isInteger(VT))
3509 unsigned Scale = NumElems / NewWidth;
3510 SmallVector<SDOperand, 8> MaskVec;
3511 for (unsigned i = 0; i < NumElems; i += Scale) {
3512 unsigned StartIdx = ~0U;
3513 for (unsigned j = 0; j < Scale; ++j) {
3514 SDOperand Elt = PermMask.getOperand(i+j);
3515 if (Elt.getOpcode() == ISD::UNDEF)
3517 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3518 if (StartIdx == ~0U)
3519 StartIdx = EltIdx - (EltIdx % Scale);
3520 if (EltIdx != StartIdx + j)
3523 if (StartIdx == ~0U)
3524 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3526 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3529 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3530 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3531 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3532 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3533 &MaskVec[0], MaskVec.size()));
3537 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3538 SDOperand V1 = Op.getOperand(0);
3539 SDOperand V2 = Op.getOperand(1);
3540 SDOperand PermMask = Op.getOperand(2);
3541 MVT::ValueType VT = Op.getValueType();
3542 unsigned NumElems = PermMask.getNumOperands();
3543 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3544 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3545 bool V1IsSplat = false;
3546 bool V2IsSplat = false;
3548 if (isUndefShuffle(Op.Val))
3549 return DAG.getNode(ISD::UNDEF, VT);
3551 if (isZeroShuffle(Op.Val))
3552 return getZeroVector(VT, DAG);
3554 if (isIdentityMask(PermMask.Val))
3556 else if (isIdentityMask(PermMask.Val, true))
3559 if (isSplatMask(PermMask.Val)) {
3560 if (NumElems <= 4) return Op;
3561 // Promote it to a v4i32 splat.
3562 return PromoteSplat(Op, DAG);
3565 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3567 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3568 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3570 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3571 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3572 // FIXME: Figure out a cleaner way to do this.
3573 // Try to make use of movq to zero out the top part.
3574 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3575 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3577 SDOperand NewV1 = NewOp.getOperand(0);
3578 SDOperand NewV2 = NewOp.getOperand(1);
3579 SDOperand NewMask = NewOp.getOperand(2);
3580 if (isCommutedMOVL(NewMask.Val, true, false)) {
3581 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3582 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3583 NewV1, NewV2, getMOVLMask(2, DAG));
3584 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3587 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3588 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3589 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3590 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3594 if (X86::isMOVLMask(PermMask.Val))
3595 return (V1IsUndef) ? V2 : Op;
3597 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3598 X86::isMOVSLDUPMask(PermMask.Val) ||
3599 X86::isMOVHLPSMask(PermMask.Val) ||
3600 X86::isMOVHPMask(PermMask.Val) ||
3601 X86::isMOVLPMask(PermMask.Val))
3604 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3605 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3606 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3608 bool Commuted = false;
3609 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3610 // 1,1,1,1 -> v8i16 though.
3611 V1IsSplat = isSplatVector(V1.Val);
3612 V2IsSplat = isSplatVector(V2.Val);
3614 // Canonicalize the splat or undef, if present, to be on the RHS.
3615 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3616 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3617 std::swap(V1IsSplat, V2IsSplat);
3618 std::swap(V1IsUndef, V2IsUndef);
3622 // FIXME: Figure out a cleaner way to do this.
3623 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3624 if (V2IsUndef) return V1;
3625 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3627 // V2 is a splat, so the mask may be malformed. That is, it may point
3628 // to any V2 element. The instruction selectior won't like this. Get
3629 // a corrected mask and commute to form a proper MOVS{S|D}.
3630 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3631 if (NewMask.Val != PermMask.Val)
3632 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3637 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3638 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3639 X86::isUNPCKLMask(PermMask.Val) ||
3640 X86::isUNPCKHMask(PermMask.Val))
3644 // Normalize mask so all entries that point to V2 points to its first
3645 // element then try to match unpck{h|l} again. If match, return a
3646 // new vector_shuffle with the corrected mask.
3647 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3648 if (NewMask.Val != PermMask.Val) {
3649 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3650 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3651 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3652 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3653 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3654 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3659 // Normalize the node to match x86 shuffle ops if needed
3660 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3661 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3664 // Commute is back and try unpck* again.
3665 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3666 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3667 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3668 X86::isUNPCKLMask(PermMask.Val) ||
3669 X86::isUNPCKHMask(PermMask.Val))
3673 // If VT is integer, try PSHUF* first, then SHUFP*.
3674 if (MVT::isInteger(VT)) {
3675 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3676 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3677 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3678 X86::isPSHUFDMask(PermMask.Val)) ||
3679 X86::isPSHUFHWMask(PermMask.Val) ||
3680 X86::isPSHUFLWMask(PermMask.Val)) {
3681 if (V2.getOpcode() != ISD::UNDEF)
3682 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3683 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3687 if (X86::isSHUFPMask(PermMask.Val) &&
3688 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3691 // Floating point cases in the other order.
3692 if (X86::isSHUFPMask(PermMask.Val))
3694 if (X86::isPSHUFDMask(PermMask.Val) ||
3695 X86::isPSHUFHWMask(PermMask.Val) ||
3696 X86::isPSHUFLWMask(PermMask.Val)) {
3697 if (V2.getOpcode() != ISD::UNDEF)
3698 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3699 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3704 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3705 if (VT == MVT::v8i16) {
3706 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3711 // Handle all 4 wide cases with a number of shuffles.
3712 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3713 // Don't do this for MMX.
3714 MVT::ValueType MaskVT = PermMask.getValueType();
3715 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3716 SmallVector<std::pair<int, int>, 8> Locs;
3717 Locs.reserve(NumElems);
3718 SmallVector<SDOperand, 8> Mask1(NumElems,
3719 DAG.getNode(ISD::UNDEF, MaskEVT));
3720 SmallVector<SDOperand, 8> Mask2(NumElems,
3721 DAG.getNode(ISD::UNDEF, MaskEVT));
3724 // If no more than two elements come from either vector. This can be
3725 // implemented with two shuffles. First shuffle gather the elements.
3726 // The second shuffle, which takes the first shuffle as both of its
3727 // vector operands, put the elements into the right order.
3728 for (unsigned i = 0; i != NumElems; ++i) {
3729 SDOperand Elt = PermMask.getOperand(i);
3730 if (Elt.getOpcode() == ISD::UNDEF) {
3731 Locs[i] = std::make_pair(-1, -1);
3733 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3734 if (Val < NumElems) {
3735 Locs[i] = std::make_pair(0, NumLo);
3739 Locs[i] = std::make_pair(1, NumHi);
3740 if (2+NumHi < NumElems)
3741 Mask1[2+NumHi] = Elt;
3746 if (NumLo <= 2 && NumHi <= 2) {
3747 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3748 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3749 &Mask1[0], Mask1.size()));
3750 for (unsigned i = 0; i != NumElems; ++i) {
3751 if (Locs[i].first == -1)
3754 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3755 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3756 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3760 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3761 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3762 &Mask2[0], Mask2.size()));
3765 // Break it into (shuffle shuffle_hi, shuffle_lo).
3767 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3768 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3769 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3770 unsigned MaskIdx = 0;
3772 unsigned HiIdx = NumElems/2;
3773 for (unsigned i = 0; i != NumElems; ++i) {
3774 if (i == NumElems/2) {
3780 SDOperand Elt = PermMask.getOperand(i);
3781 if (Elt.getOpcode() == ISD::UNDEF) {
3782 Locs[i] = std::make_pair(-1, -1);
3783 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3784 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3785 (*MaskPtr)[LoIdx] = Elt;
3788 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3789 (*MaskPtr)[HiIdx] = Elt;
3794 SDOperand LoShuffle =
3795 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3796 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3797 &LoMask[0], LoMask.size()));
3798 SDOperand HiShuffle =
3799 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3800 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3801 &HiMask[0], HiMask.size()));
3802 SmallVector<SDOperand, 8> MaskOps;
3803 for (unsigned i = 0; i != NumElems; ++i) {
3804 if (Locs[i].first == -1) {
3805 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3807 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3808 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3811 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3812 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3813 &MaskOps[0], MaskOps.size()));
3820 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3821 SelectionDAG &DAG) {
3822 MVT::ValueType VT = Op.getValueType();
3823 if (MVT::getSizeInBits(VT) == 8) {
3824 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3825 Op.getOperand(0), Op.getOperand(1));
3826 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3827 DAG.getValueType(VT));
3828 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3829 } else if (MVT::getSizeInBits(VT) == 16) {
3830 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3831 Op.getOperand(0), Op.getOperand(1));
3832 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3833 DAG.getValueType(VT));
3834 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3841 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3842 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3845 if (Subtarget->hasSSE41())
3846 return LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3848 MVT::ValueType VT = Op.getValueType();
3849 // TODO: handle v16i8.
3850 if (MVT::getSizeInBits(VT) == 16) {
3851 SDOperand Vec = Op.getOperand(0);
3852 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3854 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3855 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3856 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3858 // Transform it so it match pextrw which produces a 32-bit result.
3859 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3860 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3861 Op.getOperand(0), Op.getOperand(1));
3862 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3863 DAG.getValueType(VT));
3864 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3865 } else if (MVT::getSizeInBits(VT) == 32) {
3866 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3869 // SHUFPS the element to the lowest double word, then movss.
3870 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3871 SmallVector<SDOperand, 8> IdxVec;
3873 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3875 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3877 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3879 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3880 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3881 &IdxVec[0], IdxVec.size());
3882 SDOperand Vec = Op.getOperand(0);
3883 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3884 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3885 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3886 DAG.getIntPtrConstant(0));
3887 } else if (MVT::getSizeInBits(VT) == 64) {
3888 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3889 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3890 // to match extract_elt for f64.
3891 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3895 // UNPCKHPD the element to the lowest double word, then movsd.
3896 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3897 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3898 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3899 SmallVector<SDOperand, 8> IdxVec;
3900 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3902 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3903 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3904 &IdxVec[0], IdxVec.size());
3905 SDOperand Vec = Op.getOperand(0);
3906 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3907 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3908 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3909 DAG.getIntPtrConstant(0));
3916 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3917 MVT::ValueType VT = Op.getValueType();
3918 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3920 SDOperand N0 = Op.getOperand(0);
3921 SDOperand N1 = Op.getOperand(1);
3922 SDOperand N2 = Op.getOperand(2);
3924 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3925 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3927 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3929 if (N1.getValueType() != MVT::i32)
3930 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3931 if (N2.getValueType() != MVT::i32)
3932 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3933 return DAG.getNode(Opc, VT, N0, N1, N2);
3934 } else if (EVT == MVT::f32) {
3935 // Bits [7:6] of the constant are the source select. This will always be
3936 // zero here. The DAG Combiner may combine an extract_elt index into these
3937 // bits. For example (insert (extract, 3), 2) could be matched by putting
3938 // the '3' into bits [7:6] of X86ISD::INSERTPS.
3939 // Bits [5:4] of the constant are the destination select. This is the
3940 // value of the incoming immediate.
3941 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
3942 // combine either bitwise AND or insert of float 0.0 to set these bits.
3943 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3944 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3950 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3951 MVT::ValueType VT = Op.getValueType();
3952 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3954 if (Subtarget->hasSSE41())
3955 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3960 SDOperand N0 = Op.getOperand(0);
3961 SDOperand N1 = Op.getOperand(1);
3962 SDOperand N2 = Op.getOperand(2);
3964 if (MVT::getSizeInBits(EVT) == 16) {
3965 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3966 // as its second argument.
3967 if (N1.getValueType() != MVT::i32)
3968 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3969 if (N2.getValueType() != MVT::i32)
3970 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3971 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3977 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3978 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3979 MVT::ValueType VT = MVT::v2i32;
3980 switch (Op.getValueType()) {
3987 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
3988 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
3991 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3992 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3993 // one of the above mentioned nodes. It has to be wrapped because otherwise
3994 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3995 // be used to form addressing mode. These wrapped nodes will be selected
3998 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3999 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4000 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
4002 CP->getAlignment());
4003 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4004 // With PIC, the address is actually $g + Offset.
4005 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4006 !Subtarget->isPICStyleRIPRel()) {
4007 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4008 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4016 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4017 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4018 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4019 // If it's a debug information descriptor, don't mess with it.
4020 if (DAG.isVerifiedDebugInfoDesc(Op))
4022 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4023 // With PIC, the address is actually $g + Offset.
4024 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4025 !Subtarget->isPICStyleRIPRel()) {
4026 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4027 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4031 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4032 // load the value at address GV, not the value of GV itself. This means that
4033 // the GlobalAddress must be in the base or index register of the address, not
4034 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4035 // The same applies for external symbols during PIC codegen
4036 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4037 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4038 PseudoSourceValue::getGOT(), 0);
4043 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
4045 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4046 const MVT::ValueType PtrVT) {
4048 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4049 DAG.getNode(X86ISD::GlobalBaseReg,
4051 InFlag = Chain.getValue(1);
4053 // emit leal symbol@TLSGD(,%ebx,1), %eax
4054 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4055 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4056 GA->getValueType(0),
4058 SDOperand Ops[] = { Chain, TGA, InFlag };
4059 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4060 InFlag = Result.getValue(2);
4061 Chain = Result.getValue(1);
4063 // call ___tls_get_addr. This function receives its argument in
4064 // the register EAX.
4065 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4066 InFlag = Chain.getValue(1);
4068 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4069 SDOperand Ops1[] = { Chain,
4070 DAG.getTargetExternalSymbol("___tls_get_addr",
4072 DAG.getRegister(X86::EAX, PtrVT),
4073 DAG.getRegister(X86::EBX, PtrVT),
4075 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4076 InFlag = Chain.getValue(1);
4078 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4081 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4082 // "local exec" model.
4084 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4085 const MVT::ValueType PtrVT) {
4086 // Get the Thread Pointer
4087 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4088 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4090 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4091 GA->getValueType(0),
4093 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4095 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4096 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4097 PseudoSourceValue::getGOT(), 0);
4099 // The address of the thread local variable is the add of the thread
4100 // pointer with the offset of the variable.
4101 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4105 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4106 // TODO: implement the "local dynamic" model
4107 // TODO: implement the "initial exec"model for pic executables
4108 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4109 "TLS not implemented for non-ELF and 64-bit targets");
4110 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4111 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4112 // otherwise use the "Local Exec"TLS Model
4113 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4114 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4116 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4120 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4121 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4122 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4123 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4124 // With PIC, the address is actually $g + Offset.
4125 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4126 !Subtarget->isPICStyleRIPRel()) {
4127 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4128 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4135 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4136 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4137 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4138 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4139 // With PIC, the address is actually $g + Offset.
4140 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4141 !Subtarget->isPICStyleRIPRel()) {
4142 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4143 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4150 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4151 /// take a 2 x i32 value to shift plus a shift amount.
4152 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4153 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4154 MVT::ValueType VT = Op.getValueType();
4155 unsigned VTBits = MVT::getSizeInBits(VT);
4156 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4157 SDOperand ShOpLo = Op.getOperand(0);
4158 SDOperand ShOpHi = Op.getOperand(1);
4159 SDOperand ShAmt = Op.getOperand(2);
4160 SDOperand Tmp1 = isSRA ?
4161 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4162 DAG.getConstant(0, VT);
4164 SDOperand Tmp2, Tmp3;
4165 if (Op.getOpcode() == ISD::SHL_PARTS) {
4166 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4167 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4169 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4170 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4173 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4174 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4175 DAG.getConstant(VTBits, MVT::i8));
4176 SDOperand Cond = DAG.getNode(X86ISD::CMP, VT,
4177 AndNode, DAG.getConstant(0, MVT::i8));
4180 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4181 VTs = DAG.getNodeValueTypes(VT, MVT::Flag);
4182 SmallVector<SDOperand, 4> Ops;
4183 if (Op.getOpcode() == ISD::SHL_PARTS) {
4184 Ops.push_back(Tmp2);
4185 Ops.push_back(Tmp3);
4187 Ops.push_back(Cond);
4188 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4191 Ops.push_back(Tmp3);
4192 Ops.push_back(Tmp1);
4194 Ops.push_back(Cond);
4195 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4197 Ops.push_back(Tmp2);
4198 Ops.push_back(Tmp3);
4200 Ops.push_back(Cond);
4201 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4204 Ops.push_back(Tmp3);
4205 Ops.push_back(Tmp1);
4207 Ops.push_back(Cond);
4208 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4211 VTs = DAG.getNodeValueTypes(VT, VT);
4215 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4218 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4219 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4220 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
4221 "Unknown SINT_TO_FP to lower!");
4223 // These are really Legal; caller falls through into that case.
4224 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4226 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4227 Subtarget->is64Bit())
4230 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4231 MachineFunction &MF = DAG.getMachineFunction();
4232 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4233 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4234 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4236 PseudoSourceValue::getFixedStack(),
4241 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4243 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4245 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4246 SmallVector<SDOperand, 8> Ops;
4247 Ops.push_back(Chain);
4248 Ops.push_back(StackSlot);
4249 Ops.push_back(DAG.getValueType(SrcVT));
4250 SDOperand Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4251 Tys, &Ops[0], Ops.size());
4254 Chain = Result.getValue(1);
4255 SDOperand InFlag = Result.getValue(2);
4257 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4258 // shouldn't be necessary except that RFP cannot be live across
4259 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4260 MachineFunction &MF = DAG.getMachineFunction();
4261 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4262 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4263 Tys = DAG.getVTList(MVT::Other);
4264 SmallVector<SDOperand, 8> Ops;
4265 Ops.push_back(Chain);
4266 Ops.push_back(Result);
4267 Ops.push_back(StackSlot);
4268 Ops.push_back(DAG.getValueType(Op.getValueType()));
4269 Ops.push_back(InFlag);
4270 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4271 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4272 PseudoSourceValue::getFixedStack(), SSFI);
4278 std::pair<SDOperand,SDOperand> X86TargetLowering::
4279 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4280 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4281 "Unknown FP_TO_SINT to lower!");
4283 // These are really Legal.
4284 if (Op.getValueType() == MVT::i32 &&
4285 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4286 return std::make_pair(SDOperand(), SDOperand());
4287 if (Subtarget->is64Bit() &&
4288 Op.getValueType() == MVT::i64 &&
4289 Op.getOperand(0).getValueType() != MVT::f80)
4290 return std::make_pair(SDOperand(), SDOperand());
4292 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4294 MachineFunction &MF = DAG.getMachineFunction();
4295 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4296 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4297 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4299 switch (Op.getValueType()) {
4300 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4301 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4302 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4303 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4306 SDOperand Chain = DAG.getEntryNode();
4307 SDOperand Value = Op.getOperand(0);
4308 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4309 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4310 Chain = DAG.getStore(Chain, Value, StackSlot,
4311 PseudoSourceValue::getFixedStack(), SSFI);
4312 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4314 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4316 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4317 Chain = Value.getValue(1);
4318 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4319 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4322 // Build the FP_TO_INT*_IN_MEM
4323 SDOperand Ops[] = { Chain, Value, StackSlot };
4324 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4326 return std::make_pair(FIST, StackSlot);
4329 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4330 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4331 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4332 if (FIST.Val == 0) return SDOperand();
4335 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4338 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4339 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4340 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4341 if (FIST.Val == 0) return 0;
4343 // Return an i64 load from the stack slot.
4344 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4346 // Use a MERGE_VALUES node to drop the chain result value.
4347 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4350 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4351 MVT::ValueType VT = Op.getValueType();
4352 MVT::ValueType EltVT = VT;
4353 if (MVT::isVector(VT))
4354 EltVT = MVT::getVectorElementType(VT);
4355 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4356 std::vector<Constant*> CV;
4357 if (EltVT == MVT::f64) {
4358 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4362 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4368 Constant *C = ConstantVector::get(CV);
4369 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4370 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4371 PseudoSourceValue::getConstantPool(), 0,
4373 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4376 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4377 MVT::ValueType VT = Op.getValueType();
4378 MVT::ValueType EltVT = VT;
4379 unsigned EltNum = 1;
4380 if (MVT::isVector(VT)) {
4381 EltVT = MVT::getVectorElementType(VT);
4382 EltNum = MVT::getVectorNumElements(VT);
4384 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4385 std::vector<Constant*> CV;
4386 if (EltVT == MVT::f64) {
4387 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4391 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4397 Constant *C = ConstantVector::get(CV);
4398 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4399 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4400 PseudoSourceValue::getConstantPool(), 0,
4402 if (MVT::isVector(VT)) {
4403 return DAG.getNode(ISD::BIT_CONVERT, VT,
4404 DAG.getNode(ISD::XOR, MVT::v2i64,
4405 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4406 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4408 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4412 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4413 SDOperand Op0 = Op.getOperand(0);
4414 SDOperand Op1 = Op.getOperand(1);
4415 MVT::ValueType VT = Op.getValueType();
4416 MVT::ValueType SrcVT = Op1.getValueType();
4417 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4419 // If second operand is smaller, extend it first.
4420 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4421 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4423 SrcTy = MVT::getTypeForValueType(SrcVT);
4425 // And if it is bigger, shrink it first.
4426 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4427 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4429 SrcTy = MVT::getTypeForValueType(SrcVT);
4432 // At this point the operands and the result should have the same
4433 // type, and that won't be f80 since that is not custom lowered.
4435 // First get the sign bit of second operand.
4436 std::vector<Constant*> CV;
4437 if (SrcVT == MVT::f64) {
4438 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4439 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4441 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4442 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4443 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4444 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4446 Constant *C = ConstantVector::get(CV);
4447 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4448 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4449 PseudoSourceValue::getConstantPool(), 0,
4451 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4453 // Shift sign bit right or left if the two operands have different types.
4454 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4455 // Op0 is MVT::f32, Op1 is MVT::f64.
4456 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4457 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4458 DAG.getConstant(32, MVT::i32));
4459 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4460 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4461 DAG.getIntPtrConstant(0));
4464 // Clear first operand sign bit.
4466 if (VT == MVT::f64) {
4467 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4468 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4470 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4471 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4472 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4473 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4475 C = ConstantVector::get(CV);
4476 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4477 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4478 PseudoSourceValue::getConstantPool(), 0,
4480 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4482 // Or the value with the sign bit.
4483 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4486 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4487 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4489 SDOperand Op0 = Op.getOperand(0);
4490 SDOperand Op1 = Op.getOperand(1);
4491 SDOperand CC = Op.getOperand(2);
4492 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4493 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4496 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4498 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4499 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4500 DAG.getConstant(X86CC, MVT::i8), Cond);
4503 assert(isFP && "Illegal integer SetCC!");
4505 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4506 switch (SetCCOpcode) {
4507 default: assert(false && "Illegal floating point SetCC!");
4508 case ISD::SETOEQ: { // !PF & ZF
4509 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4510 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4511 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4512 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4513 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4515 case ISD::SETUNE: { // PF | !ZF
4516 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4517 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4518 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4519 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4520 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4526 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4527 bool addTest = true;
4528 SDOperand Cond = Op.getOperand(0);
4531 if (Cond.getOpcode() == ISD::SETCC)
4532 Cond = LowerSETCC(Cond, DAG);
4534 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4535 // setting operand in place of the X86ISD::SETCC.
4536 if (Cond.getOpcode() == X86ISD::SETCC) {
4537 CC = Cond.getOperand(0);
4539 SDOperand Cmp = Cond.getOperand(1);
4540 unsigned Opc = Cmp.getOpcode();
4541 MVT::ValueType VT = Op.getValueType();
4543 bool IllegalFPCMov = false;
4544 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4545 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4546 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4548 if ((Opc == X86ISD::CMP ||
4549 Opc == X86ISD::COMI ||
4550 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4557 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4558 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4561 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4563 SmallVector<SDOperand, 4> Ops;
4564 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4565 // condition is true.
4566 Ops.push_back(Op.getOperand(2));
4567 Ops.push_back(Op.getOperand(1));
4569 Ops.push_back(Cond);
4570 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4573 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4574 bool addTest = true;
4575 SDOperand Chain = Op.getOperand(0);
4576 SDOperand Cond = Op.getOperand(1);
4577 SDOperand Dest = Op.getOperand(2);
4580 if (Cond.getOpcode() == ISD::SETCC)
4581 Cond = LowerSETCC(Cond, DAG);
4583 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4584 // setting operand in place of the X86ISD::SETCC.
4585 if (Cond.getOpcode() == X86ISD::SETCC) {
4586 CC = Cond.getOperand(0);
4588 SDOperand Cmp = Cond.getOperand(1);
4589 unsigned Opc = Cmp.getOpcode();
4590 if (Opc == X86ISD::CMP ||
4591 Opc == X86ISD::COMI ||
4592 Opc == X86ISD::UCOMI) {
4599 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4600 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4602 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4603 Chain, Op.getOperand(2), CC, Cond);
4607 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4608 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4609 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4610 // that the guard pages used by the OS virtual memory manager are allocated in
4611 // correct sequence.
4613 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4614 SelectionDAG &DAG) {
4615 assert(Subtarget->isTargetCygMing() &&
4616 "This should be used only on Cygwin/Mingw targets");
4619 SDOperand Chain = Op.getOperand(0);
4620 SDOperand Size = Op.getOperand(1);
4621 // FIXME: Ensure alignment here
4625 MVT::ValueType IntPtr = getPointerTy();
4626 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4628 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4629 Flag = Chain.getValue(1);
4631 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4632 SDOperand Ops[] = { Chain,
4633 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4634 DAG.getRegister(X86::EAX, IntPtr),
4636 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4637 Flag = Chain.getValue(1);
4639 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4641 std::vector<MVT::ValueType> Tys;
4642 Tys.push_back(SPTy);
4643 Tys.push_back(MVT::Other);
4644 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4645 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4648 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4649 SDOperand InFlag(0, 0);
4650 SDOperand Chain = Op.getOperand(0);
4652 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4653 if (Align == 0) Align = 1;
4655 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4656 // If not DWORD aligned or size is more than the threshold, call memset.
4657 // The libc version is likely to be faster for these cases. It can use the
4658 // address value and run time information about the CPU.
4659 if ((Align & 3) != 0 ||
4660 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4661 MVT::ValueType IntPtr = getPointerTy();
4662 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4663 TargetLowering::ArgListTy Args;
4664 TargetLowering::ArgListEntry Entry;
4665 Entry.Node = Op.getOperand(1);
4666 Entry.Ty = IntPtrTy;
4667 Args.push_back(Entry);
4668 // Extend the unsigned i8 argument to be an int value for the call.
4669 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4670 Entry.Ty = IntPtrTy;
4671 Args.push_back(Entry);
4672 Entry.Node = Op.getOperand(3);
4673 Args.push_back(Entry);
4674 std::pair<SDOperand,SDOperand> CallResult =
4675 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4676 false, DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4677 return CallResult.second;
4682 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4683 unsigned BytesLeft = 0;
4684 bool TwoRepStos = false;
4687 uint64_t Val = ValC->getValue() & 255;
4689 // If the value is a constant, then we can potentially use larger sets.
4690 switch (Align & 3) {
4691 case 2: // WORD aligned
4694 Val = (Val << 8) | Val;
4696 case 0: // DWORD aligned
4699 Val = (Val << 8) | Val;
4700 Val = (Val << 16) | Val;
4701 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4704 Val = (Val << 32) | Val;
4707 default: // Byte aligned
4710 Count = Op.getOperand(3);
4714 if (AVT > MVT::i8) {
4716 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4717 Count = DAG.getIntPtrConstant(I->getValue() / UBytes);
4718 BytesLeft = I->getValue() % UBytes;
4720 assert(AVT >= MVT::i32 &&
4721 "Do not use rep;stos if not at least DWORD aligned");
4722 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4723 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4728 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4730 InFlag = Chain.getValue(1);
4733 Count = Op.getOperand(3);
4734 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4735 InFlag = Chain.getValue(1);
4738 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4740 InFlag = Chain.getValue(1);
4741 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4742 Op.getOperand(1), InFlag);
4743 InFlag = Chain.getValue(1);
4745 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4746 SmallVector<SDOperand, 8> Ops;
4747 Ops.push_back(Chain);
4748 Ops.push_back(DAG.getValueType(AVT));
4749 Ops.push_back(InFlag);
4750 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4753 InFlag = Chain.getValue(1);
4754 Count = Op.getOperand(3);
4755 MVT::ValueType CVT = Count.getValueType();
4756 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4757 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4758 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4760 InFlag = Chain.getValue(1);
4761 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4763 Ops.push_back(Chain);
4764 Ops.push_back(DAG.getValueType(MVT::i8));
4765 Ops.push_back(InFlag);
4766 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4767 } else if (BytesLeft) {
4768 // Issue stores for the last 1 - 7 bytes.
4770 unsigned Val = ValC->getValue() & 255;
4771 unsigned Offset = I->getValue() - BytesLeft;
4772 SDOperand DstAddr = Op.getOperand(1);
4773 MVT::ValueType AddrVT = DstAddr.getValueType();
4774 if (BytesLeft >= 4) {
4775 Val = (Val << 8) | Val;
4776 Val = (Val << 16) | Val;
4777 Value = DAG.getConstant(Val, MVT::i32);
4778 Chain = DAG.getStore(Chain, Value,
4779 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4780 DAG.getConstant(Offset, AddrVT)),
4785 if (BytesLeft >= 2) {
4786 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4787 Chain = DAG.getStore(Chain, Value,
4788 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4789 DAG.getConstant(Offset, AddrVT)),
4794 if (BytesLeft == 1) {
4795 Value = DAG.getConstant(Val, MVT::i8);
4796 Chain = DAG.getStore(Chain, Value,
4797 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4798 DAG.getConstant(Offset, AddrVT)),
4806 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4811 SelectionDAG &DAG) {
4813 unsigned BytesLeft = 0;
4814 switch (Align & 3) {
4815 case 2: // WORD aligned
4818 case 0: // DWORD aligned
4820 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4823 default: // Byte aligned
4828 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4829 SDOperand Count = DAG.getIntPtrConstant(Size / UBytes);
4830 BytesLeft = Size % UBytes;
4832 SDOperand InFlag(0, 0);
4833 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4835 InFlag = Chain.getValue(1);
4836 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4838 InFlag = Chain.getValue(1);
4839 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4841 InFlag = Chain.getValue(1);
4843 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4844 SmallVector<SDOperand, 8> Ops;
4845 Ops.push_back(Chain);
4846 Ops.push_back(DAG.getValueType(AVT));
4847 Ops.push_back(InFlag);
4848 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4851 // Issue loads and stores for the last 1 - 7 bytes.
4852 unsigned Offset = Size - BytesLeft;
4853 SDOperand DstAddr = Dest;
4854 MVT::ValueType DstVT = DstAddr.getValueType();
4855 SDOperand SrcAddr = Source;
4856 MVT::ValueType SrcVT = SrcAddr.getValueType();
4858 if (BytesLeft >= 4) {
4859 Value = DAG.getLoad(MVT::i32, Chain,
4860 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4861 DAG.getConstant(Offset, SrcVT)),
4863 Chain = Value.getValue(1);
4864 Chain = DAG.getStore(Chain, Value,
4865 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4866 DAG.getConstant(Offset, DstVT)),
4871 if (BytesLeft >= 2) {
4872 Value = DAG.getLoad(MVT::i16, Chain,
4873 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4874 DAG.getConstant(Offset, SrcVT)),
4876 Chain = Value.getValue(1);
4877 Chain = DAG.getStore(Chain, Value,
4878 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4879 DAG.getConstant(Offset, DstVT)),
4885 if (BytesLeft == 1) {
4886 Value = DAG.getLoad(MVT::i8, Chain,
4887 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4888 DAG.getConstant(Offset, SrcVT)),
4890 Chain = Value.getValue(1);
4891 Chain = DAG.getStore(Chain, Value,
4892 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4893 DAG.getConstant(Offset, DstVT)),
4901 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4902 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4903 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4904 SDOperand TheChain = N->getOperand(0);
4905 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4906 if (Subtarget->is64Bit()) {
4907 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4908 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4909 MVT::i64, rax.getValue(2));
4910 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4911 DAG.getConstant(32, MVT::i8));
4913 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4916 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4917 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4920 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4921 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4922 MVT::i32, eax.getValue(2));
4923 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4924 SDOperand Ops[] = { eax, edx };
4925 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4927 // Use a MERGE_VALUES to return the value and chain.
4928 Ops[1] = edx.getValue(1);
4929 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4930 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4933 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4934 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4936 if (!Subtarget->is64Bit()) {
4937 // vastart just stores the address of the VarArgsFrameIndex slot into the
4938 // memory location argument.
4939 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4940 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4944 // gp_offset (0 - 6 * 8)
4945 // fp_offset (48 - 48 + 8 * 16)
4946 // overflow_arg_area (point to parameters coming in memory).
4948 SmallVector<SDOperand, 8> MemOps;
4949 SDOperand FIN = Op.getOperand(1);
4951 SDOperand Store = DAG.getStore(Op.getOperand(0),
4952 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4954 MemOps.push_back(Store);
4957 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4958 Store = DAG.getStore(Op.getOperand(0),
4959 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4961 MemOps.push_back(Store);
4963 // Store ptr to overflow_arg_area
4964 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4965 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4966 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4967 MemOps.push_back(Store);
4969 // Store ptr to reg_save_area.
4970 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4971 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4972 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4973 MemOps.push_back(Store);
4974 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4977 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4978 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4979 SDOperand Chain = Op.getOperand(0);
4980 SDOperand DstPtr = Op.getOperand(1);
4981 SDOperand SrcPtr = Op.getOperand(2);
4982 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4983 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4985 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr, SrcSV, 0);
4986 Chain = SrcPtr.getValue(1);
4987 for (unsigned i = 0; i < 3; ++i) {
4988 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr, SrcSV, 0);
4989 Chain = Val.getValue(1);
4990 Chain = DAG.getStore(Chain, Val, DstPtr, DstSV, 0);
4993 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
4994 DAG.getIntPtrConstant(8));
4995 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
4996 DAG.getIntPtrConstant(8));
5002 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5003 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5005 default: return SDOperand(); // Don't custom lower most intrinsics.
5006 // Comparison intrinsics.
5007 case Intrinsic::x86_sse_comieq_ss:
5008 case Intrinsic::x86_sse_comilt_ss:
5009 case Intrinsic::x86_sse_comile_ss:
5010 case Intrinsic::x86_sse_comigt_ss:
5011 case Intrinsic::x86_sse_comige_ss:
5012 case Intrinsic::x86_sse_comineq_ss:
5013 case Intrinsic::x86_sse_ucomieq_ss:
5014 case Intrinsic::x86_sse_ucomilt_ss:
5015 case Intrinsic::x86_sse_ucomile_ss:
5016 case Intrinsic::x86_sse_ucomigt_ss:
5017 case Intrinsic::x86_sse_ucomige_ss:
5018 case Intrinsic::x86_sse_ucomineq_ss:
5019 case Intrinsic::x86_sse2_comieq_sd:
5020 case Intrinsic::x86_sse2_comilt_sd:
5021 case Intrinsic::x86_sse2_comile_sd:
5022 case Intrinsic::x86_sse2_comigt_sd:
5023 case Intrinsic::x86_sse2_comige_sd:
5024 case Intrinsic::x86_sse2_comineq_sd:
5025 case Intrinsic::x86_sse2_ucomieq_sd:
5026 case Intrinsic::x86_sse2_ucomilt_sd:
5027 case Intrinsic::x86_sse2_ucomile_sd:
5028 case Intrinsic::x86_sse2_ucomigt_sd:
5029 case Intrinsic::x86_sse2_ucomige_sd:
5030 case Intrinsic::x86_sse2_ucomineq_sd: {
5032 ISD::CondCode CC = ISD::SETCC_INVALID;
5035 case Intrinsic::x86_sse_comieq_ss:
5036 case Intrinsic::x86_sse2_comieq_sd:
5040 case Intrinsic::x86_sse_comilt_ss:
5041 case Intrinsic::x86_sse2_comilt_sd:
5045 case Intrinsic::x86_sse_comile_ss:
5046 case Intrinsic::x86_sse2_comile_sd:
5050 case Intrinsic::x86_sse_comigt_ss:
5051 case Intrinsic::x86_sse2_comigt_sd:
5055 case Intrinsic::x86_sse_comige_ss:
5056 case Intrinsic::x86_sse2_comige_sd:
5060 case Intrinsic::x86_sse_comineq_ss:
5061 case Intrinsic::x86_sse2_comineq_sd:
5065 case Intrinsic::x86_sse_ucomieq_ss:
5066 case Intrinsic::x86_sse2_ucomieq_sd:
5067 Opc = X86ISD::UCOMI;
5070 case Intrinsic::x86_sse_ucomilt_ss:
5071 case Intrinsic::x86_sse2_ucomilt_sd:
5072 Opc = X86ISD::UCOMI;
5075 case Intrinsic::x86_sse_ucomile_ss:
5076 case Intrinsic::x86_sse2_ucomile_sd:
5077 Opc = X86ISD::UCOMI;
5080 case Intrinsic::x86_sse_ucomigt_ss:
5081 case Intrinsic::x86_sse2_ucomigt_sd:
5082 Opc = X86ISD::UCOMI;
5085 case Intrinsic::x86_sse_ucomige_ss:
5086 case Intrinsic::x86_sse2_ucomige_sd:
5087 Opc = X86ISD::UCOMI;
5090 case Intrinsic::x86_sse_ucomineq_ss:
5091 case Intrinsic::x86_sse2_ucomineq_sd:
5092 Opc = X86ISD::UCOMI;
5098 SDOperand LHS = Op.getOperand(1);
5099 SDOperand RHS = Op.getOperand(2);
5100 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5102 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5103 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5104 DAG.getConstant(X86CC, MVT::i8), Cond);
5105 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5110 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5111 // Depths > 0 not supported yet!
5112 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5115 // Just load the return address
5116 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5117 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5120 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5121 // Depths > 0 not supported yet!
5122 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5125 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5126 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5127 DAG.getIntPtrConstant(4));
5130 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5131 SelectionDAG &DAG) {
5132 // Is not yet supported on x86-64
5133 if (Subtarget->is64Bit())
5136 return DAG.getIntPtrConstant(8);
5139 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5141 assert(!Subtarget->is64Bit() &&
5142 "Lowering of eh_return builtin is not supported yet on x86-64");
5144 MachineFunction &MF = DAG.getMachineFunction();
5145 SDOperand Chain = Op.getOperand(0);
5146 SDOperand Offset = Op.getOperand(1);
5147 SDOperand Handler = Op.getOperand(2);
5149 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5152 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5153 DAG.getIntPtrConstant(-4UL));
5154 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5155 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5156 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5157 MF.getRegInfo().addLiveOut(X86::ECX);
5159 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5160 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5163 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5164 SelectionDAG &DAG) {
5165 SDOperand Root = Op.getOperand(0);
5166 SDOperand Trmp = Op.getOperand(1); // trampoline
5167 SDOperand FPtr = Op.getOperand(2); // nested function
5168 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5170 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5172 const X86InstrInfo *TII =
5173 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5175 if (Subtarget->is64Bit()) {
5176 SDOperand OutChains[6];
5178 // Large code-model.
5180 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5181 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5183 const unsigned char N86R10 =
5184 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5185 const unsigned char N86R11 =
5186 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5188 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5190 // Load the pointer to the nested function into R11.
5191 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5192 SDOperand Addr = Trmp;
5193 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5196 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5197 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5199 // Load the 'nest' parameter value into R10.
5200 // R10 is specified in X86CallingConv.td
5201 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5202 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5203 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5206 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5207 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5209 // Jump to the nested function.
5210 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5211 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5212 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5215 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5216 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5217 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5221 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5222 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5224 const Function *Func =
5225 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5226 unsigned CC = Func->getCallingConv();
5231 assert(0 && "Unsupported calling convention");
5232 case CallingConv::C:
5233 case CallingConv::X86_StdCall: {
5234 // Pass 'nest' parameter in ECX.
5235 // Must be kept in sync with X86CallingConv.td
5238 // Check that ECX wasn't needed by an 'inreg' parameter.
5239 const FunctionType *FTy = Func->getFunctionType();
5240 const ParamAttrsList *Attrs = Func->getParamAttrs();
5242 if (Attrs && !Func->isVarArg()) {
5243 unsigned InRegCount = 0;
5246 for (FunctionType::param_iterator I = FTy->param_begin(),
5247 E = FTy->param_end(); I != E; ++I, ++Idx)
5248 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5249 // FIXME: should only count parameters that are lowered to integers.
5250 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5252 if (InRegCount > 2) {
5253 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5259 case CallingConv::X86_FastCall:
5260 // Pass 'nest' parameter in EAX.
5261 // Must be kept in sync with X86CallingConv.td
5266 SDOperand OutChains[4];
5267 SDOperand Addr, Disp;
5269 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5270 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5272 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5273 const unsigned char N86Reg =
5274 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5275 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5278 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5279 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5281 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5282 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5283 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5284 TrmpAddr, 5, false, 1);
5286 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5287 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5290 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5291 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5295 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5297 The rounding mode is in bits 11:10 of FPSR, and has the following
5304 FLT_ROUNDS, on the other hand, expects the following:
5311 To perform the conversion, we do:
5312 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5315 MachineFunction &MF = DAG.getMachineFunction();
5316 const TargetMachine &TM = MF.getTarget();
5317 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5318 unsigned StackAlignment = TFI.getStackAlignment();
5319 MVT::ValueType VT = Op.getValueType();
5321 // Save FP Control Word to stack slot
5322 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5323 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5325 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5326 DAG.getEntryNode(), StackSlot);
5328 // Load FP Control Word from stack slot
5329 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5331 // Transform as necessary
5333 DAG.getNode(ISD::SRL, MVT::i16,
5334 DAG.getNode(ISD::AND, MVT::i16,
5335 CWD, DAG.getConstant(0x800, MVT::i16)),
5336 DAG.getConstant(11, MVT::i8));
5338 DAG.getNode(ISD::SRL, MVT::i16,
5339 DAG.getNode(ISD::AND, MVT::i16,
5340 CWD, DAG.getConstant(0x400, MVT::i16)),
5341 DAG.getConstant(9, MVT::i8));
5344 DAG.getNode(ISD::AND, MVT::i16,
5345 DAG.getNode(ISD::ADD, MVT::i16,
5346 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5347 DAG.getConstant(1, MVT::i16)),
5348 DAG.getConstant(3, MVT::i16));
5351 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5352 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5355 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5356 MVT::ValueType VT = Op.getValueType();
5357 MVT::ValueType OpVT = VT;
5358 unsigned NumBits = MVT::getSizeInBits(VT);
5360 Op = Op.getOperand(0);
5361 if (VT == MVT::i8) {
5362 // Zero extend to i32 since there is not an i8 bsr.
5364 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5367 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5368 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5369 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5371 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5372 SmallVector<SDOperand, 4> Ops;
5374 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5375 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5376 Ops.push_back(Op.getValue(1));
5377 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5379 // Finally xor with NumBits-1.
5380 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5383 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5387 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5388 MVT::ValueType VT = Op.getValueType();
5389 MVT::ValueType OpVT = VT;
5390 unsigned NumBits = MVT::getSizeInBits(VT);
5392 Op = Op.getOperand(0);
5393 if (VT == MVT::i8) {
5395 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5398 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5399 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5400 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5402 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5403 SmallVector<SDOperand, 4> Ops;
5405 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5406 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5407 Ops.push_back(Op.getValue(1));
5408 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5411 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5415 SDOperand X86TargetLowering::LowerLCS(SDOperand Op, SelectionDAG &DAG) {
5416 MVT::ValueType T = cast<AtomicSDNode>(Op.Val)->getVT();
5420 case MVT::i8: Reg = X86::AL; size = 1; break;
5421 case MVT::i16: Reg = X86::AX; size = 2; break;
5422 case MVT::i32: Reg = X86::EAX; size = 4; break;
5424 if (Subtarget->is64Bit()) {
5425 Reg = X86::RAX; size = 8;
5426 } else //Should go away when LowerType stuff lands
5427 return SDOperand(ExpandATOMIC_LCS(Op.Val, DAG), 0);
5430 SDOperand cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5431 Op.getOperand(3), SDOperand());
5432 SDOperand Ops[] = { cpIn.getValue(0),
5435 DAG.getTargetConstant(size, MVT::i8),
5437 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5438 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5440 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5444 SDNode* X86TargetLowering::ExpandATOMIC_LCS(SDNode* Op, SelectionDAG &DAG) {
5445 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5446 assert (T == MVT::i64 && "Only know how to expand i64 CAS");
5447 SDOperand cpInL, cpInH;
5448 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5449 DAG.getConstant(0, MVT::i32));
5450 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5451 DAG.getConstant(1, MVT::i32));
5452 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5453 cpInL, SDOperand());
5454 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5455 cpInH, cpInL.getValue(1));
5456 SDOperand swapInL, swapInH;
5457 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5458 DAG.getConstant(0, MVT::i32));
5459 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5460 DAG.getConstant(1, MVT::i32));
5461 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5462 swapInL, cpInH.getValue(1));
5463 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5464 swapInH, swapInL.getValue(1));
5465 SDOperand Ops[] = { swapInH.getValue(0),
5467 swapInH.getValue(1)};
5468 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5469 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5470 SDOperand cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5471 Result.getValue(1));
5472 SDOperand cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5473 cpOutL.getValue(2));
5474 SDOperand OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5475 SDOperand ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5476 Tys = DAG.getVTList(MVT::i64, MVT::Other);
5477 return DAG.getNode(ISD::MERGE_VALUES, Tys, ResultVal, cpOutH.getValue(1)).Val;
5480 /// LowerOperation - Provide custom lowering hooks for some operations.
5482 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5483 switch (Op.getOpcode()) {
5484 default: assert(0 && "Should not custom lower this!");
5485 case ISD::ATOMIC_LCS: return LowerLCS(Op,DAG);
5486 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5487 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5488 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5489 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5490 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5491 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5492 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5493 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5494 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5495 case ISD::SHL_PARTS:
5496 case ISD::SRA_PARTS:
5497 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5498 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5499 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5500 case ISD::FABS: return LowerFABS(Op, DAG);
5501 case ISD::FNEG: return LowerFNEG(Op, DAG);
5502 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5503 case ISD::SETCC: return LowerSETCC(Op, DAG);
5504 case ISD::SELECT: return LowerSELECT(Op, DAG);
5505 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5506 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5507 case ISD::CALL: return LowerCALL(Op, DAG);
5508 case ISD::RET: return LowerRET(Op, DAG);
5509 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5510 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5511 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
5512 case ISD::VASTART: return LowerVASTART(Op, DAG);
5513 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5514 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5515 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5516 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5517 case ISD::FRAME_TO_ARGS_OFFSET:
5518 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5519 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5520 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5521 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5522 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5523 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5524 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5526 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5527 case ISD::READCYCLECOUNTER:
5528 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5532 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5533 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5534 switch (N->getOpcode()) {
5535 default: assert(0 && "Should not custom lower this!");
5536 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5537 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5538 case ISD::ATOMIC_LCS: return ExpandATOMIC_LCS(N, DAG);
5542 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5544 default: return NULL;
5545 case X86ISD::BSF: return "X86ISD::BSF";
5546 case X86ISD::BSR: return "X86ISD::BSR";
5547 case X86ISD::SHLD: return "X86ISD::SHLD";
5548 case X86ISD::SHRD: return "X86ISD::SHRD";
5549 case X86ISD::FAND: return "X86ISD::FAND";
5550 case X86ISD::FOR: return "X86ISD::FOR";
5551 case X86ISD::FXOR: return "X86ISD::FXOR";
5552 case X86ISD::FSRL: return "X86ISD::FSRL";
5553 case X86ISD::FILD: return "X86ISD::FILD";
5554 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5555 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5556 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5557 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5558 case X86ISD::FLD: return "X86ISD::FLD";
5559 case X86ISD::FST: return "X86ISD::FST";
5560 case X86ISD::FP_GET_ST0_ST1: return "X86ISD::FP_GET_ST0_ST1";
5561 case X86ISD::CALL: return "X86ISD::CALL";
5562 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5563 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5564 case X86ISD::CMP: return "X86ISD::CMP";
5565 case X86ISD::COMI: return "X86ISD::COMI";
5566 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5567 case X86ISD::SETCC: return "X86ISD::SETCC";
5568 case X86ISD::CMOV: return "X86ISD::CMOV";
5569 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5570 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5571 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5572 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5573 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5574 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5575 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5576 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5577 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5578 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5579 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5580 case X86ISD::FMAX: return "X86ISD::FMAX";
5581 case X86ISD::FMIN: return "X86ISD::FMIN";
5582 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5583 case X86ISD::FRCP: return "X86ISD::FRCP";
5584 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5585 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5586 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5587 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5588 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5589 case X86ISD::LCMPXCHG_DAG: return "x86ISD::LCMPXCHG_DAG";
5590 case X86ISD::LCMPXCHG8_DAG: return "x86ISD::LCMPXCHG8_DAG";
5594 // isLegalAddressingMode - Return true if the addressing mode represented
5595 // by AM is legal for this target, for a load/store of the specified type.
5596 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5597 const Type *Ty) const {
5598 // X86 supports extremely general addressing modes.
5600 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5601 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5605 // We can only fold this if we don't need an extra load.
5606 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5609 // X86-64 only supports addr of globals in small code model.
5610 if (Subtarget->is64Bit()) {
5611 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5613 // If lower 4G is not available, then we must use rip-relative addressing.
5614 if (AM.BaseOffs || AM.Scale > 1)
5625 // These scales always work.
5630 // These scales are formed with basereg+scalereg. Only accept if there is
5635 default: // Other stuff never works.
5643 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5644 if (!Ty1->isInteger() || !Ty2->isInteger())
5646 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5647 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5648 if (NumBits1 <= NumBits2)
5650 return Subtarget->is64Bit() || NumBits1 < 64;
5653 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5654 MVT::ValueType VT2) const {
5655 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5657 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5658 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5659 if (NumBits1 <= NumBits2)
5661 return Subtarget->is64Bit() || NumBits1 < 64;
5664 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5665 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5666 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5667 /// are assumed to be legal.
5669 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5670 // Only do shuffles on 128-bit vector types for now.
5671 if (MVT::getSizeInBits(VT) == 64) return false;
5672 return (Mask.Val->getNumOperands() <= 4 ||
5673 isIdentityMask(Mask.Val) ||
5674 isIdentityMask(Mask.Val, true) ||
5675 isSplatMask(Mask.Val) ||
5676 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5677 X86::isUNPCKLMask(Mask.Val) ||
5678 X86::isUNPCKHMask(Mask.Val) ||
5679 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5680 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5683 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5685 SelectionDAG &DAG) const {
5686 unsigned NumElts = BVOps.size();
5687 // Only do shuffles on 128-bit vector types for now.
5688 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5689 if (NumElts == 2) return true;
5691 return (isMOVLMask(&BVOps[0], 4) ||
5692 isCommutedMOVL(&BVOps[0], 4, true) ||
5693 isSHUFPMask(&BVOps[0], 4) ||
5694 isCommutedSHUFP(&BVOps[0], 4));
5699 //===----------------------------------------------------------------------===//
5700 // X86 Scheduler Hooks
5701 //===----------------------------------------------------------------------===//
5704 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5705 MachineBasicBlock *BB) {
5706 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5707 switch (MI->getOpcode()) {
5708 default: assert(false && "Unexpected instr type to insert");
5709 case X86::CMOV_FR32:
5710 case X86::CMOV_FR64:
5711 case X86::CMOV_V4F32:
5712 case X86::CMOV_V2F64:
5713 case X86::CMOV_V2I64: {
5714 // To "insert" a SELECT_CC instruction, we actually have to insert the
5715 // diamond control-flow pattern. The incoming instruction knows the
5716 // destination vreg to set, the condition code register to branch on, the
5717 // true/false values to select between, and a branch opcode to use.
5718 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5719 ilist<MachineBasicBlock>::iterator It = BB;
5725 // cmpTY ccX, r1, r2
5727 // fallthrough --> copy0MBB
5728 MachineBasicBlock *thisMBB = BB;
5729 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5730 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5732 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5733 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5734 MachineFunction *F = BB->getParent();
5735 F->getBasicBlockList().insert(It, copy0MBB);
5736 F->getBasicBlockList().insert(It, sinkMBB);
5737 // Update machine-CFG edges by first adding all successors of the current
5738 // block to the new block which will contain the Phi node for the select.
5739 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5740 e = BB->succ_end(); i != e; ++i)
5741 sinkMBB->addSuccessor(*i);
5742 // Next, remove all successors of the current block, and add the true
5743 // and fallthrough blocks as its successors.
5744 while(!BB->succ_empty())
5745 BB->removeSuccessor(BB->succ_begin());
5746 BB->addSuccessor(copy0MBB);
5747 BB->addSuccessor(sinkMBB);
5750 // %FalseValue = ...
5751 // # fallthrough to sinkMBB
5754 // Update machine-CFG edges
5755 BB->addSuccessor(sinkMBB);
5758 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5761 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5762 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5763 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5765 delete MI; // The pseudo instruction is gone now.
5769 case X86::FP32_TO_INT16_IN_MEM:
5770 case X86::FP32_TO_INT32_IN_MEM:
5771 case X86::FP32_TO_INT64_IN_MEM:
5772 case X86::FP64_TO_INT16_IN_MEM:
5773 case X86::FP64_TO_INT32_IN_MEM:
5774 case X86::FP64_TO_INT64_IN_MEM:
5775 case X86::FP80_TO_INT16_IN_MEM:
5776 case X86::FP80_TO_INT32_IN_MEM:
5777 case X86::FP80_TO_INT64_IN_MEM: {
5778 // Change the floating point control register to use "round towards zero"
5779 // mode when truncating to an integer value.
5780 MachineFunction *F = BB->getParent();
5781 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5782 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5784 // Load the old value of the high byte of the control word...
5786 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5787 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5789 // Set the high part to be round to zero...
5790 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5793 // Reload the modified control word now...
5794 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5796 // Restore the memory image of control word to original value
5797 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5800 // Get the X86 opcode to use.
5802 switch (MI->getOpcode()) {
5803 default: assert(0 && "illegal opcode!");
5804 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5805 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5806 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5807 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5808 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5809 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5810 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5811 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5812 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5816 MachineOperand &Op = MI->getOperand(0);
5817 if (Op.isRegister()) {
5818 AM.BaseType = X86AddressMode::RegBase;
5819 AM.Base.Reg = Op.getReg();
5821 AM.BaseType = X86AddressMode::FrameIndexBase;
5822 AM.Base.FrameIndex = Op.getIndex();
5824 Op = MI->getOperand(1);
5825 if (Op.isImmediate())
5826 AM.Scale = Op.getImm();
5827 Op = MI->getOperand(2);
5828 if (Op.isImmediate())
5829 AM.IndexReg = Op.getImm();
5830 Op = MI->getOperand(3);
5831 if (Op.isGlobalAddress()) {
5832 AM.GV = Op.getGlobal();
5834 AM.Disp = Op.getImm();
5836 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5837 .addReg(MI->getOperand(4).getReg());
5839 // Reload the original control word now.
5840 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5842 delete MI; // The pseudo instruction is gone now.
5848 //===----------------------------------------------------------------------===//
5849 // X86 Optimization Hooks
5850 //===----------------------------------------------------------------------===//
5852 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5856 const SelectionDAG &DAG,
5857 unsigned Depth) const {
5858 unsigned Opc = Op.getOpcode();
5859 assert((Opc >= ISD::BUILTIN_OP_END ||
5860 Opc == ISD::INTRINSIC_WO_CHAIN ||
5861 Opc == ISD::INTRINSIC_W_CHAIN ||
5862 Opc == ISD::INTRINSIC_VOID) &&
5863 "Should use MaskedValueIsZero if you don't know whether Op"
5864 " is a target node!");
5866 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
5870 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
5871 Mask.getBitWidth() - 1);
5876 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5877 /// element of the result of the vector shuffle.
5878 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5879 MVT::ValueType VT = N->getValueType(0);
5880 SDOperand PermMask = N->getOperand(2);
5881 unsigned NumElems = PermMask.getNumOperands();
5882 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5884 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5886 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5887 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5888 SDOperand Idx = PermMask.getOperand(i);
5889 if (Idx.getOpcode() == ISD::UNDEF)
5890 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5891 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5896 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5897 /// node is a GlobalAddress + an offset.
5898 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5899 unsigned Opc = N->getOpcode();
5900 if (Opc == X86ISD::Wrapper) {
5901 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5902 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5905 } else if (Opc == ISD::ADD) {
5906 SDOperand N1 = N->getOperand(0);
5907 SDOperand N2 = N->getOperand(1);
5908 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5909 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5911 Offset += V->getSignExtended();
5914 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5915 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5917 Offset += V->getSignExtended();
5925 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5927 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5928 MachineFrameInfo *MFI) {
5929 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5932 SDOperand Loc = N->getOperand(1);
5933 SDOperand BaseLoc = Base->getOperand(1);
5934 if (Loc.getOpcode() == ISD::FrameIndex) {
5935 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5937 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5938 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5939 int FS = MFI->getObjectSize(FI);
5940 int BFS = MFI->getObjectSize(BFI);
5941 if (FS != BFS || FS != Size) return false;
5942 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5944 GlobalValue *GV1 = NULL;
5945 GlobalValue *GV2 = NULL;
5946 int64_t Offset1 = 0;
5947 int64_t Offset2 = 0;
5948 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5949 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5950 if (isGA1 && isGA2 && GV1 == GV2)
5951 return Offset1 == (Offset2 + Dist*Size);
5957 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5958 const X86Subtarget *Subtarget) {
5961 if (isGAPlusOffset(Base, GV, Offset))
5962 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5963 // DAG combine handles the stack object case.
5968 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5969 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5970 /// if the load addresses are consecutive, non-overlapping, and in the right
5972 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5973 const X86Subtarget *Subtarget) {
5974 MachineFunction &MF = DAG.getMachineFunction();
5975 MachineFrameInfo *MFI = MF.getFrameInfo();
5976 MVT::ValueType VT = N->getValueType(0);
5977 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5978 SDOperand PermMask = N->getOperand(2);
5979 int NumElems = (int)PermMask.getNumOperands();
5980 SDNode *Base = NULL;
5981 for (int i = 0; i < NumElems; ++i) {
5982 SDOperand Idx = PermMask.getOperand(i);
5983 if (Idx.getOpcode() == ISD::UNDEF) {
5984 if (!Base) return SDOperand();
5987 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5988 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5992 else if (!isConsecutiveLoad(Arg.Val, Base,
5993 i, MVT::getSizeInBits(EVT)/8,MFI))
5998 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5999 LoadSDNode *LD = cast<LoadSDNode>(Base);
6001 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6002 LD->getSrcValueOffset(), LD->isVolatile());
6004 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6005 LD->getSrcValueOffset(), LD->isVolatile(),
6006 LD->getAlignment());
6010 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6011 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6012 const X86Subtarget *Subtarget) {
6013 SDOperand Cond = N->getOperand(0);
6015 // If we have SSE[12] support, try to form min/max nodes.
6016 if (Subtarget->hasSSE2() &&
6017 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6018 if (Cond.getOpcode() == ISD::SETCC) {
6019 // Get the LHS/RHS of the select.
6020 SDOperand LHS = N->getOperand(1);
6021 SDOperand RHS = N->getOperand(2);
6022 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6024 unsigned Opcode = 0;
6025 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6028 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6031 if (!UnsafeFPMath) break;
6033 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6035 Opcode = X86ISD::FMIN;
6038 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6041 if (!UnsafeFPMath) break;
6043 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6045 Opcode = X86ISD::FMAX;
6048 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6051 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6054 if (!UnsafeFPMath) break;
6056 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6058 Opcode = X86ISD::FMIN;
6061 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6064 if (!UnsafeFPMath) break;
6066 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6068 Opcode = X86ISD::FMAX;
6074 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6082 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6083 static SDOperand PerformSTORECombine(StoreSDNode *St, SelectionDAG &DAG,
6084 const X86Subtarget *Subtarget) {
6085 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
6086 // the FP state in cases where an emms may be missing.
6087 // A preferable solution to the general problem is to figure out the right
6088 // places to insert EMMS. This qualifies as a quick hack.
6089 if (MVT::isVector(St->getValue().getValueType()) &&
6090 MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
6091 isa<LoadSDNode>(St->getValue()) &&
6092 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6093 St->getChain().hasOneUse() && !St->isVolatile()) {
6094 SDNode* LdVal = St->getValue().Val;
6096 int TokenFactorIndex = -1;
6097 SmallVector<SDOperand, 8> Ops;
6098 SDNode* ChainVal = St->getChain().Val;
6099 // Must be a store of a load. We currently handle two cases: the load
6100 // is a direct child, and it's under an intervening TokenFactor. It is
6101 // possible to dig deeper under nested TokenFactors.
6102 if (ChainVal == LdVal)
6103 Ld = cast<LoadSDNode>(St->getChain());
6104 else if (St->getValue().hasOneUse() &&
6105 ChainVal->getOpcode() == ISD::TokenFactor) {
6106 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6107 if (ChainVal->getOperand(i).Val == LdVal) {
6108 TokenFactorIndex = i;
6109 Ld = cast<LoadSDNode>(St->getValue());
6111 Ops.push_back(ChainVal->getOperand(i));
6115 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6116 if (Subtarget->is64Bit()) {
6117 SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6118 Ld->getBasePtr(), Ld->getSrcValue(),
6119 Ld->getSrcValueOffset(), Ld->isVolatile(),
6120 Ld->getAlignment());
6121 SDOperand NewChain = NewLd.getValue(1);
6122 if (TokenFactorIndex != -1) {
6123 Ops.push_back(NewLd);
6124 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6127 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6128 St->getSrcValue(), St->getSrcValueOffset(),
6129 St->isVolatile(), St->getAlignment());
6132 // Otherwise, lower to two 32-bit copies.
6133 SDOperand LoAddr = Ld->getBasePtr();
6134 SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6135 DAG.getConstant(MVT::i32, 4));
6137 SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6138 Ld->getSrcValue(), Ld->getSrcValueOffset(),
6139 Ld->isVolatile(), Ld->getAlignment());
6140 SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6141 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6143 MinAlign(Ld->getAlignment(), 4));
6145 SDOperand NewChain = LoLd.getValue(1);
6146 if (TokenFactorIndex != -1) {
6147 Ops.push_back(LoLd);
6148 Ops.push_back(HiLd);
6149 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6153 LoAddr = St->getBasePtr();
6154 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6155 DAG.getConstant(MVT::i32, 4));
6157 SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6158 St->getSrcValue(), St->getSrcValueOffset(),
6159 St->isVolatile(), St->getAlignment());
6160 SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6161 St->getSrcValue(), St->getSrcValueOffset()+4,
6163 MinAlign(St->getAlignment(), 4));
6164 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6170 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6171 /// X86ISD::FXOR nodes.
6172 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6173 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6174 // F[X]OR(0.0, x) -> x
6175 // F[X]OR(x, 0.0) -> x
6176 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6177 if (C->getValueAPF().isPosZero())
6178 return N->getOperand(1);
6179 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6180 if (C->getValueAPF().isPosZero())
6181 return N->getOperand(0);
6185 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6186 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6187 // FAND(0.0, x) -> 0.0
6188 // FAND(x, 0.0) -> 0.0
6189 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6190 if (C->getValueAPF().isPosZero())
6191 return N->getOperand(0);
6192 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6193 if (C->getValueAPF().isPosZero())
6194 return N->getOperand(1);
6199 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6200 DAGCombinerInfo &DCI) const {
6201 SelectionDAG &DAG = DCI.DAG;
6202 switch (N->getOpcode()) {
6204 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
6205 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6207 return PerformSTORECombine(cast<StoreSDNode>(N), DAG, Subtarget);
6209 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6210 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6216 //===----------------------------------------------------------------------===//
6217 // X86 Inline Assembly Support
6218 //===----------------------------------------------------------------------===//
6220 /// getConstraintType - Given a constraint letter, return the type of
6221 /// constraint it is for this target.
6222 X86TargetLowering::ConstraintType
6223 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6224 if (Constraint.size() == 1) {
6225 switch (Constraint[0]) {
6234 return C_RegisterClass;
6239 return TargetLowering::getConstraintType(Constraint);
6242 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6243 /// with another that has more specific requirements based on the type of the
6244 /// corresponding operand.
6245 void X86TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT,
6246 std::string& s) const {
6247 if (MVT::isFloatingPoint(ConstraintVT)) {
6248 if (Subtarget->hasSSE2())
6250 else if (Subtarget->hasSSE1())
6255 return TargetLowering::lowerXConstraint(ConstraintVT, s);
6258 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6259 /// vector. If it is invalid, don't add anything to Ops.
6260 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6262 std::vector<SDOperand>&Ops,
6263 SelectionDAG &DAG) {
6264 SDOperand Result(0, 0);
6266 switch (Constraint) {
6269 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6270 if (C->getValue() <= 31) {
6271 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6277 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6278 if (C->getValue() <= 255) {
6279 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6285 // Literal immediates are always ok.
6286 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6287 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6291 // If we are in non-pic codegen mode, we allow the address of a global (with
6292 // an optional displacement) to be used with 'i'.
6293 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6296 // Match either (GA) or (GA+C)
6298 Offset = GA->getOffset();
6299 } else if (Op.getOpcode() == ISD::ADD) {
6300 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6301 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6303 Offset = GA->getOffset()+C->getValue();
6305 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6306 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6308 Offset = GA->getOffset()+C->getValue();
6315 // If addressing this global requires a load (e.g. in PIC mode), we can't
6317 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6321 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6327 // Otherwise, not valid for this mode.
6333 Ops.push_back(Result);
6336 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6339 std::vector<unsigned> X86TargetLowering::
6340 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6341 MVT::ValueType VT) const {
6342 if (Constraint.size() == 1) {
6343 // FIXME: not handling fp-stack yet!
6344 switch (Constraint[0]) { // GCC X86 Constraint Letters
6345 default: break; // Unknown constraint letter
6346 case 'A': // EAX/EDX
6347 if (VT == MVT::i32 || VT == MVT::i64)
6348 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6350 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6353 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6354 else if (VT == MVT::i16)
6355 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6356 else if (VT == MVT::i8)
6357 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6358 else if (VT == MVT::i64)
6359 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6364 return std::vector<unsigned>();
6367 std::pair<unsigned, const TargetRegisterClass*>
6368 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6369 MVT::ValueType VT) const {
6370 // First, see if this is a constraint that directly corresponds to an LLVM
6372 if (Constraint.size() == 1) {
6373 // GCC Constraint Letters
6374 switch (Constraint[0]) {
6376 case 'r': // GENERAL_REGS
6377 case 'R': // LEGACY_REGS
6378 case 'l': // INDEX_REGS
6379 if (VT == MVT::i64 && Subtarget->is64Bit())
6380 return std::make_pair(0U, X86::GR64RegisterClass);
6382 return std::make_pair(0U, X86::GR32RegisterClass);
6383 else if (VT == MVT::i16)
6384 return std::make_pair(0U, X86::GR16RegisterClass);
6385 else if (VT == MVT::i8)
6386 return std::make_pair(0U, X86::GR8RegisterClass);
6388 case 'y': // MMX_REGS if MMX allowed.
6389 if (!Subtarget->hasMMX()) break;
6390 return std::make_pair(0U, X86::VR64RegisterClass);
6392 case 'Y': // SSE_REGS if SSE2 allowed
6393 if (!Subtarget->hasSSE2()) break;
6395 case 'x': // SSE_REGS if SSE1 allowed
6396 if (!Subtarget->hasSSE1()) break;
6400 // Scalar SSE types.
6403 return std::make_pair(0U, X86::FR32RegisterClass);
6406 return std::make_pair(0U, X86::FR64RegisterClass);
6414 return std::make_pair(0U, X86::VR128RegisterClass);
6420 // Use the default implementation in TargetLowering to convert the register
6421 // constraint into a member of a register class.
6422 std::pair<unsigned, const TargetRegisterClass*> Res;
6423 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6425 // Not found as a standard register?
6426 if (Res.second == 0) {
6427 // GCC calls "st(0)" just plain "st".
6428 if (StringsEqualNoCase("{st}", Constraint)) {
6429 Res.first = X86::ST0;
6430 Res.second = X86::RFP80RegisterClass;
6436 // Otherwise, check to see if this is a register class of the wrong value
6437 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6438 // turn into {ax},{dx}.
6439 if (Res.second->hasType(VT))
6440 return Res; // Correct type already, nothing to do.
6442 // All of the single-register GCC register classes map their values onto
6443 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6444 // really want an 8-bit or 32-bit register, map to the appropriate register
6445 // class and return the appropriate register.
6446 if (Res.second != X86::GR16RegisterClass)
6449 if (VT == MVT::i8) {
6450 unsigned DestReg = 0;
6451 switch (Res.first) {
6453 case X86::AX: DestReg = X86::AL; break;
6454 case X86::DX: DestReg = X86::DL; break;
6455 case X86::CX: DestReg = X86::CL; break;
6456 case X86::BX: DestReg = X86::BL; break;
6459 Res.first = DestReg;
6460 Res.second = Res.second = X86::GR8RegisterClass;
6462 } else if (VT == MVT::i32) {
6463 unsigned DestReg = 0;
6464 switch (Res.first) {
6466 case X86::AX: DestReg = X86::EAX; break;
6467 case X86::DX: DestReg = X86::EDX; break;
6468 case X86::CX: DestReg = X86::ECX; break;
6469 case X86::BX: DestReg = X86::EBX; break;
6470 case X86::SI: DestReg = X86::ESI; break;
6471 case X86::DI: DestReg = X86::EDI; break;
6472 case X86::BP: DestReg = X86::EBP; break;
6473 case X86::SP: DestReg = X86::ESP; break;
6476 Res.first = DestReg;
6477 Res.second = Res.second = X86::GR32RegisterClass;
6479 } else if (VT == MVT::i64) {
6480 unsigned DestReg = 0;
6481 switch (Res.first) {
6483 case X86::AX: DestReg = X86::RAX; break;
6484 case X86::DX: DestReg = X86::RDX; break;
6485 case X86::CX: DestReg = X86::RCX; break;
6486 case X86::BX: DestReg = X86::RBX; break;
6487 case X86::SI: DestReg = X86::RSI; break;
6488 case X86::DI: DestReg = X86::RDI; break;
6489 case X86::BP: DestReg = X86::RBP; break;
6490 case X86::SP: DestReg = X86::RSP; break;
6493 Res.first = DestReg;
6494 Res.second = Res.second = X86::GR64RegisterClass;