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/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/Support/CommandLine.h"
45 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
47 // Forward declarations.
48 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
51 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
52 : TargetLowering(TM) {
53 Subtarget = &TM.getSubtarget<X86Subtarget>();
54 X86ScalarSSEf64 = Subtarget->hasSSE2();
55 X86ScalarSSEf32 = Subtarget->hasSSE1();
56 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
60 RegInfo = TM.getRegisterInfo();
63 // Set up the TargetLowering object.
65 // X86 is weird, it always uses i8 for shift amounts and setcc results.
66 setShiftAmountType(MVT::i8);
67 setBooleanContents(ZeroOrOneBooleanContent);
68 setSchedulingPreference(SchedulingForRegPressure);
69 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
70 setStackPointerRegisterToSaveRestore(X86StackPtr);
72 if (Subtarget->isTargetDarwin()) {
73 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
74 setUseUnderscoreSetJmp(false);
75 setUseUnderscoreLongJmp(false);
76 } else if (Subtarget->isTargetMingw()) {
77 // MS runtime is weird: it exports _setjmp, but longjmp!
78 setUseUnderscoreSetJmp(true);
79 setUseUnderscoreLongJmp(false);
81 setUseUnderscoreSetJmp(true);
82 setUseUnderscoreLongJmp(true);
85 // Set up the register classes.
86 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
87 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
88 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
89 if (Subtarget->is64Bit())
90 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
92 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
94 // We don't accept any truncstore of integer registers.
95 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
96 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
97 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
98 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
99 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
100 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
102 // SETOEQ and SETUNE require checking two conditions.
103 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
104 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
105 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
106 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
107 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
108 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
110 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
112 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
114 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
116 if (Subtarget->is64Bit()) {
117 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
118 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
119 } else if (!UseSoftFloat) {
120 if (X86ScalarSSEf64) {
121 // We have an impenetrably clever algorithm for ui64->double only.
122 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
124 // We have an algorithm for SSE2, and we turn this into a 64-bit
125 // FILD for other targets.
126 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
129 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
131 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
132 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
134 if (!UseSoftFloat && !NoImplicitFloat) {
135 // SSE has no i16 to fp conversion, only i32
136 if (X86ScalarSSEf32) {
137 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
138 // f32 and f64 cases are Legal, f80 case is not
139 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
141 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
142 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
145 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
146 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
149 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
150 // are Legal, f80 is custom lowered.
151 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
152 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
154 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
156 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
157 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
159 if (X86ScalarSSEf32) {
160 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
161 // f32 and f64 cases are Legal, f80 case is not
162 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
164 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
165 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
168 // Handle FP_TO_UINT by promoting the destination to a larger signed
170 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
171 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
172 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
174 if (Subtarget->is64Bit()) {
175 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
176 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
177 } else if (!UseSoftFloat) {
178 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
179 // Expand FP_TO_UINT into a select.
180 // FIXME: We would like to use a Custom expander here eventually to do
181 // the optimal thing for SSE vs. the default expansion in the legalizer.
182 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
184 // With SSE3 we can use fisttpll to convert to a signed i64; without
185 // SSE, we're stuck with a fistpll.
186 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
189 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
190 if (!X86ScalarSSEf64) {
191 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
192 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
195 // Scalar integer divide and remainder are lowered to use operations that
196 // produce two results, to match the available instructions. This exposes
197 // the two-result form to trivial CSE, which is able to combine x/y and x%y
198 // into a single instruction.
200 // Scalar integer multiply-high is also lowered to use two-result
201 // operations, to match the available instructions. However, plain multiply
202 // (low) operations are left as Legal, as there are single-result
203 // instructions for this in x86. Using the two-result multiply instructions
204 // when both high and low results are needed must be arranged by dagcombine.
205 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
206 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
207 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
208 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
209 setOperationAction(ISD::SREM , MVT::i8 , Expand);
210 setOperationAction(ISD::UREM , MVT::i8 , Expand);
211 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
212 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
213 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
214 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
215 setOperationAction(ISD::SREM , MVT::i16 , Expand);
216 setOperationAction(ISD::UREM , MVT::i16 , Expand);
217 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
218 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
219 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
220 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
221 setOperationAction(ISD::SREM , MVT::i32 , Expand);
222 setOperationAction(ISD::UREM , MVT::i32 , Expand);
223 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
224 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
225 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
226 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
227 setOperationAction(ISD::SREM , MVT::i64 , Expand);
228 setOperationAction(ISD::UREM , MVT::i64 , Expand);
230 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
231 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
232 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
233 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
234 if (Subtarget->is64Bit())
235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
236 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
237 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
239 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
240 setOperationAction(ISD::FREM , MVT::f32 , Expand);
241 setOperationAction(ISD::FREM , MVT::f64 , Expand);
242 setOperationAction(ISD::FREM , MVT::f80 , Expand);
243 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
245 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
246 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
247 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
248 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
249 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
250 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
251 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
252 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
253 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
254 if (Subtarget->is64Bit()) {
255 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
256 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
257 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
260 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
261 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
263 // These should be promoted to a larger select which is supported.
264 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
265 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
266 // X86 wants to expand cmov itself.
267 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
268 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
269 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
270 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
271 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
272 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
273 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
274 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
275 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
276 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
277 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
278 if (Subtarget->is64Bit()) {
279 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
280 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
282 // X86 ret instruction may pop stack.
283 setOperationAction(ISD::RET , MVT::Other, Custom);
284 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
287 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
288 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
289 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
290 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
291 if (Subtarget->is64Bit())
292 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
293 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
294 if (Subtarget->is64Bit()) {
295 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
296 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
297 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
298 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
300 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
301 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
302 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
303 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
304 if (Subtarget->is64Bit()) {
305 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
306 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
307 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
310 if (Subtarget->hasSSE1())
311 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
313 if (!Subtarget->hasSSE2())
314 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
316 // Expand certain atomics
317 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
318 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
319 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
320 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
322 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
323 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
324 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
325 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
327 if (!Subtarget->is64Bit()) {
328 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
329 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
330 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
331 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
332 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
333 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
334 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
337 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
338 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
339 // FIXME - use subtarget debug flags
340 if (!Subtarget->isTargetDarwin() &&
341 !Subtarget->isTargetELF() &&
342 !Subtarget->isTargetCygMing()) {
343 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
344 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
347 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
348 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
349 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
350 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
351 if (Subtarget->is64Bit()) {
352 setExceptionPointerRegister(X86::RAX);
353 setExceptionSelectorRegister(X86::RDX);
355 setExceptionPointerRegister(X86::EAX);
356 setExceptionSelectorRegister(X86::EDX);
358 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
359 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
361 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
363 setOperationAction(ISD::TRAP, MVT::Other, Legal);
365 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
366 setOperationAction(ISD::VASTART , MVT::Other, Custom);
367 setOperationAction(ISD::VAEND , MVT::Other, Expand);
368 if (Subtarget->is64Bit()) {
369 setOperationAction(ISD::VAARG , MVT::Other, Custom);
370 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
372 setOperationAction(ISD::VAARG , MVT::Other, Expand);
373 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
376 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
377 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
378 if (Subtarget->is64Bit())
379 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
380 if (Subtarget->isTargetCygMing())
381 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
383 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
385 if (!UseSoftFloat && X86ScalarSSEf64) {
386 // f32 and f64 use SSE.
387 // Set up the FP register classes.
388 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
389 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
391 // Use ANDPD to simulate FABS.
392 setOperationAction(ISD::FABS , MVT::f64, Custom);
393 setOperationAction(ISD::FABS , MVT::f32, Custom);
395 // Use XORP to simulate FNEG.
396 setOperationAction(ISD::FNEG , MVT::f64, Custom);
397 setOperationAction(ISD::FNEG , MVT::f32, Custom);
399 // Use ANDPD and ORPD to simulate FCOPYSIGN.
400 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
401 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
403 // We don't support sin/cos/fmod
404 setOperationAction(ISD::FSIN , MVT::f64, Expand);
405 setOperationAction(ISD::FCOS , MVT::f64, Expand);
406 setOperationAction(ISD::FSIN , MVT::f32, Expand);
407 setOperationAction(ISD::FCOS , MVT::f32, Expand);
409 // Expand FP immediates into loads from the stack, except for the special
411 addLegalFPImmediate(APFloat(+0.0)); // xorpd
412 addLegalFPImmediate(APFloat(+0.0f)); // xorps
414 // Floating truncations from f80 and extensions to f80 go through memory.
415 // If optimizing, we lie about this though and handle it in
416 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
418 setConvertAction(MVT::f32, MVT::f80, Expand);
419 setConvertAction(MVT::f64, MVT::f80, Expand);
420 setConvertAction(MVT::f80, MVT::f32, Expand);
421 setConvertAction(MVT::f80, MVT::f64, Expand);
423 } else if (!UseSoftFloat && X86ScalarSSEf32) {
424 // Use SSE for f32, x87 for f64.
425 // Set up the FP register classes.
426 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
427 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
429 // Use ANDPS to simulate FABS.
430 setOperationAction(ISD::FABS , MVT::f32, Custom);
432 // Use XORP to simulate FNEG.
433 setOperationAction(ISD::FNEG , MVT::f32, Custom);
435 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
437 // Use ANDPS and ORPS to simulate FCOPYSIGN.
438 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
439 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
441 // We don't support sin/cos/fmod
442 setOperationAction(ISD::FSIN , MVT::f32, Expand);
443 setOperationAction(ISD::FCOS , MVT::f32, Expand);
445 // Special cases we handle for FP constants.
446 addLegalFPImmediate(APFloat(+0.0f)); // xorps
447 addLegalFPImmediate(APFloat(+0.0)); // FLD0
448 addLegalFPImmediate(APFloat(+1.0)); // FLD1
449 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
450 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
452 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
453 // this though and handle it in InstructionSelectPreprocess so that
454 // dagcombine2 can hack on these.
456 setConvertAction(MVT::f32, MVT::f64, Expand);
457 setConvertAction(MVT::f32, MVT::f80, Expand);
458 setConvertAction(MVT::f80, MVT::f32, Expand);
459 setConvertAction(MVT::f64, MVT::f32, Expand);
460 // And x87->x87 truncations also.
461 setConvertAction(MVT::f80, MVT::f64, Expand);
465 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
466 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
468 } else if (!UseSoftFloat) {
469 // f32 and f64 in x87.
470 // Set up the FP register classes.
471 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
472 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
474 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
475 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
476 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
477 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
479 // Floating truncations go through memory. If optimizing, we lie about
480 // this though and handle it in InstructionSelectPreprocess so that
481 // dagcombine2 can hack on these.
483 setConvertAction(MVT::f80, MVT::f32, Expand);
484 setConvertAction(MVT::f64, MVT::f32, Expand);
485 setConvertAction(MVT::f80, MVT::f64, Expand);
489 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
490 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
492 addLegalFPImmediate(APFloat(+0.0)); // FLD0
493 addLegalFPImmediate(APFloat(+1.0)); // FLD1
494 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
495 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
496 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
497 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
498 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
499 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
502 // Long double always uses X87.
504 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
505 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
506 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
509 APFloat TmpFlt(+0.0);
510 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
512 addLegalFPImmediate(TmpFlt); // FLD0
514 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
515 APFloat TmpFlt2(+1.0);
516 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
518 addLegalFPImmediate(TmpFlt2); // FLD1
519 TmpFlt2.changeSign();
520 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
524 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
525 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
529 // Always use a library call for pow.
530 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
531 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
532 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
534 setOperationAction(ISD::FLOG, MVT::f80, Expand);
535 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
536 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
537 setOperationAction(ISD::FEXP, MVT::f80, Expand);
538 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
540 // First set operation action for all vector types to either promote
541 // (for widening) or expand (for scalarization). Then we will selectively
542 // turn on ones that can be effectively codegen'd.
543 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
544 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
545 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
560 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
561 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
591 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
592 // with -msoft-float, disable use of MMX as well.
593 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
594 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
595 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
596 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
597 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
598 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
600 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
601 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
602 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
603 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
605 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
606 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
607 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
608 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
610 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
611 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
613 setOperationAction(ISD::AND, MVT::v8i8, Promote);
614 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
615 setOperationAction(ISD::AND, MVT::v4i16, Promote);
616 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
617 setOperationAction(ISD::AND, MVT::v2i32, Promote);
618 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
619 setOperationAction(ISD::AND, MVT::v1i64, Legal);
621 setOperationAction(ISD::OR, MVT::v8i8, Promote);
622 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
623 setOperationAction(ISD::OR, MVT::v4i16, Promote);
624 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
625 setOperationAction(ISD::OR, MVT::v2i32, Promote);
626 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
627 setOperationAction(ISD::OR, MVT::v1i64, Legal);
629 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
630 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
631 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
632 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
633 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
634 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
635 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
637 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
638 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
639 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
640 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
641 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
642 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
643 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
644 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
645 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
647 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
648 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
649 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
650 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
651 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
653 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
654 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
655 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
656 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
658 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
659 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
660 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
661 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
663 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
665 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
666 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
667 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
668 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
669 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
670 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
673 if (!UseSoftFloat && Subtarget->hasSSE1()) {
674 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
676 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
677 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
678 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
679 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
680 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
681 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
682 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
683 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
684 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
685 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
686 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
687 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
690 if (!UseSoftFloat && Subtarget->hasSSE2()) {
691 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
693 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
694 // registers cannot be used even for integer operations.
695 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
696 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
697 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
698 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
700 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
701 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
702 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
703 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
704 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
705 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
706 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
707 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
708 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
709 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
710 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
711 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
712 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
713 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
714 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
715 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
717 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
718 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
719 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
720 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
722 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
723 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
724 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
725 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
726 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
728 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
729 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
730 MVT VT = (MVT::SimpleValueType)i;
731 // Do not attempt to custom lower non-power-of-2 vectors
732 if (!isPowerOf2_32(VT.getVectorNumElements()))
734 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
735 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
739 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
740 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
741 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
742 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
743 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
744 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
746 if (Subtarget->is64Bit()) {
747 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
748 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
751 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
752 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
753 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
754 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
755 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
756 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
757 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
758 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
759 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
760 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
761 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
762 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
765 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
767 // Custom lower v2i64 and v2f64 selects.
768 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
769 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
770 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
771 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
775 if (Subtarget->hasSSE41()) {
776 // FIXME: Do we need to handle scalar-to-vector here?
777 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
779 // i8 and i16 vectors are custom , because the source register and source
780 // source memory operand types are not the same width. f32 vectors are
781 // custom since the immediate controlling the insert encodes additional
783 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
784 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
785 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
786 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
788 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
789 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
790 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
791 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
793 if (Subtarget->is64Bit()) {
794 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
795 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
799 if (Subtarget->hasSSE42()) {
800 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
803 // We want to custom lower some of our intrinsics.
804 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
806 // Add/Sub/Mul with overflow operations are custom lowered.
807 setOperationAction(ISD::SADDO, MVT::i32, Custom);
808 setOperationAction(ISD::SADDO, MVT::i64, Custom);
809 setOperationAction(ISD::UADDO, MVT::i32, Custom);
810 setOperationAction(ISD::UADDO, MVT::i64, Custom);
811 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
812 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
813 setOperationAction(ISD::USUBO, MVT::i32, Custom);
814 setOperationAction(ISD::USUBO, MVT::i64, Custom);
815 setOperationAction(ISD::SMULO, MVT::i32, Custom);
816 setOperationAction(ISD::SMULO, MVT::i64, Custom);
817 setOperationAction(ISD::UMULO, MVT::i32, Custom);
818 setOperationAction(ISD::UMULO, MVT::i64, Custom);
820 if (!Subtarget->is64Bit()) {
821 // These libcalls are not available in 32-bit.
822 setLibcallName(RTLIB::SHL_I128, 0);
823 setLibcallName(RTLIB::SRL_I128, 0);
824 setLibcallName(RTLIB::SRA_I128, 0);
827 // We have target-specific dag combine patterns for the following nodes:
828 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
829 setTargetDAGCombine(ISD::BUILD_VECTOR);
830 setTargetDAGCombine(ISD::SELECT);
831 setTargetDAGCombine(ISD::SHL);
832 setTargetDAGCombine(ISD::SRA);
833 setTargetDAGCombine(ISD::SRL);
834 setTargetDAGCombine(ISD::STORE);
835 if (Subtarget->is64Bit())
836 setTargetDAGCombine(ISD::MUL);
838 computeRegisterProperties();
840 // FIXME: These should be based on subtarget info. Plus, the values should
841 // be smaller when we are in optimizing for size mode.
842 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
843 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
844 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
845 allowUnalignedMemoryAccesses = true; // x86 supports it!
846 setPrefLoopAlignment(16);
847 benefitFromCodePlacementOpt = true;
851 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
856 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
857 /// the desired ByVal argument alignment.
858 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
861 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
862 if (VTy->getBitWidth() == 128)
864 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
865 unsigned EltAlign = 0;
866 getMaxByValAlign(ATy->getElementType(), EltAlign);
867 if (EltAlign > MaxAlign)
869 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
870 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
871 unsigned EltAlign = 0;
872 getMaxByValAlign(STy->getElementType(i), EltAlign);
873 if (EltAlign > MaxAlign)
882 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
883 /// function arguments in the caller parameter area. For X86, aggregates
884 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
885 /// are at 4-byte boundaries.
886 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
887 if (Subtarget->is64Bit()) {
888 // Max of 8 and alignment of type.
889 unsigned TyAlign = TD->getABITypeAlignment(Ty);
896 if (Subtarget->hasSSE1())
897 getMaxByValAlign(Ty, Align);
901 /// getOptimalMemOpType - Returns the target specific optimal type for load
902 /// and store operations as a result of memset, memcpy, and memmove
903 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
906 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
907 bool isSrcConst, bool isSrcStr) const {
908 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
909 // linux. This is because the stack realignment code can't handle certain
910 // cases like PR2962. This should be removed when PR2962 is fixed.
911 if (!NoImplicitFloat && Subtarget->getStackAlignment() >= 16) {
912 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
914 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
917 if (Subtarget->is64Bit() && Size >= 8)
922 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
924 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
925 SelectionDAG &DAG) const {
926 if (usesGlobalOffsetTable())
927 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
928 if (!Subtarget->isPICStyleRIPRel())
929 // This doesn't have DebugLoc associated with it, but is not really the
930 // same as a Register.
931 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
936 //===----------------------------------------------------------------------===//
937 // Return Value Calling Convention Implementation
938 //===----------------------------------------------------------------------===//
940 #include "X86GenCallingConv.inc"
942 /// LowerRET - Lower an ISD::RET node.
943 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
944 DebugLoc dl = Op.getDebugLoc();
945 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
947 SmallVector<CCValAssign, 16> RVLocs;
948 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
949 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
950 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
951 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
953 // If this is the first return lowered for this function, add the regs to the
954 // liveout set for the function.
955 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
956 for (unsigned i = 0; i != RVLocs.size(); ++i)
957 if (RVLocs[i].isRegLoc())
958 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
960 SDValue Chain = Op.getOperand(0);
962 // Handle tail call return.
963 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
964 if (Chain.getOpcode() == X86ISD::TAILCALL) {
965 SDValue TailCall = Chain;
966 SDValue TargetAddress = TailCall.getOperand(1);
967 SDValue StackAdjustment = TailCall.getOperand(2);
968 assert(((TargetAddress.getOpcode() == ISD::Register &&
969 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
970 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
971 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
972 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
973 "Expecting an global address, external symbol, or register");
974 assert(StackAdjustment.getOpcode() == ISD::Constant &&
975 "Expecting a const value");
977 SmallVector<SDValue,8> Operands;
978 Operands.push_back(Chain.getOperand(0));
979 Operands.push_back(TargetAddress);
980 Operands.push_back(StackAdjustment);
981 // Copy registers used by the call. Last operand is a flag so it is not
983 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
984 Operands.push_back(Chain.getOperand(i));
986 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
993 SmallVector<SDValue, 6> RetOps;
994 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
995 // Operand #1 = Bytes To Pop
996 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
998 // Copy the result values into the output registers.
999 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1000 CCValAssign &VA = RVLocs[i];
1001 assert(VA.isRegLoc() && "Can only return in registers!");
1002 SDValue ValToCopy = Op.getOperand(i*2+1);
1004 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1005 // the RET instruction and handled by the FP Stackifier.
1006 if (VA.getLocReg() == X86::ST0 ||
1007 VA.getLocReg() == X86::ST1) {
1008 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1009 // change the value to the FP stack register class.
1010 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1011 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1012 RetOps.push_back(ValToCopy);
1013 // Don't emit a copytoreg.
1017 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1018 // which is returned in RAX / RDX.
1019 if (Subtarget->is64Bit()) {
1020 MVT ValVT = ValToCopy.getValueType();
1021 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1022 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1023 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1024 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1028 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1029 Flag = Chain.getValue(1);
1032 // The x86-64 ABI for returning structs by value requires that we copy
1033 // the sret argument into %rax for the return. We saved the argument into
1034 // a virtual register in the entry block, so now we copy the value out
1036 if (Subtarget->is64Bit() &&
1037 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1038 MachineFunction &MF = DAG.getMachineFunction();
1039 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1040 unsigned Reg = FuncInfo->getSRetReturnReg();
1042 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1043 FuncInfo->setSRetReturnReg(Reg);
1045 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1047 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1048 Flag = Chain.getValue(1);
1051 RetOps[0] = Chain; // Update chain.
1053 // Add the flag if we have it.
1055 RetOps.push_back(Flag);
1057 return DAG.getNode(X86ISD::RET_FLAG, dl,
1058 MVT::Other, &RetOps[0], RetOps.size());
1062 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1063 /// appropriate copies out of appropriate physical registers. This assumes that
1064 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1065 /// being lowered. The returns a SDNode with the same number of values as the
1067 SDNode *X86TargetLowering::
1068 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1069 unsigned CallingConv, SelectionDAG &DAG) {
1071 DebugLoc dl = TheCall->getDebugLoc();
1072 // Assign locations to each value returned by this call.
1073 SmallVector<CCValAssign, 16> RVLocs;
1074 bool isVarArg = TheCall->isVarArg();
1075 bool Is64Bit = Subtarget->is64Bit();
1076 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1077 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1079 SmallVector<SDValue, 8> ResultVals;
1081 // Copy all of the result registers out of their specified physreg.
1082 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1083 CCValAssign &VA = RVLocs[i];
1084 MVT CopyVT = VA.getValVT();
1086 // If this is x86-64, and we disabled SSE, we can't return FP values
1087 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1088 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1089 cerr << "SSE register return with SSE disabled\n";
1093 // If this is a call to a function that returns an fp value on the floating
1094 // point stack, but where we prefer to use the value in xmm registers, copy
1095 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1096 if ((VA.getLocReg() == X86::ST0 ||
1097 VA.getLocReg() == X86::ST1) &&
1098 isScalarFPTypeInSSEReg(VA.getValVT())) {
1103 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1104 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1105 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1106 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1107 MVT::v2i64, InFlag).getValue(1);
1108 Val = Chain.getValue(0);
1109 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1110 Val, DAG.getConstant(0, MVT::i64));
1112 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1113 MVT::i64, InFlag).getValue(1);
1114 Val = Chain.getValue(0);
1116 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1118 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1119 CopyVT, InFlag).getValue(1);
1120 Val = Chain.getValue(0);
1122 InFlag = Chain.getValue(2);
1124 if (CopyVT != VA.getValVT()) {
1125 // Round the F80 the right size, which also moves to the appropriate xmm
1127 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1128 // This truncation won't change the value.
1129 DAG.getIntPtrConstant(1));
1132 ResultVals.push_back(Val);
1135 // Merge everything together with a MERGE_VALUES node.
1136 ResultVals.push_back(Chain);
1137 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1138 &ResultVals[0], ResultVals.size()).getNode();
1142 //===----------------------------------------------------------------------===//
1143 // C & StdCall & Fast Calling Convention implementation
1144 //===----------------------------------------------------------------------===//
1145 // StdCall calling convention seems to be standard for many Windows' API
1146 // routines and around. It differs from C calling convention just a little:
1147 // callee should clean up the stack, not caller. Symbols should be also
1148 // decorated in some fancy way :) It doesn't support any vector arguments.
1149 // For info on fast calling convention see Fast Calling Convention (tail call)
1150 // implementation LowerX86_32FastCCCallTo.
1152 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1154 static bool CallIsStructReturn(CallSDNode *TheCall) {
1155 unsigned NumOps = TheCall->getNumArgs();
1159 return TheCall->getArgFlags(0).isSRet();
1162 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1163 /// return semantics.
1164 static bool ArgsAreStructReturn(SDValue Op) {
1165 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1169 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1172 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1173 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1175 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1179 switch (CallingConv) {
1182 case CallingConv::X86_StdCall:
1183 return !Subtarget->is64Bit();
1184 case CallingConv::X86_FastCall:
1185 return !Subtarget->is64Bit();
1186 case CallingConv::Fast:
1187 return PerformTailCallOpt;
1191 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1192 /// given CallingConvention value.
1193 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1194 if (Subtarget->is64Bit()) {
1195 if (Subtarget->isTargetWin64())
1196 return CC_X86_Win64_C;
1197 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1198 return CC_X86_64_TailCall;
1203 if (CC == CallingConv::X86_FastCall)
1204 return CC_X86_32_FastCall;
1205 else if (CC == CallingConv::Fast)
1206 return CC_X86_32_FastCC;
1211 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1212 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1214 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1215 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1216 if (CC == CallingConv::X86_FastCall)
1218 else if (CC == CallingConv::X86_StdCall)
1224 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1225 /// in a register before calling.
1226 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1227 return !IsTailCall && !Is64Bit &&
1228 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1229 Subtarget->isPICStyleGOT();
1232 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1233 /// address to be loaded in a register.
1235 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1236 return !Is64Bit && IsTailCall &&
1237 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1238 Subtarget->isPICStyleGOT();
1241 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1242 /// by "Src" to address "Dst" with size and alignment information specified by
1243 /// the specific parameter attribute. The copy will be passed as a byval
1244 /// function parameter.
1246 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1247 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1249 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1250 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1251 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1254 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1255 const CCValAssign &VA,
1256 MachineFrameInfo *MFI,
1258 SDValue Root, unsigned i) {
1259 // Create the nodes corresponding to a load from this parameter slot.
1260 ISD::ArgFlagsTy Flags =
1261 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1262 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1263 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1265 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1266 // changed with more analysis.
1267 // In case of tail call optimization mark all arguments mutable. Since they
1268 // could be overwritten by lowering of arguments in case of a tail call.
1269 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1270 VA.getLocMemOffset(), isImmutable);
1271 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1272 if (Flags.isByVal())
1274 return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1275 PseudoSourceValue::getFixedStack(FI), 0);
1279 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1280 MachineFunction &MF = DAG.getMachineFunction();
1281 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1282 DebugLoc dl = Op.getDebugLoc();
1284 const Function* Fn = MF.getFunction();
1285 if (Fn->hasExternalLinkage() &&
1286 Subtarget->isTargetCygMing() &&
1287 Fn->getName() == "main")
1288 FuncInfo->setForceFramePointer(true);
1290 // Decorate the function name.
1291 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1293 MachineFrameInfo *MFI = MF.getFrameInfo();
1294 SDValue Root = Op.getOperand(0);
1295 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1296 unsigned CC = MF.getFunction()->getCallingConv();
1297 bool Is64Bit = Subtarget->is64Bit();
1298 bool IsWin64 = Subtarget->isTargetWin64();
1300 assert(!(isVarArg && CC == CallingConv::Fast) &&
1301 "Var args not supported with calling convention fastcc");
1303 // Assign locations to all of the incoming arguments.
1304 SmallVector<CCValAssign, 16> ArgLocs;
1305 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1306 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1308 SmallVector<SDValue, 8> ArgValues;
1309 unsigned LastVal = ~0U;
1310 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1311 CCValAssign &VA = ArgLocs[i];
1312 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1314 assert(VA.getValNo() != LastVal &&
1315 "Don't support value assigned to multiple locs yet");
1316 LastVal = VA.getValNo();
1318 if (VA.isRegLoc()) {
1319 MVT RegVT = VA.getLocVT();
1320 TargetRegisterClass *RC = NULL;
1321 if (RegVT == MVT::i32)
1322 RC = X86::GR32RegisterClass;
1323 else if (Is64Bit && RegVT == MVT::i64)
1324 RC = X86::GR64RegisterClass;
1325 else if (RegVT == MVT::f32)
1326 RC = X86::FR32RegisterClass;
1327 else if (RegVT == MVT::f64)
1328 RC = X86::FR64RegisterClass;
1329 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1330 RC = X86::VR128RegisterClass;
1331 else if (RegVT.isVector()) {
1332 assert(RegVT.getSizeInBits() == 64);
1334 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1336 // Darwin calling convention passes MMX values in either GPRs or
1337 // XMMs in x86-64. Other targets pass them in memory.
1338 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1339 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1342 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1347 assert(0 && "Unknown argument type!");
1350 unsigned Reg = DAG.getMachineFunction().addLiveIn(VA.getLocReg(), RC);
1351 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1353 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1354 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1356 if (VA.getLocInfo() == CCValAssign::SExt)
1357 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1358 DAG.getValueType(VA.getValVT()));
1359 else if (VA.getLocInfo() == CCValAssign::ZExt)
1360 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1361 DAG.getValueType(VA.getValVT()));
1363 if (VA.getLocInfo() != CCValAssign::Full)
1364 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1366 // Handle MMX values passed in GPRs.
1367 if (Is64Bit && RegVT != VA.getLocVT()) {
1368 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1369 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1370 else if (RC == X86::VR128RegisterClass) {
1371 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1372 ArgValue, DAG.getConstant(0, MVT::i64));
1373 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1377 ArgValues.push_back(ArgValue);
1379 assert(VA.isMemLoc());
1380 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1384 // The x86-64 ABI for returning structs by value requires that we copy
1385 // the sret argument into %rax for the return. Save the argument into
1386 // a virtual register so that we can access it from the return points.
1387 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1388 MachineFunction &MF = DAG.getMachineFunction();
1389 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1390 unsigned Reg = FuncInfo->getSRetReturnReg();
1392 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1393 FuncInfo->setSRetReturnReg(Reg);
1395 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1396 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1399 unsigned StackSize = CCInfo.getNextStackOffset();
1400 // align stack specially for tail calls
1401 if (PerformTailCallOpt && CC == CallingConv::Fast)
1402 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1404 // If the function takes variable number of arguments, make a frame index for
1405 // the start of the first vararg value... for expansion of llvm.va_start.
1407 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1408 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1411 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1413 // FIXME: We should really autogenerate these arrays
1414 static const unsigned GPR64ArgRegsWin64[] = {
1415 X86::RCX, X86::RDX, X86::R8, X86::R9
1417 static const unsigned XMMArgRegsWin64[] = {
1418 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1420 static const unsigned GPR64ArgRegs64Bit[] = {
1421 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1423 static const unsigned XMMArgRegs64Bit[] = {
1424 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1425 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1427 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1430 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1431 GPR64ArgRegs = GPR64ArgRegsWin64;
1432 XMMArgRegs = XMMArgRegsWin64;
1434 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1435 GPR64ArgRegs = GPR64ArgRegs64Bit;
1436 XMMArgRegs = XMMArgRegs64Bit;
1438 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1440 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1443 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1444 "SSE register cannot be used when SSE is disabled!");
1445 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloat) &&
1446 "SSE register cannot be used when SSE is disabled!");
1447 if (UseSoftFloat || NoImplicitFloat || !Subtarget->hasSSE1())
1448 // Kernel mode asks for SSE to be disabled, so don't push them
1450 TotalNumXMMRegs = 0;
1452 // For X86-64, if there are vararg parameters that are passed via
1453 // registers, then we must store them to their spots on the stack so they
1454 // may be loaded by deferencing the result of va_next.
1455 VarArgsGPOffset = NumIntRegs * 8;
1456 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1457 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1458 TotalNumXMMRegs * 16, 16);
1460 // Store the integer parameter registers.
1461 SmallVector<SDValue, 8> MemOps;
1462 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1463 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1464 DAG.getIntPtrConstant(VarArgsGPOffset));
1465 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1466 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1467 X86::GR64RegisterClass);
1468 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1470 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1471 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1472 MemOps.push_back(Store);
1473 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1474 DAG.getIntPtrConstant(8));
1477 // Now store the XMM (fp + vector) parameter registers.
1478 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1479 DAG.getIntPtrConstant(VarArgsFPOffset));
1480 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1481 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1482 X86::VR128RegisterClass);
1483 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1485 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1486 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1487 MemOps.push_back(Store);
1488 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1489 DAG.getIntPtrConstant(16));
1491 if (!MemOps.empty())
1492 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1493 &MemOps[0], MemOps.size());
1497 ArgValues.push_back(Root);
1499 // Some CCs need callee pop.
1500 if (IsCalleePop(isVarArg, CC)) {
1501 BytesToPopOnReturn = StackSize; // Callee pops everything.
1502 BytesCallerReserves = 0;
1504 BytesToPopOnReturn = 0; // Callee pops nothing.
1505 // If this is an sret function, the return should pop the hidden pointer.
1506 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1507 BytesToPopOnReturn = 4;
1508 BytesCallerReserves = StackSize;
1512 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1513 if (CC == CallingConv::X86_FastCall)
1514 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1517 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1519 // Return the new list of results.
1520 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1521 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1525 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1526 const SDValue &StackPtr,
1527 const CCValAssign &VA,
1529 SDValue Arg, ISD::ArgFlagsTy Flags) {
1530 DebugLoc dl = TheCall->getDebugLoc();
1531 unsigned LocMemOffset = VA.getLocMemOffset();
1532 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1533 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1534 if (Flags.isByVal()) {
1535 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1537 return DAG.getStore(Chain, dl, Arg, PtrOff,
1538 PseudoSourceValue::getStack(), LocMemOffset);
1541 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1542 /// optimization is performed and it is required.
1544 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1545 SDValue &OutRetAddr,
1551 if (!IsTailCall || FPDiff==0) return Chain;
1553 // Adjust the Return address stack slot.
1554 MVT VT = getPointerTy();
1555 OutRetAddr = getReturnAddressFrameIndex(DAG);
1557 // Load the "old" Return address.
1558 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1559 return SDValue(OutRetAddr.getNode(), 1);
1562 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1563 /// optimization is performed and it is required (FPDiff!=0).
1565 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1566 SDValue Chain, SDValue RetAddrFrIdx,
1567 bool Is64Bit, int FPDiff, DebugLoc dl) {
1568 // Store the return address to the appropriate stack slot.
1569 if (!FPDiff) return Chain;
1570 // Calculate the new stack slot for the return address.
1571 int SlotSize = Is64Bit ? 8 : 4;
1572 int NewReturnAddrFI =
1573 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1574 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1575 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1576 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1577 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1581 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1582 MachineFunction &MF = DAG.getMachineFunction();
1583 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1584 SDValue Chain = TheCall->getChain();
1585 unsigned CC = TheCall->getCallingConv();
1586 bool isVarArg = TheCall->isVarArg();
1587 bool IsTailCall = TheCall->isTailCall() &&
1588 CC == CallingConv::Fast && PerformTailCallOpt;
1589 SDValue Callee = TheCall->getCallee();
1590 bool Is64Bit = Subtarget->is64Bit();
1591 bool IsStructRet = CallIsStructReturn(TheCall);
1592 DebugLoc dl = TheCall->getDebugLoc();
1594 assert(!(isVarArg && CC == CallingConv::Fast) &&
1595 "Var args not supported with calling convention fastcc");
1597 // Analyze operands of the call, assigning locations to each operand.
1598 SmallVector<CCValAssign, 16> ArgLocs;
1599 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1600 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1602 // Get a count of how many bytes are to be pushed on the stack.
1603 unsigned NumBytes = CCInfo.getNextStackOffset();
1604 if (PerformTailCallOpt && CC == CallingConv::Fast)
1605 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1609 // Lower arguments at fp - stackoffset + fpdiff.
1610 unsigned NumBytesCallerPushed =
1611 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1612 FPDiff = NumBytesCallerPushed - NumBytes;
1614 // Set the delta of movement of the returnaddr stackslot.
1615 // But only set if delta is greater than previous delta.
1616 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1617 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1620 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1622 SDValue RetAddrFrIdx;
1623 // Load return adress for tail calls.
1624 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1627 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1628 SmallVector<SDValue, 8> MemOpChains;
1631 // Walk the register/memloc assignments, inserting copies/loads. In the case
1632 // of tail call optimization arguments are handle later.
1633 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1634 CCValAssign &VA = ArgLocs[i];
1635 SDValue Arg = TheCall->getArg(i);
1636 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1637 bool isByVal = Flags.isByVal();
1639 // Promote the value if needed.
1640 switch (VA.getLocInfo()) {
1641 default: assert(0 && "Unknown loc info!");
1642 case CCValAssign::Full: break;
1643 case CCValAssign::SExt:
1644 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1646 case CCValAssign::ZExt:
1647 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1649 case CCValAssign::AExt:
1650 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1654 if (VA.isRegLoc()) {
1656 MVT RegVT = VA.getLocVT();
1657 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1658 switch (VA.getLocReg()) {
1661 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1663 // Special case: passing MMX values in GPR registers.
1664 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1667 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1668 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1669 // Special case: passing MMX values in XMM registers.
1670 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1671 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1672 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1677 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1679 if (!IsTailCall || (IsTailCall && isByVal)) {
1680 assert(VA.isMemLoc());
1681 if (StackPtr.getNode() == 0)
1682 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1684 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1685 Chain, Arg, Flags));
1690 if (!MemOpChains.empty())
1691 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1692 &MemOpChains[0], MemOpChains.size());
1694 // Build a sequence of copy-to-reg nodes chained together with token chain
1695 // and flag operands which copy the outgoing args into registers.
1697 // Tail call byval lowering might overwrite argument registers so in case of
1698 // tail call optimization the copies to registers are lowered later.
1700 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1701 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1702 RegsToPass[i].second, InFlag);
1703 InFlag = Chain.getValue(1);
1706 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1708 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1709 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1710 DAG.getNode(X86ISD::GlobalBaseReg,
1711 DebugLoc::getUnknownLoc(),
1714 InFlag = Chain.getValue(1);
1716 // If we are tail calling and generating PIC/GOT style code load the address
1717 // of the callee into ecx. The value in ecx is used as target of the tail
1718 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1719 // calls on PIC/GOT architectures. Normally we would just put the address of
1720 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1721 // restored (since ebx is callee saved) before jumping to the target@PLT.
1722 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1723 // Note: The actual moving to ecx is done further down.
1724 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1725 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1726 !G->getGlobal()->hasProtectedVisibility())
1727 Callee = LowerGlobalAddress(Callee, DAG);
1728 else if (isa<ExternalSymbolSDNode>(Callee))
1729 Callee = LowerExternalSymbol(Callee,DAG);
1732 if (Is64Bit && isVarArg) {
1733 // From AMD64 ABI document:
1734 // For calls that may call functions that use varargs or stdargs
1735 // (prototype-less calls or calls to functions containing ellipsis (...) in
1736 // the declaration) %al is used as hidden argument to specify the number
1737 // of SSE registers used. The contents of %al do not need to match exactly
1738 // the number of registers, but must be an ubound on the number of SSE
1739 // registers used and is in the range 0 - 8 inclusive.
1741 // FIXME: Verify this on Win64
1742 // Count the number of XMM registers allocated.
1743 static const unsigned XMMArgRegs[] = {
1744 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1745 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1747 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1748 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1749 && "SSE registers cannot be used when SSE is disabled");
1751 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1752 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1753 InFlag = Chain.getValue(1);
1757 // For tail calls lower the arguments to the 'real' stack slot.
1759 SmallVector<SDValue, 8> MemOpChains2;
1762 // Do not flag preceeding copytoreg stuff together with the following stuff.
1764 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1765 CCValAssign &VA = ArgLocs[i];
1766 if (!VA.isRegLoc()) {
1767 assert(VA.isMemLoc());
1768 SDValue Arg = TheCall->getArg(i);
1769 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1770 // Create frame index.
1771 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1772 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1773 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1774 FIN = DAG.getFrameIndex(FI, getPointerTy());
1776 if (Flags.isByVal()) {
1777 // Copy relative to framepointer.
1778 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1779 if (StackPtr.getNode() == 0)
1780 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1782 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1784 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1787 // Store relative to framepointer.
1788 MemOpChains2.push_back(
1789 DAG.getStore(Chain, dl, Arg, FIN,
1790 PseudoSourceValue::getFixedStack(FI), 0));
1795 if (!MemOpChains2.empty())
1796 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1797 &MemOpChains2[0], MemOpChains2.size());
1799 // Copy arguments to their registers.
1800 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1801 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1802 RegsToPass[i].second, InFlag);
1803 InFlag = Chain.getValue(1);
1807 // Store the return address to the appropriate stack slot.
1808 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1812 // If the callee is a GlobalAddress node (quite common, every direct call is)
1813 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1814 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1815 // We should use extra load for direct calls to dllimported functions in
1817 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1818 getTargetMachine(), true))
1819 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1821 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1822 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1823 } else if (IsTailCall) {
1824 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1826 Chain = DAG.getCopyToReg(Chain, dl,
1827 DAG.getRegister(Opc, getPointerTy()),
1829 Callee = DAG.getRegister(Opc, getPointerTy());
1830 // Add register as live out.
1831 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1834 // Returns a chain & a flag for retval copy to use.
1835 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1836 SmallVector<SDValue, 8> Ops;
1839 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1840 DAG.getIntPtrConstant(0, true), InFlag);
1841 InFlag = Chain.getValue(1);
1843 // Returns a chain & a flag for retval copy to use.
1844 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1848 Ops.push_back(Chain);
1849 Ops.push_back(Callee);
1852 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1854 // Add argument registers to the end of the list so that they are known live
1856 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1857 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1858 RegsToPass[i].second.getValueType()));
1860 // Add an implicit use GOT pointer in EBX.
1861 if (!IsTailCall && !Is64Bit &&
1862 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1863 Subtarget->isPICStyleGOT())
1864 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1866 // Add an implicit use of AL for x86 vararg functions.
1867 if (Is64Bit && isVarArg)
1868 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1870 if (InFlag.getNode())
1871 Ops.push_back(InFlag);
1874 assert(InFlag.getNode() &&
1875 "Flag must be set. Depend on flag being set in LowerRET");
1876 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1877 TheCall->getVTList(), &Ops[0], Ops.size());
1879 return SDValue(Chain.getNode(), Op.getResNo());
1882 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1883 InFlag = Chain.getValue(1);
1885 // Create the CALLSEQ_END node.
1886 unsigned NumBytesForCalleeToPush;
1887 if (IsCalleePop(isVarArg, CC))
1888 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1889 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1890 // If this is is a call to a struct-return function, the callee
1891 // pops the hidden struct pointer, so we have to push it back.
1892 // This is common for Darwin/X86, Linux & Mingw32 targets.
1893 NumBytesForCalleeToPush = 4;
1895 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1897 // Returns a flag for retval copy to use.
1898 Chain = DAG.getCALLSEQ_END(Chain,
1899 DAG.getIntPtrConstant(NumBytes, true),
1900 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1903 InFlag = Chain.getValue(1);
1905 // Handle result values, copying them out of physregs into vregs that we
1907 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1912 //===----------------------------------------------------------------------===//
1913 // Fast Calling Convention (tail call) implementation
1914 //===----------------------------------------------------------------------===//
1916 // Like std call, callee cleans arguments, convention except that ECX is
1917 // reserved for storing the tail called function address. Only 2 registers are
1918 // free for argument passing (inreg). Tail call optimization is performed
1920 // * tailcallopt is enabled
1921 // * caller/callee are fastcc
1922 // On X86_64 architecture with GOT-style position independent code only local
1923 // (within module) calls are supported at the moment.
1924 // To keep the stack aligned according to platform abi the function
1925 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1926 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1927 // If a tail called function callee has more arguments than the caller the
1928 // caller needs to make sure that there is room to move the RETADDR to. This is
1929 // achieved by reserving an area the size of the argument delta right after the
1930 // original REtADDR, but before the saved framepointer or the spilled registers
1931 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1943 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1944 /// for a 16 byte align requirement.
1945 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1946 SelectionDAG& DAG) {
1947 MachineFunction &MF = DAG.getMachineFunction();
1948 const TargetMachine &TM = MF.getTarget();
1949 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1950 unsigned StackAlignment = TFI.getStackAlignment();
1951 uint64_t AlignMask = StackAlignment - 1;
1952 int64_t Offset = StackSize;
1953 uint64_t SlotSize = TD->getPointerSize();
1954 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1955 // Number smaller than 12 so just add the difference.
1956 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1958 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1959 Offset = ((~AlignMask) & Offset) + StackAlignment +
1960 (StackAlignment-SlotSize);
1965 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1966 /// following the call is a return. A function is eligible if caller/callee
1967 /// calling conventions match, currently only fastcc supports tail calls, and
1968 /// the function CALL is immediatly followed by a RET.
1969 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1971 SelectionDAG& DAG) const {
1972 if (!PerformTailCallOpt)
1975 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1976 MachineFunction &MF = DAG.getMachineFunction();
1977 unsigned CallerCC = MF.getFunction()->getCallingConv();
1978 unsigned CalleeCC= TheCall->getCallingConv();
1979 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1980 SDValue Callee = TheCall->getCallee();
1981 // On x86/32Bit PIC/GOT tail calls are supported.
1982 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1983 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1986 // Can only do local tail calls (in same module, hidden or protected) on
1987 // x86_64 PIC/GOT at the moment.
1988 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1989 return G->getGlobal()->hasHiddenVisibility()
1990 || G->getGlobal()->hasProtectedVisibility();
1998 X86TargetLowering::createFastISel(MachineFunction &mf,
1999 MachineModuleInfo *mmo,
2001 DenseMap<const Value *, unsigned> &vm,
2002 DenseMap<const BasicBlock *,
2003 MachineBasicBlock *> &bm,
2004 DenseMap<const AllocaInst *, int> &am
2006 , SmallSet<Instruction*, 8> &cil
2009 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2017 //===----------------------------------------------------------------------===//
2018 // Other Lowering Hooks
2019 //===----------------------------------------------------------------------===//
2022 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2023 MachineFunction &MF = DAG.getMachineFunction();
2024 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2025 int ReturnAddrIndex = FuncInfo->getRAIndex();
2027 if (ReturnAddrIndex == 0) {
2028 // Set up a frame object for the return address.
2029 uint64_t SlotSize = TD->getPointerSize();
2030 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2031 FuncInfo->setRAIndex(ReturnAddrIndex);
2034 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2038 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2039 /// specific condition code, returning the condition code and the LHS/RHS of the
2040 /// comparison to make.
2041 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2042 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2044 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2045 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2046 // X > -1 -> X == 0, jump !sign.
2047 RHS = DAG.getConstant(0, RHS.getValueType());
2048 return X86::COND_NS;
2049 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2050 // X < 0 -> X == 0, jump on sign.
2052 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2054 RHS = DAG.getConstant(0, RHS.getValueType());
2055 return X86::COND_LE;
2059 switch (SetCCOpcode) {
2060 default: assert(0 && "Invalid integer condition!");
2061 case ISD::SETEQ: return X86::COND_E;
2062 case ISD::SETGT: return X86::COND_G;
2063 case ISD::SETGE: return X86::COND_GE;
2064 case ISD::SETLT: return X86::COND_L;
2065 case ISD::SETLE: return X86::COND_LE;
2066 case ISD::SETNE: return X86::COND_NE;
2067 case ISD::SETULT: return X86::COND_B;
2068 case ISD::SETUGT: return X86::COND_A;
2069 case ISD::SETULE: return X86::COND_BE;
2070 case ISD::SETUGE: return X86::COND_AE;
2074 // First determine if it is required or is profitable to flip the operands.
2076 // If LHS is a foldable load, but RHS is not, flip the condition.
2077 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2078 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2079 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2080 std::swap(LHS, RHS);
2083 switch (SetCCOpcode) {
2089 std::swap(LHS, RHS);
2093 // On a floating point condition, the flags are set as follows:
2095 // 0 | 0 | 0 | X > Y
2096 // 0 | 0 | 1 | X < Y
2097 // 1 | 0 | 0 | X == Y
2098 // 1 | 1 | 1 | unordered
2099 switch (SetCCOpcode) {
2100 default: assert(0 && "Condcode should be pre-legalized away");
2102 case ISD::SETEQ: return X86::COND_E;
2103 case ISD::SETOLT: // flipped
2105 case ISD::SETGT: return X86::COND_A;
2106 case ISD::SETOLE: // flipped
2108 case ISD::SETGE: return X86::COND_AE;
2109 case ISD::SETUGT: // flipped
2111 case ISD::SETLT: return X86::COND_B;
2112 case ISD::SETUGE: // flipped
2114 case ISD::SETLE: return X86::COND_BE;
2116 case ISD::SETNE: return X86::COND_NE;
2117 case ISD::SETUO: return X86::COND_P;
2118 case ISD::SETO: return X86::COND_NP;
2122 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2123 /// code. Current x86 isa includes the following FP cmov instructions:
2124 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2125 static bool hasFPCMov(unsigned X86CC) {
2141 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2142 /// the specified range (L, H].
2143 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2144 return (Val < 0) || (Val >= Low && Val < Hi);
2147 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2148 /// specified value.
2149 static bool isUndefOrEqual(int Val, int CmpVal) {
2150 if (Val < 0 || Val == CmpVal)
2155 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2156 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2157 /// the second operand.
2158 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2159 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2160 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2161 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2162 return (Mask[0] < 2 && Mask[1] < 2);
2166 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2167 SmallVector<int, 8> M;
2169 return ::isPSHUFDMask(M, N->getValueType(0));
2172 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2173 /// is suitable for input to PSHUFHW.
2174 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2175 if (VT != MVT::v8i16)
2178 // Lower quadword copied in order or undef.
2179 for (int i = 0; i != 4; ++i)
2180 if (Mask[i] >= 0 && Mask[i] != i)
2183 // Upper quadword shuffled.
2184 for (int i = 4; i != 8; ++i)
2185 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2191 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2192 SmallVector<int, 8> M;
2194 return ::isPSHUFHWMask(M, N->getValueType(0));
2197 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2198 /// is suitable for input to PSHUFLW.
2199 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2200 if (VT != MVT::v8i16)
2203 // Upper quadword copied in order.
2204 for (int i = 4; i != 8; ++i)
2205 if (Mask[i] >= 0 && Mask[i] != i)
2208 // Lower quadword shuffled.
2209 for (int i = 0; i != 4; ++i)
2216 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2217 SmallVector<int, 8> M;
2219 return ::isPSHUFLWMask(M, N->getValueType(0));
2222 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2223 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2224 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2225 int NumElems = VT.getVectorNumElements();
2226 if (NumElems != 2 && NumElems != 4)
2229 int Half = NumElems / 2;
2230 for (int i = 0; i < Half; ++i)
2231 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2233 for (int i = Half; i < NumElems; ++i)
2234 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2240 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2241 SmallVector<int, 8> M;
2243 return ::isSHUFPMask(M, N->getValueType(0));
2246 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2247 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2248 /// half elements to come from vector 1 (which would equal the dest.) and
2249 /// the upper half to come from vector 2.
2250 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2251 int NumElems = VT.getVectorNumElements();
2253 if (NumElems != 2 && NumElems != 4)
2256 int Half = NumElems / 2;
2257 for (int i = 0; i < Half; ++i)
2258 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2260 for (int i = Half; i < NumElems; ++i)
2261 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2266 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2267 SmallVector<int, 8> M;
2269 return isCommutedSHUFPMask(M, N->getValueType(0));
2272 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2273 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2274 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2275 if (N->getValueType(0).getVectorNumElements() != 4)
2278 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2279 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2280 isUndefOrEqual(N->getMaskElt(1), 7) &&
2281 isUndefOrEqual(N->getMaskElt(2), 2) &&
2282 isUndefOrEqual(N->getMaskElt(3), 3);
2285 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2286 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2287 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2288 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2290 if (NumElems != 2 && NumElems != 4)
2293 for (unsigned i = 0; i < NumElems/2; ++i)
2294 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2297 for (unsigned i = NumElems/2; i < NumElems; ++i)
2298 if (!isUndefOrEqual(N->getMaskElt(i), i))
2304 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2305 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2307 bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2308 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2310 if (NumElems != 2 && NumElems != 4)
2313 for (unsigned i = 0; i < NumElems/2; ++i)
2314 if (!isUndefOrEqual(N->getMaskElt(i), i))
2317 for (unsigned i = 0; i < NumElems/2; ++i)
2318 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2324 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2325 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2327 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2328 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2333 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2334 isUndefOrEqual(N->getMaskElt(1), 3) &&
2335 isUndefOrEqual(N->getMaskElt(2), 2) &&
2336 isUndefOrEqual(N->getMaskElt(3), 3);
2339 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2340 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2341 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2342 bool V2IsSplat = false) {
2343 int NumElts = VT.getVectorNumElements();
2344 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2347 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2349 int BitI1 = Mask[i+1];
2350 if (!isUndefOrEqual(BitI, j))
2353 if (!isUndefOrEqual(BitI1, NumElts))
2356 if (!isUndefOrEqual(BitI1, j + NumElts))
2363 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2364 SmallVector<int, 8> M;
2366 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2369 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2370 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2371 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, MVT VT,
2372 bool V2IsSplat = false) {
2373 int NumElts = VT.getVectorNumElements();
2374 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2377 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2379 int BitI1 = Mask[i+1];
2380 if (!isUndefOrEqual(BitI, j + NumElts/2))
2383 if (isUndefOrEqual(BitI1, NumElts))
2386 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2393 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2394 SmallVector<int, 8> M;
2396 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2399 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2400 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2402 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2403 int NumElems = VT.getVectorNumElements();
2404 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2407 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2409 int BitI1 = Mask[i+1];
2410 if (!isUndefOrEqual(BitI, j))
2412 if (!isUndefOrEqual(BitI1, j))
2418 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2419 SmallVector<int, 8> M;
2421 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2424 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2425 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2427 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2428 int NumElems = VT.getVectorNumElements();
2429 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2432 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2434 int BitI1 = Mask[i+1];
2435 if (!isUndefOrEqual(BitI, j))
2437 if (!isUndefOrEqual(BitI1, j))
2443 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2444 SmallVector<int, 8> M;
2446 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2449 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2450 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2451 /// MOVSD, and MOVD, i.e. setting the lowest element.
2452 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2453 int NumElts = VT.getVectorNumElements();
2454 if (NumElts != 2 && NumElts != 4)
2457 if (!isUndefOrEqual(Mask[0], NumElts))
2460 for (int i = 1; i < NumElts; ++i)
2461 if (!isUndefOrEqual(Mask[i], i))
2467 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2468 SmallVector<int, 8> M;
2470 return ::isMOVLMask(M, N->getValueType(0));
2473 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2474 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2475 /// element of vector 2 and the other elements to come from vector 1 in order.
2476 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2477 bool V2IsSplat = false, bool V2IsUndef = false) {
2478 int NumOps = VT.getVectorNumElements();
2479 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2482 if (!isUndefOrEqual(Mask[0], 0))
2485 for (int i = 1; i < NumOps; ++i)
2486 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2487 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2488 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2494 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2495 bool V2IsUndef = false) {
2496 SmallVector<int, 8> M;
2498 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2501 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2502 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2503 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2504 if (N->getValueType(0).getVectorNumElements() != 4)
2507 // Expect 1, 1, 3, 3
2508 for (unsigned i = 0; i < 2; ++i) {
2509 int Elt = N->getMaskElt(i);
2510 if (Elt >= 0 && Elt != 1)
2515 for (unsigned i = 2; i < 4; ++i) {
2516 int Elt = N->getMaskElt(i);
2517 if (Elt >= 0 && Elt != 3)
2522 // Don't use movshdup if it can be done with a shufps.
2523 // FIXME: verify that matching u, u, 3, 3 is what we want.
2527 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2528 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2529 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2530 if (N->getValueType(0).getVectorNumElements() != 4)
2533 // Expect 0, 0, 2, 2
2534 for (unsigned i = 0; i < 2; ++i)
2535 if (N->getMaskElt(i) > 0)
2539 for (unsigned i = 2; i < 4; ++i) {
2540 int Elt = N->getMaskElt(i);
2541 if (Elt >= 0 && Elt != 2)
2546 // Don't use movsldup if it can be done with a shufps.
2550 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2551 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2552 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2553 int e = N->getValueType(0).getVectorNumElements() / 2;
2555 for (int i = 0; i < e; ++i)
2556 if (!isUndefOrEqual(N->getMaskElt(i), i))
2558 for (int i = 0; i < e; ++i)
2559 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2564 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2565 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2567 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2568 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2569 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2571 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2573 for (int i = 0; i < NumOperands; ++i) {
2574 int Val = SVOp->getMaskElt(NumOperands-i-1);
2575 if (Val < 0) Val = 0;
2576 if (Val >= NumOperands) Val -= NumOperands;
2578 if (i != NumOperands - 1)
2584 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2585 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2587 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2588 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2590 // 8 nodes, but we only care about the last 4.
2591 for (unsigned i = 7; i >= 4; --i) {
2592 int Val = SVOp->getMaskElt(i);
2601 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2602 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2604 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2605 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2607 // 8 nodes, but we only care about the first 4.
2608 for (int i = 3; i >= 0; --i) {
2609 int Val = SVOp->getMaskElt(i);
2618 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2619 /// their permute mask.
2620 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2621 SelectionDAG &DAG) {
2622 MVT VT = SVOp->getValueType(0);
2623 unsigned NumElems = VT.getVectorNumElements();
2624 SmallVector<int, 8> MaskVec;
2626 for (unsigned i = 0; i != NumElems; ++i) {
2627 int idx = SVOp->getMaskElt(i);
2629 MaskVec.push_back(idx);
2630 else if (idx < (int)NumElems)
2631 MaskVec.push_back(idx + NumElems);
2633 MaskVec.push_back(idx - NumElems);
2635 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2636 SVOp->getOperand(0), &MaskVec[0]);
2639 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2640 /// the two vector operands have swapped position.
2641 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, MVT VT) {
2642 unsigned NumElems = VT.getVectorNumElements();
2643 for (unsigned i = 0; i != NumElems; ++i) {
2647 else if (idx < (int)NumElems)
2648 Mask[i] = idx + NumElems;
2650 Mask[i] = idx - NumElems;
2654 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2655 /// match movhlps. The lower half elements should come from upper half of
2656 /// V1 (and in order), and the upper half elements should come from the upper
2657 /// half of V2 (and in order).
2658 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2659 if (Op->getValueType(0).getVectorNumElements() != 4)
2661 for (unsigned i = 0, e = 2; i != e; ++i)
2662 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2664 for (unsigned i = 2; i != 4; ++i)
2665 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2670 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2671 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2673 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2674 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2676 N = N->getOperand(0).getNode();
2677 if (!ISD::isNON_EXTLoad(N))
2680 *LD = cast<LoadSDNode>(N);
2684 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2685 /// match movlp{s|d}. The lower half elements should come from lower half of
2686 /// V1 (and in order), and the upper half elements should come from the upper
2687 /// half of V2 (and in order). And since V1 will become the source of the
2688 /// MOVLP, it must be either a vector load or a scalar load to vector.
2689 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2690 ShuffleVectorSDNode *Op) {
2691 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2693 // Is V2 is a vector load, don't do this transformation. We will try to use
2694 // load folding shufps op.
2695 if (ISD::isNON_EXTLoad(V2))
2698 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2700 if (NumElems != 2 && NumElems != 4)
2702 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2703 if (!isUndefOrEqual(Op->getMaskElt(i), i))
2705 for (unsigned i = NumElems/2; i != NumElems; ++i)
2706 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2711 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2713 static bool isSplatVector(SDNode *N) {
2714 if (N->getOpcode() != ISD::BUILD_VECTOR)
2717 SDValue SplatValue = N->getOperand(0);
2718 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2719 if (N->getOperand(i) != SplatValue)
2724 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2726 static inline bool isZeroNode(SDValue Elt) {
2727 return ((isa<ConstantSDNode>(Elt) &&
2728 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2729 (isa<ConstantFPSDNode>(Elt) &&
2730 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2733 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2734 /// to an zero vector.
2735 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2736 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2737 SDValue V1 = N->getOperand(0);
2738 SDValue V2 = N->getOperand(1);
2739 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2740 for (unsigned i = 0; i != NumElems; ++i) {
2741 int Idx = N->getMaskElt(i);
2742 if (Idx >= (int)NumElems) {
2743 unsigned Opc = V2.getOpcode();
2744 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2746 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V2.getOperand(Idx-NumElems)))
2748 } else if (Idx >= 0) {
2749 unsigned Opc = V1.getOpcode();
2750 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2752 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V1.getOperand(Idx)))
2759 /// getZeroVector - Returns a vector of specified type with all zero elements.
2761 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2763 assert(VT.isVector() && "Expected a vector type");
2765 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2766 // type. This ensures they get CSE'd.
2768 if (VT.getSizeInBits() == 64) { // MMX
2769 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2770 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2771 } else if (HasSSE2) { // SSE2
2772 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2773 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2775 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2776 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2778 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2781 /// getOnesVector - Returns a vector of specified type with all bits set.
2783 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2784 assert(VT.isVector() && "Expected a vector type");
2786 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2787 // type. This ensures they get CSE'd.
2788 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2790 if (VT.getSizeInBits() == 64) // MMX
2791 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2793 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2794 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2798 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2799 /// that point to V2 points to its first element.
2800 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2801 MVT VT = SVOp->getValueType(0);
2802 unsigned NumElems = VT.getVectorNumElements();
2804 bool Changed = false;
2805 SmallVector<int, 8> MaskVec;
2806 SVOp->getMask(MaskVec);
2808 for (unsigned i = 0; i != NumElems; ++i) {
2809 if (MaskVec[i] > (int)NumElems) {
2810 MaskVec[i] = NumElems;
2815 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
2816 SVOp->getOperand(1), &MaskVec[0]);
2817 return SDValue(SVOp, 0);
2820 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2821 /// operation of specified width.
2822 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2824 unsigned NumElems = VT.getVectorNumElements();
2825 SmallVector<int, 8> Mask;
2826 Mask.push_back(NumElems);
2827 for (unsigned i = 1; i != NumElems; ++i)
2829 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2832 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
2833 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2835 unsigned NumElems = VT.getVectorNumElements();
2836 SmallVector<int, 8> Mask;
2837 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2839 Mask.push_back(i + NumElems);
2841 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2844 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
2845 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2847 unsigned NumElems = VT.getVectorNumElements();
2848 unsigned Half = NumElems/2;
2849 SmallVector<int, 8> Mask;
2850 for (unsigned i = 0; i != Half; ++i) {
2851 Mask.push_back(i + Half);
2852 Mask.push_back(i + NumElems + Half);
2854 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2857 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2858 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
2860 if (SV->getValueType(0).getVectorNumElements() <= 4)
2861 return SDValue(SV, 0);
2863 MVT PVT = MVT::v4f32;
2864 MVT VT = SV->getValueType(0);
2865 DebugLoc dl = SV->getDebugLoc();
2866 SDValue V1 = SV->getOperand(0);
2867 int NumElems = VT.getVectorNumElements();
2868 int EltNo = SV->getSplatIndex();
2870 // unpack elements to the correct location
2871 while (NumElems > 4) {
2872 if (EltNo < NumElems/2) {
2873 V1 = getUnpackl(DAG, dl, VT, V1, V1);
2875 V1 = getUnpackh(DAG, dl, VT, V1, V1);
2876 EltNo -= NumElems/2;
2881 // Perform the splat.
2882 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
2883 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
2884 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
2885 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
2888 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2889 /// vector of zero or undef vector. This produces a shuffle where the low
2890 /// element of V2 is swizzled into the zero/undef vector, landing at element
2891 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2892 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2893 bool isZero, bool HasSSE2,
2894 SelectionDAG &DAG) {
2895 MVT VT = V2.getValueType();
2897 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
2898 unsigned NumElems = VT.getVectorNumElements();
2899 SmallVector<int, 16> MaskVec;
2900 for (unsigned i = 0; i != NumElems; ++i)
2901 // If this is the insertion idx, put the low elt of V2 here.
2902 MaskVec.push_back(i == Idx ? NumElems : i);
2903 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
2906 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2907 /// a shuffle that is zero.
2909 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
2910 bool Low, SelectionDAG &DAG) {
2911 unsigned NumZeros = 0;
2912 for (int i = 0; i < NumElems; ++i) {
2913 unsigned Index = Low ? i : NumElems-i-1;
2914 int Idx = SVOp->getMaskElt(Index);
2919 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
2920 if (Elt.getNode() && isZeroNode(Elt))
2928 /// isVectorShift - Returns true if the shuffle can be implemented as a
2929 /// logical left or right shift of a vector.
2930 /// FIXME: split into pslldqi, psrldqi, palignr variants.
2931 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
2932 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
2933 int NumElems = SVOp->getValueType(0).getVectorNumElements();
2936 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
2939 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
2943 bool SeenV1 = false;
2944 bool SeenV2 = false;
2945 for (int i = NumZeros; i < NumElems; ++i) {
2946 int Val = isLeft ? (i - NumZeros) : i;
2947 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
2959 if (SeenV1 && SeenV2)
2962 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
2968 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2970 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
2971 unsigned NumNonZero, unsigned NumZero,
2972 SelectionDAG &DAG, TargetLowering &TLI) {
2976 DebugLoc dl = Op.getDebugLoc();
2979 for (unsigned i = 0; i < 16; ++i) {
2980 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2981 if (ThisIsNonZero && First) {
2983 V = getZeroVector(MVT::v8i16, true, DAG, dl);
2985 V = DAG.getUNDEF(MVT::v8i16);
2990 SDValue ThisElt(0, 0), LastElt(0, 0);
2991 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2992 if (LastIsNonZero) {
2993 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
2994 MVT::i16, Op.getOperand(i-1));
2996 if (ThisIsNonZero) {
2997 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
2998 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
2999 ThisElt, DAG.getConstant(8, MVT::i8));
3001 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3005 if (ThisElt.getNode())
3006 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3007 DAG.getIntPtrConstant(i/2));
3011 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3014 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3016 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3017 unsigned NumNonZero, unsigned NumZero,
3018 SelectionDAG &DAG, TargetLowering &TLI) {
3022 DebugLoc dl = Op.getDebugLoc();
3025 for (unsigned i = 0; i < 8; ++i) {
3026 bool isNonZero = (NonZeros & (1 << i)) != 0;
3030 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3032 V = DAG.getUNDEF(MVT::v8i16);
3035 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3036 MVT::v8i16, V, Op.getOperand(i),
3037 DAG.getIntPtrConstant(i));
3044 /// getVShift - Return a vector logical shift node.
3046 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3047 unsigned NumBits, SelectionDAG &DAG,
3048 const TargetLowering &TLI, DebugLoc dl) {
3049 bool isMMX = VT.getSizeInBits() == 64;
3050 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3051 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3052 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3053 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3054 DAG.getNode(Opc, dl, ShVT, SrcOp,
3055 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3059 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3060 DebugLoc dl = Op.getDebugLoc();
3061 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3062 if (ISD::isBuildVectorAllZeros(Op.getNode())
3063 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3064 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3065 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3066 // eliminated on x86-32 hosts.
3067 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3070 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3071 return getOnesVector(Op.getValueType(), DAG, dl);
3072 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3075 MVT VT = Op.getValueType();
3076 MVT EVT = VT.getVectorElementType();
3077 unsigned EVTBits = EVT.getSizeInBits();
3079 unsigned NumElems = Op.getNumOperands();
3080 unsigned NumZero = 0;
3081 unsigned NumNonZero = 0;
3082 unsigned NonZeros = 0;
3083 bool IsAllConstants = true;
3084 SmallSet<SDValue, 8> Values;
3085 for (unsigned i = 0; i < NumElems; ++i) {
3086 SDValue Elt = Op.getOperand(i);
3087 if (Elt.getOpcode() == ISD::UNDEF)
3090 if (Elt.getOpcode() != ISD::Constant &&
3091 Elt.getOpcode() != ISD::ConstantFP)
3092 IsAllConstants = false;
3093 if (isZeroNode(Elt))
3096 NonZeros |= (1 << i);
3101 if (NumNonZero == 0) {
3102 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3103 return DAG.getUNDEF(VT);
3106 // Special case for single non-zero, non-undef, element.
3107 if (NumNonZero == 1 && NumElems <= 4) {
3108 unsigned Idx = CountTrailingZeros_32(NonZeros);
3109 SDValue Item = Op.getOperand(Idx);
3111 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3112 // the value are obviously zero, truncate the value to i32 and do the
3113 // insertion that way. Only do this if the value is non-constant or if the
3114 // value is a constant being inserted into element 0. It is cheaper to do
3115 // a constant pool load than it is to do a movd + shuffle.
3116 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3117 (!IsAllConstants || Idx == 0)) {
3118 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3119 // Handle MMX and SSE both.
3120 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3121 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3123 // Truncate the value (which may itself be a constant) to i32, and
3124 // convert it to a vector with movd (S2V+shuffle to zero extend).
3125 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3126 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3127 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3128 Subtarget->hasSSE2(), DAG);
3130 // Now we have our 32-bit value zero extended in the low element of
3131 // a vector. If Idx != 0, swizzle it into place.
3133 SmallVector<int, 4> Mask;
3134 Mask.push_back(Idx);
3135 for (unsigned i = 1; i != VecElts; ++i)
3137 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3138 DAG.getUNDEF(Item.getValueType()),
3141 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3145 // If we have a constant or non-constant insertion into the low element of
3146 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3147 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3148 // depending on what the source datatype is. Because we can only get here
3149 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3151 // Don't do this for i64 values on x86-32.
3152 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3153 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3154 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3155 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3156 Subtarget->hasSSE2(), DAG);
3159 // Is it a vector logical left shift?
3160 if (NumElems == 2 && Idx == 1 &&
3161 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3162 unsigned NumBits = VT.getSizeInBits();
3163 return getVShift(true, VT,
3164 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3165 VT, Op.getOperand(1)),
3166 NumBits/2, DAG, *this, dl);
3169 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3172 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3173 // is a non-constant being inserted into an element other than the low one,
3174 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3175 // movd/movss) to move this into the low element, then shuffle it into
3177 if (EVTBits == 32) {
3178 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3180 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3181 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3182 Subtarget->hasSSE2(), DAG);
3183 SmallVector<int, 8> MaskVec;
3184 for (unsigned i = 0; i < NumElems; i++)
3185 MaskVec.push_back(i == Idx ? 0 : 1);
3186 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3190 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3191 if (Values.size() == 1)
3194 // A vector full of immediates; various special cases are already
3195 // handled, so this is best done with a single constant-pool load.
3199 // Let legalizer expand 2-wide build_vectors.
3200 if (EVTBits == 64) {
3201 if (NumNonZero == 1) {
3202 // One half is zero or undef.
3203 unsigned Idx = CountTrailingZeros_32(NonZeros);
3204 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3205 Op.getOperand(Idx));
3206 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3207 Subtarget->hasSSE2(), DAG);
3212 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3213 if (EVTBits == 8 && NumElems == 16) {
3214 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3216 if (V.getNode()) return V;
3219 if (EVTBits == 16 && NumElems == 8) {
3220 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3222 if (V.getNode()) return V;
3225 // If element VT is == 32 bits, turn it into a number of shuffles.
3226 SmallVector<SDValue, 8> V;
3228 if (NumElems == 4 && NumZero > 0) {
3229 for (unsigned i = 0; i < 4; ++i) {
3230 bool isZero = !(NonZeros & (1 << i));
3232 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3234 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3237 for (unsigned i = 0; i < 2; ++i) {
3238 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3241 V[i] = V[i*2]; // Must be a zero vector.
3244 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3247 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3250 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3255 SmallVector<int, 8> MaskVec;
3256 bool Reverse = (NonZeros & 0x3) == 2;
3257 for (unsigned i = 0; i < 2; ++i)
3258 MaskVec.push_back(Reverse ? 1-i : i);
3259 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3260 for (unsigned i = 0; i < 2; ++i)
3261 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3262 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3265 if (Values.size() > 2) {
3266 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3267 // values to be inserted is equal to the number of elements, in which case
3268 // use the unpack code below in the hopes of matching the consecutive elts
3269 // load merge pattern for shuffles.
3270 // FIXME: We could probably just check that here directly.
3271 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3272 getSubtarget()->hasSSE41()) {
3273 V[0] = DAG.getUNDEF(VT);
3274 for (unsigned i = 0; i < NumElems; ++i)
3275 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3276 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3277 Op.getOperand(i), DAG.getIntPtrConstant(i));
3280 // Expand into a number of unpckl*.
3282 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3283 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3284 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3285 for (unsigned i = 0; i < NumElems; ++i)
3286 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3288 while (NumElems != 0) {
3289 for (unsigned i = 0; i < NumElems; ++i)
3290 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3299 // v8i16 shuffles - Prefer shuffles in the following order:
3300 // 1. [all] pshuflw, pshufhw, optional move
3301 // 2. [ssse3] 1 x pshufb
3302 // 3. [ssse3] 2 x pshufb + 1 x por
3303 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3305 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3306 SelectionDAG &DAG, X86TargetLowering &TLI) {
3307 SDValue V1 = SVOp->getOperand(0);
3308 SDValue V2 = SVOp->getOperand(1);
3309 DebugLoc dl = SVOp->getDebugLoc();
3310 SmallVector<int, 8> MaskVals;
3312 // Determine if more than 1 of the words in each of the low and high quadwords
3313 // of the result come from the same quadword of one of the two inputs. Undef
3314 // mask values count as coming from any quadword, for better codegen.
3315 SmallVector<unsigned, 4> LoQuad(4);
3316 SmallVector<unsigned, 4> HiQuad(4);
3317 BitVector InputQuads(4);
3318 for (unsigned i = 0; i < 8; ++i) {
3319 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3320 int EltIdx = SVOp->getMaskElt(i);
3321 MaskVals.push_back(EltIdx);
3330 InputQuads.set(EltIdx / 4);
3333 int BestLoQuad = -1;
3334 unsigned MaxQuad = 1;
3335 for (unsigned i = 0; i < 4; ++i) {
3336 if (LoQuad[i] > MaxQuad) {
3338 MaxQuad = LoQuad[i];
3342 int BestHiQuad = -1;
3344 for (unsigned i = 0; i < 4; ++i) {
3345 if (HiQuad[i] > MaxQuad) {
3347 MaxQuad = HiQuad[i];
3351 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3352 // of the two input vectors, shuffle them into one input vector so only a
3353 // single pshufb instruction is necessary. If There are more than 2 input
3354 // quads, disable the next transformation since it does not help SSSE3.
3355 bool V1Used = InputQuads[0] || InputQuads[1];
3356 bool V2Used = InputQuads[2] || InputQuads[3];
3357 if (TLI.getSubtarget()->hasSSSE3()) {
3358 if (InputQuads.count() == 2 && V1Used && V2Used) {
3359 BestLoQuad = InputQuads.find_first();
3360 BestHiQuad = InputQuads.find_next(BestLoQuad);
3362 if (InputQuads.count() > 2) {
3368 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3369 // the shuffle mask. If a quad is scored as -1, that means that it contains
3370 // words from all 4 input quadwords.
3372 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3373 SmallVector<int, 8> MaskV;
3374 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3375 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3376 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3377 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3378 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3379 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3381 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3382 // source words for the shuffle, to aid later transformations.
3383 bool AllWordsInNewV = true;
3384 bool InOrder[2] = { true, true };
3385 for (unsigned i = 0; i != 8; ++i) {
3386 int idx = MaskVals[i];
3388 InOrder[i/4] = false;
3389 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3391 AllWordsInNewV = false;
3395 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3396 if (AllWordsInNewV) {
3397 for (int i = 0; i != 8; ++i) {
3398 int idx = MaskVals[i];
3401 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3402 if ((idx != i) && idx < 4)
3404 if ((idx != i) && idx > 3)
3413 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3414 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3415 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3416 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3417 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3421 // If we have SSSE3, and all words of the result are from 1 input vector,
3422 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3423 // is present, fall back to case 4.
3424 if (TLI.getSubtarget()->hasSSSE3()) {
3425 SmallVector<SDValue,16> pshufbMask;
3427 // If we have elements from both input vectors, set the high bit of the
3428 // shuffle mask element to zero out elements that come from V2 in the V1
3429 // mask, and elements that come from V1 in the V2 mask, so that the two
3430 // results can be OR'd together.
3431 bool TwoInputs = V1Used && V2Used;
3432 for (unsigned i = 0; i != 8; ++i) {
3433 int EltIdx = MaskVals[i] * 2;
3434 if (TwoInputs && (EltIdx >= 16)) {
3435 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3436 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3439 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3440 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3442 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3443 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3444 DAG.getNode(ISD::BUILD_VECTOR, dl,
3445 MVT::v16i8, &pshufbMask[0], 16));
3447 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3449 // Calculate the shuffle mask for the second input, shuffle it, and
3450 // OR it with the first shuffled input.
3452 for (unsigned i = 0; i != 8; ++i) {
3453 int EltIdx = MaskVals[i] * 2;
3455 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3456 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3459 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3460 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3462 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3463 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3464 DAG.getNode(ISD::BUILD_VECTOR, dl,
3465 MVT::v16i8, &pshufbMask[0], 16));
3466 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3467 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3470 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3471 // and update MaskVals with new element order.
3472 BitVector InOrder(8);
3473 if (BestLoQuad >= 0) {
3474 SmallVector<int, 8> MaskV;
3475 for (int i = 0; i != 4; ++i) {
3476 int idx = MaskVals[i];
3478 MaskV.push_back(-1);
3480 } else if ((idx / 4) == BestLoQuad) {
3481 MaskV.push_back(idx & 3);
3484 MaskV.push_back(-1);
3487 for (unsigned i = 4; i != 8; ++i)
3489 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3493 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3494 // and update MaskVals with the new element order.
3495 if (BestHiQuad >= 0) {
3496 SmallVector<int, 8> MaskV;
3497 for (unsigned i = 0; i != 4; ++i)
3499 for (unsigned i = 4; i != 8; ++i) {
3500 int idx = MaskVals[i];
3502 MaskV.push_back(-1);
3504 } else if ((idx / 4) == BestHiQuad) {
3505 MaskV.push_back((idx & 3) + 4);
3508 MaskV.push_back(-1);
3511 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3515 // In case BestHi & BestLo were both -1, which means each quadword has a word
3516 // from each of the four input quadwords, calculate the InOrder bitvector now
3517 // before falling through to the insert/extract cleanup.
3518 if (BestLoQuad == -1 && BestHiQuad == -1) {
3520 for (int i = 0; i != 8; ++i)
3521 if (MaskVals[i] < 0 || MaskVals[i] == i)
3525 // The other elements are put in the right place using pextrw and pinsrw.
3526 for (unsigned i = 0; i != 8; ++i) {
3529 int EltIdx = MaskVals[i];
3532 SDValue ExtOp = (EltIdx < 8)
3533 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3534 DAG.getIntPtrConstant(EltIdx))
3535 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3536 DAG.getIntPtrConstant(EltIdx - 8));
3537 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3538 DAG.getIntPtrConstant(i));
3543 // v16i8 shuffles - Prefer shuffles in the following order:
3544 // 1. [ssse3] 1 x pshufb
3545 // 2. [ssse3] 2 x pshufb + 1 x por
3546 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3548 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3549 SelectionDAG &DAG, X86TargetLowering &TLI) {
3550 SDValue V1 = SVOp->getOperand(0);
3551 SDValue V2 = SVOp->getOperand(1);
3552 DebugLoc dl = SVOp->getDebugLoc();
3553 SmallVector<int, 16> MaskVals;
3554 SVOp->getMask(MaskVals);
3556 // If we have SSSE3, case 1 is generated when all result bytes come from
3557 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3558 // present, fall back to case 3.
3559 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3562 for (unsigned i = 0; i < 16; ++i) {
3563 int EltIdx = MaskVals[i];
3572 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3573 if (TLI.getSubtarget()->hasSSSE3()) {
3574 SmallVector<SDValue,16> pshufbMask;
3576 // If all result elements are from one input vector, then only translate
3577 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3579 // Otherwise, we have elements from both input vectors, and must zero out
3580 // elements that come from V2 in the first mask, and V1 in the second mask
3581 // so that we can OR them together.
3582 bool TwoInputs = !(V1Only || V2Only);
3583 for (unsigned i = 0; i != 16; ++i) {
3584 int EltIdx = MaskVals[i];
3585 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3586 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3589 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3591 // If all the elements are from V2, assign it to V1 and return after
3592 // building the first pshufb.
3595 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3596 DAG.getNode(ISD::BUILD_VECTOR, dl,
3597 MVT::v16i8, &pshufbMask[0], 16));
3601 // Calculate the shuffle mask for the second input, shuffle it, and
3602 // OR it with the first shuffled input.
3604 for (unsigned i = 0; i != 16; ++i) {
3605 int EltIdx = MaskVals[i];
3607 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3610 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3612 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3613 DAG.getNode(ISD::BUILD_VECTOR, dl,
3614 MVT::v16i8, &pshufbMask[0], 16));
3615 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3618 // No SSSE3 - Calculate in place words and then fix all out of place words
3619 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3620 // the 16 different words that comprise the two doublequadword input vectors.
3621 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3622 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3623 SDValue NewV = V2Only ? V2 : V1;
3624 for (int i = 0; i != 8; ++i) {
3625 int Elt0 = MaskVals[i*2];
3626 int Elt1 = MaskVals[i*2+1];
3628 // This word of the result is all undef, skip it.
3629 if (Elt0 < 0 && Elt1 < 0)
3632 // This word of the result is already in the correct place, skip it.
3633 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3635 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3638 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3639 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3642 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3643 // using a single extract together, load it and store it.
3644 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3645 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3646 DAG.getIntPtrConstant(Elt1 / 2));
3647 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3648 DAG.getIntPtrConstant(i));
3652 // If Elt1 is defined, extract it from the appropriate source. If the
3653 // source byte is not also odd, shift the extracted word left 8 bits
3654 // otherwise clear the bottom 8 bits if we need to do an or.
3656 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3657 DAG.getIntPtrConstant(Elt1 / 2));
3658 if ((Elt1 & 1) == 0)
3659 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3660 DAG.getConstant(8, TLI.getShiftAmountTy()));
3662 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3663 DAG.getConstant(0xFF00, MVT::i16));
3665 // If Elt0 is defined, extract it from the appropriate source. If the
3666 // source byte is not also even, shift the extracted word right 8 bits. If
3667 // Elt1 was also defined, OR the extracted values together before
3668 // inserting them in the result.
3670 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3671 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3672 if ((Elt0 & 1) != 0)
3673 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3674 DAG.getConstant(8, TLI.getShiftAmountTy()));
3676 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3677 DAG.getConstant(0x00FF, MVT::i16));
3678 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3681 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3682 DAG.getIntPtrConstant(i));
3684 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3687 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3688 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3689 /// done when every pair / quad of shuffle mask elements point to elements in
3690 /// the right sequence. e.g.
3691 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3693 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3695 TargetLowering &TLI, DebugLoc dl) {
3696 MVT VT = SVOp->getValueType(0);
3697 SDValue V1 = SVOp->getOperand(0);
3698 SDValue V2 = SVOp->getOperand(1);
3699 unsigned NumElems = VT.getVectorNumElements();
3700 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3701 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3702 MVT MaskEltVT = MaskVT.getVectorElementType();
3704 switch (VT.getSimpleVT()) {
3705 default: assert(false && "Unexpected!");
3706 case MVT::v4f32: NewVT = MVT::v2f64; break;
3707 case MVT::v4i32: NewVT = MVT::v2i64; break;
3708 case MVT::v8i16: NewVT = MVT::v4i32; break;
3709 case MVT::v16i8: NewVT = MVT::v4i32; break;
3712 if (NewWidth == 2) {
3718 int Scale = NumElems / NewWidth;
3719 SmallVector<int, 8> MaskVec;
3720 for (unsigned i = 0; i < NumElems; i += Scale) {
3722 for (int j = 0; j < Scale; ++j) {
3723 int EltIdx = SVOp->getMaskElt(i+j);
3727 StartIdx = EltIdx - (EltIdx % Scale);
3728 if (EltIdx != StartIdx + j)
3732 MaskVec.push_back(-1);
3734 MaskVec.push_back(StartIdx / Scale);
3737 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3738 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3739 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3742 /// getVZextMovL - Return a zero-extending vector move low node.
3744 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3745 SDValue SrcOp, SelectionDAG &DAG,
3746 const X86Subtarget *Subtarget, DebugLoc dl) {
3747 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3748 LoadSDNode *LD = NULL;
3749 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3750 LD = dyn_cast<LoadSDNode>(SrcOp);
3752 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3754 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3755 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3756 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3757 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3758 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3760 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3761 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3762 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3763 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3771 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3772 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3773 DAG.getNode(ISD::BIT_CONVERT, dl,
3777 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3780 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3781 SDValue V1 = SVOp->getOperand(0);
3782 SDValue V2 = SVOp->getOperand(1);
3783 DebugLoc dl = SVOp->getDebugLoc();
3784 MVT VT = SVOp->getValueType(0);
3786 SmallVector<std::pair<int, int>, 8> Locs;
3788 SmallVector<int, 8> Mask1(4U, -1);
3789 SmallVector<int, 8> PermMask;
3790 SVOp->getMask(PermMask);
3794 for (unsigned i = 0; i != 4; ++i) {
3795 int Idx = PermMask[i];
3797 Locs[i] = std::make_pair(-1, -1);
3799 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3801 Locs[i] = std::make_pair(0, NumLo);
3805 Locs[i] = std::make_pair(1, NumHi);
3807 Mask1[2+NumHi] = Idx;
3813 if (NumLo <= 2 && NumHi <= 2) {
3814 // If no more than two elements come from either vector. This can be
3815 // implemented with two shuffles. First shuffle gather the elements.
3816 // The second shuffle, which takes the first shuffle as both of its
3817 // vector operands, put the elements into the right order.
3818 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3820 SmallVector<int, 8> Mask2(4U, -1);
3822 for (unsigned i = 0; i != 4; ++i) {
3823 if (Locs[i].first == -1)
3826 unsigned Idx = (i < 2) ? 0 : 4;
3827 Idx += Locs[i].first * 2 + Locs[i].second;
3832 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
3833 } else if (NumLo == 3 || NumHi == 3) {
3834 // Otherwise, we must have three elements from one vector, call it X, and
3835 // one element from the other, call it Y. First, use a shufps to build an
3836 // intermediate vector with the one element from Y and the element from X
3837 // that will be in the same half in the final destination (the indexes don't
3838 // matter). Then, use a shufps to build the final vector, taking the half
3839 // containing the element from Y from the intermediate, and the other half
3842 // Normalize it so the 3 elements come from V1.
3843 CommuteVectorShuffleMask(PermMask, VT);
3847 // Find the element from V2.
3849 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3850 int Val = PermMask[HiIndex];
3857 Mask1[0] = PermMask[HiIndex];
3859 Mask1[2] = PermMask[HiIndex^1];
3861 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3864 Mask1[0] = PermMask[0];
3865 Mask1[1] = PermMask[1];
3866 Mask1[2] = HiIndex & 1 ? 6 : 4;
3867 Mask1[3] = HiIndex & 1 ? 4 : 6;
3868 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3870 Mask1[0] = HiIndex & 1 ? 2 : 0;
3871 Mask1[1] = HiIndex & 1 ? 0 : 2;
3872 Mask1[2] = PermMask[2];
3873 Mask1[3] = PermMask[3];
3878 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
3882 // Break it into (shuffle shuffle_hi, shuffle_lo).
3884 SmallVector<int,8> LoMask(4U, -1);
3885 SmallVector<int,8> HiMask(4U, -1);
3887 SmallVector<int,8> *MaskPtr = &LoMask;
3888 unsigned MaskIdx = 0;
3891 for (unsigned i = 0; i != 4; ++i) {
3898 int Idx = PermMask[i];
3900 Locs[i] = std::make_pair(-1, -1);
3901 } else if (Idx < 4) {
3902 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3903 (*MaskPtr)[LoIdx] = Idx;
3906 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3907 (*MaskPtr)[HiIdx] = Idx;
3912 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
3913 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
3914 SmallVector<int, 8> MaskOps;
3915 for (unsigned i = 0; i != 4; ++i) {
3916 if (Locs[i].first == -1) {
3917 MaskOps.push_back(-1);
3919 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3920 MaskOps.push_back(Idx);
3923 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
3927 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3928 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
3929 SDValue V1 = Op.getOperand(0);
3930 SDValue V2 = Op.getOperand(1);
3931 MVT VT = Op.getValueType();
3932 DebugLoc dl = Op.getDebugLoc();
3933 unsigned NumElems = VT.getVectorNumElements();
3934 bool isMMX = VT.getSizeInBits() == 64;
3935 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3936 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3937 bool V1IsSplat = false;
3938 bool V2IsSplat = false;
3940 if (isZeroShuffle(SVOp))
3941 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3943 // Promote splats to v4f32.
3944 if (SVOp->isSplat()) {
3945 if (isMMX || NumElems < 4)
3947 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
3950 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3952 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3953 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3954 if (NewOp.getNode())
3955 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3956 LowerVECTOR_SHUFFLE(NewOp, DAG));
3957 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3958 // FIXME: Figure out a cleaner way to do this.
3959 // Try to make use of movq to zero out the top part.
3960 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
3961 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3962 if (NewOp.getNode()) {
3963 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
3964 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
3965 DAG, Subtarget, dl);
3967 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
3968 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3969 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
3970 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3971 DAG, Subtarget, dl);
3975 if (X86::isPSHUFDMask(SVOp))
3978 // Check if this can be converted into a logical shift.
3979 bool isLeft = false;
3982 bool isShift = getSubtarget()->hasSSE2() &&
3983 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
3984 if (isShift && ShVal.hasOneUse()) {
3985 // If the shifted value has multiple uses, it may be cheaper to use
3986 // v_set0 + movlhps or movhlps, etc.
3987 MVT EVT = VT.getVectorElementType();
3988 ShAmt *= EVT.getSizeInBits();
3989 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
3992 if (X86::isMOVLMask(SVOp)) {
3995 if (ISD::isBuildVectorAllZeros(V1.getNode()))
3996 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4001 // FIXME: fold these into legal mask.
4002 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4003 X86::isMOVSLDUPMask(SVOp) ||
4004 X86::isMOVHLPSMask(SVOp) ||
4005 X86::isMOVHPMask(SVOp) ||
4006 X86::isMOVLPMask(SVOp)))
4009 if (ShouldXformToMOVHLPS(SVOp) ||
4010 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4011 return CommuteVectorShuffle(SVOp, DAG);
4014 // No better options. Use a vshl / vsrl.
4015 MVT EVT = VT.getVectorElementType();
4016 ShAmt *= EVT.getSizeInBits();
4017 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4020 bool Commuted = false;
4021 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4022 // 1,1,1,1 -> v8i16 though.
4023 V1IsSplat = isSplatVector(V1.getNode());
4024 V2IsSplat = isSplatVector(V2.getNode());
4026 // Canonicalize the splat or undef, if present, to be on the RHS.
4027 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4028 Op = CommuteVectorShuffle(SVOp, DAG);
4029 SVOp = cast<ShuffleVectorSDNode>(Op);
4030 V1 = SVOp->getOperand(0);
4031 V2 = SVOp->getOperand(1);
4032 std::swap(V1IsSplat, V2IsSplat);
4033 std::swap(V1IsUndef, V2IsUndef);
4037 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4038 // Shuffling low element of v1 into undef, just return v1.
4041 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4042 // the instruction selector will not match, so get a canonical MOVL with
4043 // swapped operands to undo the commute.
4044 return getMOVL(DAG, dl, VT, V2, V1);
4047 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4048 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4049 X86::isUNPCKLMask(SVOp) ||
4050 X86::isUNPCKHMask(SVOp))
4054 // Normalize mask so all entries that point to V2 points to its first
4055 // element then try to match unpck{h|l} again. If match, return a
4056 // new vector_shuffle with the corrected mask.
4057 SDValue NewMask = NormalizeMask(SVOp, DAG);
4058 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4059 if (NSVOp != SVOp) {
4060 if (X86::isUNPCKLMask(NSVOp, true)) {
4062 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4069 // Commute is back and try unpck* again.
4070 // FIXME: this seems wrong.
4071 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4072 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4073 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4074 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4075 X86::isUNPCKLMask(NewSVOp) ||
4076 X86::isUNPCKHMask(NewSVOp))
4080 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4082 // Normalize the node to match x86 shuffle ops if needed
4083 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4084 return CommuteVectorShuffle(SVOp, DAG);
4086 // Check for legal shuffle and return?
4087 SmallVector<int, 16> PermMask;
4088 SVOp->getMask(PermMask);
4089 if (isShuffleMaskLegal(PermMask, VT))
4092 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4093 if (VT == MVT::v8i16) {
4094 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4095 if (NewOp.getNode())
4099 if (VT == MVT::v16i8) {
4100 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4101 if (NewOp.getNode())
4105 // Handle all 4 wide cases with a number of shuffles except for MMX.
4106 if (NumElems == 4 && !isMMX)
4107 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4113 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4114 SelectionDAG &DAG) {
4115 MVT VT = Op.getValueType();
4116 DebugLoc dl = Op.getDebugLoc();
4117 if (VT.getSizeInBits() == 8) {
4118 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4119 Op.getOperand(0), Op.getOperand(1));
4120 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4121 DAG.getValueType(VT));
4122 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4123 } else if (VT.getSizeInBits() == 16) {
4124 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4125 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4127 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4128 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4129 DAG.getNode(ISD::BIT_CONVERT, dl,
4133 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4134 Op.getOperand(0), Op.getOperand(1));
4135 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4136 DAG.getValueType(VT));
4137 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4138 } else if (VT == MVT::f32) {
4139 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4140 // the result back to FR32 register. It's only worth matching if the
4141 // result has a single use which is a store or a bitcast to i32. And in
4142 // the case of a store, it's not worth it if the index is a constant 0,
4143 // because a MOVSSmr can be used instead, which is smaller and faster.
4144 if (!Op.hasOneUse())
4146 SDNode *User = *Op.getNode()->use_begin();
4147 if ((User->getOpcode() != ISD::STORE ||
4148 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4149 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4150 (User->getOpcode() != ISD::BIT_CONVERT ||
4151 User->getValueType(0) != MVT::i32))
4153 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4154 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4157 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4158 } else if (VT == MVT::i32) {
4159 // ExtractPS works with constant index.
4160 if (isa<ConstantSDNode>(Op.getOperand(1)))
4168 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4169 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4172 if (Subtarget->hasSSE41()) {
4173 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4178 MVT VT = Op.getValueType();
4179 DebugLoc dl = Op.getDebugLoc();
4180 // TODO: handle v16i8.
4181 if (VT.getSizeInBits() == 16) {
4182 SDValue Vec = Op.getOperand(0);
4183 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4185 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4186 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4187 DAG.getNode(ISD::BIT_CONVERT, dl,
4190 // Transform it so it match pextrw which produces a 32-bit result.
4191 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4192 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4193 Op.getOperand(0), Op.getOperand(1));
4194 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4195 DAG.getValueType(VT));
4196 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4197 } else if (VT.getSizeInBits() == 32) {
4198 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4202 // SHUFPS the element to the lowest double word, then movss.
4203 int Mask[4] = { Idx, -1, -1, -1 };
4204 MVT VVT = Op.getOperand(0).getValueType();
4205 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4206 DAG.getUNDEF(VVT), Mask);
4207 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4208 DAG.getIntPtrConstant(0));
4209 } else if (VT.getSizeInBits() == 64) {
4210 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4211 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4212 // to match extract_elt for f64.
4213 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4217 // UNPCKHPD the element to the lowest double word, then movsd.
4218 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4219 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4220 int Mask[2] = { 1, -1 };
4221 MVT VVT = Op.getOperand(0).getValueType();
4222 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4223 DAG.getUNDEF(VVT), Mask);
4224 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4225 DAG.getIntPtrConstant(0));
4232 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4233 MVT VT = Op.getValueType();
4234 MVT EVT = VT.getVectorElementType();
4235 DebugLoc dl = Op.getDebugLoc();
4237 SDValue N0 = Op.getOperand(0);
4238 SDValue N1 = Op.getOperand(1);
4239 SDValue N2 = Op.getOperand(2);
4241 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4242 isa<ConstantSDNode>(N2)) {
4243 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4245 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4247 if (N1.getValueType() != MVT::i32)
4248 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4249 if (N2.getValueType() != MVT::i32)
4250 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4251 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4252 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4253 // Bits [7:6] of the constant are the source select. This will always be
4254 // zero here. The DAG Combiner may combine an extract_elt index into these
4255 // bits. For example (insert (extract, 3), 2) could be matched by putting
4256 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4257 // Bits [5:4] of the constant are the destination select. This is the
4258 // value of the incoming immediate.
4259 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4260 // combine either bitwise AND or insert of float 0.0 to set these bits.
4261 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4262 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4263 } else if (EVT == MVT::i32) {
4264 // InsertPS works with constant index.
4265 if (isa<ConstantSDNode>(N2))
4272 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4273 MVT VT = Op.getValueType();
4274 MVT EVT = VT.getVectorElementType();
4276 if (Subtarget->hasSSE41())
4277 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4282 DebugLoc dl = Op.getDebugLoc();
4283 SDValue N0 = Op.getOperand(0);
4284 SDValue N1 = Op.getOperand(1);
4285 SDValue N2 = Op.getOperand(2);
4287 if (EVT.getSizeInBits() == 16) {
4288 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4289 // as its second argument.
4290 if (N1.getValueType() != MVT::i32)
4291 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4292 if (N2.getValueType() != MVT::i32)
4293 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4294 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4300 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4301 DebugLoc dl = Op.getDebugLoc();
4302 if (Op.getValueType() == MVT::v2f32)
4303 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4304 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4305 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4306 Op.getOperand(0))));
4308 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4309 MVT VT = MVT::v2i32;
4310 switch (Op.getValueType().getSimpleVT()) {
4317 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4318 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4321 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4322 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4323 // one of the above mentioned nodes. It has to be wrapped because otherwise
4324 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4325 // be used to form addressing mode. These wrapped nodes will be selected
4328 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4329 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4330 // FIXME there isn't really any debug info here, should come from the parent
4331 DebugLoc dl = CP->getDebugLoc();
4332 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4333 CP->getAlignment());
4334 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4335 // With PIC, the address is actually $g + Offset.
4336 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4337 !Subtarget->isPICStyleRIPRel()) {
4338 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4339 DAG.getNode(X86ISD::GlobalBaseReg,
4340 DebugLoc::getUnknownLoc(),
4349 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4351 SelectionDAG &DAG) const {
4352 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4353 bool ExtraLoadRequired =
4354 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4356 // Create the TargetGlobalAddress node, folding in the constant
4357 // offset if it is legal.
4359 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4360 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4363 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4364 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4366 // With PIC, the address is actually $g + Offset.
4367 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4368 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4369 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4373 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4374 // load the value at address GV, not the value of GV itself. This means that
4375 // the GlobalAddress must be in the base or index register of the address, not
4376 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4377 // The same applies for external symbols during PIC codegen
4378 if (ExtraLoadRequired)
4379 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4380 PseudoSourceValue::getGOT(), 0);
4382 // If there was a non-zero offset that we didn't fold, create an explicit
4385 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4386 DAG.getConstant(Offset, getPointerTy()));
4392 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4393 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4394 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4395 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4399 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4400 SDValue *InFlag, const MVT PtrVT, unsigned ReturnReg) {
4401 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4402 DebugLoc dl = GA->getDebugLoc();
4403 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4404 GA->getValueType(0),
4407 SDValue Ops[] = { Chain, TGA, *InFlag };
4408 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4410 SDValue Ops[] = { Chain, TGA };
4411 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4413 SDValue Flag = Chain.getValue(1);
4414 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4417 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4419 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4422 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4423 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4424 DAG.getNode(X86ISD::GlobalBaseReg,
4425 DebugLoc::getUnknownLoc(),
4427 InFlag = Chain.getValue(1);
4429 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX);
4432 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4434 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4436 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX);
4439 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4440 // "local exec" model.
4441 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4442 const MVT PtrVT, TLSModel::Model model,
4444 DebugLoc dl = GA->getDebugLoc();
4445 // Get the Thread Pointer
4446 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4447 DebugLoc::getUnknownLoc(), PtrVT,
4448 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4451 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4454 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4456 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4457 GA->getValueType(0),
4459 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
4461 if (model == TLSModel::InitialExec)
4462 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4463 PseudoSourceValue::getGOT(), 0);
4465 // The address of the thread local variable is the add of the thread
4466 // pointer with the offset of the variable.
4467 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4471 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4472 // TODO: implement the "local dynamic" model
4473 // TODO: implement the "initial exec"model for pic executables
4474 assert(Subtarget->isTargetELF() &&
4475 "TLS not implemented for non-ELF targets");
4476 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4477 GlobalValue *GV = GA->getGlobal();
4478 TLSModel::Model model =
4479 getTLSModel (GV, getTargetMachine().getRelocationModel());
4480 if (Subtarget->is64Bit()) {
4482 case TLSModel::GeneralDynamic:
4483 case TLSModel::LocalDynamic: // not implemented
4484 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4486 case TLSModel::InitialExec:
4487 case TLSModel::LocalExec:
4488 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, true);
4492 case TLSModel::GeneralDynamic:
4493 case TLSModel::LocalDynamic: // not implemented
4494 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4496 case TLSModel::InitialExec:
4497 case TLSModel::LocalExec:
4498 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, false);
4501 assert(0 && "Unreachable");
4506 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4507 // FIXME there isn't really any debug info here
4508 DebugLoc dl = Op.getDebugLoc();
4509 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4510 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4511 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4512 // With PIC, the address is actually $g + Offset.
4513 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4514 !Subtarget->isPICStyleRIPRel()) {
4515 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4516 DAG.getNode(X86ISD::GlobalBaseReg,
4517 DebugLoc::getUnknownLoc(),
4525 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4526 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4527 // FIXME there isn't really any debug into here
4528 DebugLoc dl = JT->getDebugLoc();
4529 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4530 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4531 // With PIC, the address is actually $g + Offset.
4532 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4533 !Subtarget->isPICStyleRIPRel()) {
4534 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4535 DAG.getNode(X86ISD::GlobalBaseReg,
4536 DebugLoc::getUnknownLoc(),
4544 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4545 /// take a 2 x i32 value to shift plus a shift amount.
4546 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4547 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4548 MVT VT = Op.getValueType();
4549 unsigned VTBits = VT.getSizeInBits();
4550 DebugLoc dl = Op.getDebugLoc();
4551 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4552 SDValue ShOpLo = Op.getOperand(0);
4553 SDValue ShOpHi = Op.getOperand(1);
4554 SDValue ShAmt = Op.getOperand(2);
4555 SDValue Tmp1 = isSRA ?
4556 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4557 DAG.getConstant(VTBits - 1, MVT::i8)) :
4558 DAG.getConstant(0, VT);
4561 if (Op.getOpcode() == ISD::SHL_PARTS) {
4562 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4563 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4565 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4566 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4569 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4570 DAG.getConstant(VTBits, MVT::i8));
4571 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4572 AndNode, DAG.getConstant(0, MVT::i8));
4575 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4576 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4577 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4579 if (Op.getOpcode() == ISD::SHL_PARTS) {
4580 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4581 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4583 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4584 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4587 SDValue Ops[2] = { Lo, Hi };
4588 return DAG.getMergeValues(Ops, 2, dl);
4591 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4592 MVT SrcVT = Op.getOperand(0).getValueType();
4593 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4594 "Unknown SINT_TO_FP to lower!");
4596 // These are really Legal; caller falls through into that case.
4597 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4599 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4600 Subtarget->is64Bit())
4603 DebugLoc dl = Op.getDebugLoc();
4604 unsigned Size = SrcVT.getSizeInBits()/8;
4605 MachineFunction &MF = DAG.getMachineFunction();
4606 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4607 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4608 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4610 PseudoSourceValue::getFixedStack(SSFI), 0);
4611 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4614 SDValue X86TargetLowering::BuildFILD(SDValue Op, MVT SrcVT, SDValue Chain,
4616 SelectionDAG &DAG) {
4618 DebugLoc dl = Op.getDebugLoc();
4620 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4622 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4624 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4625 SmallVector<SDValue, 8> Ops;
4626 Ops.push_back(Chain);
4627 Ops.push_back(StackSlot);
4628 Ops.push_back(DAG.getValueType(SrcVT));
4629 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4630 Tys, &Ops[0], Ops.size());
4633 Chain = Result.getValue(1);
4634 SDValue InFlag = Result.getValue(2);
4636 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4637 // shouldn't be necessary except that RFP cannot be live across
4638 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4639 MachineFunction &MF = DAG.getMachineFunction();
4640 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4641 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4642 Tys = DAG.getVTList(MVT::Other);
4643 SmallVector<SDValue, 8> Ops;
4644 Ops.push_back(Chain);
4645 Ops.push_back(Result);
4646 Ops.push_back(StackSlot);
4647 Ops.push_back(DAG.getValueType(Op.getValueType()));
4648 Ops.push_back(InFlag);
4649 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4650 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4651 PseudoSourceValue::getFixedStack(SSFI), 0);
4657 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4658 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4659 // This algorithm is not obvious. Here it is in C code, more or less:
4661 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4662 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4663 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4665 // Copy ints to xmm registers.
4666 __m128i xh = _mm_cvtsi32_si128( hi );
4667 __m128i xl = _mm_cvtsi32_si128( lo );
4669 // Combine into low half of a single xmm register.
4670 __m128i x = _mm_unpacklo_epi32( xh, xl );
4674 // Merge in appropriate exponents to give the integer bits the right
4676 x = _mm_unpacklo_epi32( x, exp );
4678 // Subtract away the biases to deal with the IEEE-754 double precision
4680 d = _mm_sub_pd( (__m128d) x, bias );
4682 // All conversions up to here are exact. The correctly rounded result is
4683 // calculated using the current rounding mode using the following
4685 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4686 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4687 // store doesn't really need to be here (except
4688 // maybe to zero the other double)
4693 DebugLoc dl = Op.getDebugLoc();
4695 // Build some magic constants.
4696 std::vector<Constant*> CV0;
4697 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4698 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4699 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4700 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4701 Constant *C0 = ConstantVector::get(CV0);
4702 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4704 std::vector<Constant*> CV1;
4705 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4706 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4707 Constant *C1 = ConstantVector::get(CV1);
4708 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4710 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4711 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4713 DAG.getIntPtrConstant(1)));
4714 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4715 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4717 DAG.getIntPtrConstant(0)));
4718 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4719 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4720 PseudoSourceValue::getConstantPool(), 0,
4722 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
4723 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4724 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4725 PseudoSourceValue::getConstantPool(), 0,
4727 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4729 // Add the halves; easiest way is to swap them into another reg first.
4730 int ShufMask[2] = { 1, -1 };
4731 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
4732 DAG.getUNDEF(MVT::v2f64), ShufMask);
4733 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4734 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4735 DAG.getIntPtrConstant(0));
4738 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4739 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4740 DebugLoc dl = Op.getDebugLoc();
4741 // FP constant to bias correct the final result.
4742 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4745 // Load the 32-bit value into an XMM register.
4746 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4747 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4749 DAG.getIntPtrConstant(0)));
4751 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4752 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4753 DAG.getIntPtrConstant(0));
4755 // Or the load with the bias.
4756 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4757 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4758 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4760 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4761 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4762 MVT::v2f64, Bias)));
4763 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4764 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4765 DAG.getIntPtrConstant(0));
4767 // Subtract the bias.
4768 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4770 // Handle final rounding.
4771 MVT DestVT = Op.getValueType();
4773 if (DestVT.bitsLT(MVT::f64)) {
4774 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4775 DAG.getIntPtrConstant(0));
4776 } else if (DestVT.bitsGT(MVT::f64)) {
4777 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4780 // Handle final rounding.
4784 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4785 SDValue N0 = Op.getOperand(0);
4786 DebugLoc dl = Op.getDebugLoc();
4788 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4789 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4790 // the optimization here.
4791 if (DAG.SignBitIsZero(N0))
4792 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4794 MVT SrcVT = N0.getValueType();
4795 if (SrcVT == MVT::i64) {
4796 // We only handle SSE2 f64 target here; caller can handle the rest.
4797 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4800 return LowerUINT_TO_FP_i64(Op, DAG);
4801 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
4802 return LowerUINT_TO_FP_i32(Op, DAG);
4805 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
4807 // Make a 64-bit buffer, and use it to build an FILD.
4808 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
4809 SDValue WordOff = DAG.getConstant(4, getPointerTy());
4810 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
4811 getPointerTy(), StackSlot, WordOff);
4812 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4813 StackSlot, NULL, 0);
4814 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
4815 OffsetSlot, NULL, 0);
4816 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
4819 std::pair<SDValue,SDValue> X86TargetLowering::
4820 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
4821 DebugLoc dl = Op.getDebugLoc();
4823 MVT DstTy = Op.getValueType();
4826 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
4830 assert(DstTy.getSimpleVT() <= MVT::i64 &&
4831 DstTy.getSimpleVT() >= MVT::i16 &&
4832 "Unknown FP_TO_SINT to lower!");
4834 // These are really Legal.
4835 if (DstTy == MVT::i32 &&
4836 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4837 return std::make_pair(SDValue(), SDValue());
4838 if (Subtarget->is64Bit() &&
4839 DstTy == MVT::i64 &&
4840 Op.getOperand(0).getValueType() != MVT::f80)
4841 return std::make_pair(SDValue(), SDValue());
4843 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4845 MachineFunction &MF = DAG.getMachineFunction();
4846 unsigned MemSize = DstTy.getSizeInBits()/8;
4847 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4848 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4851 switch (DstTy.getSimpleVT()) {
4852 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4853 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4854 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4855 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4858 SDValue Chain = DAG.getEntryNode();
4859 SDValue Value = Op.getOperand(0);
4860 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4861 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4862 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
4863 PseudoSourceValue::getFixedStack(SSFI), 0);
4864 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4866 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4868 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
4869 Chain = Value.getValue(1);
4870 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4871 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4874 // Build the FP_TO_INT*_IN_MEM
4875 SDValue Ops[] = { Chain, Value, StackSlot };
4876 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
4878 return std::make_pair(FIST, StackSlot);
4881 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4882 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
4883 SDValue FIST = Vals.first, StackSlot = Vals.second;
4884 if (FIST.getNode() == 0) return SDValue();
4887 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4888 FIST, StackSlot, NULL, 0);
4891 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
4892 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
4893 SDValue FIST = Vals.first, StackSlot = Vals.second;
4894 assert(FIST.getNode() && "Unexpected failure");
4897 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4898 FIST, StackSlot, NULL, 0);
4901 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4902 DebugLoc dl = Op.getDebugLoc();
4903 MVT VT = Op.getValueType();
4906 EltVT = VT.getVectorElementType();
4907 std::vector<Constant*> CV;
4908 if (EltVT == MVT::f64) {
4909 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4913 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4919 Constant *C = ConstantVector::get(CV);
4920 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4921 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4922 PseudoSourceValue::getConstantPool(), 0,
4924 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
4927 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4928 DebugLoc dl = Op.getDebugLoc();
4929 MVT VT = Op.getValueType();
4931 unsigned EltNum = 1;
4932 if (VT.isVector()) {
4933 EltVT = VT.getVectorElementType();
4934 EltNum = VT.getVectorNumElements();
4936 std::vector<Constant*> CV;
4937 if (EltVT == MVT::f64) {
4938 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4942 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4948 Constant *C = ConstantVector::get(CV);
4949 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4950 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4951 PseudoSourceValue::getConstantPool(), 0,
4953 if (VT.isVector()) {
4954 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4955 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
4956 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4958 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
4960 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
4964 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4965 SDValue Op0 = Op.getOperand(0);
4966 SDValue Op1 = Op.getOperand(1);
4967 DebugLoc dl = Op.getDebugLoc();
4968 MVT VT = Op.getValueType();
4969 MVT SrcVT = Op1.getValueType();
4971 // If second operand is smaller, extend it first.
4972 if (SrcVT.bitsLT(VT)) {
4973 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
4976 // And if it is bigger, shrink it first.
4977 if (SrcVT.bitsGT(VT)) {
4978 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
4982 // At this point the operands and the result should have the same
4983 // type, and that won't be f80 since that is not custom lowered.
4985 // First get the sign bit of second operand.
4986 std::vector<Constant*> CV;
4987 if (SrcVT == MVT::f64) {
4988 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4989 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4991 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4992 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4993 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4994 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4996 Constant *C = ConstantVector::get(CV);
4997 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4998 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
4999 PseudoSourceValue::getConstantPool(), 0,
5001 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5003 // Shift sign bit right or left if the two operands have different types.
5004 if (SrcVT.bitsGT(VT)) {
5005 // Op0 is MVT::f32, Op1 is MVT::f64.
5006 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5007 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5008 DAG.getConstant(32, MVT::i32));
5009 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5010 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5011 DAG.getIntPtrConstant(0));
5014 // Clear first operand sign bit.
5016 if (VT == MVT::f64) {
5017 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5018 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5020 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5021 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5022 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5023 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5025 C = ConstantVector::get(CV);
5026 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5027 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5028 PseudoSourceValue::getConstantPool(), 0,
5030 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5032 // Or the value with the sign bit.
5033 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5036 /// Emit nodes that will be selected as "test Op0,Op0", or something
5038 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5039 SelectionDAG &DAG) {
5040 DebugLoc dl = Op.getDebugLoc();
5042 // CF and OF aren't always set the way we want. Determine which
5043 // of these we need.
5044 bool NeedCF = false;
5045 bool NeedOF = false;
5047 case X86::COND_A: case X86::COND_AE:
5048 case X86::COND_B: case X86::COND_BE:
5051 case X86::COND_G: case X86::COND_GE:
5052 case X86::COND_L: case X86::COND_LE:
5053 case X86::COND_O: case X86::COND_NO:
5059 // See if we can use the EFLAGS value from the operand instead of
5060 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5061 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5062 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5063 unsigned Opcode = 0;
5064 unsigned NumOperands = 0;
5065 switch (Op.getNode()->getOpcode()) {
5067 // Due to an isel shortcoming, be conservative if this add is likely to
5068 // be selected as part of a load-modify-store instruction. When the root
5069 // node in a match is a store, isel doesn't know how to remap non-chain
5070 // non-flag uses of other nodes in the match, such as the ADD in this
5071 // case. This leads to the ADD being left around and reselected, with
5072 // the result being two adds in the output.
5073 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5074 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5075 if (UI->getOpcode() == ISD::STORE)
5077 if (ConstantSDNode *C =
5078 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5079 // An add of one will be selected as an INC.
5080 if (C->getAPIntValue() == 1) {
5081 Opcode = X86ISD::INC;
5085 // An add of negative one (subtract of one) will be selected as a DEC.
5086 if (C->getAPIntValue().isAllOnesValue()) {
5087 Opcode = X86ISD::DEC;
5092 // Otherwise use a regular EFLAGS-setting add.
5093 Opcode = X86ISD::ADD;
5097 // Due to the ISEL shortcoming noted above, be conservative if this sub is
5098 // likely to be selected as part of a load-modify-store instruction.
5099 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5100 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5101 if (UI->getOpcode() == ISD::STORE)
5103 // Otherwise use a regular EFLAGS-setting sub.
5104 Opcode = X86ISD::SUB;
5111 return SDValue(Op.getNode(), 1);
5117 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5118 SmallVector<SDValue, 4> Ops;
5119 for (unsigned i = 0; i != NumOperands; ++i)
5120 Ops.push_back(Op.getOperand(i));
5121 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5122 DAG.ReplaceAllUsesWith(Op, New);
5123 return SDValue(New.getNode(), 1);
5127 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5128 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5129 DAG.getConstant(0, Op.getValueType()));
5132 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5134 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5135 SelectionDAG &DAG) {
5136 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5137 if (C->getAPIntValue() == 0)
5138 return EmitTest(Op0, X86CC, DAG);
5140 DebugLoc dl = Op0.getDebugLoc();
5141 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5144 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5145 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5146 SDValue Op0 = Op.getOperand(0);
5147 SDValue Op1 = Op.getOperand(1);
5148 DebugLoc dl = Op.getDebugLoc();
5149 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5151 // Lower (X & (1 << N)) == 0 to BT(X, N).
5152 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5153 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5154 if (Op0.getOpcode() == ISD::AND &&
5156 Op1.getOpcode() == ISD::Constant &&
5157 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5158 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5160 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5161 if (ConstantSDNode *Op010C =
5162 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5163 if (Op010C->getZExtValue() == 1) {
5164 LHS = Op0.getOperand(0);
5165 RHS = Op0.getOperand(1).getOperand(1);
5167 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5168 if (ConstantSDNode *Op000C =
5169 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5170 if (Op000C->getZExtValue() == 1) {
5171 LHS = Op0.getOperand(1);
5172 RHS = Op0.getOperand(0).getOperand(1);
5174 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5175 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5176 SDValue AndLHS = Op0.getOperand(0);
5177 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5178 LHS = AndLHS.getOperand(0);
5179 RHS = AndLHS.getOperand(1);
5183 if (LHS.getNode()) {
5184 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5185 // instruction. Since the shift amount is in-range-or-undefined, we know
5186 // that doing a bittest on the i16 value is ok. We extend to i32 because
5187 // the encoding for the i16 version is larger than the i32 version.
5188 if (LHS.getValueType() == MVT::i8)
5189 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5191 // If the operand types disagree, extend the shift amount to match. Since
5192 // BT ignores high bits (like shifts) we can use anyextend.
5193 if (LHS.getValueType() != RHS.getValueType())
5194 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5196 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5197 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5198 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5199 DAG.getConstant(Cond, MVT::i8), BT);
5203 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5204 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5206 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5207 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5208 DAG.getConstant(X86CC, MVT::i8), Cond);
5211 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5213 SDValue Op0 = Op.getOperand(0);
5214 SDValue Op1 = Op.getOperand(1);
5215 SDValue CC = Op.getOperand(2);
5216 MVT VT = Op.getValueType();
5217 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5218 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5219 DebugLoc dl = Op.getDebugLoc();
5223 MVT VT0 = Op0.getValueType();
5224 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5225 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5228 switch (SetCCOpcode) {
5231 case ISD::SETEQ: SSECC = 0; break;
5233 case ISD::SETGT: Swap = true; // Fallthrough
5235 case ISD::SETOLT: SSECC = 1; break;
5237 case ISD::SETGE: Swap = true; // Fallthrough
5239 case ISD::SETOLE: SSECC = 2; break;
5240 case ISD::SETUO: SSECC = 3; break;
5242 case ISD::SETNE: SSECC = 4; break;
5243 case ISD::SETULE: Swap = true;
5244 case ISD::SETUGE: SSECC = 5; break;
5245 case ISD::SETULT: Swap = true;
5246 case ISD::SETUGT: SSECC = 6; break;
5247 case ISD::SETO: SSECC = 7; break;
5250 std::swap(Op0, Op1);
5252 // In the two special cases we can't handle, emit two comparisons.
5254 if (SetCCOpcode == ISD::SETUEQ) {
5256 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5257 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5258 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5260 else if (SetCCOpcode == ISD::SETONE) {
5262 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5263 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5264 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5266 assert(0 && "Illegal FP comparison");
5268 // Handle all other FP comparisons here.
5269 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5272 // We are handling one of the integer comparisons here. Since SSE only has
5273 // GT and EQ comparisons for integer, swapping operands and multiple
5274 // operations may be required for some comparisons.
5275 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5276 bool Swap = false, Invert = false, FlipSigns = false;
5278 switch (VT.getSimpleVT()) {
5280 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5281 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5282 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5283 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5286 switch (SetCCOpcode) {
5288 case ISD::SETNE: Invert = true;
5289 case ISD::SETEQ: Opc = EQOpc; break;
5290 case ISD::SETLT: Swap = true;
5291 case ISD::SETGT: Opc = GTOpc; break;
5292 case ISD::SETGE: Swap = true;
5293 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5294 case ISD::SETULT: Swap = true;
5295 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5296 case ISD::SETUGE: Swap = true;
5297 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5300 std::swap(Op0, Op1);
5302 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5303 // bits of the inputs before performing those operations.
5305 MVT EltVT = VT.getVectorElementType();
5306 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5308 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5309 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5311 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5312 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5315 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5317 // If the logical-not of the result is required, perform that now.
5319 Result = DAG.getNOT(dl, Result, VT);
5324 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5325 static bool isX86LogicalCmp(SDValue Op) {
5326 unsigned Opc = Op.getNode()->getOpcode();
5327 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5329 if (Op.getResNo() == 1 &&
5330 (Opc == X86ISD::ADD ||
5331 Opc == X86ISD::SUB ||
5332 Opc == X86ISD::SMUL ||
5333 Opc == X86ISD::UMUL ||
5334 Opc == X86ISD::INC ||
5335 Opc == X86ISD::DEC))
5341 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5342 bool addTest = true;
5343 SDValue Cond = Op.getOperand(0);
5344 DebugLoc dl = Op.getDebugLoc();
5347 if (Cond.getOpcode() == ISD::SETCC)
5348 Cond = LowerSETCC(Cond, DAG);
5350 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5351 // setting operand in place of the X86ISD::SETCC.
5352 if (Cond.getOpcode() == X86ISD::SETCC) {
5353 CC = Cond.getOperand(0);
5355 SDValue Cmp = Cond.getOperand(1);
5356 unsigned Opc = Cmp.getOpcode();
5357 MVT VT = Op.getValueType();
5359 bool IllegalFPCMov = false;
5360 if (VT.isFloatingPoint() && !VT.isVector() &&
5361 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5362 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5364 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5365 Opc == X86ISD::BT) { // FIXME
5372 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5373 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5376 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5377 SmallVector<SDValue, 4> Ops;
5378 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5379 // condition is true.
5380 Ops.push_back(Op.getOperand(2));
5381 Ops.push_back(Op.getOperand(1));
5383 Ops.push_back(Cond);
5384 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5387 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5388 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5389 // from the AND / OR.
5390 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5391 Opc = Op.getOpcode();
5392 if (Opc != ISD::OR && Opc != ISD::AND)
5394 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5395 Op.getOperand(0).hasOneUse() &&
5396 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5397 Op.getOperand(1).hasOneUse());
5400 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5401 // 1 and that the SETCC node has a single use.
5402 static bool isXor1OfSetCC(SDValue Op) {
5403 if (Op.getOpcode() != ISD::XOR)
5405 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5406 if (N1C && N1C->getAPIntValue() == 1) {
5407 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5408 Op.getOperand(0).hasOneUse();
5413 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5414 bool addTest = true;
5415 SDValue Chain = Op.getOperand(0);
5416 SDValue Cond = Op.getOperand(1);
5417 SDValue Dest = Op.getOperand(2);
5418 DebugLoc dl = Op.getDebugLoc();
5421 if (Cond.getOpcode() == ISD::SETCC)
5422 Cond = LowerSETCC(Cond, DAG);
5424 // FIXME: LowerXALUO doesn't handle these!!
5425 else if (Cond.getOpcode() == X86ISD::ADD ||
5426 Cond.getOpcode() == X86ISD::SUB ||
5427 Cond.getOpcode() == X86ISD::SMUL ||
5428 Cond.getOpcode() == X86ISD::UMUL)
5429 Cond = LowerXALUO(Cond, DAG);
5432 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5433 // setting operand in place of the X86ISD::SETCC.
5434 if (Cond.getOpcode() == X86ISD::SETCC) {
5435 CC = Cond.getOperand(0);
5437 SDValue Cmp = Cond.getOperand(1);
5438 unsigned Opc = Cmp.getOpcode();
5439 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5440 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5444 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5448 // These can only come from an arithmetic instruction with overflow,
5449 // e.g. SADDO, UADDO.
5450 Cond = Cond.getNode()->getOperand(1);
5457 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5458 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5459 if (CondOpc == ISD::OR) {
5460 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5461 // two branches instead of an explicit OR instruction with a
5463 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5464 isX86LogicalCmp(Cmp)) {
5465 CC = Cond.getOperand(0).getOperand(0);
5466 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5467 Chain, Dest, CC, Cmp);
5468 CC = Cond.getOperand(1).getOperand(0);
5472 } else { // ISD::AND
5473 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5474 // two branches instead of an explicit AND instruction with a
5475 // separate test. However, we only do this if this block doesn't
5476 // have a fall-through edge, because this requires an explicit
5477 // jmp when the condition is false.
5478 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5479 isX86LogicalCmp(Cmp) &&
5480 Op.getNode()->hasOneUse()) {
5481 X86::CondCode CCode =
5482 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5483 CCode = X86::GetOppositeBranchCondition(CCode);
5484 CC = DAG.getConstant(CCode, MVT::i8);
5485 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5486 // Look for an unconditional branch following this conditional branch.
5487 // We need this because we need to reverse the successors in order
5488 // to implement FCMP_OEQ.
5489 if (User.getOpcode() == ISD::BR) {
5490 SDValue FalseBB = User.getOperand(1);
5492 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5493 assert(NewBR == User);
5496 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5497 Chain, Dest, CC, Cmp);
5498 X86::CondCode CCode =
5499 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5500 CCode = X86::GetOppositeBranchCondition(CCode);
5501 CC = DAG.getConstant(CCode, MVT::i8);
5507 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5508 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5509 // It should be transformed during dag combiner except when the condition
5510 // is set by a arithmetics with overflow node.
5511 X86::CondCode CCode =
5512 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5513 CCode = X86::GetOppositeBranchCondition(CCode);
5514 CC = DAG.getConstant(CCode, MVT::i8);
5515 Cond = Cond.getOperand(0).getOperand(1);
5521 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5522 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5524 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5525 Chain, Dest, CC, Cond);
5529 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5530 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5531 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5532 // that the guard pages used by the OS virtual memory manager are allocated in
5533 // correct sequence.
5535 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5536 SelectionDAG &DAG) {
5537 assert(Subtarget->isTargetCygMing() &&
5538 "This should be used only on Cygwin/Mingw targets");
5539 DebugLoc dl = Op.getDebugLoc();
5542 SDValue Chain = Op.getOperand(0);
5543 SDValue Size = Op.getOperand(1);
5544 // FIXME: Ensure alignment here
5548 MVT IntPtr = getPointerTy();
5549 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5551 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5553 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5554 Flag = Chain.getValue(1);
5556 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5557 SDValue Ops[] = { Chain,
5558 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5559 DAG.getRegister(X86::EAX, IntPtr),
5560 DAG.getRegister(X86StackPtr, SPTy),
5562 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5563 Flag = Chain.getValue(1);
5565 Chain = DAG.getCALLSEQ_END(Chain,
5566 DAG.getIntPtrConstant(0, true),
5567 DAG.getIntPtrConstant(0, true),
5570 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5572 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5573 return DAG.getMergeValues(Ops1, 2, dl);
5577 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5579 SDValue Dst, SDValue Src,
5580 SDValue Size, unsigned Align,
5582 uint64_t DstSVOff) {
5583 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5585 // If not DWORD aligned or size is more than the threshold, call the library.
5586 // The libc version is likely to be faster for these cases. It can use the
5587 // address value and run time information about the CPU.
5588 if ((Align & 3) != 0 ||
5590 ConstantSize->getZExtValue() >
5591 getSubtarget()->getMaxInlineSizeThreshold()) {
5592 SDValue InFlag(0, 0);
5594 // Check to see if there is a specialized entry-point for memory zeroing.
5595 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5597 if (const char *bzeroEntry = V &&
5598 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5599 MVT IntPtr = getPointerTy();
5600 const Type *IntPtrTy = TD->getIntPtrType();
5601 TargetLowering::ArgListTy Args;
5602 TargetLowering::ArgListEntry Entry;
5604 Entry.Ty = IntPtrTy;
5605 Args.push_back(Entry);
5607 Args.push_back(Entry);
5608 std::pair<SDValue,SDValue> CallResult =
5609 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5610 CallingConv::C, false,
5611 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5612 return CallResult.second;
5615 // Otherwise have the target-independent code call memset.
5619 uint64_t SizeVal = ConstantSize->getZExtValue();
5620 SDValue InFlag(0, 0);
5623 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5624 unsigned BytesLeft = 0;
5625 bool TwoRepStos = false;
5628 uint64_t Val = ValC->getZExtValue() & 255;
5630 // If the value is a constant, then we can potentially use larger sets.
5631 switch (Align & 3) {
5632 case 2: // WORD aligned
5635 Val = (Val << 8) | Val;
5637 case 0: // DWORD aligned
5640 Val = (Val << 8) | Val;
5641 Val = (Val << 16) | Val;
5642 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5645 Val = (Val << 32) | Val;
5648 default: // Byte aligned
5651 Count = DAG.getIntPtrConstant(SizeVal);
5655 if (AVT.bitsGT(MVT::i8)) {
5656 unsigned UBytes = AVT.getSizeInBits() / 8;
5657 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5658 BytesLeft = SizeVal % UBytes;
5661 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5663 InFlag = Chain.getValue(1);
5666 Count = DAG.getIntPtrConstant(SizeVal);
5667 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5668 InFlag = Chain.getValue(1);
5671 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5674 InFlag = Chain.getValue(1);
5675 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5678 InFlag = Chain.getValue(1);
5680 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5681 SmallVector<SDValue, 8> Ops;
5682 Ops.push_back(Chain);
5683 Ops.push_back(DAG.getValueType(AVT));
5684 Ops.push_back(InFlag);
5685 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5688 InFlag = Chain.getValue(1);
5690 MVT CVT = Count.getValueType();
5691 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5692 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5693 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5696 InFlag = Chain.getValue(1);
5697 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5699 Ops.push_back(Chain);
5700 Ops.push_back(DAG.getValueType(MVT::i8));
5701 Ops.push_back(InFlag);
5702 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5703 } else if (BytesLeft) {
5704 // Handle the last 1 - 7 bytes.
5705 unsigned Offset = SizeVal - BytesLeft;
5706 MVT AddrVT = Dst.getValueType();
5707 MVT SizeVT = Size.getValueType();
5709 Chain = DAG.getMemset(Chain, dl,
5710 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5711 DAG.getConstant(Offset, AddrVT)),
5713 DAG.getConstant(BytesLeft, SizeVT),
5714 Align, DstSV, DstSVOff + Offset);
5717 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5722 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5723 SDValue Chain, SDValue Dst, SDValue Src,
5724 SDValue Size, unsigned Align,
5726 const Value *DstSV, uint64_t DstSVOff,
5727 const Value *SrcSV, uint64_t SrcSVOff) {
5728 // This requires the copy size to be a constant, preferrably
5729 // within a subtarget-specific limit.
5730 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5733 uint64_t SizeVal = ConstantSize->getZExtValue();
5734 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5737 /// If not DWORD aligned, call the library.
5738 if ((Align & 3) != 0)
5743 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5746 unsigned UBytes = AVT.getSizeInBits() / 8;
5747 unsigned CountVal = SizeVal / UBytes;
5748 SDValue Count = DAG.getIntPtrConstant(CountVal);
5749 unsigned BytesLeft = SizeVal % UBytes;
5751 SDValue InFlag(0, 0);
5752 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5755 InFlag = Chain.getValue(1);
5756 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5759 InFlag = Chain.getValue(1);
5760 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5763 InFlag = Chain.getValue(1);
5765 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5766 SmallVector<SDValue, 8> Ops;
5767 Ops.push_back(Chain);
5768 Ops.push_back(DAG.getValueType(AVT));
5769 Ops.push_back(InFlag);
5770 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5772 SmallVector<SDValue, 4> Results;
5773 Results.push_back(RepMovs);
5775 // Handle the last 1 - 7 bytes.
5776 unsigned Offset = SizeVal - BytesLeft;
5777 MVT DstVT = Dst.getValueType();
5778 MVT SrcVT = Src.getValueType();
5779 MVT SizeVT = Size.getValueType();
5780 Results.push_back(DAG.getMemcpy(Chain, dl,
5781 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5782 DAG.getConstant(Offset, DstVT)),
5783 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5784 DAG.getConstant(Offset, SrcVT)),
5785 DAG.getConstant(BytesLeft, SizeVT),
5786 Align, AlwaysInline,
5787 DstSV, DstSVOff + Offset,
5788 SrcSV, SrcSVOff + Offset));
5791 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5792 &Results[0], Results.size());
5795 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5796 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5797 DebugLoc dl = Op.getDebugLoc();
5799 if (!Subtarget->is64Bit()) {
5800 // vastart just stores the address of the VarArgsFrameIndex slot into the
5801 // memory location argument.
5802 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5803 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
5807 // gp_offset (0 - 6 * 8)
5808 // fp_offset (48 - 48 + 8 * 16)
5809 // overflow_arg_area (point to parameters coming in memory).
5811 SmallVector<SDValue, 8> MemOps;
5812 SDValue FIN = Op.getOperand(1);
5814 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
5815 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5817 MemOps.push_back(Store);
5820 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5821 FIN, DAG.getIntPtrConstant(4));
5822 Store = DAG.getStore(Op.getOperand(0), dl,
5823 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5825 MemOps.push_back(Store);
5827 // Store ptr to overflow_arg_area
5828 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5829 FIN, DAG.getIntPtrConstant(4));
5830 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5831 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
5832 MemOps.push_back(Store);
5834 // Store ptr to reg_save_area.
5835 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5836 FIN, DAG.getIntPtrConstant(8));
5837 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5838 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
5839 MemOps.push_back(Store);
5840 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5841 &MemOps[0], MemOps.size());
5844 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5845 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5846 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5847 SDValue Chain = Op.getOperand(0);
5848 SDValue SrcPtr = Op.getOperand(1);
5849 SDValue SrcSV = Op.getOperand(2);
5851 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5856 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5857 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5858 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5859 SDValue Chain = Op.getOperand(0);
5860 SDValue DstPtr = Op.getOperand(1);
5861 SDValue SrcPtr = Op.getOperand(2);
5862 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5863 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5864 DebugLoc dl = Op.getDebugLoc();
5866 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
5867 DAG.getIntPtrConstant(24), 8, false,
5868 DstSV, 0, SrcSV, 0);
5872 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5873 DebugLoc dl = Op.getDebugLoc();
5874 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5876 default: return SDValue(); // Don't custom lower most intrinsics.
5877 // Comparison intrinsics.
5878 case Intrinsic::x86_sse_comieq_ss:
5879 case Intrinsic::x86_sse_comilt_ss:
5880 case Intrinsic::x86_sse_comile_ss:
5881 case Intrinsic::x86_sse_comigt_ss:
5882 case Intrinsic::x86_sse_comige_ss:
5883 case Intrinsic::x86_sse_comineq_ss:
5884 case Intrinsic::x86_sse_ucomieq_ss:
5885 case Intrinsic::x86_sse_ucomilt_ss:
5886 case Intrinsic::x86_sse_ucomile_ss:
5887 case Intrinsic::x86_sse_ucomigt_ss:
5888 case Intrinsic::x86_sse_ucomige_ss:
5889 case Intrinsic::x86_sse_ucomineq_ss:
5890 case Intrinsic::x86_sse2_comieq_sd:
5891 case Intrinsic::x86_sse2_comilt_sd:
5892 case Intrinsic::x86_sse2_comile_sd:
5893 case Intrinsic::x86_sse2_comigt_sd:
5894 case Intrinsic::x86_sse2_comige_sd:
5895 case Intrinsic::x86_sse2_comineq_sd:
5896 case Intrinsic::x86_sse2_ucomieq_sd:
5897 case Intrinsic::x86_sse2_ucomilt_sd:
5898 case Intrinsic::x86_sse2_ucomile_sd:
5899 case Intrinsic::x86_sse2_ucomigt_sd:
5900 case Intrinsic::x86_sse2_ucomige_sd:
5901 case Intrinsic::x86_sse2_ucomineq_sd: {
5903 ISD::CondCode CC = ISD::SETCC_INVALID;
5906 case Intrinsic::x86_sse_comieq_ss:
5907 case Intrinsic::x86_sse2_comieq_sd:
5911 case Intrinsic::x86_sse_comilt_ss:
5912 case Intrinsic::x86_sse2_comilt_sd:
5916 case Intrinsic::x86_sse_comile_ss:
5917 case Intrinsic::x86_sse2_comile_sd:
5921 case Intrinsic::x86_sse_comigt_ss:
5922 case Intrinsic::x86_sse2_comigt_sd:
5926 case Intrinsic::x86_sse_comige_ss:
5927 case Intrinsic::x86_sse2_comige_sd:
5931 case Intrinsic::x86_sse_comineq_ss:
5932 case Intrinsic::x86_sse2_comineq_sd:
5936 case Intrinsic::x86_sse_ucomieq_ss:
5937 case Intrinsic::x86_sse2_ucomieq_sd:
5938 Opc = X86ISD::UCOMI;
5941 case Intrinsic::x86_sse_ucomilt_ss:
5942 case Intrinsic::x86_sse2_ucomilt_sd:
5943 Opc = X86ISD::UCOMI;
5946 case Intrinsic::x86_sse_ucomile_ss:
5947 case Intrinsic::x86_sse2_ucomile_sd:
5948 Opc = X86ISD::UCOMI;
5951 case Intrinsic::x86_sse_ucomigt_ss:
5952 case Intrinsic::x86_sse2_ucomigt_sd:
5953 Opc = X86ISD::UCOMI;
5956 case Intrinsic::x86_sse_ucomige_ss:
5957 case Intrinsic::x86_sse2_ucomige_sd:
5958 Opc = X86ISD::UCOMI;
5961 case Intrinsic::x86_sse_ucomineq_ss:
5962 case Intrinsic::x86_sse2_ucomineq_sd:
5963 Opc = X86ISD::UCOMI;
5968 SDValue LHS = Op.getOperand(1);
5969 SDValue RHS = Op.getOperand(2);
5970 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
5971 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
5972 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5973 DAG.getConstant(X86CC, MVT::i8), Cond);
5974 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
5977 // Fix vector shift instructions where the last operand is a non-immediate
5979 case Intrinsic::x86_sse2_pslli_w:
5980 case Intrinsic::x86_sse2_pslli_d:
5981 case Intrinsic::x86_sse2_pslli_q:
5982 case Intrinsic::x86_sse2_psrli_w:
5983 case Intrinsic::x86_sse2_psrli_d:
5984 case Intrinsic::x86_sse2_psrli_q:
5985 case Intrinsic::x86_sse2_psrai_w:
5986 case Intrinsic::x86_sse2_psrai_d:
5987 case Intrinsic::x86_mmx_pslli_w:
5988 case Intrinsic::x86_mmx_pslli_d:
5989 case Intrinsic::x86_mmx_pslli_q:
5990 case Intrinsic::x86_mmx_psrli_w:
5991 case Intrinsic::x86_mmx_psrli_d:
5992 case Intrinsic::x86_mmx_psrli_q:
5993 case Intrinsic::x86_mmx_psrai_w:
5994 case Intrinsic::x86_mmx_psrai_d: {
5995 SDValue ShAmt = Op.getOperand(2);
5996 if (isa<ConstantSDNode>(ShAmt))
5999 unsigned NewIntNo = 0;
6000 MVT ShAmtVT = MVT::v4i32;
6002 case Intrinsic::x86_sse2_pslli_w:
6003 NewIntNo = Intrinsic::x86_sse2_psll_w;
6005 case Intrinsic::x86_sse2_pslli_d:
6006 NewIntNo = Intrinsic::x86_sse2_psll_d;
6008 case Intrinsic::x86_sse2_pslli_q:
6009 NewIntNo = Intrinsic::x86_sse2_psll_q;
6011 case Intrinsic::x86_sse2_psrli_w:
6012 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6014 case Intrinsic::x86_sse2_psrli_d:
6015 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6017 case Intrinsic::x86_sse2_psrli_q:
6018 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6020 case Intrinsic::x86_sse2_psrai_w:
6021 NewIntNo = Intrinsic::x86_sse2_psra_w;
6023 case Intrinsic::x86_sse2_psrai_d:
6024 NewIntNo = Intrinsic::x86_sse2_psra_d;
6027 ShAmtVT = MVT::v2i32;
6029 case Intrinsic::x86_mmx_pslli_w:
6030 NewIntNo = Intrinsic::x86_mmx_psll_w;
6032 case Intrinsic::x86_mmx_pslli_d:
6033 NewIntNo = Intrinsic::x86_mmx_psll_d;
6035 case Intrinsic::x86_mmx_pslli_q:
6036 NewIntNo = Intrinsic::x86_mmx_psll_q;
6038 case Intrinsic::x86_mmx_psrli_w:
6039 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6041 case Intrinsic::x86_mmx_psrli_d:
6042 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6044 case Intrinsic::x86_mmx_psrli_q:
6045 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6047 case Intrinsic::x86_mmx_psrai_w:
6048 NewIntNo = Intrinsic::x86_mmx_psra_w;
6050 case Intrinsic::x86_mmx_psrai_d:
6051 NewIntNo = Intrinsic::x86_mmx_psra_d;
6053 default: abort(); // Can't reach here.
6058 MVT VT = Op.getValueType();
6059 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6060 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6061 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6062 DAG.getConstant(NewIntNo, MVT::i32),
6063 Op.getOperand(1), ShAmt);
6068 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6069 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6070 DebugLoc dl = Op.getDebugLoc();
6073 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6075 DAG.getConstant(TD->getPointerSize(),
6076 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6077 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6078 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6083 // Just load the return address.
6084 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6085 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6086 RetAddrFI, NULL, 0);
6089 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6090 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6091 MFI->setFrameAddressIsTaken(true);
6092 MVT VT = Op.getValueType();
6093 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6094 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6095 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6096 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6098 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6102 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6103 SelectionDAG &DAG) {
6104 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6107 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6109 MachineFunction &MF = DAG.getMachineFunction();
6110 SDValue Chain = Op.getOperand(0);
6111 SDValue Offset = Op.getOperand(1);
6112 SDValue Handler = Op.getOperand(2);
6113 DebugLoc dl = Op.getDebugLoc();
6115 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6117 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6119 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6120 DAG.getIntPtrConstant(-TD->getPointerSize()));
6121 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6122 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6123 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6124 MF.getRegInfo().addLiveOut(StoreAddrReg);
6126 return DAG.getNode(X86ISD::EH_RETURN, dl,
6128 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6131 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6132 SelectionDAG &DAG) {
6133 SDValue Root = Op.getOperand(0);
6134 SDValue Trmp = Op.getOperand(1); // trampoline
6135 SDValue FPtr = Op.getOperand(2); // nested function
6136 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6137 DebugLoc dl = Op.getDebugLoc();
6139 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6141 const X86InstrInfo *TII =
6142 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6144 if (Subtarget->is64Bit()) {
6145 SDValue OutChains[6];
6147 // Large code-model.
6149 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6150 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6152 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6153 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6155 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6157 // Load the pointer to the nested function into R11.
6158 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6159 SDValue Addr = Trmp;
6160 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6163 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6164 DAG.getConstant(2, MVT::i64));
6165 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6167 // Load the 'nest' parameter value into R10.
6168 // R10 is specified in X86CallingConv.td
6169 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6170 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6171 DAG.getConstant(10, MVT::i64));
6172 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6173 Addr, TrmpAddr, 10);
6175 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6176 DAG.getConstant(12, MVT::i64));
6177 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6179 // Jump to the nested function.
6180 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6181 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6182 DAG.getConstant(20, MVT::i64));
6183 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6184 Addr, TrmpAddr, 20);
6186 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6187 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6188 DAG.getConstant(22, MVT::i64));
6189 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6193 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6194 return DAG.getMergeValues(Ops, 2, dl);
6196 const Function *Func =
6197 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6198 unsigned CC = Func->getCallingConv();
6203 assert(0 && "Unsupported calling convention");
6204 case CallingConv::C:
6205 case CallingConv::X86_StdCall: {
6206 // Pass 'nest' parameter in ECX.
6207 // Must be kept in sync with X86CallingConv.td
6210 // Check that ECX wasn't needed by an 'inreg' parameter.
6211 const FunctionType *FTy = Func->getFunctionType();
6212 const AttrListPtr &Attrs = Func->getAttributes();
6214 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6215 unsigned InRegCount = 0;
6218 for (FunctionType::param_iterator I = FTy->param_begin(),
6219 E = FTy->param_end(); I != E; ++I, ++Idx)
6220 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6221 // FIXME: should only count parameters that are lowered to integers.
6222 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6224 if (InRegCount > 2) {
6225 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6231 case CallingConv::X86_FastCall:
6232 case CallingConv::Fast:
6233 // Pass 'nest' parameter in EAX.
6234 // Must be kept in sync with X86CallingConv.td
6239 SDValue OutChains[4];
6242 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6243 DAG.getConstant(10, MVT::i32));
6244 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6246 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6247 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6248 OutChains[0] = DAG.getStore(Root, dl,
6249 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6252 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6253 DAG.getConstant(1, MVT::i32));
6254 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6256 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6257 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6258 DAG.getConstant(5, MVT::i32));
6259 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6260 TrmpAddr, 5, false, 1);
6262 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6263 DAG.getConstant(6, MVT::i32));
6264 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6267 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6268 return DAG.getMergeValues(Ops, 2, dl);
6272 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6274 The rounding mode is in bits 11:10 of FPSR, and has the following
6281 FLT_ROUNDS, on the other hand, expects the following:
6288 To perform the conversion, we do:
6289 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6292 MachineFunction &MF = DAG.getMachineFunction();
6293 const TargetMachine &TM = MF.getTarget();
6294 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6295 unsigned StackAlignment = TFI.getStackAlignment();
6296 MVT VT = Op.getValueType();
6297 DebugLoc dl = Op.getDebugLoc();
6299 // Save FP Control Word to stack slot
6300 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6301 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6303 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6304 DAG.getEntryNode(), StackSlot);
6306 // Load FP Control Word from stack slot
6307 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6309 // Transform as necessary
6311 DAG.getNode(ISD::SRL, dl, MVT::i16,
6312 DAG.getNode(ISD::AND, dl, MVT::i16,
6313 CWD, DAG.getConstant(0x800, MVT::i16)),
6314 DAG.getConstant(11, MVT::i8));
6316 DAG.getNode(ISD::SRL, dl, MVT::i16,
6317 DAG.getNode(ISD::AND, dl, MVT::i16,
6318 CWD, DAG.getConstant(0x400, MVT::i16)),
6319 DAG.getConstant(9, MVT::i8));
6322 DAG.getNode(ISD::AND, dl, MVT::i16,
6323 DAG.getNode(ISD::ADD, dl, MVT::i16,
6324 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6325 DAG.getConstant(1, MVT::i16)),
6326 DAG.getConstant(3, MVT::i16));
6329 return DAG.getNode((VT.getSizeInBits() < 16 ?
6330 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6333 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6334 MVT VT = Op.getValueType();
6336 unsigned NumBits = VT.getSizeInBits();
6337 DebugLoc dl = Op.getDebugLoc();
6339 Op = Op.getOperand(0);
6340 if (VT == MVT::i8) {
6341 // Zero extend to i32 since there is not an i8 bsr.
6343 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6346 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6347 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6348 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6350 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6351 SmallVector<SDValue, 4> Ops;
6353 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6354 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6355 Ops.push_back(Op.getValue(1));
6356 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6358 // Finally xor with NumBits-1.
6359 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6362 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6366 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6367 MVT VT = Op.getValueType();
6369 unsigned NumBits = VT.getSizeInBits();
6370 DebugLoc dl = Op.getDebugLoc();
6372 Op = Op.getOperand(0);
6373 if (VT == MVT::i8) {
6375 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6378 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6379 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6380 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6382 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6383 SmallVector<SDValue, 4> Ops;
6385 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6386 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6387 Ops.push_back(Op.getValue(1));
6388 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6391 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6395 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6396 MVT VT = Op.getValueType();
6397 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6398 DebugLoc dl = Op.getDebugLoc();
6400 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6401 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6402 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6403 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6404 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6406 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6407 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6408 // return AloBlo + AloBhi + AhiBlo;
6410 SDValue A = Op.getOperand(0);
6411 SDValue B = Op.getOperand(1);
6413 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6414 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6415 A, DAG.getConstant(32, MVT::i32));
6416 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6417 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6418 B, DAG.getConstant(32, MVT::i32));
6419 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6420 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6422 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6423 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6425 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6426 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6428 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6429 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6430 AloBhi, DAG.getConstant(32, MVT::i32));
6431 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6432 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6433 AhiBlo, DAG.getConstant(32, MVT::i32));
6434 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6435 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6440 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6441 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6442 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6443 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6444 // has only one use.
6445 SDNode *N = Op.getNode();
6446 SDValue LHS = N->getOperand(0);
6447 SDValue RHS = N->getOperand(1);
6448 unsigned BaseOp = 0;
6450 DebugLoc dl = Op.getDebugLoc();
6452 switch (Op.getOpcode()) {
6453 default: assert(0 && "Unknown ovf instruction!");
6455 // A subtract of one will be selected as a INC. Note that INC doesn't
6456 // set CF, so we can't do this for UADDO.
6457 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6458 if (C->getAPIntValue() == 1) {
6459 BaseOp = X86ISD::INC;
6463 BaseOp = X86ISD::ADD;
6467 BaseOp = X86ISD::ADD;
6471 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6472 // set CF, so we can't do this for USUBO.
6473 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6474 if (C->getAPIntValue() == 1) {
6475 BaseOp = X86ISD::DEC;
6479 BaseOp = X86ISD::SUB;
6483 BaseOp = X86ISD::SUB;
6487 BaseOp = X86ISD::SMUL;
6491 BaseOp = X86ISD::UMUL;
6496 // Also sets EFLAGS.
6497 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6498 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6501 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6502 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6504 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6508 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6509 MVT T = Op.getValueType();
6510 DebugLoc dl = Op.getDebugLoc();
6513 switch(T.getSimpleVT()) {
6515 assert(false && "Invalid value type!");
6516 case MVT::i8: Reg = X86::AL; size = 1; break;
6517 case MVT::i16: Reg = X86::AX; size = 2; break;
6518 case MVT::i32: Reg = X86::EAX; size = 4; break;
6520 assert(Subtarget->is64Bit() && "Node not type legal!");
6521 Reg = X86::RAX; size = 8;
6524 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6525 Op.getOperand(2), SDValue());
6526 SDValue Ops[] = { cpIn.getValue(0),
6529 DAG.getTargetConstant(size, MVT::i8),
6531 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6532 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6534 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6538 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6539 SelectionDAG &DAG) {
6540 assert(Subtarget->is64Bit() && "Result not type legalized?");
6541 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6542 SDValue TheChain = Op.getOperand(0);
6543 DebugLoc dl = Op.getDebugLoc();
6544 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6545 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6546 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6548 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6549 DAG.getConstant(32, MVT::i8));
6551 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6554 return DAG.getMergeValues(Ops, 2, dl);
6557 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6558 SDNode *Node = Op.getNode();
6559 DebugLoc dl = Node->getDebugLoc();
6560 MVT T = Node->getValueType(0);
6561 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6562 DAG.getConstant(0, T), Node->getOperand(2));
6563 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6564 cast<AtomicSDNode>(Node)->getMemoryVT(),
6565 Node->getOperand(0),
6566 Node->getOperand(1), negOp,
6567 cast<AtomicSDNode>(Node)->getSrcValue(),
6568 cast<AtomicSDNode>(Node)->getAlignment());
6571 /// LowerOperation - Provide custom lowering hooks for some operations.
6573 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6574 switch (Op.getOpcode()) {
6575 default: assert(0 && "Should not custom lower this!");
6576 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6577 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6578 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6579 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6580 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6581 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6582 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6583 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6584 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6585 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6586 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6587 case ISD::SHL_PARTS:
6588 case ISD::SRA_PARTS:
6589 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6590 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6591 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6592 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6593 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
6594 case ISD::FABS: return LowerFABS(Op, DAG);
6595 case ISD::FNEG: return LowerFNEG(Op, DAG);
6596 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6597 case ISD::SETCC: return LowerSETCC(Op, DAG);
6598 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6599 case ISD::SELECT: return LowerSELECT(Op, DAG);
6600 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6601 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6602 case ISD::CALL: return LowerCALL(Op, DAG);
6603 case ISD::RET: return LowerRET(Op, DAG);
6604 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6605 case ISD::VASTART: return LowerVASTART(Op, DAG);
6606 case ISD::VAARG: return LowerVAARG(Op, DAG);
6607 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6608 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6609 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6610 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6611 case ISD::FRAME_TO_ARGS_OFFSET:
6612 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6613 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6614 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6615 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6616 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6617 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6618 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6619 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6625 case ISD::UMULO: return LowerXALUO(Op, DAG);
6626 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6630 void X86TargetLowering::
6631 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6632 SelectionDAG &DAG, unsigned NewOp) {
6633 MVT T = Node->getValueType(0);
6634 DebugLoc dl = Node->getDebugLoc();
6635 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6637 SDValue Chain = Node->getOperand(0);
6638 SDValue In1 = Node->getOperand(1);
6639 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6640 Node->getOperand(2), DAG.getIntPtrConstant(0));
6641 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6642 Node->getOperand(2), DAG.getIntPtrConstant(1));
6643 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6644 // have a MemOperand. Pass the info through as a normal operand.
6645 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6646 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6647 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6648 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6649 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6650 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6651 Results.push_back(Result.getValue(2));
6654 /// ReplaceNodeResults - Replace a node with an illegal result type
6655 /// with a new node built out of custom code.
6656 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6657 SmallVectorImpl<SDValue>&Results,
6658 SelectionDAG &DAG) {
6659 DebugLoc dl = N->getDebugLoc();
6660 switch (N->getOpcode()) {
6662 assert(false && "Do not know how to custom type legalize this operation!");
6664 case ISD::FP_TO_SINT: {
6665 std::pair<SDValue,SDValue> Vals =
6666 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
6667 SDValue FIST = Vals.first, StackSlot = Vals.second;
6668 if (FIST.getNode() != 0) {
6669 MVT VT = N->getValueType(0);
6670 // Return a load from the stack slot.
6671 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6675 case ISD::READCYCLECOUNTER: {
6676 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6677 SDValue TheChain = N->getOperand(0);
6678 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6679 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6681 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6683 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6684 SDValue Ops[] = { eax, edx };
6685 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6686 Results.push_back(edx.getValue(1));
6689 case ISD::ATOMIC_CMP_SWAP: {
6690 MVT T = N->getValueType(0);
6691 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6692 SDValue cpInL, cpInH;
6693 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6694 DAG.getConstant(0, MVT::i32));
6695 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6696 DAG.getConstant(1, MVT::i32));
6697 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6698 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6700 SDValue swapInL, swapInH;
6701 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6702 DAG.getConstant(0, MVT::i32));
6703 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6704 DAG.getConstant(1, MVT::i32));
6705 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6707 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6708 swapInL.getValue(1));
6709 SDValue Ops[] = { swapInH.getValue(0),
6711 swapInH.getValue(1) };
6712 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6713 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6714 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6715 MVT::i32, Result.getValue(1));
6716 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6717 MVT::i32, cpOutL.getValue(2));
6718 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6719 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6720 Results.push_back(cpOutH.getValue(1));
6723 case ISD::ATOMIC_LOAD_ADD:
6724 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6726 case ISD::ATOMIC_LOAD_AND:
6727 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6729 case ISD::ATOMIC_LOAD_NAND:
6730 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6732 case ISD::ATOMIC_LOAD_OR:
6733 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6735 case ISD::ATOMIC_LOAD_SUB:
6736 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6738 case ISD::ATOMIC_LOAD_XOR:
6739 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6741 case ISD::ATOMIC_SWAP:
6742 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6747 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6749 default: return NULL;
6750 case X86ISD::BSF: return "X86ISD::BSF";
6751 case X86ISD::BSR: return "X86ISD::BSR";
6752 case X86ISD::SHLD: return "X86ISD::SHLD";
6753 case X86ISD::SHRD: return "X86ISD::SHRD";
6754 case X86ISD::FAND: return "X86ISD::FAND";
6755 case X86ISD::FOR: return "X86ISD::FOR";
6756 case X86ISD::FXOR: return "X86ISD::FXOR";
6757 case X86ISD::FSRL: return "X86ISD::FSRL";
6758 case X86ISD::FILD: return "X86ISD::FILD";
6759 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6760 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6761 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6762 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6763 case X86ISD::FLD: return "X86ISD::FLD";
6764 case X86ISD::FST: return "X86ISD::FST";
6765 case X86ISD::CALL: return "X86ISD::CALL";
6766 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6767 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6768 case X86ISD::BT: return "X86ISD::BT";
6769 case X86ISD::CMP: return "X86ISD::CMP";
6770 case X86ISD::COMI: return "X86ISD::COMI";
6771 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6772 case X86ISD::SETCC: return "X86ISD::SETCC";
6773 case X86ISD::CMOV: return "X86ISD::CMOV";
6774 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6775 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6776 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6777 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6778 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6779 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6780 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6781 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6782 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6783 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6784 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6785 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
6786 case X86ISD::FMAX: return "X86ISD::FMAX";
6787 case X86ISD::FMIN: return "X86ISD::FMIN";
6788 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6789 case X86ISD::FRCP: return "X86ISD::FRCP";
6790 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6791 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
6792 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6793 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6794 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6795 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6796 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6797 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6798 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6799 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6800 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6801 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6802 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6803 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6804 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6805 case X86ISD::VSHL: return "X86ISD::VSHL";
6806 case X86ISD::VSRL: return "X86ISD::VSRL";
6807 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6808 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6809 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6810 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6811 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6812 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6813 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6814 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6815 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6816 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6817 case X86ISD::ADD: return "X86ISD::ADD";
6818 case X86ISD::SUB: return "X86ISD::SUB";
6819 case X86ISD::SMUL: return "X86ISD::SMUL";
6820 case X86ISD::UMUL: return "X86ISD::UMUL";
6821 case X86ISD::INC: return "X86ISD::INC";
6822 case X86ISD::DEC: return "X86ISD::DEC";
6823 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
6827 // isLegalAddressingMode - Return true if the addressing mode represented
6828 // by AM is legal for this target, for a load/store of the specified type.
6829 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6830 const Type *Ty) const {
6831 // X86 supports extremely general addressing modes.
6833 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6834 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6838 // We can only fold this if we don't need an extra load.
6839 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6841 // If BaseGV requires a register, we cannot also have a BaseReg.
6842 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6846 // X86-64 only supports addr of globals in small code model.
6847 if (Subtarget->is64Bit()) {
6848 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6850 // If lower 4G is not available, then we must use rip-relative addressing.
6851 if (AM.BaseOffs || AM.Scale > 1)
6862 // These scales always work.
6867 // These scales are formed with basereg+scalereg. Only accept if there is
6872 default: // Other stuff never works.
6880 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6881 if (!Ty1->isInteger() || !Ty2->isInteger())
6883 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6884 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6885 if (NumBits1 <= NumBits2)
6887 return Subtarget->is64Bit() || NumBits1 < 64;
6890 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6891 if (!VT1.isInteger() || !VT2.isInteger())
6893 unsigned NumBits1 = VT1.getSizeInBits();
6894 unsigned NumBits2 = VT2.getSizeInBits();
6895 if (NumBits1 <= NumBits2)
6897 return Subtarget->is64Bit() || NumBits1 < 64;
6900 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
6901 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6902 return Ty1 == Type::Int32Ty && Ty2 == Type::Int64Ty && Subtarget->is64Bit();
6905 bool X86TargetLowering::isZExtFree(MVT VT1, MVT VT2) const {
6906 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6907 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
6910 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6911 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6912 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6913 /// are assumed to be legal.
6915 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6917 // Only do shuffles on 128-bit vector types for now.
6918 if (VT.getSizeInBits() == 64)
6921 // FIXME: pshufb, blends, palignr, shifts.
6922 return (VT.getVectorNumElements() == 2 ||
6923 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6924 isMOVLMask(M, VT) ||
6925 isSHUFPMask(M, VT) ||
6926 isPSHUFDMask(M, VT) ||
6927 isPSHUFHWMask(M, VT) ||
6928 isPSHUFLWMask(M, VT) ||
6929 isUNPCKLMask(M, VT) ||
6930 isUNPCKHMask(M, VT) ||
6931 isUNPCKL_v_undef_Mask(M, VT) ||
6932 isUNPCKH_v_undef_Mask(M, VT));
6936 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
6938 unsigned NumElts = VT.getVectorNumElements();
6939 // FIXME: This collection of masks seems suspect.
6942 if (NumElts == 4 && VT.getSizeInBits() == 128) {
6943 return (isMOVLMask(Mask, VT) ||
6944 isCommutedMOVLMask(Mask, VT, true) ||
6945 isSHUFPMask(Mask, VT) ||
6946 isCommutedSHUFPMask(Mask, VT));
6951 //===----------------------------------------------------------------------===//
6952 // X86 Scheduler Hooks
6953 //===----------------------------------------------------------------------===//
6955 // private utility function
6957 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6958 MachineBasicBlock *MBB,
6966 TargetRegisterClass *RC,
6967 bool invSrc) const {
6968 // For the atomic bitwise operator, we generate
6971 // ld t1 = [bitinstr.addr]
6972 // op t2 = t1, [bitinstr.val]
6974 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6976 // fallthrough -->nextMBB
6977 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6978 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6979 MachineFunction::iterator MBBIter = MBB;
6982 /// First build the CFG
6983 MachineFunction *F = MBB->getParent();
6984 MachineBasicBlock *thisMBB = MBB;
6985 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6986 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6987 F->insert(MBBIter, newMBB);
6988 F->insert(MBBIter, nextMBB);
6990 // Move all successors to thisMBB to nextMBB
6991 nextMBB->transferSuccessors(thisMBB);
6993 // Update thisMBB to fall through to newMBB
6994 thisMBB->addSuccessor(newMBB);
6996 // newMBB jumps to itself and fall through to nextMBB
6997 newMBB->addSuccessor(nextMBB);
6998 newMBB->addSuccessor(newMBB);
7000 // Insert instructions into newMBB based on incoming instruction
7001 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7002 "unexpected number of operands");
7003 DebugLoc dl = bInstr->getDebugLoc();
7004 MachineOperand& destOper = bInstr->getOperand(0);
7005 MachineOperand* argOpers[2 + X86AddrNumOperands];
7006 int numArgs = bInstr->getNumOperands() - 1;
7007 for (int i=0; i < numArgs; ++i)
7008 argOpers[i] = &bInstr->getOperand(i+1);
7010 // x86 address has 4 operands: base, index, scale, and displacement
7011 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7012 int valArgIndx = lastAddrIndx + 1;
7014 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7015 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7016 for (int i=0; i <= lastAddrIndx; ++i)
7017 (*MIB).addOperand(*argOpers[i]);
7019 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7021 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7026 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7027 assert((argOpers[valArgIndx]->isReg() ||
7028 argOpers[valArgIndx]->isImm()) &&
7030 if (argOpers[valArgIndx]->isReg())
7031 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7033 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7035 (*MIB).addOperand(*argOpers[valArgIndx]);
7037 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7040 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7041 for (int i=0; i <= lastAddrIndx; ++i)
7042 (*MIB).addOperand(*argOpers[i]);
7044 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7045 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7047 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7051 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7053 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7057 // private utility function: 64 bit atomics on 32 bit host.
7059 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7060 MachineBasicBlock *MBB,
7065 bool invSrc) const {
7066 // For the atomic bitwise operator, we generate
7067 // thisMBB (instructions are in pairs, except cmpxchg8b)
7068 // ld t1,t2 = [bitinstr.addr]
7070 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7071 // op t5, t6 <- out1, out2, [bitinstr.val]
7072 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7073 // mov ECX, EBX <- t5, t6
7074 // mov EAX, EDX <- t1, t2
7075 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7076 // mov t3, t4 <- EAX, EDX
7078 // result in out1, out2
7079 // fallthrough -->nextMBB
7081 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7082 const unsigned LoadOpc = X86::MOV32rm;
7083 const unsigned copyOpc = X86::MOV32rr;
7084 const unsigned NotOpc = X86::NOT32r;
7085 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7086 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7087 MachineFunction::iterator MBBIter = MBB;
7090 /// First build the CFG
7091 MachineFunction *F = MBB->getParent();
7092 MachineBasicBlock *thisMBB = MBB;
7093 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7094 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7095 F->insert(MBBIter, newMBB);
7096 F->insert(MBBIter, nextMBB);
7098 // Move all successors to thisMBB to nextMBB
7099 nextMBB->transferSuccessors(thisMBB);
7101 // Update thisMBB to fall through to newMBB
7102 thisMBB->addSuccessor(newMBB);
7104 // newMBB jumps to itself and fall through to nextMBB
7105 newMBB->addSuccessor(nextMBB);
7106 newMBB->addSuccessor(newMBB);
7108 DebugLoc dl = bInstr->getDebugLoc();
7109 // Insert instructions into newMBB based on incoming instruction
7110 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7111 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7112 "unexpected number of operands");
7113 MachineOperand& dest1Oper = bInstr->getOperand(0);
7114 MachineOperand& dest2Oper = bInstr->getOperand(1);
7115 MachineOperand* argOpers[2 + X86AddrNumOperands];
7116 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7117 argOpers[i] = &bInstr->getOperand(i+2);
7119 // x86 address has 4 operands: base, index, scale, and displacement
7120 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7122 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7123 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7124 for (int i=0; i <= lastAddrIndx; ++i)
7125 (*MIB).addOperand(*argOpers[i]);
7126 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7127 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7128 // add 4 to displacement.
7129 for (int i=0; i <= lastAddrIndx-2; ++i)
7130 (*MIB).addOperand(*argOpers[i]);
7131 MachineOperand newOp3 = *(argOpers[3]);
7133 newOp3.setImm(newOp3.getImm()+4);
7135 newOp3.setOffset(newOp3.getOffset()+4);
7136 (*MIB).addOperand(newOp3);
7137 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7139 // t3/4 are defined later, at the bottom of the loop
7140 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7141 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7142 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7143 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7144 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7145 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7147 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7148 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7150 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7151 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7157 int valArgIndx = lastAddrIndx + 1;
7158 assert((argOpers[valArgIndx]->isReg() ||
7159 argOpers[valArgIndx]->isImm()) &&
7161 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7162 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7163 if (argOpers[valArgIndx]->isReg())
7164 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7166 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7167 if (regOpcL != X86::MOV32rr)
7169 (*MIB).addOperand(*argOpers[valArgIndx]);
7170 assert(argOpers[valArgIndx + 1]->isReg() ==
7171 argOpers[valArgIndx]->isReg());
7172 assert(argOpers[valArgIndx + 1]->isImm() ==
7173 argOpers[valArgIndx]->isImm());
7174 if (argOpers[valArgIndx + 1]->isReg())
7175 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7177 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7178 if (regOpcH != X86::MOV32rr)
7180 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7182 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7184 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7187 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7189 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7192 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7193 for (int i=0; i <= lastAddrIndx; ++i)
7194 (*MIB).addOperand(*argOpers[i]);
7196 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7197 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7199 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7200 MIB.addReg(X86::EAX);
7201 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7202 MIB.addReg(X86::EDX);
7205 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7207 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7211 // private utility function
7213 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7214 MachineBasicBlock *MBB,
7215 unsigned cmovOpc) const {
7216 // For the atomic min/max operator, we generate
7219 // ld t1 = [min/max.addr]
7220 // mov t2 = [min/max.val]
7222 // cmov[cond] t2 = t1
7224 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7226 // fallthrough -->nextMBB
7228 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7229 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7230 MachineFunction::iterator MBBIter = MBB;
7233 /// First build the CFG
7234 MachineFunction *F = MBB->getParent();
7235 MachineBasicBlock *thisMBB = MBB;
7236 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7237 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7238 F->insert(MBBIter, newMBB);
7239 F->insert(MBBIter, nextMBB);
7241 // Move all successors to thisMBB to nextMBB
7242 nextMBB->transferSuccessors(thisMBB);
7244 // Update thisMBB to fall through to newMBB
7245 thisMBB->addSuccessor(newMBB);
7247 // newMBB jumps to newMBB and fall through to nextMBB
7248 newMBB->addSuccessor(nextMBB);
7249 newMBB->addSuccessor(newMBB);
7251 DebugLoc dl = mInstr->getDebugLoc();
7252 // Insert instructions into newMBB based on incoming instruction
7253 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7254 "unexpected number of operands");
7255 MachineOperand& destOper = mInstr->getOperand(0);
7256 MachineOperand* argOpers[2 + X86AddrNumOperands];
7257 int numArgs = mInstr->getNumOperands() - 1;
7258 for (int i=0; i < numArgs; ++i)
7259 argOpers[i] = &mInstr->getOperand(i+1);
7261 // x86 address has 4 operands: base, index, scale, and displacement
7262 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7263 int valArgIndx = lastAddrIndx + 1;
7265 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7266 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7267 for (int i=0; i <= lastAddrIndx; ++i)
7268 (*MIB).addOperand(*argOpers[i]);
7270 // We only support register and immediate values
7271 assert((argOpers[valArgIndx]->isReg() ||
7272 argOpers[valArgIndx]->isImm()) &&
7275 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7276 if (argOpers[valArgIndx]->isReg())
7277 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7279 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7280 (*MIB).addOperand(*argOpers[valArgIndx]);
7282 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7285 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7290 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7291 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7295 // Cmp and exchange if none has modified the memory location
7296 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7297 for (int i=0; i <= lastAddrIndx; ++i)
7298 (*MIB).addOperand(*argOpers[i]);
7300 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7301 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7303 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7304 MIB.addReg(X86::EAX);
7307 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7309 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7315 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7316 MachineBasicBlock *BB) const {
7317 DebugLoc dl = MI->getDebugLoc();
7318 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7319 switch (MI->getOpcode()) {
7320 default: assert(false && "Unexpected instr type to insert");
7321 case X86::CMOV_V1I64:
7322 case X86::CMOV_FR32:
7323 case X86::CMOV_FR64:
7324 case X86::CMOV_V4F32:
7325 case X86::CMOV_V2F64:
7326 case X86::CMOV_V2I64: {
7327 // To "insert" a SELECT_CC instruction, we actually have to insert the
7328 // diamond control-flow pattern. The incoming instruction knows the
7329 // destination vreg to set, the condition code register to branch on, the
7330 // true/false values to select between, and a branch opcode to use.
7331 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7332 MachineFunction::iterator It = BB;
7338 // cmpTY ccX, r1, r2
7340 // fallthrough --> copy0MBB
7341 MachineBasicBlock *thisMBB = BB;
7342 MachineFunction *F = BB->getParent();
7343 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7344 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7346 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7347 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7348 F->insert(It, copy0MBB);
7349 F->insert(It, sinkMBB);
7350 // Update machine-CFG edges by transferring all successors of the current
7351 // block to the new block which will contain the Phi node for the select.
7352 sinkMBB->transferSuccessors(BB);
7354 // Add the true and fallthrough blocks as its successors.
7355 BB->addSuccessor(copy0MBB);
7356 BB->addSuccessor(sinkMBB);
7359 // %FalseValue = ...
7360 // # fallthrough to sinkMBB
7363 // Update machine-CFG edges
7364 BB->addSuccessor(sinkMBB);
7367 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7370 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7371 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7372 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7374 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7378 case X86::FP32_TO_INT16_IN_MEM:
7379 case X86::FP32_TO_INT32_IN_MEM:
7380 case X86::FP32_TO_INT64_IN_MEM:
7381 case X86::FP64_TO_INT16_IN_MEM:
7382 case X86::FP64_TO_INT32_IN_MEM:
7383 case X86::FP64_TO_INT64_IN_MEM:
7384 case X86::FP80_TO_INT16_IN_MEM:
7385 case X86::FP80_TO_INT32_IN_MEM:
7386 case X86::FP80_TO_INT64_IN_MEM: {
7387 // Change the floating point control register to use "round towards zero"
7388 // mode when truncating to an integer value.
7389 MachineFunction *F = BB->getParent();
7390 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7391 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7393 // Load the old value of the high byte of the control word...
7395 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7396 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7399 // Set the high part to be round to zero...
7400 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7403 // Reload the modified control word now...
7404 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7406 // Restore the memory image of control word to original value
7407 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7410 // Get the X86 opcode to use.
7412 switch (MI->getOpcode()) {
7413 default: assert(0 && "illegal opcode!");
7414 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7415 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7416 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7417 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7418 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7419 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7420 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7421 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7422 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7426 MachineOperand &Op = MI->getOperand(0);
7428 AM.BaseType = X86AddressMode::RegBase;
7429 AM.Base.Reg = Op.getReg();
7431 AM.BaseType = X86AddressMode::FrameIndexBase;
7432 AM.Base.FrameIndex = Op.getIndex();
7434 Op = MI->getOperand(1);
7436 AM.Scale = Op.getImm();
7437 Op = MI->getOperand(2);
7439 AM.IndexReg = Op.getImm();
7440 Op = MI->getOperand(3);
7441 if (Op.isGlobal()) {
7442 AM.GV = Op.getGlobal();
7444 AM.Disp = Op.getImm();
7446 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7447 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7449 // Reload the original control word now.
7450 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7452 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7455 case X86::ATOMAND32:
7456 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7457 X86::AND32ri, X86::MOV32rm,
7458 X86::LCMPXCHG32, X86::MOV32rr,
7459 X86::NOT32r, X86::EAX,
7460 X86::GR32RegisterClass);
7462 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7463 X86::OR32ri, X86::MOV32rm,
7464 X86::LCMPXCHG32, X86::MOV32rr,
7465 X86::NOT32r, X86::EAX,
7466 X86::GR32RegisterClass);
7467 case X86::ATOMXOR32:
7468 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7469 X86::XOR32ri, X86::MOV32rm,
7470 X86::LCMPXCHG32, X86::MOV32rr,
7471 X86::NOT32r, X86::EAX,
7472 X86::GR32RegisterClass);
7473 case X86::ATOMNAND32:
7474 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7475 X86::AND32ri, X86::MOV32rm,
7476 X86::LCMPXCHG32, X86::MOV32rr,
7477 X86::NOT32r, X86::EAX,
7478 X86::GR32RegisterClass, true);
7479 case X86::ATOMMIN32:
7480 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7481 case X86::ATOMMAX32:
7482 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7483 case X86::ATOMUMIN32:
7484 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7485 case X86::ATOMUMAX32:
7486 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7488 case X86::ATOMAND16:
7489 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7490 X86::AND16ri, X86::MOV16rm,
7491 X86::LCMPXCHG16, X86::MOV16rr,
7492 X86::NOT16r, X86::AX,
7493 X86::GR16RegisterClass);
7495 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7496 X86::OR16ri, X86::MOV16rm,
7497 X86::LCMPXCHG16, X86::MOV16rr,
7498 X86::NOT16r, X86::AX,
7499 X86::GR16RegisterClass);
7500 case X86::ATOMXOR16:
7501 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7502 X86::XOR16ri, X86::MOV16rm,
7503 X86::LCMPXCHG16, X86::MOV16rr,
7504 X86::NOT16r, X86::AX,
7505 X86::GR16RegisterClass);
7506 case X86::ATOMNAND16:
7507 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7508 X86::AND16ri, X86::MOV16rm,
7509 X86::LCMPXCHG16, X86::MOV16rr,
7510 X86::NOT16r, X86::AX,
7511 X86::GR16RegisterClass, true);
7512 case X86::ATOMMIN16:
7513 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7514 case X86::ATOMMAX16:
7515 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7516 case X86::ATOMUMIN16:
7517 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7518 case X86::ATOMUMAX16:
7519 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7522 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7523 X86::AND8ri, X86::MOV8rm,
7524 X86::LCMPXCHG8, X86::MOV8rr,
7525 X86::NOT8r, X86::AL,
7526 X86::GR8RegisterClass);
7528 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7529 X86::OR8ri, X86::MOV8rm,
7530 X86::LCMPXCHG8, X86::MOV8rr,
7531 X86::NOT8r, X86::AL,
7532 X86::GR8RegisterClass);
7534 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7535 X86::XOR8ri, X86::MOV8rm,
7536 X86::LCMPXCHG8, X86::MOV8rr,
7537 X86::NOT8r, X86::AL,
7538 X86::GR8RegisterClass);
7539 case X86::ATOMNAND8:
7540 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7541 X86::AND8ri, X86::MOV8rm,
7542 X86::LCMPXCHG8, X86::MOV8rr,
7543 X86::NOT8r, X86::AL,
7544 X86::GR8RegisterClass, true);
7545 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7546 // This group is for 64-bit host.
7547 case X86::ATOMAND64:
7548 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7549 X86::AND64ri32, X86::MOV64rm,
7550 X86::LCMPXCHG64, X86::MOV64rr,
7551 X86::NOT64r, X86::RAX,
7552 X86::GR64RegisterClass);
7554 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7555 X86::OR64ri32, X86::MOV64rm,
7556 X86::LCMPXCHG64, X86::MOV64rr,
7557 X86::NOT64r, X86::RAX,
7558 X86::GR64RegisterClass);
7559 case X86::ATOMXOR64:
7560 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7561 X86::XOR64ri32, X86::MOV64rm,
7562 X86::LCMPXCHG64, X86::MOV64rr,
7563 X86::NOT64r, X86::RAX,
7564 X86::GR64RegisterClass);
7565 case X86::ATOMNAND64:
7566 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7567 X86::AND64ri32, X86::MOV64rm,
7568 X86::LCMPXCHG64, X86::MOV64rr,
7569 X86::NOT64r, X86::RAX,
7570 X86::GR64RegisterClass, true);
7571 case X86::ATOMMIN64:
7572 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7573 case X86::ATOMMAX64:
7574 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7575 case X86::ATOMUMIN64:
7576 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7577 case X86::ATOMUMAX64:
7578 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7580 // This group does 64-bit operations on a 32-bit host.
7581 case X86::ATOMAND6432:
7582 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7583 X86::AND32rr, X86::AND32rr,
7584 X86::AND32ri, X86::AND32ri,
7586 case X86::ATOMOR6432:
7587 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7588 X86::OR32rr, X86::OR32rr,
7589 X86::OR32ri, X86::OR32ri,
7591 case X86::ATOMXOR6432:
7592 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7593 X86::XOR32rr, X86::XOR32rr,
7594 X86::XOR32ri, X86::XOR32ri,
7596 case X86::ATOMNAND6432:
7597 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7598 X86::AND32rr, X86::AND32rr,
7599 X86::AND32ri, X86::AND32ri,
7601 case X86::ATOMADD6432:
7602 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7603 X86::ADD32rr, X86::ADC32rr,
7604 X86::ADD32ri, X86::ADC32ri,
7606 case X86::ATOMSUB6432:
7607 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7608 X86::SUB32rr, X86::SBB32rr,
7609 X86::SUB32ri, X86::SBB32ri,
7611 case X86::ATOMSWAP6432:
7612 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7613 X86::MOV32rr, X86::MOV32rr,
7614 X86::MOV32ri, X86::MOV32ri,
7619 //===----------------------------------------------------------------------===//
7620 // X86 Optimization Hooks
7621 //===----------------------------------------------------------------------===//
7623 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7627 const SelectionDAG &DAG,
7628 unsigned Depth) const {
7629 unsigned Opc = Op.getOpcode();
7630 assert((Opc >= ISD::BUILTIN_OP_END ||
7631 Opc == ISD::INTRINSIC_WO_CHAIN ||
7632 Opc == ISD::INTRINSIC_W_CHAIN ||
7633 Opc == ISD::INTRINSIC_VOID) &&
7634 "Should use MaskedValueIsZero if you don't know whether Op"
7635 " is a target node!");
7637 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7646 // These nodes' second result is a boolean.
7647 if (Op.getResNo() == 0)
7651 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7652 Mask.getBitWidth() - 1);
7657 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7658 /// node is a GlobalAddress + offset.
7659 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7660 GlobalValue* &GA, int64_t &Offset) const{
7661 if (N->getOpcode() == X86ISD::Wrapper) {
7662 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7663 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7664 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7668 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7671 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7672 const TargetLowering &TLI) {
7675 if (TLI.isGAPlusOffset(Base, GV, Offset))
7676 return (GV->getAlignment() >= N && (Offset % N) == 0);
7677 // DAG combine handles the stack object case.
7681 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
7682 MVT EVT, SDNode *&Base,
7683 SelectionDAG &DAG, MachineFrameInfo *MFI,
7684 const TargetLowering &TLI) {
7686 for (unsigned i = 0; i < NumElems; ++i) {
7687 if (N->getMaskElt(i) < 0) {
7693 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7694 if (!Elt.getNode() ||
7695 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7698 Base = Elt.getNode();
7699 if (Base->getOpcode() == ISD::UNDEF)
7703 if (Elt.getOpcode() == ISD::UNDEF)
7706 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7707 EVT.getSizeInBits()/8, i, MFI))
7713 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7714 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7715 /// if the load addresses are consecutive, non-overlapping, and in the right
7716 /// order. In the case of v2i64, it will see if it can rewrite the
7717 /// shuffle to be an appropriate build vector so it can take advantage of
7718 // performBuildVectorCombine.
7719 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7720 const TargetLowering &TLI) {
7721 DebugLoc dl = N->getDebugLoc();
7722 MVT VT = N->getValueType(0);
7723 MVT EVT = VT.getVectorElementType();
7724 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7725 unsigned NumElems = VT.getVectorNumElements();
7727 // For x86-32 machines, if we see an insert and then a shuffle in a v2i64
7728 // where the upper half is 0, it is advantageous to rewrite it as a build
7729 // vector of (0, val) so it can use movq.
7730 if (VT == MVT::v2i64) {
7732 In[0] = N->getOperand(0);
7733 In[1] = N->getOperand(1);
7734 int Idx0 = SVN->getMaskElt(0);
7735 int Idx1 = SVN->getMaskElt(1);
7736 // FIXME: can we take advantage of undef index?
7737 if (Idx0 >= 0 && Idx1 >= 0 &&
7738 In[Idx0/2].getOpcode() == ISD::INSERT_VECTOR_ELT &&
7739 In[Idx1/2].getOpcode() == ISD::BUILD_VECTOR) {
7740 ConstantSDNode* InsertVecIdx =
7741 dyn_cast<ConstantSDNode>(In[Idx0/2].getOperand(2));
7743 InsertVecIdx->getZExtValue() == (unsigned)(Idx0 % 2) &&
7744 isZeroNode(In[Idx1/2].getOperand(Idx1 % 2))) {
7745 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7746 In[Idx0/2].getOperand(1),
7747 In[Idx1/2].getOperand(Idx1 % 2));
7752 // Try to combine a vector_shuffle into a 128-bit load.
7753 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7754 SDNode *Base = NULL;
7755 if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, Base, DAG, MFI, TLI))
7758 LoadSDNode *LD = cast<LoadSDNode>(Base);
7759 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7760 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7761 LD->getSrcValue(), LD->getSrcValueOffset(),
7763 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7764 LD->getSrcValue(), LD->getSrcValueOffset(),
7765 LD->isVolatile(), LD->getAlignment());
7768 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7769 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7770 TargetLowering::DAGCombinerInfo &DCI,
7771 const X86Subtarget *Subtarget,
7772 const TargetLowering &TLI) {
7773 unsigned NumOps = N->getNumOperands();
7774 DebugLoc dl = N->getDebugLoc();
7776 // Ignore single operand BUILD_VECTOR.
7780 MVT VT = N->getValueType(0);
7781 MVT EVT = VT.getVectorElementType();
7782 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7783 // We are looking for load i64 and zero extend. We want to transform
7784 // it before legalizer has a chance to expand it. Also look for i64
7785 // BUILD_PAIR bit casted to f64.
7787 // This must be an insertion into a zero vector.
7788 SDValue HighElt = N->getOperand(1);
7789 if (!isZeroNode(HighElt))
7792 // Value must be a load.
7793 SDNode *Base = N->getOperand(0).getNode();
7794 if (!isa<LoadSDNode>(Base)) {
7795 if (Base->getOpcode() != ISD::BIT_CONVERT)
7797 Base = Base->getOperand(0).getNode();
7798 if (!isa<LoadSDNode>(Base))
7802 // Transform it into VZEXT_LOAD addr.
7803 LoadSDNode *LD = cast<LoadSDNode>(Base);
7805 // Load must not be an extload.
7806 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7809 // Load type should legal type so we don't have to legalize it.
7810 if (!TLI.isTypeLegal(VT))
7813 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7814 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7815 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7816 TargetLowering::TargetLoweringOpt TLO(DAG);
7817 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
7818 DCI.CommitTargetLoweringOpt(TLO);
7822 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7823 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7824 const X86Subtarget *Subtarget) {
7825 DebugLoc DL = N->getDebugLoc();
7826 SDValue Cond = N->getOperand(0);
7827 // Get the LHS/RHS of the select.
7828 SDValue LHS = N->getOperand(1);
7829 SDValue RHS = N->getOperand(2);
7831 // If we have SSE[12] support, try to form min/max nodes.
7832 if (Subtarget->hasSSE2() &&
7833 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
7834 Cond.getOpcode() == ISD::SETCC) {
7835 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7837 unsigned Opcode = 0;
7838 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7841 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7844 if (!UnsafeFPMath) break;
7846 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7848 Opcode = X86ISD::FMIN;
7851 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7854 if (!UnsafeFPMath) break;
7856 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7858 Opcode = X86ISD::FMAX;
7861 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7864 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7867 if (!UnsafeFPMath) break;
7869 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7871 Opcode = X86ISD::FMIN;
7874 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7877 if (!UnsafeFPMath) break;
7879 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7881 Opcode = X86ISD::FMAX;
7887 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
7890 // If this is a select between two integer constants, try to do some
7892 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
7893 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
7894 // Don't do this for crazy integer types.
7895 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
7896 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
7897 // so that TrueC (the true value) is larger than FalseC.
7898 bool NeedsCondInvert = false;
7900 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
7901 // Efficiently invertible.
7902 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
7903 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
7904 isa<ConstantSDNode>(Cond.getOperand(1))))) {
7905 NeedsCondInvert = true;
7906 std::swap(TrueC, FalseC);
7909 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
7910 if (FalseC->getAPIntValue() == 0 &&
7911 TrueC->getAPIntValue().isPowerOf2()) {
7912 if (NeedsCondInvert) // Invert the condition if needed.
7913 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7914 DAG.getConstant(1, Cond.getValueType()));
7916 // Zero extend the condition if needed.
7917 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
7919 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7920 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
7921 DAG.getConstant(ShAmt, MVT::i8));
7924 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
7925 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
7926 if (NeedsCondInvert) // Invert the condition if needed.
7927 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7928 DAG.getConstant(1, Cond.getValueType()));
7930 // Zero extend the condition if needed.
7931 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
7932 FalseC->getValueType(0), Cond);
7933 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7934 SDValue(FalseC, 0));
7937 // Optimize cases that will turn into an LEA instruction. This requires
7938 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
7939 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
7940 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
7941 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
7943 bool isFastMultiplier = false;
7945 switch ((unsigned char)Diff) {
7947 case 1: // result = add base, cond
7948 case 2: // result = lea base( , cond*2)
7949 case 3: // result = lea base(cond, cond*2)
7950 case 4: // result = lea base( , cond*4)
7951 case 5: // result = lea base(cond, cond*4)
7952 case 8: // result = lea base( , cond*8)
7953 case 9: // result = lea base(cond, cond*8)
7954 isFastMultiplier = true;
7959 if (isFastMultiplier) {
7960 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
7961 if (NeedsCondInvert) // Invert the condition if needed.
7962 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7963 DAG.getConstant(1, Cond.getValueType()));
7965 // Zero extend the condition if needed.
7966 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
7968 // Scale the condition by the difference.
7970 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
7971 DAG.getConstant(Diff, Cond.getValueType()));
7973 // Add the base if non-zero.
7974 if (FalseC->getAPIntValue() != 0)
7975 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7976 SDValue(FalseC, 0));
7986 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
7987 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
7988 TargetLowering::DAGCombinerInfo &DCI) {
7989 DebugLoc DL = N->getDebugLoc();
7991 // If the flag operand isn't dead, don't touch this CMOV.
7992 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
7995 // If this is a select between two integer constants, try to do some
7996 // optimizations. Note that the operands are ordered the opposite of SELECT
7998 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7999 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8000 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8001 // larger than FalseC (the false value).
8002 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8004 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8005 CC = X86::GetOppositeBranchCondition(CC);
8006 std::swap(TrueC, FalseC);
8009 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8010 // This is efficient for any integer data type (including i8/i16) and
8012 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8013 SDValue Cond = N->getOperand(3);
8014 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8015 DAG.getConstant(CC, MVT::i8), Cond);
8017 // Zero extend the condition if needed.
8018 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8020 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8021 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8022 DAG.getConstant(ShAmt, MVT::i8));
8023 if (N->getNumValues() == 2) // Dead flag value?
8024 return DCI.CombineTo(N, Cond, SDValue());
8028 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8029 // for any integer data type, including i8/i16.
8030 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8031 SDValue Cond = N->getOperand(3);
8032 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8033 DAG.getConstant(CC, MVT::i8), Cond);
8035 // Zero extend the condition if needed.
8036 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8037 FalseC->getValueType(0), Cond);
8038 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8039 SDValue(FalseC, 0));
8041 if (N->getNumValues() == 2) // Dead flag value?
8042 return DCI.CombineTo(N, Cond, SDValue());
8046 // Optimize cases that will turn into an LEA instruction. This requires
8047 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8048 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8049 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8050 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8052 bool isFastMultiplier = false;
8054 switch ((unsigned char)Diff) {
8056 case 1: // result = add base, cond
8057 case 2: // result = lea base( , cond*2)
8058 case 3: // result = lea base(cond, cond*2)
8059 case 4: // result = lea base( , cond*4)
8060 case 5: // result = lea base(cond, cond*4)
8061 case 8: // result = lea base( , cond*8)
8062 case 9: // result = lea base(cond, cond*8)
8063 isFastMultiplier = true;
8068 if (isFastMultiplier) {
8069 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8070 SDValue Cond = N->getOperand(3);
8071 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8072 DAG.getConstant(CC, MVT::i8), Cond);
8073 // Zero extend the condition if needed.
8074 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8076 // Scale the condition by the difference.
8078 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8079 DAG.getConstant(Diff, Cond.getValueType()));
8081 // Add the base if non-zero.
8082 if (FalseC->getAPIntValue() != 0)
8083 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8084 SDValue(FalseC, 0));
8085 if (N->getNumValues() == 2) // Dead flag value?
8086 return DCI.CombineTo(N, Cond, SDValue());
8096 /// PerformMulCombine - Optimize a single multiply with constant into two
8097 /// in order to implement it with two cheaper instructions, e.g.
8098 /// LEA + SHL, LEA + LEA.
8099 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8100 TargetLowering::DAGCombinerInfo &DCI) {
8101 if (DAG.getMachineFunction().
8102 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8105 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8108 MVT VT = N->getValueType(0);
8112 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8115 uint64_t MulAmt = C->getZExtValue();
8116 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8119 uint64_t MulAmt1 = 0;
8120 uint64_t MulAmt2 = 0;
8121 if ((MulAmt % 9) == 0) {
8123 MulAmt2 = MulAmt / 9;
8124 } else if ((MulAmt % 5) == 0) {
8126 MulAmt2 = MulAmt / 5;
8127 } else if ((MulAmt % 3) == 0) {
8129 MulAmt2 = MulAmt / 3;
8132 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8133 DebugLoc DL = N->getDebugLoc();
8135 if (isPowerOf2_64(MulAmt2) &&
8136 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8137 // If second multiplifer is pow2, issue it first. We want the multiply by
8138 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8140 std::swap(MulAmt1, MulAmt2);
8143 if (isPowerOf2_64(MulAmt1))
8144 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8145 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8147 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8148 DAG.getConstant(MulAmt1, VT));
8150 if (isPowerOf2_64(MulAmt2))
8151 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8152 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8154 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8155 DAG.getConstant(MulAmt2, VT));
8157 // Do not add new nodes to DAG combiner worklist.
8158 DCI.CombineTo(N, NewMul, false);
8164 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8166 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8167 const X86Subtarget *Subtarget) {
8168 // On X86 with SSE2 support, we can transform this to a vector shift if
8169 // all elements are shifted by the same amount. We can't do this in legalize
8170 // because the a constant vector is typically transformed to a constant pool
8171 // so we have no knowledge of the shift amount.
8172 if (!Subtarget->hasSSE2())
8175 MVT VT = N->getValueType(0);
8176 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8179 SDValue ShAmtOp = N->getOperand(1);
8180 MVT EltVT = VT.getVectorElementType();
8181 DebugLoc DL = N->getDebugLoc();
8183 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8184 unsigned NumElts = VT.getVectorNumElements();
8186 for (; i != NumElts; ++i) {
8187 SDValue Arg = ShAmtOp.getOperand(i);
8188 if (Arg.getOpcode() == ISD::UNDEF) continue;
8192 for (; i != NumElts; ++i) {
8193 SDValue Arg = ShAmtOp.getOperand(i);
8194 if (Arg.getOpcode() == ISD::UNDEF) continue;
8195 if (Arg != BaseShAmt) {
8199 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8200 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8201 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8202 DAG.getIntPtrConstant(0));
8206 if (EltVT.bitsGT(MVT::i32))
8207 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8208 else if (EltVT.bitsLT(MVT::i32))
8209 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8211 // The shift amount is identical so we can do a vector shift.
8212 SDValue ValOp = N->getOperand(0);
8213 switch (N->getOpcode()) {
8215 assert(0 && "Unknown shift opcode!");
8218 if (VT == MVT::v2i64)
8219 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8220 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8222 if (VT == MVT::v4i32)
8223 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8224 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8226 if (VT == MVT::v8i16)
8227 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8228 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8232 if (VT == MVT::v4i32)
8233 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8234 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8236 if (VT == MVT::v8i16)
8237 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8238 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8242 if (VT == MVT::v2i64)
8243 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8244 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8246 if (VT == MVT::v4i32)
8247 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8248 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8250 if (VT == MVT::v8i16)
8251 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8252 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8259 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8260 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8261 const X86Subtarget *Subtarget) {
8262 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8263 // the FP state in cases where an emms may be missing.
8264 // A preferable solution to the general problem is to figure out the right
8265 // places to insert EMMS. This qualifies as a quick hack.
8267 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8268 StoreSDNode *St = cast<StoreSDNode>(N);
8269 MVT VT = St->getValue().getValueType();
8270 if (VT.getSizeInBits() != 64)
8273 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloat && Subtarget->hasSSE2();
8274 if ((VT.isVector() ||
8275 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8276 isa<LoadSDNode>(St->getValue()) &&
8277 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8278 St->getChain().hasOneUse() && !St->isVolatile()) {
8279 SDNode* LdVal = St->getValue().getNode();
8281 int TokenFactorIndex = -1;
8282 SmallVector<SDValue, 8> Ops;
8283 SDNode* ChainVal = St->getChain().getNode();
8284 // Must be a store of a load. We currently handle two cases: the load
8285 // is a direct child, and it's under an intervening TokenFactor. It is
8286 // possible to dig deeper under nested TokenFactors.
8287 if (ChainVal == LdVal)
8288 Ld = cast<LoadSDNode>(St->getChain());
8289 else if (St->getValue().hasOneUse() &&
8290 ChainVal->getOpcode() == ISD::TokenFactor) {
8291 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8292 if (ChainVal->getOperand(i).getNode() == LdVal) {
8293 TokenFactorIndex = i;
8294 Ld = cast<LoadSDNode>(St->getValue());
8296 Ops.push_back(ChainVal->getOperand(i));
8300 if (!Ld || !ISD::isNormalLoad(Ld))
8303 // If this is not the MMX case, i.e. we are just turning i64 load/store
8304 // into f64 load/store, avoid the transformation if there are multiple
8305 // uses of the loaded value.
8306 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8309 DebugLoc LdDL = Ld->getDebugLoc();
8310 DebugLoc StDL = N->getDebugLoc();
8311 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8312 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8314 if (Subtarget->is64Bit() || F64IsLegal) {
8315 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8316 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8317 Ld->getBasePtr(), Ld->getSrcValue(),
8318 Ld->getSrcValueOffset(), Ld->isVolatile(),
8319 Ld->getAlignment());
8320 SDValue NewChain = NewLd.getValue(1);
8321 if (TokenFactorIndex != -1) {
8322 Ops.push_back(NewChain);
8323 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8326 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8327 St->getSrcValue(), St->getSrcValueOffset(),
8328 St->isVolatile(), St->getAlignment());
8331 // Otherwise, lower to two pairs of 32-bit loads / stores.
8332 SDValue LoAddr = Ld->getBasePtr();
8333 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8334 DAG.getConstant(4, MVT::i32));
8336 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8337 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8338 Ld->isVolatile(), Ld->getAlignment());
8339 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8340 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8342 MinAlign(Ld->getAlignment(), 4));
8344 SDValue NewChain = LoLd.getValue(1);
8345 if (TokenFactorIndex != -1) {
8346 Ops.push_back(LoLd);
8347 Ops.push_back(HiLd);
8348 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8352 LoAddr = St->getBasePtr();
8353 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8354 DAG.getConstant(4, MVT::i32));
8356 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8357 St->getSrcValue(), St->getSrcValueOffset(),
8358 St->isVolatile(), St->getAlignment());
8359 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8361 St->getSrcValueOffset() + 4,
8363 MinAlign(St->getAlignment(), 4));
8364 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8369 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8370 /// X86ISD::FXOR nodes.
8371 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8372 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8373 // F[X]OR(0.0, x) -> x
8374 // F[X]OR(x, 0.0) -> x
8375 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8376 if (C->getValueAPF().isPosZero())
8377 return N->getOperand(1);
8378 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8379 if (C->getValueAPF().isPosZero())
8380 return N->getOperand(0);
8384 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8385 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8386 // FAND(0.0, x) -> 0.0
8387 // FAND(x, 0.0) -> 0.0
8388 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8389 if (C->getValueAPF().isPosZero())
8390 return N->getOperand(0);
8391 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8392 if (C->getValueAPF().isPosZero())
8393 return N->getOperand(1);
8397 static SDValue PerformBTCombine(SDNode *N,
8399 TargetLowering::DAGCombinerInfo &DCI) {
8400 // BT ignores high bits in the bit index operand.
8401 SDValue Op1 = N->getOperand(1);
8402 if (Op1.hasOneUse()) {
8403 unsigned BitWidth = Op1.getValueSizeInBits();
8404 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8405 APInt KnownZero, KnownOne;
8406 TargetLowering::TargetLoweringOpt TLO(DAG);
8407 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8408 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8409 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8410 DCI.CommitTargetLoweringOpt(TLO);
8415 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8416 DAGCombinerInfo &DCI) const {
8417 SelectionDAG &DAG = DCI.DAG;
8418 switch (N->getOpcode()) {
8420 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8421 case ISD::BUILD_VECTOR:
8422 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8423 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8424 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
8425 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
8428 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8429 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8431 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8432 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8433 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8439 //===----------------------------------------------------------------------===//
8440 // X86 Inline Assembly Support
8441 //===----------------------------------------------------------------------===//
8443 /// getConstraintType - Given a constraint letter, return the type of
8444 /// constraint it is for this target.
8445 X86TargetLowering::ConstraintType
8446 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8447 if (Constraint.size() == 1) {
8448 switch (Constraint[0]) {
8460 return C_RegisterClass;
8468 return TargetLowering::getConstraintType(Constraint);
8471 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8472 /// with another that has more specific requirements based on the type of the
8473 /// corresponding operand.
8474 const char *X86TargetLowering::
8475 LowerXConstraint(MVT ConstraintVT) const {
8476 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8477 // 'f' like normal targets.
8478 if (ConstraintVT.isFloatingPoint()) {
8479 if (Subtarget->hasSSE2())
8481 if (Subtarget->hasSSE1())
8485 return TargetLowering::LowerXConstraint(ConstraintVT);
8488 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8489 /// vector. If it is invalid, don't add anything to Ops.
8490 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8493 std::vector<SDValue>&Ops,
8494 SelectionDAG &DAG) const {
8495 SDValue Result(0, 0);
8497 switch (Constraint) {
8500 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8501 if (C->getZExtValue() <= 31) {
8502 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8508 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8509 if (C->getZExtValue() <= 63) {
8510 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8516 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8517 if (C->getZExtValue() <= 255) {
8518 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8524 // 32-bit signed value
8525 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8526 const ConstantInt *CI = C->getConstantIntValue();
8527 if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8528 // Widen to 64 bits here to get it sign extended.
8529 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8532 // FIXME gcc accepts some relocatable values here too, but only in certain
8533 // memory models; it's complicated.
8538 // 32-bit unsigned value
8539 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8540 const ConstantInt *CI = C->getConstantIntValue();
8541 if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8542 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8546 // FIXME gcc accepts some relocatable values here too, but only in certain
8547 // memory models; it's complicated.
8551 // Literal immediates are always ok.
8552 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8553 // Widen to 64 bits here to get it sign extended.
8554 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8558 // If we are in non-pic codegen mode, we allow the address of a global (with
8559 // an optional displacement) to be used with 'i'.
8560 GlobalAddressSDNode *GA = 0;
8563 // Match either (GA), (GA+C), (GA+C1+C2), etc.
8565 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
8566 Offset += GA->getOffset();
8568 } else if (Op.getOpcode() == ISD::ADD) {
8569 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8570 Offset += C->getZExtValue();
8571 Op = Op.getOperand(0);
8574 } else if (Op.getOpcode() == ISD::SUB) {
8575 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8576 Offset += -C->getZExtValue();
8577 Op = Op.getOperand(0);
8582 // Otherwise, this isn't something we can handle, reject it.
8587 Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(), Offset, DAG);
8589 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8596 if (Result.getNode()) {
8597 Ops.push_back(Result);
8600 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8604 std::vector<unsigned> X86TargetLowering::
8605 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8607 if (Constraint.size() == 1) {
8608 // FIXME: not handling fp-stack yet!
8609 switch (Constraint[0]) { // GCC X86 Constraint Letters
8610 default: break; // Unknown constraint letter
8611 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8614 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8615 else if (VT == MVT::i16)
8616 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8617 else if (VT == MVT::i8)
8618 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8619 else if (VT == MVT::i64)
8620 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8625 return std::vector<unsigned>();
8628 std::pair<unsigned, const TargetRegisterClass*>
8629 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8631 // First, see if this is a constraint that directly corresponds to an LLVM
8633 if (Constraint.size() == 1) {
8634 // GCC Constraint Letters
8635 switch (Constraint[0]) {
8637 case 'r': // GENERAL_REGS
8638 case 'R': // LEGACY_REGS
8639 case 'l': // INDEX_REGS
8641 return std::make_pair(0U, X86::GR8RegisterClass);
8643 return std::make_pair(0U, X86::GR16RegisterClass);
8644 if (VT == MVT::i32 || !Subtarget->is64Bit())
8645 return std::make_pair(0U, X86::GR32RegisterClass);
8646 return std::make_pair(0U, X86::GR64RegisterClass);
8647 case 'f': // FP Stack registers.
8648 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8649 // value to the correct fpstack register class.
8650 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8651 return std::make_pair(0U, X86::RFP32RegisterClass);
8652 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8653 return std::make_pair(0U, X86::RFP64RegisterClass);
8654 return std::make_pair(0U, X86::RFP80RegisterClass);
8655 case 'y': // MMX_REGS if MMX allowed.
8656 if (!Subtarget->hasMMX()) break;
8657 return std::make_pair(0U, X86::VR64RegisterClass);
8658 case 'Y': // SSE_REGS if SSE2 allowed
8659 if (!Subtarget->hasSSE2()) break;
8661 case 'x': // SSE_REGS if SSE1 allowed
8662 if (!Subtarget->hasSSE1()) break;
8664 switch (VT.getSimpleVT()) {
8666 // Scalar SSE types.
8669 return std::make_pair(0U, X86::FR32RegisterClass);
8672 return std::make_pair(0U, X86::FR64RegisterClass);
8680 return std::make_pair(0U, X86::VR128RegisterClass);
8686 // Use the default implementation in TargetLowering to convert the register
8687 // constraint into a member of a register class.
8688 std::pair<unsigned, const TargetRegisterClass*> Res;
8689 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8691 // Not found as a standard register?
8692 if (Res.second == 0) {
8693 // GCC calls "st(0)" just plain "st".
8694 if (StringsEqualNoCase("{st}", Constraint)) {
8695 Res.first = X86::ST0;
8696 Res.second = X86::RFP80RegisterClass;
8698 // 'A' means EAX + EDX.
8699 if (Constraint == "A") {
8700 Res.first = X86::EAX;
8701 Res.second = X86::GRADRegisterClass;
8706 // Otherwise, check to see if this is a register class of the wrong value
8707 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8708 // turn into {ax},{dx}.
8709 if (Res.second->hasType(VT))
8710 return Res; // Correct type already, nothing to do.
8712 // All of the single-register GCC register classes map their values onto
8713 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8714 // really want an 8-bit or 32-bit register, map to the appropriate register
8715 // class and return the appropriate register.
8716 if (Res.second == X86::GR16RegisterClass) {
8717 if (VT == MVT::i8) {
8718 unsigned DestReg = 0;
8719 switch (Res.first) {
8721 case X86::AX: DestReg = X86::AL; break;
8722 case X86::DX: DestReg = X86::DL; break;
8723 case X86::CX: DestReg = X86::CL; break;
8724 case X86::BX: DestReg = X86::BL; break;
8727 Res.first = DestReg;
8728 Res.second = X86::GR8RegisterClass;
8730 } else if (VT == MVT::i32) {
8731 unsigned DestReg = 0;
8732 switch (Res.first) {
8734 case X86::AX: DestReg = X86::EAX; break;
8735 case X86::DX: DestReg = X86::EDX; break;
8736 case X86::CX: DestReg = X86::ECX; break;
8737 case X86::BX: DestReg = X86::EBX; break;
8738 case X86::SI: DestReg = X86::ESI; break;
8739 case X86::DI: DestReg = X86::EDI; break;
8740 case X86::BP: DestReg = X86::EBP; break;
8741 case X86::SP: DestReg = X86::ESP; break;
8744 Res.first = DestReg;
8745 Res.second = X86::GR32RegisterClass;
8747 } else if (VT == MVT::i64) {
8748 unsigned DestReg = 0;
8749 switch (Res.first) {
8751 case X86::AX: DestReg = X86::RAX; break;
8752 case X86::DX: DestReg = X86::RDX; break;
8753 case X86::CX: DestReg = X86::RCX; break;
8754 case X86::BX: DestReg = X86::RBX; break;
8755 case X86::SI: DestReg = X86::RSI; break;
8756 case X86::DI: DestReg = X86::RDI; break;
8757 case X86::BP: DestReg = X86::RBP; break;
8758 case X86::SP: DestReg = X86::RSP; break;
8761 Res.first = DestReg;
8762 Res.second = X86::GR64RegisterClass;
8765 } else if (Res.second == X86::FR32RegisterClass ||
8766 Res.second == X86::FR64RegisterClass ||
8767 Res.second == X86::VR128RegisterClass) {
8768 // Handle references to XMM physical registers that got mapped into the
8769 // wrong class. This can happen with constraints like {xmm0} where the
8770 // target independent register mapper will just pick the first match it can
8771 // find, ignoring the required type.
8773 Res.second = X86::FR32RegisterClass;
8774 else if (VT == MVT::f64)
8775 Res.second = X86::FR64RegisterClass;
8776 else if (X86::VR128RegisterClass->hasType(VT))
8777 Res.second = X86::VR128RegisterClass;
8783 //===----------------------------------------------------------------------===//
8784 // X86 Widen vector type
8785 //===----------------------------------------------------------------------===//
8787 /// getWidenVectorType: given a vector type, returns the type to widen
8788 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8789 /// If there is no vector type that we want to widen to, returns MVT::Other
8790 /// When and where to widen is target dependent based on the cost of
8791 /// scalarizing vs using the wider vector type.
8793 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8794 assert(VT.isVector());
8795 if (isTypeLegal(VT))
8798 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8799 // type based on element type. This would speed up our search (though
8800 // it may not be worth it since the size of the list is relatively
8802 MVT EltVT = VT.getVectorElementType();
8803 unsigned NElts = VT.getVectorNumElements();
8805 // On X86, it make sense to widen any vector wider than 1
8809 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8810 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8811 MVT SVT = (MVT::SimpleValueType)nVT;
8813 if (isTypeLegal(SVT) &&
8814 SVT.getVectorElementType() == EltVT &&
8815 SVT.getVectorNumElements() > NElts)